Programs & Examples On #Yui

A set of utilities and controls, created by Yahoo in JavaScript and CSS, for building richly interactive web applications using techniques such as DOM scripting, DHTML and AJAX

Dynamically add data to a javascript map

Well any Javascript object functions sort-of like a "map"

randomObject['hello'] = 'world';

Typically people build simple objects for the purpose:

var myMap = {};

// ...

myMap[newKey] = newValue;

edit — well the problem with having an explicit "put" function is that you'd then have to go to pains to avoid having the function itself look like part of the map. It's not really a Javascripty thing to do.

13 Feb 2014 — modern JavaScript has facilities for creating object properties that aren't enumerable, and it's pretty easy to do. However, it's still the case that a "put" property, enumerable or not, would claim the property name "put" and make it unavailable. That is, there's still only one namespace per object.

Set Value of Input Using Javascript Function

I'm not using YUI, but in case it helps anyone else - my issue was that I had duplicate ID's on the page (was working inside a dialog and forgot about the page underneath).

Changing the ID so it was unique allowed me to use the methods listed in Sangeet's answer.

How to get child element by class name?

Use querySelector and querySelectorAll

var testContainer = document.querySelector('#test');
var fourChildNode = testContainer.querySelector('.four');

IE9 and upper

;)

Using JavaScript to display a Blob

In your example, you should createElement('img').

In your link, base64blob != Base64.encode(blob).

This works, as long as your data is valid http://jsfiddle.net/SXFwP/ (I didn't have any BMP images so I had to use PNG).

What is the purpose for using OPTION(MAXDOP 1) in SQL Server?

As Kaboing mentioned, MAXDOP(n) actually controls the number of CPU cores that are being used in the query processor.

On a completely idle system, SQL Server will attempt to pull the tables into memory as quickly as possible and join between them in memory. It could be that, in your case, it's best to do this with a single CPU. This might have the same effect as using OPTION (FORCE ORDER) which forces the query optimizer to use the order of joins that you have specified. IN some cases, I have seen OPTION (FORCE PLAN) reduce a query from 26 seconds to 1 second of execution time.

Books Online goes on to say that possible values for MAXDOP are:

0 - Uses the actual number of available CPUs depending on the current system workload. This is the default value and recommended setting.

1 - Suppresses parallel plan generation. The operation will be executed serially.

2-64 - Limits the number of processors to the specified value. Fewer processors may be used depending on the current workload. If a value larger than the number of available CPUs is specified, the actual number of available CPUs is used.

I'm not sure what the best usage of MAXDOP is, however I would take a guess and say that if you have a table with 8 partitions on it, you would want to specify MAXDOP(8) due to I/O limitations, but I could be wrong.

Here are a few quick links I found about MAXDOP:

Books Online: Degree of Parallelism

General guidelines to use to configure the MAXDOP option

Occurrences of substring in a string

here is the other solution without using regexp/patterns/matchers or even not using StringUtils.

String str = "helloslkhellodjladfjhelloarunkumarhelloasdhelloaruhelloasrhello";
        String findStr = "hello";
        int count =0;
        int findStrLength = findStr.length();
        for(int i=0;i<str.length();i++){
            if(findStr.startsWith(Character.toString(str.charAt(i)))){
                if(str.substring(i).length() >= findStrLength){
                    if(str.substring(i, i+findStrLength).equals(findStr)){
                        count++;
                    }
                }
            }
        }
        System.out.println(count);

Multiple models in a view

I'd recommend using Html.RenderAction and PartialViewResults to accomplish this; it will allow you to display the same data, but each partial view would still have a single view model and removes the need for a BigViewModel

So your view contain something like the following:

@Html.RenderAction("Login")
@Html.RenderAction("Register")

Where Login & Register are both actions in your controller defined like the following:

public PartialViewResult Login( )
{
    return PartialView( "Login", new LoginViewModel() );
}

public PartialViewResult Register( )
{
    return PartialView( "Register", new RegisterViewModel() );
}

The Login & Register would then be user controls residing in either the current View folder, or in the Shared folder and would like something like this:

/Views/Shared/Login.cshtml: (or /Views/MyView/Login.cshtml)

@model LoginViewModel
@using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
    @Html.TextBoxFor(model => model.Email)
    @Html.PasswordFor(model => model.Password)
}

/Views/Shared/Register.cshtml: (or /Views/MyView/Register.cshtml)

@model ViewModel.RegisterViewModel
@using (Html.BeginForm("Login", "Auth", FormMethod.Post))
{
    @Html.TextBoxFor(model => model.Name)
    @Html.TextBoxFor(model => model.Email)
    @Html.PasswordFor(model => model.Password)
}

And there you have a single controller action, view and view file for each action with each totally distinct and not reliant upon one another for anything.

How to serialize a JObject without the formatting?

Call JObject's ToString(Formatting.None) method.

Alternatively if you pass the object to the JsonConvert.SerializeObject method it will return the JSON without formatting.

Documentation: Write JSON text with JToken.ToString

How to len(generator())

You can use len(list(generator_function()). However, this consumes the generator, but that's the only way you can find out how many elements are generated. So you may want to save the list somewhere if you also want to use the items.

a = list(generator_function())
print(len(a))
print(a[0])

Truncating Text in PHP?

$mystring = "this is the text I would like to truncate";

// Pass your variable to the function
$mystring = truncate($mystring);

// Truncated tring printed out;
echo $mystring;

//truncate text function
public function truncate($text) {

    //specify number fo characters to shorten by
    $chars = 25;

    $text = $text." ";
    $text = substr($text,0,$chars);
    $text = substr($text,0,strrpos($text,' '));
    $text = $text."...";
    return $text;
}

Generate class from database table

slightly modified from top reply:

declare @TableName sysname = 'HistoricCommand'

declare @Result varchar(max) = '[System.Data.Linq.Mapping.Table(Name = "' + @TableName + '")]
public class Dbo' + @TableName + '
{'

select @Result = @Result + '
    [System.Data.Linq.Mapping.Column(Name = "' + t.ColumnName + '", IsPrimaryKey = ' + pkk.ISPK + ')]
    public ' + ColumnType + NullableSign + ' ' + t.ColumnName + ' { get; set; }
'
from
(
    select 
        replace(col.name, ' ', '_') ColumnName,
        column_id ColumnId,
        case typ.name 
            when 'bigint' then 'long'
            when 'binary' then 'byte[]'
            when 'bit' then 'bool'
            when 'char' then 'string'
            when 'date' then 'DateTime'
            when 'datetime' then 'DateTime'
            when 'datetime2' then 'DateTime'
            when 'datetimeoffset' then 'DateTimeOffset'
            when 'decimal' then 'decimal'
            when 'float' then 'float'
            when 'image' then 'byte[]'
            when 'int' then 'int'
            when 'money' then 'decimal'
            when 'nchar' then 'string'
            when 'ntext' then 'string'
            when 'numeric' then 'decimal'
            when 'nvarchar' then 'string'
            when 'real' then 'double'
            when 'smalldatetime' then 'DateTime'
            when 'smallint' then 'short'
            when 'smallmoney' then 'decimal'
            when 'text' then 'string'
            when 'time' then 'TimeSpan'
            when 'timestamp' then 'DateTime'
            when 'tinyint' then 'byte'
            when 'uniqueidentifier' then 'Guid'
            when 'varbinary' then 'byte[]'
            when 'varchar' then 'string'
            else 'UNKNOWN_' + typ.name
        end ColumnType,
        case 
            when col.is_nullable = 1 and typ.name in ('bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset', 'decimal', 'float', 'int', 'money', 'numeric', 'real', 'smalldatetime', 'smallint', 'smallmoney', 'time', 'tinyint', 'uniqueidentifier') 
            then '?' 
            else '' 
        end NullableSign
    from sys.columns col
        join sys.types typ on
            col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id         
    where object_id = object_id(@TableName) 
) t, 
(
                SELECT c.name  AS 'ColumnName', CASE WHEN dd.pk IS NULL THEN 'false' ELSE 'true' END ISPK           
                FROM        sys.columns c
                    JOIN    sys.tables  t   ON c.object_id = t.object_id    
                    LEFT JOIN (SELECT   K.COLUMN_NAME , C.CONSTRAINT_TYPE as pk  
                        FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K 
                            LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C
                        ON K.TABLE_NAME = C.TABLE_NAME
                            AND K.CONSTRAINT_NAME = C.CONSTRAINT_NAME
                            AND K.CONSTRAINT_CATALOG = C.CONSTRAINT_CATALOG
                            AND K.CONSTRAINT_SCHEMA = C.CONSTRAINT_SCHEMA            
                        WHERE K.TABLE_NAME = @TableName) as dd
                     ON dd.COLUMN_NAME = c.name
                 WHERE       t.name = @TableName            
            ) pkk
where pkk.ColumnName = t.ColumnName
order by ColumnId

set @Result = @Result  + '
}'

print @Result

which makes output needed for full LINQ in C# declaration

[System.Data.Linq.Mapping.Table(Name = "HistoricCommand")]
public class DboHistoricCommand
{
    [System.Data.Linq.Mapping.Column(Name = "HistoricCommandId", IsPrimaryKey = true)]
    public int HistoricCommandId { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "PHCloudSoftwareInstanceId", IsPrimaryKey = true)]
    public int PHCloudSoftwareInstanceId { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "CommandType", IsPrimaryKey = false)]
    public int CommandType { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "InitiatedDateTime", IsPrimaryKey = false)]
    public DateTime InitiatedDateTime { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "CompletedDateTime", IsPrimaryKey = false)]
    public DateTime CompletedDateTime { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "WasSuccessful", IsPrimaryKey = false)]
    public bool WasSuccessful { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "Message", IsPrimaryKey = false)]
    public string Message { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "ResponseData", IsPrimaryKey = false)]
    public string ResponseData { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "Message_orig", IsPrimaryKey = false)]
    public string Message_orig { get; set; }

    [System.Data.Linq.Mapping.Column(Name = "Message_XX", IsPrimaryKey = false)]
    public string Message_XX { get; set; }

}

How to add a second css class with a conditional value in razor MVC 4

You can add property to your model as follows:

    public string DetailsClass { get { return Details.Count > 0 ? "show" : "hide" } }

and then your view will be simpler and will contain no logic at all:

    <div class="details @Model.DetailsClass"/>

This will work even with many classes and will not render class if it is null:

    <div class="@Model.Class1 @Model.Class2"/>

with 2 not null properties will render:

    <div class="class1 class2"/>

if class1 is null

    <div class=" class2"/>

How to convert byte array to string

Assuming that you are using UTF-8 encoding:

string convert = "This is the string to be converted";

// From string to byte array
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(convert);

// From byte array to string
string s = System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length);

Android BroadcastReceiver within Activity

 Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT);

makes the toast, but doesnt show it.

You have to do Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT).show();

How to use a parameter in ExecStart command line?

Although systemd indeed does not provide way to pass command-line arguments for unit files, there are possibilities to write instances: http://0pointer.de/blog/projects/instances.html

For example: /lib/systemd/system/[email protected] looks something like this:

[Unit]
Description=Serial Getty on %I
BindTo=dev-%i.device
After=dev-%i.device systemd-user-sessions.service

[Service]
ExecStart=-/sbin/agetty -s %I 115200,38400,9600
Restart=always
RestartSec=0

So, you may start it like:

$ systemctl start [email protected]
$ systemctl start [email protected]

For systemd it will different instances:

$ systemctl status [email protected]
[email protected] - Getty on ttyUSB0
      Loaded: loaded (/lib/systemd/system/[email protected]; static)
      Active: active (running) since Mon, 26 Sep 2011 04:20:44 +0200; 2s ago
    Main PID: 5443 (agetty)
      CGroup: name=systemd:/system/[email protected]/ttyUSB0
          + 5443 /sbin/agetty -s ttyUSB0 115200,38400,9600

It also mean great possibility enable and disable it separately.

Off course it lack much power of command line parsing, but in common way it is used as some sort of config files selection. For example you may look at Fedora [email protected]: http://pkgs.fedoraproject.org/cgit/openvpn.git/tree/[email protected]

Printing 1 to 1000 without loop or conditionals

Here are my 2 solutions. First is C# and the second in C:

C#:

const int limit = 1000;

Action<int>[] actions = new Action<int>[2];
actions[0] = (n) => { Console.WriteLine(n); };
actions[1] = (n) => { Console.WriteLine(n);  actions[Math.Sign(limit - n-1)](n + 1); };

actions[1](0);

C:

#define sign(x) (( x >> 31 ) | ( (unsigned int)( -x ) >> 31 ))

void (*actions[3])(int);

void Action0(int n)
{
    printf("%d", n);
}

void Action1(int n)
{
    int index;
    printf("%d\n", n);
    index = sign(998-n)+1;
    actions[index](++n);
}

void main()
{
    actions[0] = &Action0;
    actions[1] = 0; //Not used
    actions[2] = &Action1;

    actions[2](0);
}

Parsing a pcap file in python

You might want to start with scapy.

How to get an array of specific "key" in multidimensional array without looping

If id is the first key in the array, this'll do:

$ids = array_map('current', $users);

You should not necessarily rely on this though. :)

.NET NewtonSoft JSON deserialize map to a different property name

If you'd like to use dynamic mapping, and don't want to clutter up your model with attributes, this approach worked for me

Usage:

var settings = new JsonSerializerSettings();
settings.DateFormatString = "YYYY-MM-DD";
settings.ContractResolver = new CustomContractResolver();
this.DataContext = JsonConvert.DeserializeObject<CountResponse>(jsonString, settings);

Logic:

public class CustomContractResolver : DefaultContractResolver
{
    private Dictionary<string, string> PropertyMappings { get; set; }

    public CustomContractResolver()
    {
        this.PropertyMappings = new Dictionary<string, string> 
        {
            {"Meta", "meta"},
            {"LastUpdated", "last_updated"},
            {"Disclaimer", "disclaimer"},
            {"License", "license"},
            {"CountResults", "results"},
            {"Term", "term"},
            {"Count", "count"},
        };
    }

    protected override string ResolvePropertyName(string propertyName)
    {
        string resolvedName = null;
        var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
        return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
    }
}

Log all queries in mysql

For the record, general_log and slow_log were introduced in 5.1.6:

http://dev.mysql.com/doc/refman/5.1/en/log-destinations.html

5.2.1. Selecting General Query and Slow Query Log Output Destinations

As of MySQL 5.1.6, MySQL Server provides flexible control over the destination of output to the general query log and the slow query log, if those logs are enabled. Possible destinations for log entries are log files or the general_log and slow_log tables in the mysql database

hardcoded string "row three", should use @string resource

You can go to Design mode and select "Fix" at the bottom of the warning. Then a pop up will appear (seems like it's going to register the new string) and voila, the error is fixed.

best practice to generate random token for forgot password

This answers the 'best random' request:

Adi's answer1 from Security.StackExchange has a solution for this:

Make sure you have OpenSSL support, and you'll never go wrong with this one-liner

$token = bin2hex(openssl_random_pseudo_bytes(16));

1. Adi, Mon Nov 12 2018, Celeritas, "Generating an unguessable token for confirmation e-mails", Sep 20 '13 at 7:06, https://security.stackexchange.com/a/40314/

Sleeping in a batch file

Just for fun, if you have Node.js installed, you can use

node -e 'setTimeout(a => a, 5000)'

to sleep for 5 seconds. It works on a Mac with Node v12.14.0.

Initializing select with AngularJS and ng-repeat

The fact that angular is injecting an empty option element to the select is that the model object binded to it by default comes with an empty value in when initialized.

If you want to select a default option then you can probably can set it on the scope in the controller

$scope.filterCondition.operator = "your value here";

If you want to an empty option placeholder, this works for me

<select ng-model="filterCondition.operator" ng-options="operator.id as operator.name for operator in operators">
  <option value="">Choose Operator</option>
</select>

In MySQL, can I copy one row to insert into the same table?

Here's an answer I found online at this site Describes how to do the above1 You can find the answer at the bottom of the page. Basically, what you do is copy the row to be copied to a temporary table held in memory. You then change the Primary Key number using update. You then re-insert it into the target table. You then drop the table.

This is the code for it:

CREATE TEMPORARY TABLE rescueteam ENGINE=MEMORY SELECT * FROMfitnessreport4 WHERE rID=1;# 1 row affected. UPDATE rescueteam SET rID=Null WHERE rID=1;# 1 row affected.INSERT INTO fitnessreport4 SELECT * FROM rescueteam;# 1 row affected. DROP TABLE rescueteam# MySQL returned an empty result set (i.e. zero
rows).

I created the temporary table rescueteam. I copied the row from my original table fitnessreport4. I then set the primary key for the row in the temporary table to null so that I can copy it back to the original table without getting a Duplicate Key error. I tried this code yesterday evening and it worked.

What's the best way to get the last element of an array without deleting it?

Simply: $last_element = end((array_values($array)))

Doesn't reset the array and doesn't gives STRICT warnings.

PS. Since the most voted answer still hasn't the double parenthesis, I submitted this answer.

What is the fastest way to create a checksum for large files in C#

Ok - thanks to all of you - let me wrap this up:

  1. using a "native" exe to do the hashing took time from 6 Minutes to 10 Seconds which is huge.
  2. Increasing the buffer was even faster - 1.6GB file took 5.2 seconds using MD5 in .Net, so I will go with this solution - thanks again

SQL grouping by month and year

I guess is MS SQL as it looks like MS SQL syntax.

So you should put in the group line the same thing as in select ex:

Select MONTH(date)+'-'+YEAR(date), ....
...
...
...
group by MONTH(date)+'-'+YEAR(date)

Eclipse hangs on loading workbench

deleting workspace/.metadata/.lock and starting eclipse with -clean -refresh worked for me.

In C can a long printf statement be broken up into multiple lines?

Just some other formatting options:

printf("name: %s\targs: %s\tvalue %d\tarraysize %d\n", 
        a,        b,        c,        d);

printf("name: %s\targs: %s\tvalue %d\tarraysize %d\n", 
              a,        b,        c,            d);

printf("name: %s\t"      "args: %s\t"      "value %d\t"      "arraysize %d\n", 
        very_long_name_a, very_long_name_b, very_long_name_c, very_long_name_d);

You can add variations on the theme. The idea is that the printf() conversion speficiers and the respective variables are all lined up "nicely" (for some values of "nicely").

X-Frame-Options on apache

What did it for me was the following, I've added the following directive in both the http <VirtualHost *:80> and https <VirtualHost *:443> virtual host blocks:

ServerName your-app.com
ServerAlias www.your-app.com

Header always unset X-Frame-Options
Header set X-Frame-Options "SAMEORIGIN"

The reasoning behind this? Well by default if set, the server does not reset the X-Frame-Options header so we need to first always remove the default value, in my case it was DENY, and then with the next rule we set it to the desired value, in my case SAMEORIGIN. Of course you can use the Header set X-Frame-Options ALLOW-FROM ... rule as well.

Create multiple threads and wait all of them to complete

I think you need WaitHandler.WaitAll. Here is an example:

public static void Main(string[] args)
{
    int numOfThreads = 10;
    WaitHandle[] waitHandles = new WaitHandle[numOfThreads];

    for (int i = 0; i < numOfThreads; i++)
    {
        var j = i;
        // Or you can use AutoResetEvent/ManualResetEvent
        var handle = new EventWaitHandle(false, EventResetMode.ManualReset);
        var thread = new Thread(() =>
                                {
                                    Thread.Sleep(j * 1000);
                                    Console.WriteLine("Thread{0} exits", j);
                                    handle.Set();
                                });
        waitHandles[j] = handle;
        thread.Start();
    }
    WaitHandle.WaitAll(waitHandles);
    Console.WriteLine("Main thread exits");
    Console.Read();
}

FCL has a few more convenient functions.

(1) Task.WaitAll, as well as its overloads, when you want to do some tasks in parallel (and with no return values).

var tasks = new[]
{
    Task.Factory.StartNew(() => DoSomething1()),
    Task.Factory.StartNew(() => DoSomething2()),
    Task.Factory.StartNew(() => DoSomething3())
};
Task.WaitAll(tasks);

(2) Task.WhenAll when you want to do some tasks with return values. It performs the operations and puts the results in an array. It's thread-safe, and you don't need to using a thread-safe container and implement the add operation yourself.

var tasks = new[]
{
    Task.Factory.StartNew(() => GetSomething1()),
    Task.Factory.StartNew(() => GetSomething2()),
    Task.Factory.StartNew(() => GetSomething3())
};
var things = Task.WhenAll(tasks);

Can you force Visual Studio to always run as an Administrator in Windows 8?

NOTE in recent VS versions (2015+) it seems this extension no longer exists/has this feature.


You can also download VSCommands for VS2012 by Squared Infinity which has a feature to change it to run as admin (as well as some other cool bits and pieces)

enter image description here

Update

One can install the commands from the Visual Studio menu bar using Tools->Extensions and Updates selecting Online and searching for vscommands where then one selects VSCommands for Visual Studio 20XX depending on whether using 2012 or 2013 (or greater going forward) and download and install.

JavaScript OOP in NodeJS: how?

In the Javascript community, lots of people argue that OOP should not be used because the prototype model does not allow to do a strict and robust OOP natively. However, I don't think that OOP is a matter of langage but rather a matter of architecture.

If you want to use a real strong OOP in Javascript/Node, you can have a look at the full-stack open source framework Danf. It provides all needed features for a strong OOP code (classes, interfaces, inheritance, dependency-injection, ...). It also allows you to use the same classes on both the server (node) and client (browser) sides. Moreover, you can code your own danf modules and share them with anybody thanks to Npm.

Hidden TextArea

but is the css style tag the correct way to get cross browser compatibility?

 <textarea style="display:none;" ></textarea>

or what I learned long ago....

     <textarea hidden ></textarea>

or
the global hidden element method:

    <textarea hidden="hidden" ></textarea>       

Why is datetime.strptime not working in this simple example?

You are importing the module datetime, which doesn't have a strptime function.

That module does have a datetime object with that method though:

import datetime
dtDate = datetime.datetime.strptime(sDate, "%m/%d/%Y")

Alternatively you can import the datetime object from the module:

from datetime import datetime
dtDate = datetime.strptime(sDate, "%m/%d/%Y")

Note that the strptime method was added in python 2.5; if you are using an older version use the following code instead:

import datetime, time
dtDate = datetime.datetime(*time.strptime(sDate, "%m/%d/%Y")[:6])

How can I verify if a Windows Service is running

Here you get all available services and their status in your local machine.

ServiceController[] services = ServiceController.GetServices();
foreach(ServiceController service in services)
{
    Console.WriteLine(service.ServiceName+"=="+ service.Status);
}

You can Compare your service with service.name property inside loop and you get status of your service. For details go with the http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.aspx also http://msdn.microsoft.com/en-us/library/microsoft.windows.design.servicemanager(v=vs.90).aspx

How to remove default chrome style for select Input?

When looking at an input with a type of number, you'll notice the spinner buttons (up/down) on the right-hand side of the input field. These spinners aren't always desirable, thus the code below removes such styling to render an input that resembles that of an input with a type of text.

enter image description here

input[type=number]::-webkit-inner-spin-button, 
input[type=number]::-webkit-outer-spin-button { 
  -webkit-appearance: none; 
}

How to save a pandas DataFrame table as a png

Pandas allows you to plot tables using matplotlib (details here). Usually this plots the table directly onto a plot (with axes and everything) which is not what you want. However, these can be removed first:

import matplotlib.pyplot as plt
import pandas as pd
from pandas.table.plotting import table # EDIT: see deprecation warnings below

ax = plt.subplot(111, frame_on=False) # no visible frame
ax.xaxis.set_visible(False)  # hide the x axis
ax.yaxis.set_visible(False)  # hide the y axis

table(ax, df)  # where df is your data frame

plt.savefig('mytable.png')

The output might not be the prettiest but you can find additional arguments for the table() function here. Also thanks to this post for info on how to remove axes in matplotlib.


EDIT:

Here is a (admittedly quite hacky) way of simulating multi-indexes when plotting using the method above. If you have a multi-index data frame called df that looks like:

first  second
bar    one       1.991802
       two       0.403415
baz    one      -1.024986
       two      -0.522366
foo    one       0.350297
       two      -0.444106
qux    one      -0.472536
       two       0.999393
dtype: float64

First reset the indexes so they become normal columns

df = df.reset_index() 
df
    first second       0
0   bar    one  1.991802
1   bar    two  0.403415
2   baz    one -1.024986
3   baz    two -0.522366
4   foo    one  0.350297
5   foo    two -0.444106
6   qux    one -0.472536
7   qux    two  0.999393

Remove all duplicates from the higher order multi-index columns by setting them to an empty string (in my example I only have duplicate indexes in "first"):

df.ix[df.duplicated('first') , 'first'] = '' # see deprecation warnings below
df
  first second         0
0   bar    one  1.991802
1          two  0.403415
2   baz    one -1.024986
3          two -0.522366
4   foo    one  0.350297
5          two -0.444106
6   qux    one -0.472536
7          two  0.999393

Change the column names over your "indexes" to the empty string

new_cols = df.columns.values
new_cols[:2] = '',''  # since my index columns are the two left-most on the table
df.columns = new_cols 

Now call the table function but set all the row labels in the table to the empty string (this makes sure the actual indexes of your plot are not displayed):

table(ax, df, rowLabels=['']*df.shape[0], loc='center')

et voila:

enter image description here

Your not-so-pretty but totally functional multi-indexed table.

EDIT: DEPRECATION WARNINGS

As pointed out in the comments, the import statement for table:

from pandas.tools.plotting import table

is now deprecated in newer versions of pandas in favour of:

from pandas.plotting import table 

EDIT: DEPRECATION WARNINGS 2

The ix indexer has now been fully deprecated so we should use the loc indexer instead. Replace:

df.ix[df.duplicated('first') , 'first'] = ''

with

df.loc[df.duplicated('first') , 'first'] = ''

Sorting an array of objects by property values

You want to sort it in Javascript, right? What you want is the sort() function. In this case you need to write a comparator function and pass it to sort(), so something like this:

function comparator(a, b) {
    return parseInt(a["price"], 10) - parseInt(b["price"], 10);
}

var json = { "homes": [ /* your previous data */ ] };
console.log(json["homes"].sort(comparator));

Your comparator takes one of each of the nested hashes inside the array and decides which one is higher by checking the "price" field.

Copy output of a JavaScript variable to the clipboard

function copyToClipboard(text) {
    var dummy = document.createElement("textarea");
    // to avoid breaking orgain page when copying more words
    // cant copy when adding below this code
    // dummy.style.display = 'none'
    document.body.appendChild(dummy);
    //Be careful if you use texarea. setAttribute('value', value), which works with "input" does not work with "textarea". – Eduard
    dummy.value = text;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}
copyToClipboard('hello world')
copyToClipboard('hello\nworld')

How do I use disk caching in Picasso?

For caching, I would use OkHttp interceptors to gain control over caching policy. Check out this sample that's included in the OkHttp library.

RewriteResponseCacheControl.java

Here's how I'd use it with Picasso -

OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.networkInterceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response originalResponse = chain.proceed(chain.request());
            return originalResponse.newBuilder().header("Cache-Control", "max-age=" + (60 * 60 * 24 * 365)).build();
        }
    });

    okHttpClient.setCache(new Cache(mainActivity.getCacheDir(), Integer.MAX_VALUE));
    OkHttpDownloader okHttpDownloader = new OkHttpDownloader(okHttpClient);
    Picasso picasso = new Picasso.Builder(mainActivity).downloader(okHttpDownloader).build();
    picasso.load(imageURL).into(viewHolder.image);

ORA-12154: TNS:could not resolve the connect identifier specified (PLSQL Developer)

As I can't add a comment, just thought I'd post this for completion. tufy's answer is correct, it's to do with parenthesis (brackets) in the path to the application being run.

There is an existing networking bug where the networking layer is unable to parse program locations that contain parenthesis in the path to the executable which is attempting to connect to Oracle.

Filed with Oracle, Bug 3807408 refers.

Source

@import vs #import - iOS 7

Nice answer you can find in book Learning Cocoa with Objective-C (ISBN: 978-1-491-90139-7)

Modules are a new means of including and linking files and libraries into your projects. To understand how modules work and what benefits they have, it is important to look back into the history of Objective-C and the #import statement Whenever you want to include a file for use, you will generally have some code that looks like this:

#import "someFile.h"

Or in the case of frameworks:

#import <SomeLibrary/SomeFile.h>

Because Objective-C is a superset of the C programming language, the #import state- ment is a minor refinement upon C’s #include statement. The #include statement is very simple; it copies everything it finds in the included file into your code during compilation. This can sometimes cause significant problems. For example, imagine you have two header files: SomeFileA.h and SomeFileB.h; SomeFileA.h includes SomeFileB.h, and SomeFileB.h includes SomeFileA.h. This creates a loop, and can confuse the coimpiler. To deal with this, C programmers have to write guards against this type of event from occurring.

When using #import, you don’t need to worry about this issue or write header guards to avoid it. However, #import is still just a glorified copy-and-paste action, causing slow compilation time among a host of other smaller but still very dangerous issues (such as an included file overriding something you have declared elsewhere in your own code.)

Modules are an attempt to get around this. They are no longer a copy-and-paste into source code, but a serialised representation of the included files that can be imported into your source code only when and where they’re needed. By using modules, code will generally compile faster, and be safer than using either #include or #import.

Returning to the previous example of importing a framework:

#import <SomeLibrary/SomeFile.h>

To import this library as a module, the code would be changed to:

@import SomeLibrary;

This has the added bonus of Xcode linking the SomeLibrary framework into the project automatically. Modules also allow you to only include the components you really need into your project. For example, if you want to use the AwesomeObject component in the AwesomeLibrary framework, normally you would have to import everything just to use the one piece. However, using modules, you can just import the specific object you want to use:

@import AwesomeLibrary.AwesomeObject;

For all new projects made in Xcode 5, modules are enabled by default. If you want to use modules in older projects (and you really should) they will have to be enabled in the project’s build settings. Once you do that, you can use both #import and @import statements in your code together without any concern.

Add class to an element in Angular 4

If you want to set only one specific class, you might write a TypeScript function returning a boolean to determine when the class should be appended.

TypeScript

function hideThumbnail():boolean{
    if (/* Your criteria here */)
        return true;
}

CSS:

.request-card-hidden {
    display: none;
}

HTML:

<ion-note [class.request-card-hidden]="hideThumbnail()"></ion-note>

How to Identify Microsoft Edge browser via CSS?

/* Microsoft Edge Browser 12-18 (All versions before Chromium) */

This one should work:

@supports (-ms-ime-align:auto) {
    .selector {
        property: value;
    }
}

For more see: Browser Strangeness

Wrap long lines in Python

I'm surprised no one mentioned the implicit style above. My preference is to use parens to wrap the string while lining the string lines up visually. Personally I think this looks cleaner and more compact than starting the beginning of the string on a tabbed new line.

Note that these parens are not part of a method call — they're only implicit string literal concatenation.

Python 2:

def fun():
    print ('{0} Here is a really '
           'long sentence with {1}').format(3, 5)

Python 3 (with parens for print function):

def fun():
    print(('{0} Here is a really '
           'long sentence with {1}').format(3, 5))

Personally I think it's cleanest to separate concatenating the long string literal from printing it:

def fun():
    s = ('{0} Here is a really '
         'long sentence with {1}').format(3, 5)
    print(s)

The import org.junit cannot be resolved

If you are using Java 9 or above you may need to require the junit dependency in your module-info.java

module myModule {
    requires junit;
}

Include an SVG (hosted on GitHub) in MarkDown

The purpose of raw.github.com is to allow users to view the contents of a file, so for text based files this means (for certain content types) you can get the wrong headers and things break in the browser.

When this question was asked (in 2012) SVGs didn't work. Since then Github has implemented various improvements. Now (at least for SVG), the correct Content-Type headers are sent.

Examples

All of the ways stated below will work.

I copied the SVG image from the question to a repo on github in order to create the examples below

Linking to files using relative paths (Works, but obviously only on github.com / github.io)

Code

![Alt text](./controllers_brief.svg)
<img src="./controllers_brief.svg">

Result

See the working example on github.com.

Linking to RAW files

Code

![Alt text](https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg)
<img src="https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg">

Result

Alt text

Linking to RAW files using ?sanitize=true

Code

![Alt text](https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg?sanitize=true)
<img src="https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg?sanitize=true">

Result

Alt text

Linking to files hosted on github.io

Code

![Alt text](https://potherca-blog.github.io/StackOverflow/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg)
<img src="https://potherca-blog.github.io/StackOverflow/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg">

Result

Alt text


Some comments regarding changes that happened along the way:

  • Github has implemented a feature which makes it possible for SVG's to be used with the Markdown image syntax. The SVG image will be sanitized and displayed with the correct HTTP header. Certain tags (like <script>) are removed.

    To view the sanitized SVG or to achieve this effect from other places (i.e. from markdown files not hosted in repos on http://github.com/) simply append ?sanitize=true to the SVG's raw URL.

  • As stated by AdamKatz in the comments, using a source other than github.io can introduce potentially privacy and security risks. See the answer by CiroSantilli and the answer by DavidChambers for more details.

  • The issue to resolve this was opened on Github on October 13th 2015 and was resolved on August 31th 2017

Align image to left of text on same line - Twitter Bootstrap3

Use Nesting column

To nest your content with the default grid, add a new .row and set of .col-sm-* columns within an existing .col-sm-* column. Nested rows should include a set of columns that add up to 12 or fewer (it is not required that you use all 12 available columns).

enter image description here

_x000D_
_x000D_
<div class="row">_x000D_
  <div class="col-sm-9">_x000D_
    Level 1: .col-sm-9_x000D_
    <div class="row">_x000D_
      <div class="col-xs-8 col-sm-6">_x000D_
        Level 2: .col-xs-8 .col-sm-6_x000D_
      </div>_x000D_
      <div class="col-xs-4 col-sm-6">_x000D_
        Level 2: .col-xs-4 .col-sm-6_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

When should I use nil and NULL in Objective-C?

nil means absence of value while NULL represent No Object,

NSArray *array = @[@"Hello World !", @101,[NSNULL null] ];

Here [NSNULL null] is an object which means no object, at the same time you cannot add nil to indicate absence of object.

you can use both nil and [NSNUll null] for checking too.

Where can I set path to make.exe on Windows?

I had issues for a whilst not getting Terraform commands to run unless I was in the directory of the exe, even though I set the path correctly.

For anyone else finding this issue, I fixed it by moving the environment variable higher than others!

PHP foreach with Nested Array?

foreach ($tmpArray as $innerArray) {
    //  Check type
    if (is_array($innerArray)){
        //  Scan through inner loop
        foreach ($innerArray as $value) {
            echo $value;
        }
    }else{
        // one, two, three
        echo $innerArray;
    }
}

Print raw string from variable? (not getting the answers)

In general, to make a raw string out of a string variable, I use this:

string = "C:\\Windows\Users\alexb"

raw_string = r"{}".format(string)

output:

'C:\\\\Windows\\Users\\alexb'

PostgreSQL error 'Could not connect to server: No such file or directory'

Check there is no postmaster.pid in your postgres directory, probably /usr/local/var/postgres/

remove this and start server.

Check - https://github.com/mperham/lunchy is a great wrapper for launchctl.

Changing CSS for last <li>

$('li').last().addClass('someClass');

if you have multiple

  • group it will only select the last li.

  • How do I move a table into a schema in T-SQL

    ALTER SCHEMA TargetSchema 
        TRANSFER SourceSchema.TableName;
    

    If you want to move all tables into a new schema, you can use the undocumented (and to be deprecated at some point, but unlikely!) sp_MSforeachtable stored procedure:

    exec sp_MSforeachtable "ALTER SCHEMA TargetSchema TRANSFER ?"
    

    Ref.: ALTER SCHEMA

    SQL 2008: How do I change db schema to dbo

    How to prevent Browser cache for php site

    Prevent browser cache is not a good idea depending on the case. Looking for a solution I found solutions like this:

    <link rel="stylesheet" type="text/css" href="meu.css?v=<?=filemtime($file);?>">
    

    the problem here is that if the file is overwritten during an update on the server, which is my scenario, the cache is ignored because timestamp is modified even the content of the file is the same.

    I use this solution to force browser to download assets only if its content is modified:

    <link rel="stylesheet" type="text/css" href="meu.css?v=<?=hash_file('md5', $file);?>">
    

    Reading and writing to serial port in C on Linux

    1) I'd add a /n after init. i.e. write( USB, "init\n", 5);

    2) Double check the serial port configuration. Odds are something is incorrect in there. Just because you don't use ^Q/^S or hardware flow control doesn't mean the other side isn't expecting it.

    3) Most likely: Add a "usleep(100000); after the write(). The file-descriptor is set not to block or wait, right? How long does it take to get a response back before you can call read? (It has to be received and buffered by the kernel, through system hardware interrupts, before you can read() it.) Have you considered using select() to wait for something to read()? Perhaps with a timeout?

    Edited to Add:

    Do you need the DTR/RTS lines? Hardware flow control that tells the other side to send the computer data? e.g.

    int tmp, serialLines;
    
    cout << "Dropping Reading DTR and RTS\n";
    ioctl ( readFd, TIOCMGET, & serialLines );
    serialLines &= ~TIOCM_DTR;
    serialLines &= ~TIOCM_RTS;
    ioctl ( readFd, TIOCMSET, & serialLines );
    usleep(100000);
    ioctl ( readFd, TIOCMGET, & tmp );
    cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;
    sleep (2);
    
    cout << "Setting Reading DTR and RTS\n";
    serialLines |= TIOCM_DTR;
    serialLines |= TIOCM_RTS;
    ioctl ( readFd, TIOCMSET, & serialLines );
    ioctl ( readFd, TIOCMGET, & tmp );
    cout << "Reading DTR status: " << (tmp & TIOCM_DTR) << endl;
    

    Socket.IO - how do I get a list of connected sockets/clients?

    [email protected]

     io.in('room1').sockets.sockets.forEach((socket,key)=>{
            console.log(socket);
        })
    

    all socket instance in room1

    For loop example in MySQL

    Assume you have one table with name 'table1'. It contain one column 'col1' with varchar type. Query to crate table is give below

    CREATE TABLE `table1` (
        `col1` VARCHAR(50) NULL DEFAULT NULL
    )
    

    Now if you want to insert number from 1 to 50 in that table then use following stored procedure

    DELIMITER $$  
    CREATE PROCEDURE ABC()
    
       BEGIN
          DECLARE a INT Default 1 ;
          simple_loop: LOOP         
             insert into table1 values(a);
             SET a=a+1;
             IF a=51 THEN
                LEAVE simple_loop;
             END IF;
       END LOOP simple_loop;
    END $$
    

    To call that stored procedure use

    CALL `ABC`()
    

    How to do a HTTP HEAD request from the windows command line?

    There is a Win32 port of wget that works decently.

    PowerShell's Invoke-WebRequest -Method Head would work as well.

    Scroll part of content in fixed position container

    I changed scrollable div to be with absolute position, and everything works for me

    div.sidebar {
        overflow: hidden;
        background-color: green;
        padding: 5px;
        position: fixed;
        right: 20px;
        width: 40%;
        top: 30px;
        padding: 20px;
        bottom: 30%;
    }
    div#fixed {
        background: #76a7dc;
        color: #fff;
        height: 30px;
    }
    
    div#scrollable {
        overflow-y: scroll;
        background: lightblue;
    
        position: absolute;
        top:55px; 
        left:20px;
        right:20px;
        bottom:10px;
    }
    

    DEMO with two scrollable divs

    XMLHttpRequest cannot load an URL with jQuery

    Fiddle with 3 working solutions in action.

    Given an external JSON:

    myurl = 'http://wikidata.org/w/api.php?action=wbgetentities&sites=frwiki&titles=France&languages=zh-hans|zh-hant|fr&props=sitelinks|labels|aliases|descriptions&format=json'
    

    Solution 1: $.ajax() + jsonp:

    $.ajax({
      dataType: "jsonp",
      url: myurl ,
      }).done(function ( data ) {
      // do my stuff
    });
    

    Solution 2: $.ajax()+json+&calback=?:

    $.ajax({
      dataType: "json",
      url: myurl + '&callback=?',
      }).done(function ( data ) {
      // do my stuff
    });
    

    Solution 3: $.getJSON()+calback=?:

    $.getJSON( myurl + '&callback=?', function(data) {
      // do my stuff
    });
    

    Documentations: http://api.jquery.com/jQuery.ajax/ , http://api.jquery.com/jQuery.getJSON/

    Open a file with Notepad in C#

    You can use Process.Start, calling notepad.exe with the file as a parameter.

     Process.Start(@"notepad.exe", pathToFile);
    

    How to Get JSON Array Within JSON Object?

    Your int length = jsonObj.length(); should be int length = ja_data.length();

    View's getWidth() and getHeight() returns 0

    We can use

    @Override
     public void onWindowFocusChanged(boolean hasFocus) {
      super.onWindowFocusChanged(hasFocus);
      //Here you can get the size!
     }
    

    How to split a list by comma not space

    Create a bash function

    split_on_commas() {
      local IFS=,
      local WORD_LIST=($1)
      for word in "${WORD_LIST[@]}"; do
        echo "$word"
      done
    }
    
    split_on_commas "this,is a,list" | while read item; do
      # Custom logic goes here
      echo Item: ${item}
    done
    

    ... this generates the following output:

    Item: this
    Item: is a
    Item: list
    

    (Note, this answer has been updated according to some feedback)

    How to add the JDBC mysql driver to an Eclipse project?

    You can paste the .jar file of the driver in the Java setup instead of adding it to each project that you create. Paste it in C:\Program Files\Java\jre7\lib\ext or wherever you have installed java.

    After this you will find that the .jar driver is enlisted in the library folder of your created project(JRE system library) in the IDE. No need to add it repetitively.

    Accessing constructor of an anonymous class

    From the Java Language Specification, section 15.9.5.1:

    An anonymous class cannot have an explicitly declared constructor.

    Sorry :(

    EDIT: As an alternative, you can create some final local variables, and/or include an instance initializer in the anonymous class. For example:

    public class Test {
        public static void main(String[] args) throws Exception {
            final int fakeConstructorArg = 10;
    
            Object a = new Object() {
                {
                    System.out.println("arg = " + fakeConstructorArg);
                }
            };
        }
    }
    

    It's grotty, but it might just help you. Alternatively, use a proper nested class :)

    Is it possible to cast a Stream in Java 8?

    I don't think there is a way to do that out-of-the-box. A possibly cleaner solution would be:

    Stream.of(objects)
        .filter(c -> c instanceof Client)
        .map(c -> (Client) c)
        .map(Client::getID)
        .forEach(System.out::println);
    

    or, as suggested in the comments, you could use the cast method - the former may be easier to read though:

    Stream.of(objects)
        .filter(Client.class::isInstance)
        .map(Client.class::cast)
        .map(Client::getID)
        .forEach(System.out::println);
    

    A simple jQuery form validation script

    you can use jquery validator for that but you need to add jquery.validate.js and jquery.form.js file for that. after including validator file define your validation something like this.

    <script type="text/javascript">
    $(document).ready(function(){
        $("#formID").validate({
        rules :{
            "data[User][name]" : {
                required : true
            }
        },
        messages :{
            "data[User][name]" : {
                required : 'Enter username'
            }
        }
        });
    });
    </script>
    

    You can see required : true same there is many more property like for email you can define email : true for number number : true

    Why java.security.NoSuchProviderException No such provider: BC?

    Im not very familiar with the Android sdk, but it seems that the android-sdk comes with the BouncyCastle provider already added to the security.

    What you will have to do in the PC environment is just add it manually,

    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    

    if you have access to the policy file, just add an entry like:

    security.provider.5=org.bouncycastle.jce.provider.BouncyCastleProvider 
    

    Notice the .5 it is equal to a sequential number of the already added providers.

    Loading custom configuration files

    the articles posted by Ricky are very good, but unfortunately they don't answer your question.

    To solve your problem you should try this piece of code:

    ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
    configMap.ExeConfigFilename = @"d:\test\justAConfigFile.config.whateverYouLikeExtension";
    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
    

    If need to access a value within the config you can use the index operator:

    config.AppSettings.Settings["test"].Value;
    

    Get difference between two dates in months using Java

    You can use Joda time library for Java. It would be much easier to calculate time-diff between dates with it.

    Sample snippet for time-diff:

    Days d = Days.daysBetween(startDate, endDate);
    int days = d.getDays();
    

    How to count the number of set bits in a 32-bit integer?

      private int get_bits_set(int v)
        {
          int c; // c accumulates the total bits set in v
            for (c = 0; v>0; c++)
            {
                v &= v - 1; // clear the least significant bit set
            }
            return c;
        }
    

    How to get an object's methods?

    In ES6:

    let myObj   = {myFn : function() {}, tamato: true};
    let allKeys = Object.keys(myObj);
    let fnKeys  = allKeys.filter(key => typeof myObj[key] == 'function');
    console.log(fnKeys);
    // output: ["myFn"]
    

    Hide keyboard in react-native

    Wrap your whole component with:

    import { TouchableWithoutFeedback, Keyboard } from 'react-native'
    
    <TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
    ...
    </TouchableWithoutFeedback>
    

    Worked for me

    How can I wrap or break long text/word in a fixed width span?

    By default a span is an inline element... so that's not the default behavior.

    You can make the span behave that way by adding display: block; to your CSS.

    span {
        display: block;
        width: 100px;
    }
    

    Export a list into a CSV or TXT file in R

    You can write your For loop to individually store dataframes from a list:

    allocation = list()
    
    for(i in 1:length(allocation)){
        write.csv(data.frame(allocation[[i]]), file = paste0(path, names(allocation)[i], '.csv'))
    }
    

    Is java.sql.Timestamp timezone specific?

    Although it is not explicitly specified for setTimestamp(int parameterIndex, Timestamp x) drivers have to follow the rules established by the setTimestamp(int parameterIndex, Timestamp x, Calendar cal) javadoc:

    Sets the designated parameter to the given java.sql.Timestamp value, using the given Calendar object. The driver uses the Calendar object to construct an SQL TIMESTAMP value, which the driver then sends to the database. With a Calendar object, the driver can calculate the timestamp taking into account a custom time zone. If no Calendar object is specified, the driver uses the default time zone, which is that of the virtual machine running the application.

    When you call with setTimestamp(int parameterIndex, Timestamp x) the JDBC driver uses the time zone of the virtual machine to calculate the date and time of the timestamp in that time zone. This date and time is what is stored in the database, and if the database column does not store time zone information, then any information about the zone is lost (which means it is up to the application(s) using the database to use the same time zone consistently or come up with another scheme to discern timezone (ie store in a separate column).

    For example: Your local time zone is GMT+2. You store "2012-12-25 10:00:00 UTC". The actual value stored in the database is "2012-12-25 12:00:00". You retrieve it again: you get it back again as "2012-12-25 10:00:00 UTC" (but only if you retrieve it using getTimestamp(..)), but when another application accesses the database in time zone GMT+0, it will retrieve the timestamp as "2012-12-25 12:00:00 UTC".

    If you want to store it in a different timezone, then you need to use the setTimestamp(int parameterIndex, Timestamp x, Calendar cal) with a Calendar instance in the required timezone. Just make sure you also use the equivalent getter with the same time zone when retrieving values (if you use a TIMESTAMP without timezone information in your database).

    So, assuming you want to store the actual GMT timezone, you need to use:

    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    stmt.setTimestamp(11, tsSchedStartTime, cal);
    

    With JDBC 4.2 a compliant driver should support java.time.LocalDateTime (and java.time.LocalTime) for TIMESTAMP (and TIME) through get/set/updateObject. The java.time.Local* classes are without time zones, so no conversion needs to be applied (although that might open a new set of problems if your code did assume a specific time zone).

    System.Drawing.Image to stream C#

    Try the following:

    public static Stream ToStream(this Image image, ImageFormat format) {
      var stream = new System.IO.MemoryStream();
      image.Save(stream, format);
      stream.Position = 0;
      return stream;
    }
    

    Then you can use the following:

    var stream = myImage.ToStream(ImageFormat.Gif);
    

    Replace GIF with whatever format is appropriate for your scenario.

    How to check for changes on remote (origin) Git repository

    My regular question is rather "anything new or changed in repo" so whatchanged comes handy. Found it here.

    git whatchanged origin/master -n 1
    

    Running multiple commands with xargs

    This seems to be the safest version.

    tr '[\n]' '[\0]' < a.txt | xargs -r0 /bin/bash -c 'command1 "$@"; command2 "$@";' ''
    

    (-0 can be removed and the tr replaced with a redirect (or the file can be replaced with a null separated file instead). It is mainly in there since I mainly use xargs with find with -print0 output) (This might also be relevant on xargs versions without the -0 extension)

    It is safe, since args will pass the parameters to the shell as an array when executing it. The shell (at least bash) would then pass them as an unaltered array to the other processes when all are obtained using ["$@"][1]

    If you use ...| xargs -r0 -I{} bash -c 'f="{}"; command "$f";' '', the assignment will fail if the string contains double quotes. This is true for every variant using -i or -I. (Due to it being replaced into a string, you can always inject commands by inserting unexpected characters (like quotes, backticks or dollar signs) into the input data)

    If the commands can only take one parameter at a time:

    tr '[\n]' '[\0]' < a.txt | xargs -r0 -n1 /bin/bash -c 'command1 "$@"; command2 "$@";' ''
    

    Or with somewhat less processes:

    tr '[\n]' '[\0]' < a.txt | xargs -r0 /bin/bash -c 'for f in "$@"; do command1 "$f"; command2 "$f"; done;' ''
    

    If you have GNU xargs or another with the -P extension and you want to run 32 processes in parallel, each with not more than 10 parameters for each command:

    tr '[\n]' '[\0]' < a.txt | xargs -r0 -n10 -P32 /bin/bash -c 'command1 "$@"; command2 "$@";' ''
    

    This should be robust against any special characters in the input. (If the input is null separated.) The tr version will get some invalid input if some of the lines contain newlines, but that is unavoidable with a newline separated file.

    The blank first parameter for bash -c is due to this: (From the bash man page) (Thanks @clacke)

    -c   If the -c option is present, then  commands  are  read  from  the  first  non-option  argument  com-
         mand_string.   If there are arguments after the command_string, the first argument is assigned to $0
         and any remaining arguments are assigned to the positional parameters.  The assignment  to  $0  sets
         the name of the shell, which is used in warning and error messages.
    

    for or while loop to do something n times

    The fundamental difference in most programming languages is that unless the unexpected happens a for loop will always repeat n times or until a break statement, (which may be conditional), is met then finish with a while loop it may repeat 0 times, 1, more or even forever, depending on a given condition which must be true at the start of each loop for it to execute and always false on exiting the loop, (for completeness a do ... while loop, (or repeat until), for languages that have it, always executes at least once and does not guarantee the condition on the first execution).

    It is worth noting that in Python a for or while statement can have break, continue and else statements where:

    • break - terminates the loop
    • continue - moves on to the next time around the loop without executing following code this time around
    • else - is executed if the loop completed without any break statements being executed.

    N.B. In the now unsupported Python 2 range produced a list of integers but you could use xrange to use an iterator. In Python 3 range returns an iterator.

    So the answer to your question is 'it all depends on what you are trying to do'!

    Check whether a table contains rows or not sql server 2005

    FOR the best performance, use specific column name instead of * - for example:

    SELECT TOP 1 <columnName> 
    FROM <tableName> 
    

    This is optimal because, instead of returning the whole list of columns, it is returning just one. That can save some time.

    Also, returning just first row if there are any values, makes it even faster. Actually you got just one value as the result - if there are any rows, or no value if there is no rows.

    If you use the table in distributed manner, which is most probably the case, than transporting just one value from the server to the client is much faster.

    You also should choose wisely among all the columns to get data from a column which can take as less resource as possible.

    Variables as commands in bash scripts

    I am not sure, but it might be worth running an eval on the commands first.

    This will let bash expand the variables $TAR_CMD and such to their full breadth(just as the echo command does to the console, which you say works)

    Bash will then read the line a second time with the variables expanded.

    eval $TAR_CMD | $ENCRYPT_CMD | $SPLIT_CMD 
    

    I just did a Google search and this page looks like it might do a decent job at explaining why that is needed. http://fvue.nl/wiki/Bash:_Why_use_eval_with_variable_expansion%3F

    Python: Find in list

     lstr=[1, 2, 3]
     lstr=map(str,lstr)
     r=re.compile('^(3){1}')
     results=list(filter(r.match,lstr))
     print(results)
    

    Gradient of n colors ranging from color 1 and color 2

    Try the following:

    color.gradient <- function(x, colors=c("red","yellow","green"), colsteps=100) {
      return( colorRampPalette(colors) (colsteps) [ findInterval(x, seq(min(x),max(x), length.out=colsteps)) ] )
    }
    x <- c((1:100)^2, (100:1)^2)
    plot(x,col=color.gradient(x), pch=19,cex=2)
    

    enter image description here

    Set the Value of a Hidden field using JQuery

    Drop the hash - that's for identifying the id attribute.

    Child with max-height: 100% overflows parent

    http://jsfiddle.net/mpalpha/71Lhcb5q/

    _x000D_
    _x000D_
    .container {  
    display: flex;
      background: blue; 
      padding: 10px; 
      max-height: 200px; 
      max-width: 200px; 
    }
    
    img { 
     object-fit: contain;
      max-height: 100%; 
      max-width: 100%; 
    }
    _x000D_
    <div class="container">
      <img src="http://placekitten.com/400/500" />
    </div>
    _x000D_
    _x000D_
    _x000D_

    Rounding a variable to two decimal places C#

    Console.WriteLine(decimal.Round(pay,2));
    

    Creating a selector from a method name with parameters

    You can't pass a parameter in a @selector().

    It looks like you're trying to implement a callback. The best way to do that would be something like this:

    [object setCallbackObject:self withSelector:@selector(myMethod:)];
    

    Then in your object's setCallbackObject:withSelector: method: you can call your callback method.

    -(void)setCallbackObject:(id)anObject withSelector:(SEL)selector {
        [anObject performSelector:selector];
    }
    

    How to make Google Fonts work in IE?

    After my investigation, I came up to this solution:

    //writing the below line into the top of my style.css file
    @import url('https://fonts.googleapis.com/css?family=Assistant:200,300,400,600,700,800&subset=hebrew');
    

    MUST OBSERVE: We must need to write the font-weight correctly of this font. For example: font-weight:900; will not work as we have not included 900 like 200,300,400,600,700,800 into the URL address while importing from Google with the above link. We can add or include 900 to the above URL, but that will work only if the above Google Font has this option while embedding.

    How to filter a dictionary according to an arbitrary condition function?

    Nowadays, in Python 2.7 and up, you can use a dict comprehension:

    {k: v for k, v in points.iteritems() if v[0] < 5 and v[1] < 5}
    

    And in Python 3:

    {k: v for k, v in points.items() if v[0] < 5 and v[1] < 5}
    

    From milliseconds to hour, minutes, seconds and milliseconds

    not really eleganter, but a bit shorter would be

    function to_tuple(x):
       y = 60*60*1000
       h = x/y
       m = (x-(h*y))/(y/60)
       s = (x-(h*y)-(m*(y/60)))/1000
       mi = x-(h*y)-(m*(y/60))-(s*1000)
    
       return (h,m,s,mi)
    

    Create intermediate folders if one doesn't exist

    You have to actually call some method to create the directories. Just creating a file object will not create the corresponding file or directory on the file system.

    You can use File#mkdirs() method to create the directory: -

    theFile.mkdirs();
    

    Difference between File#mkdir() and File#mkdirs() is that, the later will create any intermediate directory if it does not exist.

    Force LF eol in git repo and working copy

    To force LF line endings for all text files, you can create .gitattributes file in top-level of your repository with the following lines (change as desired):

    # Ensure all C and PHP files use LF.
    *.c         eol=lf
    *.php       eol=lf
    

    which ensures that all files that Git considers to be text files have normalized (LF) line endings in the repository (normally core.eol configuration controls which one do you have by default).

    Based on the new attribute settings, any text files containing CRLFs should be normalized by Git. If this won't happen automatically, you can refresh a repository manually after changing line endings, so you can re-scan and commit the working directory by the following steps (given clean working directory):

    $ echo "* text=auto" >> .gitattributes
    $ rm .git/index     # Remove the index to force Git to
    $ git reset         # re-scan the working directory
    $ git status        # Show files that will be normalized
    $ git add -u
    $ git add .gitattributes
    $ git commit -m "Introduce end-of-line normalization"
    

    or as per GitHub docs:

    git add . -u
    git commit -m "Saving files before refreshing line endings"
    git rm --cached -r . # Remove every file from Git's index.
    git reset --hard # Rewrite the Git index to pick up all the new line endings.
    git add . # Add all your changed files back, and prepare them for a commit.
    git commit -m "Normalize all the line endings" # Commit the changes to your repository.
    

    See also: @Charles Bailey post.

    In addition, if you would like to exclude any files to not being treated as a text, unset their text attribute, e.g.

    manual.pdf      -text
    

    Or mark it explicitly as binary:

    # Denote all files that are truly binary and should not be modified.
    *.png binary
    *.jpg binary
    

    To see some more advanced git normalization file, check .gitattributes at Drupal core:

    # Drupal git normalization
    # @see https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html
    # @see https://www.drupal.org/node/1542048
    
    # Normally these settings would be done with macro attributes for improved
    # readability and easier maintenance. However macros can only be defined at the
    # repository root directory. Drupal avoids making any assumptions about where it
    # is installed.
    
    # Define text file attributes.
    # - Treat them as text.
    # - Ensure no CRLF line-endings, neither on checkout nor on checkin.
    # - Detect whitespace errors.
    #   - Exposed by default in `git diff --color` on the CLI.
    #   - Validate with `git diff --check`.
    #   - Deny applying with `git apply --whitespace=error-all`.
    #   - Fix automatically with `git apply --whitespace=fix`.
    
    *.config  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
    *.css     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
    *.dist    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
    *.engine  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
    *.html    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=html
    *.inc     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
    *.install text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
    *.js      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
    *.json    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
    *.lock    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
    *.map     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
    *.md      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
    *.module  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
    *.php     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
    *.po      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
    *.profile text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
    *.script  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
    *.sh      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
    *.sql     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
    *.svg     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
    *.theme   text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
    *.twig    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
    *.txt     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
    *.xml     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
    *.yml     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
    
    # Define binary file attributes.
    # - Do not treat them as text.
    # - Include binary diff in patches instead of "binary files differ."
    *.eot     -text diff
    *.exe     -text diff
    *.gif     -text diff
    *.gz      -text diff
    *.ico     -text diff
    *.jpeg    -text diff
    *.jpg     -text diff
    *.otf     -text diff
    *.phar    -text diff
    *.png     -text diff
    *.svgz    -text diff
    *.ttf     -text diff
    *.woff    -text diff
    *.woff2   -text diff
    

    See also:

    Initialising an array of fixed size in python

    An easy solution is x = [None]*length, but note that it initializes all list elements to None. If the size is really fixed, you can do x=[None,None,None,None,None] as well. But strictly speaking, you won't get undefined elements either way because this plague doesn't exist in Python.

    DateTime.Today.ToString("dd/mm/yyyy") returns invalid DateTime Value

    use MM(months) instead of mm(minutes) :

    DateTime.Now.ToString("dd/MM/yyyy");
    

    check here for more format options.

    How to validate a credit card number

    You should really use .test():

    if (!re16digit.test(document.myform.CreditCardNumber.value)) {
      alert("Please ... ");
    }
    

    You should also look around for implementations of (one or more of) the card number checksum algorithms. They're very simple.

    How to use ScrollView in Android?

    A ScrollView is a special type of FrameLayout in that it allows users to scroll through a list of views that occupy more space than the physical display.I just add some attributes .

    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"
         android:fillViewport="true"
         android:scrollbars = "vertical"
         android:scrollbarStyle="insideInset"
        >
        <TableLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:stretchColumns="1"
            >
            <!-- Add here which you want -->
        </TableLayout>
    
    </ScrollView>
    

    Can I create view with parameter in MySQL?

    Actually if you create func:

    create function p1() returns INTEGER DETERMINISTIC NO SQL return @p1;
    

    and view:

    create view h_parm as
    select * from sw_hardware_big where unit_id = p1() ;
    

    Then you can call a view with a parameter:

    select s.* from (select @p1:=12 p) parm , h_parm s;
    

    I hope it helps.

    How to import a module in Python with importlib.import_module

    And don't forget to create a __init__.py with each folder/subfolder (even if they are empty)

    Java Garbage Collection Log messages

    I just wanted to mention that one can get the detailed GC log with the

    -XX:+PrintGCDetails 
    

    parameter. Then you see the PSYoungGen or PSPermGen output like in the answer.

    Also -Xloggc:gc.log seems to generate the same output like -verbose:gc but you can specify an output file in the first.

    Example usage:

    java -Xloggc:./memory.log -XX:+PrintGCDetails Memory
    

    To visualize the data better you can try gcviewer (a more recent version can be found on github).

    Take care to write the parameters correctly, I forgot the "+" and my JBoss would not start up, without any error message!

    Fixing a systemd service 203/EXEC failure (no such file or directory)

    I ran across a Main process exited, code=exited, status=203/EXEC today as well and my bug was that I forgot to add the executable bit to the file.

    How to increase Java heap space for a tomcat app

    There is a mechanism to do it without modifying any files that are in the distribution. You can create a separate file %CATALINA_HOME%\bin\setenv.bat or $CATALINA_HOME/bin/setenv.sh and put your environment variables there. Further, the memory settings apply to the JVM, not Tomcat, so I'd set the JAVA_OPTS variable instead:

    set JAVA_OPTS=-Xmx512m

    Xampp localhost/dashboard

    If you want to display directory than edit htdocs/index.php file

    Below code is display all directory in table

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>Welcome to Nims Server</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link href="server/style.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
    <!-- START PAGE SOURCE -->
    <div id="wrap">
      <div id="top">
        <h1 id="sitename">Nims <em>Server</em> Directory list</h1>
        <div id="searchbar">
          <form action="#">
            <div id="searchfield">
              <input type="text" name="keyword" class="keyword" />
              <input class="searchbutton" type="image" src="server/images/searchgo.gif"  alt="search" />
            </div>
          </form>
        </div>
      </div>
    
    <div class="background">
    <div class="transbox">
    <table width="100%" border="0" cellspacing="3" cellpadding="5" style="border:0px solid #333333;background: #F9F9F9;"> 
    <tr>
    <?php
    //echo md5("saketbook007");
    
    //File functuion DIR is used here.
    $d = dir($_SERVER['DOCUMENT_ROOT']); 
    $i=-1;
    //Loop start with read function
    while ($entry = $d->read()) {
    if($entry == "." || $entry ==".."){
    }else{
    ?>
    <td  class="site" width="33%"><a href="<?php echo $entry;?>" ><?php echo ucfirst($entry); ?></a></td>  
    <?php 
    }
    if($i%3 == 0){
    echo "</tr><tr>";
    }
    $i++;
    }?>
    </tr> 
    </table>
    
    <?php $d->close();
    ?> 
    
    </div>
    </div>
    </div>
       </div></div></body>
    </html>
    

    Style:

    @import url("fontface.css");
    * {
        padding:0;
        margin:0;
    }
    .clear {
        clear:both;
    }
    
    body {
        background:url(images/bg.jpg) repeat;
        font-family:"Palatino Linotype", "Book Antiqua", Palatino, serif;
        color:#212713;
    }
    #wrap {
        width:1300px;
        margin:auto;
    }
    
    #sitename {
        font: normal 46px chunk;
        color:#1b2502;
        text-shadow:#5d7a17 1px 1px 1px;
        display:block;
        padding:45px 0 0 0;
        width:60%;
        float:left;
    }
    #searchbar {
        width:39%;
        float:right;
    }
    #sitename em {
        font-family:"Palatino Linotype", "Book Antiqua", Palatino, serif;
    }
    #top {
        height:145px;
    }
    img {
    
        width:90%;
        height:250px;
        padding:10px;
        border:1px solid #000;
        margin:0 0 0 50px;
    }
    
    
    .post h2 a {
        color:#656f42;
        text-decoration:none;
    }
    #searchbar {
        padding:55px 0 0 0;
    }
    #searchfield {
        background:url(images/searchbar.gif) no-repeat;
        width:239px;
        height:35px;
        float:right;
    }
    #searchfield .keyword {
        width:170px;
        background:transparent;
        border:none;
        padding:8px 0 0 10px;
        color:#fff;
        display:block;
        float:left;
    }
    #searchfield .searchbutton {
        display:block;
        float:left;
        margin:7px 0 0 5px;
    }
    
    div.background
    {
      background:url(h.jpg) repeat-x;
      border: 2px solid black;
    
      width:99%;
    }
    div.transbox
    {
      margin: 15px;
      background-color: #ffffff;
    
      border: 1px solid black;
      opacity:0.8;
      filter:alpha(opacity=60); /* For IE8 and earlier */
      height:500px;
    }
    
    .site{
    
    border:1px solid #CCC; 
    }
    
    .site a{text-decoration:none;font-weight:bold; color:#000; line-height:2}
    .site:hover{background:#000; border:1px solid #03C;}
    .site:hover a{color:#FFF}
    

    Output : enter image description here

    How to configure log4j.properties for SpringJUnit4ClassRunner?

    If you don't want to bother with a file, you can do something like this in your code:

    static
    {
        Logger rootLogger = Logger.getRootLogger();
        rootLogger.setLevel(Level.INFO);
        rootLogger.addAppender(new ConsoleAppender(
                   new PatternLayout("%-6r [%p] %c - %m%n")));
    }
    

    How to go back to previous page if back button is pressed in WebView?

    You can try this for webview in a fragment:

    private lateinit var webView: WebView
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val root = inflater.inflate(R.layout.fragment_name, container, false)
        webView = root!!.findViewById(R.id.home_web_view)
        var url: String = "http://yoururl.com"
        webView.settings.javaScriptEnabled = true
        webView.webViewClient = WebViewClient()
        webView.loadUrl(url)
        webView.canGoBack()
        webView.setOnKeyListener{ v, keyCode, event ->
            if(keyCode == KeyEvent.KEYCODE_BACK && event.action == MotionEvent.ACTION_UP
                && webView.canGoBack()){
                webView.goBack()
                return@setOnKeyListener true
            }
            false
        }
        return root
    }
    

    Installing jdk8 on ubuntu- "unable to locate package" update doesn't fix

    For me non of the above worked and I had to do as below, and it worked,

    sudo -E add-apt-repository ppa:openjdk-r/ppa

    and then,

    sudo apt-get update

    sudo apt-get install openjdk-8-jdk

    Reference: https://askubuntu.com/questions/644188/updating-jdk-7-to-8-unable-to-locate-package

    RegEx to parse or validate Base64 data

    Here's an alternative regular expression:

    ^(?=(.{4})*$)[A-Za-z0-9+/]*={0,2}$
    

    It satisfies the following conditions:

    • The string length must be a multiple of four - (?=^(.{4})*$)
    • The content must be alphanumeric characters or + or / - [A-Za-z0-9+/]*
    • It can have up to two padding (=) characters on the end - ={0,2}
    • It accepts empty strings

    How to submit an HTML form on loading the page?

    You missed the closing tag for the input fields, and you can choose any one of the events, ex: onload, onclick etc.

    (a) Onload event:

    <script type="text/javascript">
    $(document).ready(function(){
         $('#frm1').submit();
    });
    </script>
    

    (b) Onclick Event:

    <form name="frm1" id="frm1" action="../somePage" method="post">
        Please Waite... 
        <input type="hidden" name="uname" id="uname" value=<?php echo $uname;?> />
        <input type="hidden" name="price" id="price" value=<?php echo $price;?> />
        <input type="text" name="submit" id="submit" value="submit">
    </form>
    <script type="text/javascript">
    $('#submit').click(function(){
         $('#frm1').submit();
    });
    </script>
    

    How do you create a hidden div that doesn't create a line break or horizontal space?

    Use style="display: none;". Also, you probably don't need to have the DIV, just setting the style to display: none on the checkbox would probably be sufficient.

    Setting up Eclipse with JRE Path

    You should specify where Eclipse should find your JDK in the file eclipse.ini. Specifically, the following parameter (note that it is 2 separate lines in the ini file):

    -vm
    C:\Java\JDK\1.8\bin\javaw.exe
    

    or wherever your javaw.exe happens to be.

    Note: The format of the ini file is very particular; make sure to consult https://wiki.eclipse.org/Eclipse.ini to ensure you get it exactly right

    HTTP Status 405 - Method Not Allowed Error for Rest API

    In above code variable "ver" is assign to null, print "ver" before returning and see the value. As this "ver" having null service is send status as "204 No Content".

    And about status code "405 - Method Not Allowed" will get this status code when rest controller or service only supporting GET method but from client side your trying with POST with valid uri request, during such scenario get status as "405 - Method Not Allowed"

    How to play a local video with Swift?

    Here a solution for Swift 5.2

    PlayerView.swift:

    import AVFoundation
    import UIKit
    
    class PlayerView: UIView {
    
        var player: AVPlayer? {
            get {
                return playerLayer.player
            }
            set {
                playerLayer.player = newValue
            }
        }
    
        var playerLayer: AVPlayerLayer {
            return layer as! AVPlayerLayer
        }
    
        // Override UIView property
        override static var layerClass: AnyClass {
            return AVPlayerLayer.self
        }
    }
    

    VideoPlayer.swift

    import AVFoundation
    import Foundation
    
    protocol VideoPlayerDelegate {
        func downloadedProgress(progress:Double)
        func readyToPlay()
        func didUpdateProgress(progress:Double)
        func didFinishPlayItem()
        func didFailPlayToEnd()
    }
    
    let videoContext: UnsafeMutableRawPointer? = nil
    
    class VideoPlayer : NSObject {
    
        private var assetPlayer:AVPlayer?
        private var playerItem:AVPlayerItem?
        private var urlAsset:AVURLAsset?
        private var videoOutput:AVPlayerItemVideoOutput?
    
        private var assetDuration:Double = 0
        private var playerView:PlayerView?
    
        private var autoRepeatPlay:Bool = true
        private var autoPlay:Bool = true
    
        var delegate:VideoPlayerDelegate?
    
        var playerRate:Float = 1 {
            didSet {
                if let player = assetPlayer {
                    player.rate = playerRate > 0 ? playerRate : 0.0
                }
            }
        }
    
        var volume:Float = 1.0 {
            didSet {
                if let player = assetPlayer {
                    player.volume = volume > 0 ? volume : 0.0
                }
            }
        }
    
        // MARK: - Init
    
        convenience init(urlAsset:NSURL, view:PlayerView, startAutoPlay:Bool = true, repeatAfterEnd:Bool = true) {
            self.init()
    
            playerView = view
            autoPlay = startAutoPlay
            autoRepeatPlay = repeatAfterEnd
    
            if let playView = playerView, let playerLayer = playView.layer as? AVPlayerLayer {
                playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
            }
            initialSetupWithURL(url: urlAsset)
            prepareToPlay()
        }
    
        override init() {
            super.init()
        }
    
        // MARK: - Public
    
        func isPlaying() -> Bool {
            if let player = assetPlayer {
                return player.rate > 0
            } else {
                return false
            }
        }
    
        func seekToPosition(seconds:Float64) {
            if let player = assetPlayer {
                pause()
                if let timeScale = player.currentItem?.asset.duration.timescale {
                    player.seek(to: CMTimeMakeWithSeconds(seconds, preferredTimescale: timeScale), completionHandler: { (complete) in
                        self.play()
                    })
                }
            }
        }
    
        func pause() {
            if let player = assetPlayer {
                player.pause()
            }
        }
    
        func play() {
            if let player = assetPlayer {
                if (player.currentItem?.status == .readyToPlay) {
                    player.play()
                    player.rate = playerRate
                }
            }
        }
    
        func cleanUp() {
            if let item = playerItem {
                item.removeObserver(self, forKeyPath: "status")
                item.removeObserver(self, forKeyPath: "loadedTimeRanges")
            }
            NotificationCenter.default.removeObserver(self)
            assetPlayer = nil
            playerItem = nil
            urlAsset = nil
        }
    
        // MARK: - Private
    
        private func prepareToPlay() {
            let keys = ["tracks"]
            if let asset = urlAsset {
                asset.loadValuesAsynchronously(forKeys: keys, completionHandler: {
                    DispatchQueue.main.async {
                        self.startLoading()
                    }
                })
            }
        }
    
        private func startLoading(){
            var error:NSError?
            guard let asset = urlAsset else {return}
            let status:AVKeyValueStatus = asset.statusOfValue(forKey: "tracks", error: &error)
    
            if status == AVKeyValueStatus.loaded {
                assetDuration = CMTimeGetSeconds(asset.duration)
    
                let videoOutputOptions = [kCVPixelBufferPixelFormatTypeKey as String : Int(kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange)]
                videoOutput = AVPlayerItemVideoOutput(pixelBufferAttributes: videoOutputOptions)
                playerItem = AVPlayerItem(asset: asset)
    
                if let item = playerItem {
                    item.addObserver(self, forKeyPath: "status", options: .initial, context: videoContext)
                    item.addObserver(self, forKeyPath: "loadedTimeRanges", options: [.new, .old], context: videoContext)
    
                    NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
                    NotificationCenter.default.addObserver(self, selector: #selector(didFailedToPlayToEnd), name: NSNotification.Name.AVPlayerItemFailedToPlayToEndTime, object: nil)
    
                    if let output = videoOutput {
                        item.add(output)
    
                        item.audioTimePitchAlgorithm = AVAudioTimePitchAlgorithm.varispeed
                        assetPlayer = AVPlayer(playerItem: item)
    
                        if let player = assetPlayer {
                            player.rate = playerRate
                        }
    
                        addPeriodicalObserver()
                        if let playView = playerView, let layer = playView.layer as? AVPlayerLayer {
                            layer.player = assetPlayer
                            print("player created")
                        }
                    }
                }
            }
        }
    
        private func addPeriodicalObserver() {
            let timeInterval = CMTimeMake(value: 1, timescale: 1)
    
            if let player = assetPlayer {
                player.addPeriodicTimeObserver(forInterval: timeInterval, queue: DispatchQueue.main, using: { (time) in
                    self.playerDidChangeTime(time: time)
                })
            }
        }
    
        private func playerDidChangeTime(time:CMTime) {
            if let player = assetPlayer {
                let timeNow = CMTimeGetSeconds(player.currentTime())
                let progress = timeNow / assetDuration
    
                delegate?.didUpdateProgress(progress: progress)
            }
        }
    
        @objc private func playerItemDidReachEnd() {
            delegate?.didFinishPlayItem()
    
            if let player = assetPlayer {
                player.seek(to: CMTime.zero)
                if autoRepeatPlay == true {
                    play()
                }
            }
        }
    
        @objc private func didFailedToPlayToEnd() {
            delegate?.didFailPlayToEnd()
        }
    
        private func playerDidChangeStatus(status:AVPlayer.Status) {
            if status == .failed {
                print("Failed to load video")
            } else if status == .readyToPlay, let player = assetPlayer {
                volume = player.volume
                delegate?.readyToPlay()
    
                if autoPlay == true && player.rate == 0.0 {
                    play()
                }
            }
        }
    
        private func moviewPlayerLoadedTimeRangeDidUpdated(ranges:Array<NSValue>) {
            var maximum:TimeInterval = 0
            for value in ranges {
                let range:CMTimeRange = value.timeRangeValue
                let currentLoadedTimeRange = CMTimeGetSeconds(range.start) + CMTimeGetSeconds(range.duration)
                if currentLoadedTimeRange > maximum {
                    maximum = currentLoadedTimeRange
                }
            }
            let progress:Double = assetDuration == 0 ? 0.0 : Double(maximum) / assetDuration
    
            delegate?.downloadedProgress(progress: progress)
        }
    
        deinit {
            cleanUp()
        }
    
        private func initialSetupWithURL(url:NSURL) {
            let options = [AVURLAssetPreferPreciseDurationAndTimingKey : true]
            urlAsset = AVURLAsset(url: url as URL, options: options)
        }
    
        // MARK: - Observations
        override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    
            if context == videoContext {
                if let key = keyPath {
                    if key == "status", let player = assetPlayer {
                        playerDidChangeStatus(status: player.status)
                    } else if key == "loadedTimeRanges", let item = playerItem {
                        moviewPlayerLoadedTimeRangeDidUpdated(ranges: item.loadedTimeRanges)
                    }
                }
            }
        }
    }
    

    Usage:

    private var playerView: PlayerView = PlayerView()
    private var videoPlayer:VideoPlayer?
    

    and inside viewDidLoad():

    view.addSubview(playerView)
    preparePlayer()
    
    // set Constraints (if you do it purely in code)
    playerView.translatesAutoresizingMaskIntoConstraints = false
    playerView.topAnchor.constraint(equalTo: view.topAnchor, constant: 10.0).isActive = true
    playerView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10.0).isActive = true
    playerView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10.0).isActive = true
    playerView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 10.0).isActive = true
    
    private func preparePlayer() {
        if let filePath = Bundle.main.path(forResource: "my video", ofType: "mp4") {
            let fileURL = NSURL(fileURLWithPath: filePath)
            videoPlayer = VideoPlayer(urlAsset: fileURL, view: playerView)
            if let player = videoPlayer {
                player.playerRate = 0.67
            }
        }
    }
    

    Should C# or C++ be chosen for learning Games Programming (consoles)?

    I believe that C++ is the language that you are looking for. The majority of game development is in C++ because it is a multi-paradigm language (OOP, meta-programming, etc.) and because it allows memory management. What makes C++ even better is that it can be used to develop on a multitude of platforms whereas C# cannot do so on such a big scale.

    Many will say that with C# you will not have to worry about memory allocation and this is true at a certain price. You will have the burden of the .NET framework on your shoulders and will slowly see the limitations of C# in the way certain tasks must be done.

    Probably you have read from some answers that C++ is a hard programming language. This is mostly true, but perhaps you haven't heard about C++0x. Some features found in C# such as garbage collection will become available (optional for you to use) with C++0x. Also, multi-threading will finally be supported by the language with this revision of the C++ standard.

    I would recommend that you buy a few C++ books as well as C++ DirectX/OpenGL books.

    NSString with \n or line break

    Line breaks character for NSString is \r

    correct way to use [NSString StringWithFormat:@"%@\r%@",string1,string2];

    \r ----> carriage return

    MVC Return Partial View as JSON

    Url.Action("Evil", model)

    will generate a get query string but your ajax method is post and it will throw error status of 500(Internal Server Error). – Fereydoon Barikzehy Feb 14 at 9:51

    Just Add "JsonRequestBehavior.AllowGet" on your Json object.

    How to force page refreshes or reloads in jQuery?

    Replace with:

    $('#something').click(function() {
        location.reload();
    });
    

    How to edit incorrect commit message in Mercurial?

    In TortoiseHg, right-click on the revision you want to modify. Choose Modify History->Import MQ. That will convert all the revisions up to and including the selected revision from Mercurial changesets into Mercurial Queue patches. Select the Patch you want to modify the message for, and it should automatically change the screen to the MQ editor. Edit the message which is in the middle of the screen, then click QRefresh. Finally, right click on the patch and choose Modify History->Finish Patch, which will convert it from a patch back into a change set.

    Oh, this assumes that MQ is an active extension for TortoiseHG on this repository. If not, you should be able to click File->Settings, click Extensions, and click the mq checkbox. It should warn you that you have to close TortoiseHg before the extension is active, so close and reopen.

    Can I restore a single table from a full mysql mysqldump file?

    The chunks of SQL are blocked off with "Table structure for table my_table" and "Dumping data for table my_table."

    You can use a Windows command line as follows to get the line numbers for the various sections. Adjust the searched string as needed.

    find /n "for table `" sql.txt

    The following will be returned:

    ---------- SQL.TXT

    [4384]-- Table structure for table my_table

    [4500]-- Dumping data for table my_table

    [4514]-- Table structure for table some_other_table

    ... etc.

    That gets you the line numbers you need... now, if I only knew how to use them... investigating.

    Animation CSS3: display + opacity

    If possible - use visibility instead of display

    For instance:

    .child {
        visibility: hidden;
        opacity: 0;
        transition: opacity 0.3s, visibility 0.3s;
    }
    
    .parent:hover .child {
        visibility: visible;
        opacity: 1;
        transition: opacity 0.3s, visibility 0.3s;
    }
    

    How do I set up Vim autoindentation properly for editing Python files?

    Ensure you are editing the correct configuration file for VIM. Especially if you are using windows, where the file could be named _vimrc instead of .vimrc as on other platforms.

    In vim type

    :help vimrc

    and check your path to the _vimrc/.vimrc file with

    :echo $HOME

    :echo $VIM

    Make sure you are only using one file. If you want to split your configuration into smaller chunks you can source other files from inside your _vimrc file.

    :help source

    How do you change the server header returned by nginx?

    After I read Parthian Shot's answer, I dig into /usr/sbin/nginx binary file. Then I found out that the file contains these three lines.

    Server: nginx/1.12.2
    Server: nginx/1.12.2
    Server: nginx
    

    Basically first two of them are meant for server_tokens on; directive (Server version included). Then I change the search criteria to match those lines within the binary file.

    sed -i 's/Server: nginx/Server: thing/' `which nginx`
    

    After I dig farther I found out that the error message produced by nginx is also included in this file.

    <hr><center>nginx</center>
    

    There are three of them, one without the version, two of them included the version. So I run the following command to replace nginx string within the error message.

    sed -i 's/center>nginx/center>thing/' `which nginx`
    

    Save child objects automatically using JPA Hibernate

    Following program describe how bidirectional relation work in hibernate.

    When parent will save its list of child object will be auto save.

    On Parent side:

        @Entity
        @Table(name="clients")
        public class Clients implements Serializable  {
    
             @Id
             @GeneratedValue(strategy = GenerationType.IDENTITY)     
             @OneToMany(mappedBy="clients", cascade=CascadeType.ALL)
              List<SmsNumbers> smsNumbers;
        }
    

    And put the following annotation on the child side:

      @Entity
      @Table(name="smsnumbers")
      public class SmsNumbers implements Serializable {
    
         @Id
         @GeneratedValue(strategy = GenerationType.IDENTITY)
         int id;
         String number;
         String status;
         Date reg_date;
         @ManyToOne
         @JoinColumn(name = "client_id")
         private Clients clients;
    
        // and getter setter.
    
     }
    

    Main class:

     public static void main(String arr[])
     {
        Session session = HibernateUtil.openSession();
          //getting transaction object from session object
        session.beginTransaction();
    
        Clients cl=new Clients("Murali", "1010101010");
        SmsNumbers sms1=new SmsNumbers("99999", "Active", cl);
        SmsNumbers sms2=new SmsNumbers("88888", "InActive", cl);
        SmsNumbers sms3=new SmsNumbers("77777", "Active", cl);
        List<SmsNumbers> lstSmsNumbers=new ArrayList<SmsNumbers>();
        lstSmsNumbers.add(sms1);
        lstSmsNumbers.add(sms2);
        lstSmsNumbers.add(sms3);
        cl.setSmsNumbers(lstSmsNumbers);
        session.saveOrUpdate(cl);
        session.getTransaction().commit(); 
        session.close();    
    
     }
    

    How to update value of a key in dictionary in c#?

    Just use the indexer and update directly:

    dictionary["cat"] = 3
    

    Disable submit button when form invalid with AngularJS

    To add to this answer. I just found out that it will also break down if you use a hyphen in your form name (Angular 1.3):

    So this will not work:

    <form name="my-form">
        <input name="myText" type="text" ng-model="mytext" required />
        <button ng-disabled="my-form.$invalid">Save</button>
    </form>
    

    How to "select distinct" across multiple data frame columns in pandas?

    To solve a similar problem, I'm using groupby:

    print(f"Distinct entries: {len(df.groupby(['col1', 'col2']))}")
    

    Whether that's appropriate will depend on what you want to do with the result, though (in my case, I just wanted the equivalent of COUNT DISTINCT as shown).

    How do you add a JToken to an JObject?

    TL;DR: You should add a JProperty to a JObject. Simple. The index query returns a JValue, so figure out how to get the JProperty instead :)


    The accepted answer is not answering the question as it seems. What if I want to specifically add a JProperty after a specific one? First, lets start with terminologies which really had my head worked up.

    • JToken = The mother of all other types. It can be A JValue, JProperty, JArray, or JObject. This is to provide a modular design to the parsing mechanism.
    • JValue = any Json value type (string, int, boolean).
    • JProperty = any JValue or JContainer (see below) paired with a name (identifier). For example "name":"value".
    • JContainer = The mother of all types which contain other types (JObject, JValue).
    • JObject = a JContainer type that holds a collection of JProperties
    • JArray = a JContainer type that holds a collection JValue or JContainer.

    Now, when you query Json item using the index [], you are getting the JToken without the identifier, which might be a JContainer or a JValue (requires casting), but you cannot add anything after it, because it is only a value. You can change it itself, query more deep values, but you cannot add anything after it for example.

    What you actually want to get is the property as whole, and then add another property after it as desired. For this, you use JOjbect.Property("name"), and then create another JProperty of your desire and then add it after this using AddAfterSelf method. You are done then.

    For more info: http://www.newtonsoft.com/json/help/html/ModifyJson.htm

    This is the code I modified.

    public class Program
    {
      public static void Main()
      {
        try
        {
          string jsonText = @"
          {
            ""food"": {
              ""fruit"": {
                ""apple"": {
                  ""colour"": ""red"",
                  ""size"": ""small""
                },
                ""orange"": {
                  ""colour"": ""orange"",
                  ""size"": ""large""
                }
              }
            }
          }";
    
          var foodJsonObj = JObject.Parse(jsonText);
          var bananaJson = JObject.Parse(@"{ ""banana"" : { ""colour"": ""yellow"", ""size"": ""medium""}}");
    
          var fruitJObject = foodJsonObj["food"]["fruit"] as JObject;
          fruitJObject.Property("orange").AddAfterSelf(new JProperty("banana", fruitJObject));
    
          Console.WriteLine(foodJsonObj.ToString());
        }
        catch (Exception ex)
        {
          Console.WriteLine(ex.GetType().Name + ": " + ex.Message);
        }
      }
    }
    

    Ruby get object keys as array

    Use the keys method: {"apple" => "fruit", "carrot" => "vegetable"}.keys == ["apple", "carrot"]

    What is a singleton in C#?

    Whilst the there can only ever be one instance of a singleton, it is not the same as a static class. A static class can only contain static methods and can never be instantiated, whereas the instance of a singleton may be used in the same way as any other object.

    Numpy Resize/Rescale Image

    Yeah, you can install opencv (this is a library used for image processing, and computer vision), and use the cv2.resize function. And for instance use:

    import cv2
    import numpy as np
    
    img = cv2.imread('your_image.jpg')
    res = cv2.resize(img, dsize=(54, 140), interpolation=cv2.INTER_CUBIC)

    Here img is thus a numpy array containing the original image, whereas res is a numpy array containing the resized image. An important aspect is the interpolation parameter: there are several ways how to resize an image. Especially since you scale down the image, and the size of the original image is not a multiple of the size of the resized image. Possible interpolation schemas are:

    • INTER_NEAREST - a nearest-neighbor interpolation
    • INTER_LINEAR - a bilinear interpolation (used by default)
    • INTER_AREA - resampling using pixel area relation. It may be a preferred method for image decimation, as it gives moire’-free results. But when the image is zoomed, it is similar to the INTER_NEAREST method.
    • INTER_CUBIC - a bicubic interpolation over 4x4 pixel neighborhood
    • INTER_LANCZOS4 - a Lanczos interpolation over 8x8 pixel neighborhood

    Like with most options, there is no "best" option in the sense that for every resize schema, there are scenarios where one strategy can be preferred over another.

    Create a batch file to run an .exe with an additional parameter

    You can use

    start "" "%USERPROFILE%\Desktop\BGInfo\bginfo.exe" "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi"
    

    or

    start "" /D "%USERPROFILE%\Desktop\BGInfo" bginfo.exe dc_bginfo.bgi
    

    or

    "%USERPROFILE%\Desktop\BGInfo\bginfo.exe" "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi"
    

    or

    cd /D "%USERPROFILE%\Desktop\BGInfo"
    bginfo.exe dc_bginfo.bgi
    

    Help on commands start and cd is output by executing in a command prompt window help start or start /? and help cd or cd /?.

    But I do not understand why you need a batch file at all for starting the application with the additional parameter. Create a shortcut (*.lnk) on your desktop for this application. Then right click on the shortcut, left click on Properties and append after a space character "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi" as parameter.

    VBA, if a string contains a certain letter

    If you are looping through a lot of cells, use the binary function, it is much faster. Using "<> 0" in place of "> 0" also makes it faster:

    If InStrB(1, myString, "a", vbBinaryCompare) <> 0
    

    Is there a <meta> tag to turn off caching in all browsers?

    pragma is your best bet:

    <meta http-equiv="Pragma" content="no-cache">
    

    Hiding user input on terminal in Linux script

    Just supply -s to your read call like so:

    $ read -s PASSWORD
    $ echo $PASSWORD
    

    Set Locale programmatically

    I found the androidx.appcompat:appcompat:1.1.0 bug can also be fixed by simply calling getResources() in applyOverrideConfiguration()

    @Override public void
    applyOverrideConfiguration(Configuration cfgOverride)
    {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP &&
          Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
        // add this to fix androidx.appcompat:appcompat 1.1.0 bug
        // which happens on Android 6.x ~ 7.x
        getResources();
      }
    
      super.applyOverrideConfiguration(cfgOverride);
    }
    

    jQuery to loop through elements with the same class

    you can do it this way

    $('.testimonial').each(function(index, obj){
        //you can use this to access the current item
    });
    

    How do I find out if the GPS of an Android device is enabled

    This method will use the LocationManager service.

    Source Link

    //Check GPS Status true/false
    public static boolean checkGPSStatus(Context context){
        LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE );
        boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        return statusOfGPS;
    };
    

    What is a word boundary in regex, does \b match hyphen '-'?

    In the course of learning regular expression, I was really stuck in the metacharacter which is \b. I indeed didn't comprehend its meaning while I was asking myself "what it is, what it is" repetitively. After some attempts by using the website, I watch out the pink vertical dashes at the every beginning of words and at the end of words. I got it its meaning well at that time. It's now exactly word(\w)-boundary.

    My view is merely to immensely understanding-oriented. Logic behind of it should be examined from another answers.

    enter image description here

    C++ cout hex values?

    std::hex is defined in <ios> which is included by <iostream>. But to use things like std::setprecision/std::setw/std::setfill/etc you have to include <iomanip>.

    Angular get object from array by Id

    // Used In TypeScript For Angular 4+        
    const viewArray = [
              {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
              {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
              {id: 3, question: "Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
              {id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
              {id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
              {id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
              {id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
              {id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
              {id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
              {id: 10, question: "Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
              {id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
              {id: 12, question: "Do you feel a sense of peace and contentment  in your home? ", category: "Home Environment", subs: []},
              {id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
              {id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
              {id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
        ];
    
             const arrayObj = any;
             const objectData = any;
    
              for (let index = 0; index < this.viewArray.length; index++) {
                  this.arrayObj = this.viewArray[index];
                  this.arrayObj.filter((x) => {
                    if (x.id === id) {
                      this.objectData = x;
                    }
                  });
                  console.log('Json Object Data by ID ==> ', this.objectData);
                }
              };
    

    How do I delete rows in a data frame?

    Here's a quick and dirty function to remove a row by index.

    removeRowByIndex <- function(x, row_index) {
      nr <- nrow(x)
      if (nr < row_index) {
        print('row_index exceeds number of rows')
      } else if (row_index == 1)
      {
        return(x[2:nr, ])
      } else if (row_index == nr) {
        return(x[1:(nr - 1), ])
      } else {
        return (x[c(1:(row_index - 1), (row_index + 1):nr), ])
      }
    }
    

    It's main flaw is it the row_index argument doesn't follow the R pattern of being a vector of values. There may be other problems as I only spent a couple of minutes writing and testing it, and have only started using R in the last few weeks. Any comments and improvements on this would be very welcome!

    How to replace multiple substrings of a string?

    This is just a more concise recap of F.J and MiniQuark great answers. All you need to achieve multiple simultaneous string replacements is the following function:

    def multiple_replace(string, rep_dict):
        pattern = re.compile("|".join([re.escape(k) for k in sorted(rep_dict,key=len,reverse=True)]), flags=re.DOTALL)
        return pattern.sub(lambda x: rep_dict[x.group(0)], string)
    

    Usage:

    >>>multiple_replace("Do you like cafe? No, I prefer tea.", {'cafe':'tea', 'tea':'cafe', 'like':'prefer'})
    'Do you prefer tea? No, I prefer cafe.'
    

    If you wish, you can make your own dedicated replacement functions starting from this simpler one.

    Get DateTime.Now with milliseconds precision

    If you still want a date instead of a string like the other answers, just add this extension method.

    public static DateTime ToMillisecondPrecision(this DateTime d) {
        return new DateTime(d.Year, d.Month, d.Day, d.Hour, d.Minute,
                            d.Second, d.Millisecond, d.Kind);
    }
    

    generate days from date range

    For Access 2010 - multiple steps required; I followed the same pattern as posted above, but thought I could help someone in Access. Worked great for me, I didn't have to keep a seeded table of dates.

    Create a table called DUAL (similar to how the Oracle DUAL table works)

    • ID (AutoNumber)
    • DummyColumn (Text)
    • Add one row values (1,"DummyRow")

    Create a query named "ZeroThru9Q"; manually enter the following syntax:

    SELECT 0 AS a
    FROM dual
    UNION ALL
    SELECT 1
    FROM dual
    UNION ALL
    SELECT 2
    FROM dual
    UNION ALL
    SELECT 3
    FROM dual
    UNION ALL
    SELECT 4
    FROM dual
    UNION ALL
    SELECT 5
    FROM dual
    UNION ALL
    SELECT 6
    FROM dual
    UNION ALL
    SELECT 7
    FROM dual
    UNION ALL
    SELECT 8
    FROM dual
    UNION ALL
    SELECT 9
    FROM dual;
    

    Create a query named "TodayMinus1KQ" (for dates before today); manually enter the following syntax:

    SELECT date() - (a.a + (10 * b.a) + (100 * c.a)) AS MyDate
    FROM
      (SELECT *
       FROM ZeroThru9Q) AS a,
    
      (SELECT *
       FROM ZeroThru9Q) AS b,
    
      (SELECT *
       FROM ZeroThru9Q) AS c
    

    Create a query named "TodayPlus1KQ" (for dates after today); manually enter the following syntax:

    SELECT date() + (a.a + (10 * b.a) + (100 * c.a)) AS MyDate
    FROM
      (SELECT *
       FROM ZeroThru9Q) AS a,
    
      (SELECT *
       FROM ZeroThru9Q) AS b,
    
      (SELECT *
       FROM ZeroThru9Q) AS c;
    

    Create a union query named "TodayPlusMinus1KQ" (for dates +/- 1000 days):

    SELECT MyDate
    FROM TodayMinus1KQ
    UNION
    SELECT MyDate
    FROM TodayPlus1KQ;
    

    Now you can use the query:

    SELECT MyDate
    FROM TodayPlusMinus1KQ
    WHERE MyDate BETWEEN #05/01/2014# and #05/30/2014#
    

    Output grep results to text file, need cleaner output

    Redirection of program output is performed by the shell.

    grep ... > output.txt
    

    grep has no mechanism for adding blank lines between each match, but does provide options such as context around the matched line and colorization of the match itself. See the grep(1) man page for details, specifically the -C and --color options.

    How does BitLocker affect performance?

    I am talking here from a theoretical point of view; I have not tried BitLocker.

    BitLocker uses AES encryption with a 128-bit key. On a Core2 machine, clocked at 2.53 GHz, encryption speed should be about 110 MB/s, using one core. The two cores could process about 220 MB/s, assuming perfect data transfer and core synchronization with no overhead, and that nothing requires the CPU in the same time (that one hell of an assumption, actually). The X25-M G2 is announced at 250 MB/s read bandwidth (that's what the specs say), so, in "ideal" conditions, BitLocker necessarily involves a bit of a slowdown.

    However read bandwidth is not that important. It matters when you copy huge files, which is not something that you do very often. In everyday work, access time is much more important: as a developer, you create, write, read and delete many files, but they are all small (most of them are much smaller than one megabyte). This is what makes SSD "snappy". Encryption does not impact access time. So my guess is that any performance degradation will be negligible(*).

    (*) Here I assume that Microsoft's developers did their job properly.

    How do I retrieve my MySQL username and password?

    While you can't directly recover a MySQL password without bruteforcing, there might be another way - if you've used MySQL Workbench to connect to the database, and have saved the credentials to the "vault", you're golden.

    On Windows, the credentials are stored in %APPDATA%\MySQL\Workbench\workbench_user_data.dat - encrypted with CryptProtectData (without any additional entropy). Decrypting is easy peasy:

    std::vector<unsigned char> decrypt(BYTE *input, size_t length) {
        DATA_BLOB inblob { length, input };
        DATA_BLOB outblob;
    
        if (!CryptUnprotectData(&inblob, NULL, NULL, NULL, NULL, CRYPTPROTECT_UI_FORBIDDEN, &outblob)) {
                throw std::runtime_error("Couldn't decrypt");
        }
    
        std::vector<unsigned char> output(length);
        memcpy(&output[0], outblob.pbData, outblob.cbData);
    
        return output;
    }
    

    Or you can check out this DonationCoder thread for source + executable of a quick-and-dirty implementation.

    Parse rfc3339 date strings in Python?

    This has already been answered here: How do I translate a ISO 8601 datetime string into a Python datetime object?

    d = datetime.datetime.strptime( "2012-10-09T19:00:55Z", "%Y-%m-%dT%H:%M:%SZ" )
    d.weekday()
    

    Is there a timeout for idle PostgreSQL connections?

    There is a timeout on broken connections (i.e. due to network errors), which relies on the OS' TCP keepalive feature. By default on Linux, broken TCP connections are closed after ~2 hours (see sysctl net.ipv4.tcp_keepalive_time).

    There is also a timeout on abandoned transactions, idle_in_transaction_session_timeout and on locks, lock_timeout. It is recommended to set these in postgresql.conf.

    But there is no timeout for a properly established client connection. If a client wants to keep the connection open, then it should be able to do so indefinitely. If a client is leaking connections (like opening more and more connections and never closing), then fix the client. Do not try to abort properly established idle connections on the server side.

    BasicHttpBinding vs WsHttpBinding vs WebHttpBinding

    You're comparing apples to oranges here:

    • webHttpBinding is the REST-style binding, where you basically just hit a URL and get back a truckload of XML or JSON from the web service

    • basicHttpBinding and wsHttpBinding are two SOAP-based bindings which is quite different from REST. SOAP has the advantage of having WSDL and XSD to describe the service, its methods, and the data being passed around in great detail (REST doesn't have anything like that - yet). On the other hand, you can't just browse to a wsHttpBinding endpoint with your browser and look at XML - you have to use a SOAP client, e.g. the WcfTestClient or your own app.

    So your first decision must be: REST vs. SOAP (or you can expose both types of endpoints from your service - that's possible, too).

    Then, between basicHttpBinding and wsHttpBinding, there differences are as follows:

    • basicHttpBinding is the very basic binding - SOAP 1.1, not much in terms of security, not much else in terms of features - but compatible to just about any SOAP client out there --> great for interoperability, weak on features and security

    • wsHttpBinding is the full-blown binding, which supports a ton of WS-* features and standards - it has lots more security features, you can use sessionful connections, you can use reliable messaging, you can use transactional control - just a lot more stuff, but wsHttpBinding is also a lot *heavier" and adds a lot of overhead to your messages as they travel across the network

    For an in-depth comparison (including a table and code examples) between the two check out this codeproject article: Differences between BasicHttpBinding and WsHttpBinding

    How to COUNT rows within EntityFramework without loading contents?

    Query syntax:

    var count = (from o in context.MyContainer
                 where o.ID == '1'
                 from t in o.MyTable
                 select t).Count();
    

    Method syntax:

    var count = context.MyContainer
                .Where(o => o.ID == '1')
                .SelectMany(o => o.MyTable)
                .Count()
    

    Both generate the same SQL query.

    How to disable a input in angular2

    I presume you meant false instead of 'false'

    Also, [disabled] is expecting a Boolean. You should avoid returning a null.

    How can I make a link from a <td> table cell

    This might be the most simple way to make a whole <td> cell an active hyperlink just using HTML.

    I never had a satisfactory answer for this question, until about 10 minutes ago, so years in the making #humor.

    Tested on Firefox 70, this is a bare-bones example where one full line-width of the cell is active:

    <td><a href=""><div><br /></div></a></td>

    Obviously the example just links to "this document," so fill in the href="" and replace the <br /> with anything appropriate.

    Previously I used a style and class pair that I cobbled together from the answers above (Thanks to you folks.)

    Today, working on a different issue, I kept stripping it down until <div>&nbsp;</div> was the only thing left, remove the <div></div> and it stops linking beyond the text. I didn't like the short "_" the &nbsp; displayed and found a single <br /> works without an "extra line" penalty.

    If another <td></td> in the <tr> has multiple lines, and makes the row taller with word-wrap for instance, then use multiple <br /> to bring the <td> you want to be active to the correct number of lines and active the full width of each line.

    The only problem is it isn't dynamic, but usually the mouse is closer in height than width, so active everywhere on one line is better than just the width of the text.

    What does java:comp/env/ do?

    There is also a property resourceRef of JndiObjectFactoryBean that is, when set to true, used to automatically prepend the string java:comp/env/ if it is not already present.

    <bean id="someId" class="org.springframework.jndi.JndiObjectFactoryBean">
      <property name="jndiName" value="jdbc/loc"/>
      <property name="resourceRef" value="true"/>
    </bean>
    

    Filtering a pyspark dataframe using isin by exclusion

    df.filter((df.bar != 'a') & (df.bar != 'b'))
    

    How to mount a host directory in a Docker container

    If the host is windows 10 then instead of forward slash, use backward slash -

    docker run -it -p 12001:80 -v c:\Users\C\Desktop\dockerStorage:/root/sketches
    

    Make sure the host drive is shared (C in this case). In my case I got a prompt asking for share permission after running the command above.

    git rebase fatal: Needed a single revision

    git submodule deinit --all -f worked for me.

    How do I copy an object in Java?

    Yes, you are just making a reference to the object. You can clone the object if it implements Cloneable.

    Check out this wiki article about copying objects.

    Refer here: Object copying

    Creating virtual directories in IIS express

    @Be.St.'s aprroach is true, but incomplete. I'm just copying his explanation with correcting the incorrect part.

    IIS express configuration is managed by applicationhost.config.
    You can find it in

    Users\<username>\Documents\IISExpress\config folder.

    Inside you can find the sites section that hold a section for each IIS Express configured site.

    Add (or modify) a site section like this:

    <site name="WebSiteWithVirtualDirectory" id="20">
       <application path="/" applicationPool="Clr4IntegratedAppPool">
         <virtualDirectory path="/" physicalPath="c:\temp\website1" />
         <virtualDirectory path="/OffSiteStuff" physicalPath="d:\temp\SubFolderApp" />
       </application>
       <bindings>
          <binding protocol="http" bindingInformation="*:1132:localhost" />
       </bindings>
    </site>
    

    Instead of adding a new application block, you should just add a new virtualDirectory element to the application parent element.

    Edit - Visual Studio 2015

    If you're looking for the applicationHost.config file and you're using VS2015 you'll find it in:

    [solution_directory]/.vs/config/applicationHost.config

    How does inline Javascript (in HTML) work?

    Try this in the console:

    var div = document.createElement('div');
    
    div.setAttribute('onclick', 'alert(event)');
    
    div.onclick
    

    In Chrome, it shows this:

    function onclick(event) {
      alert(event)
    }
    

    ...and the non-standard name property of div.onclick is "onclick".

    So, whether or not this is anonymous depends your definition of "anonymous." Compare with something like var foo = new Function(), where foo.name is an empty string, and foo.toString() will produce something like

    function anonymous() {
    
    }
    

    Does VBScript have a substring() function?

    Yes, Mid.

    Dim sub_str
    sub_str = Mid(source_str, 10, 5)
    

    The first parameter is the source string, the second is the start index, and the third is the length.

    @bobobobo: Note that VBScript strings are 1-based, not 0-based. Passing 0 as an argument to Mid results in "invalid procedure call or argument Mid".

    2D array values C++

    Like this:

    int main()
    {
        int arr[2][5] =
        {
            {1,8,12,20,25},
            {5,9,13,24,26}
        };
    }
    

    This should be covered by your C++ textbook: which one are you using?

    Anyway, better, consider using std::vector or some ready-made matrix class e.g. from Boost.

    Delete all local git branches

    Just a note, I would upgrade to git 1.7.10. You may be getting answers here that won't work on your version. My guess is that you would have to prefix the branch name with refs/heads/.

    CAUTION, proceed with the following only if you made a copy of your working folder and .git directory.

    I sometimes just go ahead and delete the branches I don't want straight from .git/refs/heads. All these branches are text files that contain the 40 character sha-1 of the commit they point to. You will have extraneous information in your .git/config if you had specific tracking set up for any of them. You can delete those entries manually as well.

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

    Here's an approach that still uses a data-only container but doesn't require it to be synced with the application container (in terms of having the same uid/gid).

    Presumably, you want to run some app in the container as a non-root $USER without a login shell.

    In the Dockerfile:

    RUN useradd -s /bin/false myuser
    
    # Set environment variables
    ENV VOLUME_ROOT /data
    ENV USER myuser
    
    ...
    
    ENTRYPOINT ["./entrypoint.sh"]
    

    Then, in entrypoint.sh:

    chown -R $USER:$USER $VOLUME_ROOT
    su -s /bin/bash - $USER -c "cd $repo/build; $@"
    

    validate natural input number with ngpattern

    This is working

    <form name="myform" ng-submit="create()">
        <input type="number"
               name="price_field"
               ng-model="price"
               require
               ng-pattern="/^\d{0,9}(\.\d{1,9})?$/">
        <span  ng-show="myform.price_field.$error.pattern">Not valid number!</span>
        <input type="submit" class="btn">
     </form>
    

    How to achieve ripple animation using support library?

    Sometimes you have a custom background, in that cases a better solution is use android:foreground="?selectableItemBackground"

    Update

    If you want ripple effect with rounded corners and custom background you can use this:

    background_ripple.xml

    <?xml version="1.0" encoding="utf-8"?>
    <ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="@color/ripple_color">
    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="@android:color/white" />
            <corners android:radius="5dp" />
        </shape>
    </item>
    
    <item android:id="@android:id/background">
        <shape android:shape="rectangle">
            <solid android:color="@android:color/white" />
            <corners android:radius="5dp" />
        </shape>
    </item>
    

    layout.xml

    <Button
        android:id="@+id/btn_play"
        android:background="@drawable/background_ripple"
        app:backgroundTint="@color/colorPrimary"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/play_now" />
    

    I used this on API >= 21

    Printing prime numbers from 1 through 100

    Here is my implementation of Sieve of Eratosthenes (for primes between 2 & n)

    #include <iostream>
    
    int main (){
    int n=0;
    std::cout << "n = ";
    std::cin >> n;
    std::cout << std::endl;
    
    if (n==0 || n==1){
        std::cout << "No primes in this range" << std::endl;
        return 0;
    }
    
    
    const int array_len = n-2+1;
    
    int the_int_array[array_len];
    for (int counter=2; counter <=n; counter++)
        the_int_array[counter-2]=counter;
    
    
    int runner = 0;
    int new_runner = 0;
    
    while (runner < array_len ){
        if (the_int_array[runner]!=0){
            new_runner = runner;
            new_runner = new_runner + the_int_array[runner];
    
            while (new_runner < array_len){
               the_int_array[new_runner] = 0;
               new_runner = (new_runner + the_int_array[runner]);
            }
        }
    runner++;
    }
    
    runner = 0;
    
    while (runner < array_len ){
        if (the_int_array[runner]!=0)
            std::cout << the_int_array[runner] << " ";
        runner++;
    }
    
    std::cout << std::endl;
    return 0;
    

    }

    jQuery UI Dialog Box - does not open after being closed

    I believe you can only initialize the dialog one time. The example above is trying to initialize the dialog every time #terms is clicked. This will cause problems. Instead, the initialization should occur outside of the click event. Your example should probably look something like this:

    $(document).ready(function() {
        // dialog init
        $('#terms').dialog({
            autoOpen: false,
            resizable: false,
            modal: true,
            width: 400,
            height: 450,
            overlay: { backgroundColor: "#000", opacity: 0.5 },
            buttons: { "Close": function() { $(this).dialog('close'); } },
            close: function(ev, ui) { $(this).close(); }
        });
        // click event
        $('#showTerms').click(function(){
            $('#terms').dialog('open').css('display','inline');      
        });
        // date picker
        $('#form1 input#calendarTEST').datepicker({ dateFormat: 'MM d, yy' });
    });
    

    I'm thinking that once you clear that up, it should fix the 'open from link' issue you described.

    Nullable property to entity field, Entity Framework through Code First

    In Ef .net core there are two options that you can do; first with data annotations:

    public class Blog
    {
        public int BlogId { get; set; }
        [Required]
        public string Url { get; set; }
    }
    

    Or with fluent api:

    class MyContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Blog>()
                .Property(b => b.Url)
                .IsRequired(false)//optinal case
                .IsRequired()//required case
                ;
        }
    }
    
    public class Blog
    {
        public int BlogId { get; set; }
        public string Url { get; set; }
    }
    

    There are more details here

    Mongoose's find method with $or condition does not work properly

    async() => {
    let body = await model.find().or([
      { name: 'something'},
      { nickname: 'somethang'}
    ]).exec();
    console.log(body);
    }
    /* Gives an array of the searched query!
    returns [] if not found */
    

    I didn't find "ZipFile" class in the "System.IO.Compression" namespace

    The issue here is that you just Added the reference to System.IO.Compression it is missing the reference to System.IO.Compression.Filesystem.dll

    And you need to do it on .net 4.5 or later (because it doesn't exist on older versions).

    I just posted a script on TechNet Maybe somebody would find it useful it requires .net 4.5 or 4.7

    https://gallery.technet.microsoft.com/scriptcenter/Create-a-Zip-file-from-a-b23a7530

    Get current date in DD-Mon-YYY format in JavaScript/Jquery

    Use date format dd-MM-yy . It will output like: 16-December-2014.

    The program can't start because cygwin1.dll is missing... in Eclipse CDT

    You can compile with either Cygwin's g++ or MinGW (via stand-alone or using Cygwin package). However, in order to run it, you need to add the Cygwin1.dll (and others) PATH to the system Windows PATH, before any cygwin style paths.

    Thus add: ;C:\cygwin64\bin to the end of your Windows system PATH variable.

    Also, to compile for use in CMD or PowerShell, you may need to use:

    x86_64-w64-mingw32-g++.exe -static -std=c++11 prog_name.cc -o prog_name.exe
    

    (This invokes the cross-compiler, if installed.)

    Running AngularJS initialization code when view is loaded

    Since AngularJS 1.5 we should use $onInit which is available on any AngularJS component. Taken from the component lifecycle documentation since v1.5 its the preffered way:

    $onInit() - Called on each controller after all the controllers on an element have been constructed and had their bindings initialized (and before the pre & post linking functions for the directives on this element). This is a good place to put initialization code for your controller.

    var myApp = angular.module('myApp',[]);
    myApp.controller('MyCtrl', function ($scope) {
    
        //default state
        $scope.name = '';
    
        //all your init controller goodness in here
        this.$onInit = function () {
          $scope.name = 'Superhero';
        }
    });
    

    >> Fiddle Demo


    An advanced example of using component lifecycle:

    The component lifecycle gives us the ability to handle component stuff in a good way. It allows us to create events for e.g. "init", "change" or "destroy" of an component. In that way we are able to manage stuff which is depending on the lifecycle of an component. This little example shows to register & unregister an $rootScope event listener $on. By knowing, that an event $on binded on $rootScope will not be undinded when the controller loses its reference in the view or getting destroyed we need to destroy a $rootScope.$on listener manually. A good place to put that stuff is $onDestroy lifecycle function of an component:

    var myApp = angular.module('myApp',[]);
    
    myApp.controller('MyCtrl', function ($scope, $rootScope) {
    
      var registerScope = null;
    
      this.$onInit = function () {
        //register rootScope event
        registerScope = $rootScope.$on('someEvent', function(event) {
            console.log("fired");
        });
      }
    
      this.$onDestroy = function () {
        //unregister rootScope event by calling the return function
        registerScope();
      }
    });
    

    >> Fiddle demo

    IntelliJ IDEA "The selected directory is not a valid home for JDK"

    May be your jdk is in /usr/lib/jvm/. This variant for linux.

    SQL Server 2008: How to query all databases sizes?

    sometimes SECURITY issues prevent from asking for all the db's and you need to query one by one with the db prefix, for those cases i created this dynamic query

    go
    declare @Results table ([Name] nvarchar(max), [DataFileSizeMB] int, [LogFileSizeMB] int);
    
    declare @QaQuery nvarchar(max)
    declare @name nvarchar(max)
    
    declare MY_CURSOR cursor 
      local static read_only forward_only
    for 
    select name from master.dbo.sysdatabases where name not in ('master', 'tempdb', 'model', 'msdb', 'rdsadmin');
    
    open MY_CURSOR
    fetch next from MY_CURSOR into @name
    while @@FETCH_STATUS = 0
    begin 
        if(len(@name)>0)
        begin
            print @name + ' Column Exist'
            set @QaQuery = N'select 
                                '''+@name+''' as Name
                                ,sum(case when type = 0 then size else 0 end) as DataFileSizeMB
                                ,sum(case when type = 1 then size else 0 end) as LogFileSizeMB
                            from ['+@name+'].sys.database_files
                            group by replace(name, ''_log'', '''')';
    
            insert @Results exec sp_executesql @QaQuery;
        end
      fetch next from MY_CURSOR into @name
    end
    close MY_CURSOR
    deallocate MY_CURSOR
    
    select * from @Results order by DataFileSizeMB desc
    go
    

    List all virtualenv

    To list all the virtual environments (if using the anaconda distribution):

    conda info --envs
    

    Hope my answer helps someone...

    How can I display a pdf document into a Webview?

    This is the actual usage limit that google allows before you get the error mentioned in the comments, if it's a once in a lifetime pdf that the user will open in app then i feel its completely safe. Although it is advised to to follow the the native approach using the built in framework in Android from Android 5.0 / Lollipop, it's called PDFRenderer.

    Append data frames together in a for loop

    Here are some tidyverse and custom function options that might work depending on your needs:

    library(tidyverse)
    
    # custom function to generate, filter, and mutate the data:
    combine_dfs <- function(i){
     data_frame(x = rnorm(5), y = runif(5)) %>% 
        filter(x < y) %>% 
        mutate(x_plus_y = x + y) %>% 
        mutate(i = i)
    }
    
    df <- 1:5 %>% map_df(~combine_dfs(.))
    df <- map_df(1:5, ~combine_dfs(.)) # both give the same results
    > df %>% head()
    # A tibble: 6 x 4
           x      y x_plus_y     i
       <dbl>  <dbl>    <dbl> <int>
    1 -0.973 0.673    -0.300     1
    2 -0.553 0.0463   -0.507     1
    3  0.250 0.716     0.967     2
    4 -0.745 0.0640   -0.681     2
    5 -0.736 0.228    -0.508     2
    6 -0.365 0.496     0.131     3
    

    You could do something similar if you had a directory of files that needed to be combined:

    dir_path <- '/path/to/data/test_directory/'
    list.files(dir_path)
    
    combine_files <- function(path, file){
      read_csv(paste0(path, file)) %>% 
        filter(a < b) %>% 
        mutate(a_plus_b = a + b) %>% 
        mutate(file_name = file) 
    }
    
    df <- list.files(dir_path, '\\.csv$') %>% 
      map_df(~combine_files(dir_path, .))
    
    # or if you have Excel files, using the readxl package:
    combine_xl_files <- function(path, file){
      readxl::read_xlsx(paste0(path, file)) %>% 
        filter(a < b) %>% 
        mutate(a_plus_b = a + b) %>% 
        mutate(file_name = file) 
    }
    
    df <- list.files(dir_path, '\\.xlsx$') %>% 
      map_df(~combine_xl_files(dir_path, .))
    

    How to upgrade Git on Windows to the latest version?

    I don't think your problem is related to Windows global PATH, as remote is specific to repo.

    I recommend you to use Git under Cygwin. Git could work under Windows command line, but there may be some weird problems hard to figure out. Under Cygwin it's more nature and has less error.

    All you need is to type bash in Window CMD then start to use the Unix tools and commands. You can use a shortcut to load bash, it's as easy as use normal Windows CMD.

    The same is true for Rails and Ruby. I used RailsInstaller before, but found using Cygwin to install Rails is more stable.

    Finally I'll suggest to install Ubuntu dual boot if you have time(about a month to get familiar). Windows is not very friendly to every Unix tools ultimately. You'll find all pain stopped.

    How does one convert a grayscale image to RGB in OpenCV (Python)?

    I am promoting my comment to an answer:

    The easy way is:

    You could draw in the original 'frame' itself instead of using gray image.

    The hard way (method you were trying to implement):

    backtorgb = cv2.cvtColor(gray,cv2.COLOR_GRAY2RGB) is the correct syntax.

    SQL "between" not inclusive

    It is inclusive. You are comparing datetimes to dates. The second date is interpreted as midnight when the day starts.

    One way to fix this is:

    SELECT *
    FROM Cases
    WHERE cast(created_at as date) BETWEEN '2013-05-01' AND '2013-05-01'
    

    Another way to fix it is with explicit binary comparisons

    SELECT *
    FROM Cases
    WHERE created_at >= '2013-05-01' AND created_at < '2013-05-02'
    

    Aaron Bertrand has a long blog entry on dates (here), where he discusses this and other date issues.

    How to trigger SIGUSR1 and SIGUSR2?

    They are user-defined signals, so they aren't triggered by any particular action. You can explicitly send them programmatically:

    #include <signal.h>
    
    kill(pid, SIGUSR1);
    

    where pid is the process id of the receiving process. At the receiving end, you can register a signal handler for them:

    #include <signal.h>
    
    void my_handler(int signum)
    {
        if (signum == SIGUSR1)
        {
            printf("Received SIGUSR1!\n");
        }
    }
    
    signal(SIGUSR1, my_handler);
    

    How can I get double quotes into a string literal?

    Escape the quotes with backslashes:

    printf("She said \"time flies like an arrow, but fruit flies like a banana\"."); 
    

    There are special escape characters that you can use in string literals, and these are denoted with a leading backslash.

    Make javascript alert Yes/No Instead of Ok/Cancel

    In an attempt to solve a similar situation I've come across this example and adapted it. It uses JQUERY UI Dialog as Nikhil D suggested. Here is a look at the code:

    HTML:

    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
    <input type="button" id="box" value="Confirm the thing?" />
    <div id="dialog-confirm"></div>
    

    JavaScript:

    $('#box').click(function buttonAction() {
      $("#dialog-confirm").html("Do you want to do the thing?");
    
      // Define the Dialog and its properties.
      $("#dialog-confirm").dialog({
        resizable: false,
        modal: true,
        title: "Do the thing?",
        height: 250,
        width: 400,
        buttons: {
          "Yes": function() {
            $(this).dialog('close');
            alert("Yes, do the thing");
          },
          "No": function() {
            $(this).dialog('close');
            alert("Nope, don't do the thing");
          }
        }
      });
    });
    
    $('#box').click(buttonAction);
    

    I have a few more tweaks I need to do to make this example work for my application. Will update this if I see it fit into the answer. Hope this helps someone.

    Unstaged changes left after git reset --hard

    I hit a similar issue also involving .gitattributes, but for my case involved GitHub's LFS. While this isn't exactly the OP's scenario, I think it provides an opportunity to illustrate what the .gitattributes file does and why it can lead to unstaged changes in the form of "phantom" differences.

    In my case, a file already was in my repository, like since the beginning of time. In a recent commit, I added a new git-lfs track rule using a pattern that was in hindsight a bit too broad, and ending up matching this ancient file. I know I didn't want to change this file; I know I didn't change the file, but now it was in my unstaged changes and no amount of checkouts or hard resets on that file was going to fix it. Why?

    GitHub LFS extension works primarily through leveraging the hooks that git provides access through via the .gitattributes file. Generally, entries in .gitattributes specify how matching files should be processed. In the OP's case, it was concerned with normalizing line endings; in mine, it was whether to let LFS handle the file storage. In either case, the actually file that git sees when computing a git diff does not match the file that you see when you inspect the file. Hence, if you change how a file is processed via the .gitattributes pattern that matches it, it will show up as unstaged changes in the status report, even if there really is no change in the file.

    All that said, my "answer" to the question is that if the change in .gitattributes file is something you wanted to do, you should should really just add the changes and move on. If not, then amend the .gitattributes to better represent what you want to be doing.

    References

    1. GitHub LFS Specification - Great description of how they hook into the clean and smudge function calls to replace your file in the git objects with a simple text file with a hash.

    2. gitattributes Documentation - All the details on what is available to customize how git processes your documents.

    INSERT with SELECT

    Correct Syntax: select spelling was wrong

    INSERT INTO courses (name, location, gid)
    SELECT name, location, 'whatever you want' 
    FROM courses 
    WHERE cid = $ci 
    

    Express.js - app.listen vs server.listen

    I came with same question but after google, I found there is no big difference :)

    From Github

    If you wish to create both an HTTP and HTTPS server you may do so with the "http" and "https" modules as shown here.

    /**
     * Listen for connections.
     *
     * A node `http.Server` is returned, with this
     * application (which is a `Function`) as its
     * callback. If you wish to create both an HTTP
     * and HTTPS server you may do so with the "http"
     * and "https" modules as shown here:
     *
     *    var http = require('http')
     *      , https = require('https')
     *      , express = require('express')
     *      , app = express();
     *
     *    http.createServer(app).listen(80);
     *    https.createServer({ ... }, app).listen(443);
     *
     * @return {http.Server}
     * @api public
     */
    
    app.listen = function(){
      var server = http.createServer(this);
      return server.listen.apply(server, arguments);
    };
    

    Also if you want to work with socket.io see their example

    See this

    I prefer app.listen() :)

    How to find the socket buffer size of linux

    For getting the buffer size in c/c++ program the following is the flow

    int n;
    unsigned int m = sizeof(n);
    int fdsocket;
    fdsocket = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); // example
    getsockopt(fdsocket,SOL_SOCKET,SO_RCVBUF,(void *)&n, &m);
    // now the variable n will have the socket size
    

    Groovy: How to check if a string contains any element of an array?

    def valid = pointAddress.findAll { a ->
        validPointTypes.any { a.contains(it) }
    }
    

    Should do it

    jQuery - If element has class do this

    First, you're missing some parentheses in your conditional:

    if ($("#about").hasClass("opened")) {
      $("#about").animate({right: "-700px"}, 2000);
    }
    

    But you can also simplify this to:

    $('#about.opened').animate(...);
    

    If #about doesn't have the opened class, it won't animate.

    If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)

    CASE .. WHEN expression in Oracle SQL

    Since web search for Oracle case tops to that link, I add here for case statement, though not answer to the question asked about case expression:

    CASE
       WHEN grade = 'A' THEN dbms_output.put_line('Excellent');
       WHEN grade = 'B' THEN dbms_output.put_line('Very Good');
       WHEN grade = 'C' THEN dbms_output.put_line('Good');
       WHEN grade = 'D' THEN dbms_output.put_line('Fair');
       WHEN grade = 'F' THEN dbms_output.put_line('Poor');
       ELSE dbms_output.put_line('No such grade');
    END CASE;
    

    or other variant:

    CASE grade
       WHEN 'A' THEN dbms_output.put_line('Excellent');
       WHEN 'B' THEN dbms_output.put_line('Very Good');
       WHEN 'C' THEN dbms_output.put_line('Good');
       WHEN 'D' THEN dbms_output.put_line('Fair');
       WHEN 'F' THEN dbms_output.put_line('Poor');
       ELSE dbms_output.put_line('No such grade');
    END CASE;
    

    Per Oracle docs: https://docs.oracle.com/cd/B10501_01/appdev.920/a96624/04_struc.htm

    Remove duplicated rows using dplyr

    When selecting columns in R for a reduced data-set you can often end up with duplicates.

    These two lines give the same result. Each outputs a unique data-set with two selected columns only:

    distinct(mtcars, cyl, hp);
    
    summarise(group_by(mtcars, cyl, hp));
    

    PDO Prepared Inserts multiple rows in single query

    You can insert multiple rows in a single query with this function:

    function insertMultiple($query,$rows) {
        if (count($rows)>0) {
            $args = array_fill(0, count($rows[0]), '?');
    
            $params = array();
            foreach($rows as $row)
            {
                $values[] = "(".implode(',', $args).")";
                foreach($row as $value)
                {
                    $params[] = $value;
                }
            }
    
            $query = $query." VALUES ".implode(',', $values);
            $stmt = $PDO->prepare($query);
            $stmt->execute($params);
        }
    }
    

    $row is an array of arrays of values. In your case you would call the function with

    insertMultiple("INSERT INTO tbl (`key1`,`key2`)",array(array('r1v1','r1v2'),array('r2v1','r2v2')));
    

    This has the benefit that you use prepared statements, while inserting multiple rows with a single query. Security!

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

    Important:

    Make sure you're using System.Windows.Media.Brush and not System.Drawing.Brush

    They're not compatible and you'll get binding errors.

    The color enumeration you need to use is also different

    System.Windows.Media.Colors.Aquamarine (class name is Colors) <--- use this one System.Drawing.Color.Aquamarine (class name is Color)

    If in doubt use Snoop and inspect the element's background property to look for binding errors - or just look in your debug log.