Programs & Examples On #Quantmod

quantmod is a package for R designed to assist quantitative traders in the development, testing, and deployment of statistically based trading models.

Error in model.frame.default: variable lengths differ

Another thing that can cause this error is creating a model with the centering/scaling standardize function from the arm package -- m <- standardize(lm(y ~ x, data = train))

If you then try predict(m), you get the same error as in this question.

How can I display a JavaScript object?

To print the full object with Node.js with colors as a bonus:

console.dir(object, {depth: null, colors: true})

Colors are of course optional, 'depth: null' will print the full object.

The options don't seem to be supported in browsers.

References:

https://developer.mozilla.org/en-US/docs/Web/API/Console/dir

https://nodejs.org/api/console.html#console_console_dir_obj_options

Set line spacing

Try the line-height property.

For example, 12px font-size and 4px distant from the bottom and upper lines:

line-height: 20px; /* 4px +12px + 4px */

Or with em units

line-height: 1.7em; /* 1em = 12px in this case. 20/12 == 1.666666  */

How do I combine two dataframes?

I believe you can use the append method

bigdata = data1.append(data2, ignore_index=True)

to keep their indexes just dont use the ignore_index keyword ...

OSError [Errno 22] invalid argument when use open() in Python

In my case,the problem exists beacause I have not set permission for drive "C:\" and when I change my path to other drive like "F:\" my problem resolved.

C++ Returning reference to local variable

This code snippet:

int& func1()
{
    int i;
    i = 1;
    return i;
}

will not work because you're returning an alias (a reference) to an object with a lifetime limited to the scope of the function call. That means once func1() returns, int i dies, making the reference returned from the function worthless because it now refers to an object that doesn't exist.

int main()
{
    int& p = func1();
    /* p is garbage */
}

The second version does work because the variable is allocated on the free store, which is not bound to the lifetime of the function call. However, you are responsible for deleteing the allocated int.

int* func2()
{
    int* p;
    p = new int;
    *p = 1;
    return p;
}

int main()
{
    int* p = func2();
    /* pointee still exists */
    delete p; // get rid of it
}

Typically you would wrap the pointer in some RAII class and/or a factory function so you don't have to delete it yourself.

In either case, you can just return the value itself (although I realize the example you provided was probably contrived):

int func3()
{
    return 1;
}

int main()
{
    int v = func3();
    // do whatever you want with the returned value
}

Note that it's perfectly fine to return big objects the same way func3() returns primitive values because just about every compiler nowadays implements some form of return value optimization:

class big_object 
{ 
public:
    big_object(/* constructor arguments */);
    ~big_object();
    big_object(const big_object& rhs);
    big_object& operator=(const big_object& rhs);
    /* public methods */
private:
    /* data members */
};

big_object func4()
{
    return big_object(/* constructor arguments */);
}

int main()
{
     // no copy is actually made, if your compiler supports RVO
    big_object o = func4();    
}

Interestingly, binding a temporary to a const reference is perfectly legal C++.

int main()
{
    // This works! The returned temporary will last as long as the reference exists
    const big_object& o = func4();    
    // This does *not* work! It's not legal C++ because reference is not const.
    // big_object& o = func4();  
}

Java ArrayList for integers

Actually what u did is also not wrong your declaration is right . With your declaration JVM will create a ArrayList of integer arrays i.e each entry in arraylist correspond to an integer array hence your add function should pass a integer array as a parameter.

For Ex:

list.add(new Integer[3]);

In this way first entry of ArrayList is an integer array which can hold at max 3 values.

Encrypt and decrypt a string in C#?

With the reference of Encrypt and Decrypt a String in c#, I found one of good solution :

static readonly string PasswordHash = "P@@Sw0rd";
static readonly string SaltKey = "S@LT&KEY";
static readonly string VIKey = "@1B2c3D4e5F6g7H8";

For Encrypt

public static string Encrypt(string plainText)
{
    byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

    byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
    var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };
    var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));

    byte[] cipherTextBytes;

    using (var memoryStream = new MemoryStream())
    {
        using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
        {
            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
            cryptoStream.FlushFinalBlock();
            cipherTextBytes = memoryStream.ToArray();
            cryptoStream.Close();
        }
        memoryStream.Close();
    }
    return Convert.ToBase64String(cipherTextBytes);
}

For Decrypt

public static string Decrypt(string encryptedText)
{
    byte[] cipherTextBytes = Convert.FromBase64String(encryptedText);
    byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
    var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None };

    var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
    var memoryStream = new MemoryStream(cipherTextBytes);
    var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
    byte[] plainTextBytes = new byte[cipherTextBytes.Length];

    int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
    memoryStream.Close();
    cryptoStream.Close();
    return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray());
}

Generate a random date between two other dates

Updated answer

It's even more simple using Faker.

Installation

pip install faker

Usage:

from faker import Faker
fake = Faker()

fake.date_between(start_date='today', end_date='+30y')
# datetime.date(2025, 3, 12)

fake.date_time_between(start_date='-30y', end_date='now')
# datetime.datetime(2007, 2, 28, 11, 28, 16)

# Or if you need a more specific date boundaries, provide the start 
# and end dates explicitly.
import datetime
start_date = datetime.date(year=2015, month=1, day=1)
fake.date_between(start_date=start_date, end_date='+30y')

Old answer

It's very simple using radar

Installation

pip install radar

Usage

import datetime

import radar 

# Generate random datetime (parsing dates from str values)
radar.random_datetime(start='2000-05-24', stop='2013-05-24T23:59:59')

# Generate random datetime from datetime.datetime values
radar.random_datetime(
    start = datetime.datetime(year=2000, month=5, day=24),
    stop = datetime.datetime(year=2013, month=5, day=24)
)

# Just render some random datetime. If no range is given, start defaults to 
# 1970-01-01 and stop defaults to datetime.datetime.now()
radar.random_datetime()

How to check task status in Celery?

Old question but I recently ran into this problem.

If you're trying to get the task_id you can do it like this:

import celery
from celery_app import add
from celery import uuid

task_id = uuid()
result = add.apply_async((2, 2), task_id=task_id)

Now you know exactly what the task_id is and can now use it to get the AsyncResult:

# grab the AsyncResult 
result = celery.result.AsyncResult(task_id)

# print the task id
print result.task_id
09dad9cf-c9fa-4aee-933f-ff54dae39bdf

# print the AsyncResult's status
print result.status
SUCCESS

# print the result returned 
print result.result
4

How to update Identity Column in SQL Server?

You can not update identity column.

SQL Server does not allow to update the identity column unlike what you can do with other columns with an update statement.

Although there are some alternatives to achieve a similar kind of requirement.

  • When Identity column value needs to be updated for new records

Use DBCC CHECKIDENT which checks the current identity value for the table and if it's needed, changes the identity value.

DBCC CHECKIDENT('tableName', RESEED, NEW_RESEED_VALUE)
  • When Identity column value needs to be updated for existing records

Use IDENTITY_INSERT which allows explicit values to be inserted into the identity column of a table.

SET IDENTITY_INSERT YourTable {ON|OFF}

Example:

-- Set Identity insert on so that value can be inserted into this column
SET IDENTITY_INSERT YourTable ON
GO
-- Insert the record which you want to update with new value in the identity column
INSERT INTO YourTable(IdentityCol, otherCol) VALUES(13,'myValue')
GO
-- Delete the old row of which you have inserted a copy (above) (make sure about FK's)
DELETE FROM YourTable WHERE ID=3
GO
--Now set the idenetity_insert OFF to back to the previous track
SET IDENTITY_INSERT YourTable OFF

Laravel - Session store not set on request

If adding your routes inside the web middleware doesn't work for any reason then try adding this to $middleware into Kernel.php

protected $middleware = [
        //...
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
];

PHP Unset Array value effect on other indexes

The Key Disappears, whether it is numeric or not. Try out the test script below.

<?php
    $t = array( 'a', 'b', 'c', 'd' );
    foreach($t as $k => $v)
        echo($k . ": " . $v . "<br/>");
    // Output: 0: a, 1: b, 2: c, 3: d

    unset($t[1]);

    foreach($t as $k => $v)
        echo($k . ": " . $v . "<br/>");
    // Output: 0: a, 2: c, 3: d
?>

How to build minified and uncompressed bundle with webpack?

You can use a single config file, and include the UglifyJS plugin conditionally using an environment variable:

const webpack = require('webpack');
const TerserPlugin = require('terser-webpack-plugin');

const PROD = JSON.parse(process.env.PROD_ENV || '0');

module.exports = {

  entry: './entry.js',
  devtool: 'source-map',
  output: {
    path: './dist',
    filename: PROD ? 'bundle.min.js' : 'bundle.js'
  },
  optimization: {
    minimize: PROD,
    minimizer: [
      new TerserPlugin({ parallel: true })
  ]
};

and then just set this variable when you want to minify it:

$ PROD_ENV=1 webpack

Edit:

As mentioned in the comments, NODE_ENV is generally used (by convention) to state whether a particular environment is a production or a development environment. To check it, you can also set const PROD = (process.env.NODE_ENV === 'production'), and continue normally.

How to create a foreign key in phpmyadmin

A simple SQL example would be like this:

ALTER TABLE `<table_name>` ADD `<column_name>` INT(11) NULL DEFAULT NULL ;

Make sure you use back ticks `` in table name and column name

ERROR 1130 (HY000): Host '' is not allowed to connect to this MySQL server

For those who are able to access cpanel, there is a simpler way getting around it.

  1. log in cpanel => "Remote MySQL" under DATABASES section:

  2. Add the IPs / hostname which you are accessing from

  3. done!!!

What is the unix command to see how much disk space there is and how much is remaining?

I love doing du -sh * | sort -nr | less to sort by the largest files first

Can I obtain method parameter name using Java reflection?

So you should be able to do:

Whatever.declaredMethods
        .find { it.name == 'aMethod' }
        .parameters
        .collect { "$it.type : $it.name" }

But you'll probably get a list like so:

["int : arg0"]

I believe this will be fixed in Groovy 2.5+

So currently, the answer is:

  • If it's a Groovy class, then no, you can't get the name, but you should be able to in the future.
  • If it's a Java class compiled under Java 8, you should be able to.

See also:


For every method, then something like:

Whatever.declaredMethods
        .findAll { !it.synthetic }
        .collect { method -> 
            println method
            method.name + " -> " + method.parameters.collect { "[$it.type : $it.name]" }.join(';')
        }
        .each {
            println it
        }

How to convert List<string> to List<int>?

What no TryParse? Safe LINQ version that filters out invalid ints (for C# 6.0 and below):

List<int>  ints = strings
    .Select(s => { int i; return int.TryParse(s, out i) ? i : (int?)null; })
    .Where(i => i.HasValue)
    .Select(i => i.Value)
    .ToList();

credit to Olivier Jacot-Descombes for the idea and the C# 7.0 version.

Angular directives - when and how to use compile, controller, pre-link and post-link

In which order the directive functions are executed?

For a single directive

Based on the following plunk, consider the following HTML markup:

<body>
    <div log='some-div'></div>
</body>

With the following directive declaration:

myApp.directive('log', function() {
  
    return {
        controller: function( $scope, $element, $attrs, $transclude ) {
            console.log( $attrs.log + ' (controller)' );
        },
        compile: function compile( tElement, tAttributes ) {
            console.log( tAttributes.log + ' (compile)'  );
            return {
                pre: function preLink( scope, element, attributes ) {
                    console.log( attributes.log + ' (pre-link)'  );
                },
                post: function postLink( scope, element, attributes ) {
                    console.log( attributes.log + ' (post-link)'  );
                }
            };
         }
     };  
     
});

The console output will be:

some-div (compile)
some-div (controller)
some-div (pre-link)
some-div (post-link)

We can see that compile is executed first, then controller, then pre-link and last is post-link.

For nested directives

Note: The following does not apply to directives that render their children in their link function. Quite a few Angular directives do so (like ngIf, ngRepeat, or any directive with transclude). These directives will natively have their link function called before their child directives compile is called.

The original HTML markup is often made of nested elements, each with its own directive. Like in the following markup (see plunk):

<body>
    <div log='parent'>
        <div log='..first-child'></div>
        <div log='..second-child'></div>
    </div>
</body>

The console output will look like this:

// The compile phase
parent (compile)
..first-child (compile)
..second-child (compile)

// The link phase   
parent (controller)
parent (pre-link)
..first-child (controller)
..first-child (pre-link)
..first-child (post-link)
..second-child (controller)
..second-child (pre-link)
..second-child (post-link)
parent (post-link)

We can distinguish two phases here - the compile phase and the link phase.

The compile phase

When the DOM is loaded Angular starts the compile phase, where it traverses the markup top-down, and calls compile on all directives. Graphically, we could express it like so:

An image illustrating the compilation loop for children

It is perhaps important to mention that at this stage, the templates the compile function gets are the source templates (not instance template).

The link phase

DOM instances are often simply the result of a source template being rendered to the DOM, but they may be created by ng-repeat, or introduced on the fly.

Whenever a new instance of an element with a directive is rendered to the DOM, the link phase starts.

In this phase, Angular calls controller, pre-link, iterates children, and call post-link on all directives, like so:

An illustration demonstrating the link phase steps

ScalaTest in sbt: is there a way to run a single test without tags?

Just to simplify the example of Tyler.

test:-prefix is not needed.

So according to his example:

In the sbt-console:

testOnly *LoginServiceSpec

And in the terminal:

sbt "testOnly *LoginServiceSpec"

Avoid browser popup blockers

I tried multiple solutions, but his is the only one that actually worked for me in all the browsers

let newTab = window.open(); newTab.location.href = url;

Why can't I display a pound (£) symbol in HTML?

1st: the pound symbol is a "special" char in utf8 encoding (try saving £$ in a iso-8859-1 (or iso-8859-15) file and you will get ä when encoding using header)

2nd: change your encoding to utf8 form the file. there are plenty of methods to do it. notepad and notepad++ are great sugestions.

3rd: use ob_start(); (in php) BEFORE YOU MAKE ANY OUTPUT if you are getting weird encoding errors, like missing the encoding sometimes. and YES, this solves it! this kind of errors occurs when a page is encoded in windows-1252(ANSI),ASCII,iso-8859-1(5) and then you have all the others in utf8. this is a terrible error and can cause weird things like session_start(); not working.

4th: other php solutions:

utf8_encode('£');
htmlentities('£');
echo '&amp;pound;';

5th: javascript solutions:

document.getElementById('id_goes_here').innerText.replace('£','&amp;pound;');
document.getElementById('id_goes_here').innerText.replace('£',"\u00A3");
$(this).html().replace('£','&amp;pound;'); //jquery
$(this).html().replace('£',"\u00A3"); //jquery
String.fromCharCode('163');

you MUST send £, so it will repair the broken encoded code point. please, avoid these solutions! use php! these solutions only show how to 'fix' the error, and the last one only to create the well-encoded char.

Show a div as a modal pop up

A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:

  • 1. Create a div with semi transparent background & show it on top of your content page on click.
  • 2. Show your pop up div or alert div on top of the semi transparent dimming/hiding div.
  • So we need three divs:

  • content(main content of the site).
  • hider(To dim the content).
  • popup_box(the modal div to display).

    First let us define the CSS:

        #hider
        {
            position:absolute;
            top: 0%;
            left: 0%;
            width:1600px;
            height:2000px;
            margin-top: -800px; /*set to a negative number 1/2 of your height*/
            margin-left: -500px; /*set to a negative number 1/2 of your width*/
            /*
            z- index must be lower than pop up box
           */
            z-index: 99;
           background-color:Black;
           //for transparency
           opacity:0.6;
        }
    
        #popup_box  
        {
    
        position:absolute;
            top: 50%;
            left: 50%;
            width:10em;
            height:10em;
            margin-top: -5em; /*set to a negative number 1/2 of your height*/
            margin-left: -5em; /*set to a negative number 1/2 of your width*/
            border: 1px solid #ccc;
            border:  2px solid black;
            z-index:100; 
    
        }
    

    It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
    Here comes the java Script:

            $(document).ready(function () {
            //hide hider and popup_box
            $("#hider").hide();
            $("#popup_box").hide();
    
            //on click show the hider div and the message
            $("#showpopup").click(function () {
                $("#hider").fadeIn("slow");
                $('#popup_box').fadeIn("slow");
            });
            //on click hide the message and the
            $("#buttonClose").click(function () {
    
                $("#hider").fadeOut("slow");
                $('#popup_box').fadeOut("slow");
            });
    
            });
    

    And finally the HTML:

    <div id="hider"></div>
    <div id="popup_box">
        Message<br />
        <a id="buttonClose">Close</a>
    </div>    
    <div id="content">
        Page's main content.<br />
        <a id="showpopup">ClickMe</a>
    </div>
    

    I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.

  • inserting characters at the start and end of a string

    Adding to C2H5OH's answer, in Python 3.6+ you can use format strings to make it a bit cleaner:

    s = "something about cupcakes"
    print(f"L{s}LL")
    

    How to update Xcode from command line

    What you are actually using is the command to install the Xcode command line tools - xcode-select --install. Hence the error message you got - the tools are already installed.

    The command you need to update Xcode is softwareupdate command [args ...]. You can use softwareupdate --list to see what's available and then softwareupdate --install -a to install all updates or softwareupdate --install <product name> to install just the Xcode update (if available). You can get the name from the list command.

    As it was mentioned in the comments here is the man page for the softwareupdate tool.

    2019 Update

    A lot of users are experiencing problems where softwareupdate --install -a will in fact not update to the newest version of Xcode. The cause for this is more than likely a pending macOS update (as @brianlmerritt pointed out below). In most cases updating macOS first will solve the problem and allow Xcode to be updated as well.

    Updating the Xcode Command Line Tools

    A large portion of users are landing on this answer in an attempt to update the Xcode Command Line Tools. The easiest way to achieve this is by removing the old version of the tools, and installing the new one.

    sudo rm -rf /Library/Developer/CommandLineTools
    xcode-select --install
    

    A popup will appear and guide you through the rest of the process.

    using where and inner join in mysql

    Try this :

    SELECT
        (
          SELECT
              `NAME`
          FROM
              locations
          WHERE
              ID = school_locations.LOCATION_ID
        ) as `NAME`
    FROM
         school_locations
    WHERE
         (
          SELECT
              `TYPE`
          FROM
              locations
          WHERE
              ID = school_locations.LOCATION_ID
         ) = 'coun';
    

    Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`

    The specific code I used to fix this was:

      renderSeparator(sectionID, rowID, adjacentRowHighlighted) {
        return (
          <View style={styles.separator} key={`${sectionID}-${rowID}`}/>
        )
      }
    

    I'm including the specific code because you need the keys to be unique--even for separators. If you do something similar e.g., if you set this to a constant, you will just get another annoying error about reuse of keys. If you don't know JSX, constructing the callback to JS to execute the various parts can be quite a pain.

    And on the ListView, obviously attaching this:

    <ListView
      style={styles.listview}
      dataSource={this.state.dataSource}
      renderRow={this.renderRow.bind(this)}
      renderSeparator={this.renderSeparator.bind(this)}
      renderSectionHeader={this.renderSectionHeader.bind(this)}/>
    

    Credit to coldbuffet and Nader Dabit who pointed me down this path.

    Using Jquery Ajax to retrieve data from Mysql


    You can't return ajax return value. You stored global variable store your return values after return.
    Or Change ur code like this one.

    AjaxGet = function (url) {
        var result = $.ajax({
            type: "POST",
            url: url,
           param: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
           async: false,
            success: function (data) {
                // nothing needed here
          }
        }) .responseText ;
        return  result;
    }
    

    Invalid syntax when using "print"?

    They changed print in Python 3. In 2 it was a statement, now it is a function and requires parenthesis.

    Here's the docs from Python 3.0.

    Why am I getting error CS0246: The type or namespace name could not be found?

    It might be due to "client profile" of the .NET Framework. Try to use the "full version" of .NET.

    Determine the size of an InputStream

    If you know that your InputStream is a FileInputStream or a ByteArrayInputStream, you can use a little reflection to get at the stream size without reading the entire contents. Here's an example method:

    static long getInputLength(InputStream inputStream) {
        try {
            if (inputStream instanceof FilterInputStream) {
                FilterInputStream filtered = (FilterInputStream)inputStream;
                Field field = FilterInputStream.class.getDeclaredField("in");
                field.setAccessible(true);
                InputStream internal = (InputStream) field.get(filtered);
                return getInputLength(internal);
            } else if (inputStream instanceof ByteArrayInputStream) {
                ByteArrayInputStream wrapper = (ByteArrayInputStream)inputStream;
                Field field = ByteArrayInputStream.class.getDeclaredField("buf");
                field.setAccessible(true);
                byte[] buffer = (byte[])field.get(wrapper);
                return buffer.length;
            } else if (inputStream instanceof FileInputStream) {
                FileInputStream fileStream = (FileInputStream)inputStream;
                return fileStream.getChannel().size();
            }
        } catch (NoSuchFieldException | IllegalAccessException | IOException exception) {
            // Ignore all errors and just return -1.
        }
        return -1;
    }
    

    This could be extended to support additional input streams, I am sure.

    Why is Visual Studio 2013 very slow?

    I had similar problems when moving from Visual Studio 2012 → Visual Studio 2013. The IDE would lock up after almost every click or save, and building would take several times longer. None of the solutions listed here helped.

    What finally did help was moving my projects to a local drive. Visual Studio 2012 had no problems storing my projects on a network share, but Visual Studio 2013 for some reason couldn't handle it.

    jQuery $(this) keyword

    $(document).ready(function(){
       $('.somediv').click(function(){
       $(this).addClass('newDiv'); // this means the div which is clicked
       });                         // so instead of using a selector again $('.somediv');
    });                           // you use $(this) which much better and neater:=)
    

    SQL JOIN vs IN performance?

    This Thread is pretty old but still mentioned often. For my personal taste it is a bit incomplete, because there is another way to ask the database with the EXISTS keyword which I found to be faster more often than not.

    So if you are only interested in values from table a you can use this query:

    SELECT  a.*
    FROM    a
    WHERE   EXISTS (
        SELECT  *
        FROM    b
        WHERE   b.col = a.col
        )
    

    The difference might be huge if col is not indexed, because the db does not have to find all records in b which have the same value in col, it only has to find the very first one. If there is no index on b.col and a lot of records in b a table scan might be the consequence. With IN or a JOIN this would be a full table scan, with EXISTS this would be only a partial table scan (until the first matching record is found).

    If there a lots of records in b which have the same col value you will also waste a lot of memory for reading all these records into a temporary space just to find that your condition is satisfied. With exists this can be usually avoided.

    I have often found EXISTS faster then IN even if there is an index. It depends on the database system (the optimizer), the data and last not least on the type of index which is used.

    if, elif, else statement issues in Bash

    You have some syntax issues with your script. Here is a fixed version:

    #!/bin/bash
    
    if [ "$seconds" -eq 0 ]; then
       timezone_string="Z"
    elif [ "$seconds" -gt 0 ]; then
       timezone_string=$(printf "%02d:%02d" $((seconds/3600)) $(((seconds / 60) % 60)))
    else
       echo "Unknown parameter"
    fi
    

    How to include another XHTML in XHTML using JSF 2.0 Facelets?

    <ui:include>

    Most basic way is <ui:include>. The included content must be placed inside <ui:composition>.

    Kickoff example of the master page /page.xhtml:

    <!DOCTYPE html>
    <html lang="en"
        xmlns="http://www.w3.org/1999/xhtml"
        xmlns:f="http://xmlns.jcp.org/jsf/core"
        xmlns:h="http://xmlns.jcp.org/jsf/html"
        xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
        <h:head>
            <title>Include demo</title>
        </h:head>
        <h:body>
            <h1>Master page</h1>
            <p>Master page blah blah lorem ipsum</p>
            <ui:include src="/WEB-INF/include.xhtml" />
        </h:body>
    </html>
    

    The include page /WEB-INF/include.xhtml (yes, this is the file in its entirety, any tags outside <ui:composition> are unnecessary as they are ignored by Facelets anyway):

    <ui:composition 
        xmlns="http://www.w3.org/1999/xhtml"
        xmlns:f="http://xmlns.jcp.org/jsf/core"
        xmlns:h="http://xmlns.jcp.org/jsf/html"
        xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
        <h2>Include page</h2>
        <p>Include page blah blah lorem ipsum</p>
    </ui:composition>
      
    

    This needs to be opened by /page.xhtml. Do note that you don't need to repeat <html>, <h:head> and <h:body> inside the include file as that would otherwise result in invalid HTML.

    You can use a dynamic EL expression in <ui:include src>. See also How to ajax-refresh dynamic include content by navigation menu? (JSF SPA).


    <ui:define>/<ui:insert>

    A more advanced way of including is templating. This includes basically the other way round. The master template page should use <ui:insert> to declare places to insert defined template content. The template client page which is using the master template page should use <ui:define> to define the template content which is to be inserted.

    Master template page /WEB-INF/template.xhtml (as a design hint: the header, menu and footer can in turn even be <ui:include> files):

    <!DOCTYPE html>
    <html lang="en"
        xmlns="http://www.w3.org/1999/xhtml"
        xmlns:f="http://xmlns.jcp.org/jsf/core"
        xmlns:h="http://xmlns.jcp.org/jsf/html"
        xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
        <h:head>
            <title><ui:insert name="title">Default title</ui:insert></title>
        </h:head>
        <h:body>
            <div id="header">Header</div>
            <div id="menu">Menu</div>
            <div id="content"><ui:insert name="content">Default content</ui:insert></div>
            <div id="footer">Footer</div>
        </h:body>
    </html>
    

    Template client page /page.xhtml (note the template attribute; also here, this is the file in its entirety):

    <ui:composition template="/WEB-INF/template.xhtml"
        xmlns="http://www.w3.org/1999/xhtml"
        xmlns:f="http://xmlns.jcp.org/jsf/core"
        xmlns:h="http://xmlns.jcp.org/jsf/html"
        xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    
        <ui:define name="title">
            New page title here
        </ui:define>
    
        <ui:define name="content">
            <h1>New content here</h1>
            <p>Blah blah</p>
        </ui:define>
    </ui:composition>
    

    This needs to be opened by /page.xhtml. If there is no <ui:define>, then the default content inside <ui:insert> will be displayed instead, if any.


    <ui:param>

    You can pass parameters to <ui:include> or <ui:composition template> by <ui:param>.

    <ui:include ...>
        <ui:param name="foo" value="#{bean.foo}" />
    </ui:include>
    
    <ui:composition template="...">
        <ui:param name="foo" value="#{bean.foo}" />
        ...
    </ui:composition >
    

    Inside the include/template file, it'll be available as #{foo}. In case you need to pass "many" parameters to <ui:include>, then you'd better consider registering the include file as a tagfile, so that you can ultimately use it like so <my:tagname foo="#{bean.foo}">. See also When to use <ui:include>, tag files, composite components and/or custom components?

    You can even pass whole beans, methods and parameters via <ui:param>. See also JSF 2: how to pass an action including an argument to be invoked to a Facelets sub view (using ui:include and ui:param)?


    Design hints

    The files which aren't supposed to be publicly accessible by just entering/guessing its URL, need to be placed in /WEB-INF folder, like as the include file and the template file in above example. See also Which XHTML files do I need to put in /WEB-INF and which not?

    There doesn't need to be any markup (HTML code) outside <ui:composition> and <ui:define>. You can put any, but they will be ignored by Facelets. Putting markup in there is only useful for web designers. See also Is there a way to run a JSF page without building the whole project?

    The HTML5 doctype is the recommended doctype these days, "in spite of" that it's a XHTML file. You should see XHTML as a language which allows you to produce HTML output using a XML based tool. See also Is it possible to use JSF+Facelets with HTML 4/5? and JavaServer Faces 2.2 and HTML5 support, why is XHTML still being used.

    CSS/JS/image files can be included as dynamically relocatable/localized/versioned resources. See also How to reference CSS / JS / image resource in Facelets template?

    You can put Facelets files in a reusable JAR file. See also Structure for multiple JSF projects with shared code.

    For real world examples of advanced Facelets templating, check the src/main/webapp folder of Java EE Kickoff App source code and OmniFaces showcase site source code.

    Lining up labels with radio buttons in bootstrap

    This is all nicely lined up including the field label. Lining up the field label was the tricky part.

    enter image description here

    HTML Code:

    <div class="form-group">
        <label class="control-label col-md-5">Create a</label>
        <div class="col-md-7">
            <label class="radio-inline control-label">
                <input checked="checked" id="TaskLog_TaskTypeId" name="TaskLog.TaskTypeId" type="radio" value="2"> Task
            </label>
            <label class="radio-inline control-label">
                <input id="TaskLog_TaskTypeId" name="TaskLog.TaskTypeId" type="radio" value="1"> Note
            </label>
        </div>
    </div>
    

    CSHTML / Razor Code:

    <div class="form-group">
        @Html.Label("Create a", htmlAttributes: new { @class = "control-label col-md-5" })
        <div class="col-md-7">
            <label class="radio-inline control-label">
                @Html.RadioButtonFor(model => model.TaskTypeId, Model.TaskTaskTypeId) Task
            </label>
            <label class="radio-inline control-label">
                @Html.RadioButtonFor(model => model.TaskTypeId, Model.NoteTaskTypeId) Note
            </label>
        </div>
    </div>
    

    Set initial focus in an Android application

    @Someone Somewhere, I tried all of the above to no avail. The fix I found is from http://www.helloandroid.com/tutorials/remove-autofocus-edittext-android . Basically, you need to create an invisible layout just above the problematic Button:

    <LinearLayout android:focusable="true"
                  android:focusableInTouchMode="true" 
                  android:layout_width="0px"
                  android:layout_height="0px" >
        <requestFocus />
    </LinearLayout>
    

    How to preview an image before and after upload?

    meVeekay's answer was good and am just making it more improvised by doing 2 things.

    1. Check whether browser supports HTML5 FileReader() or not.

    2. Allow only image file to be upload by checking its extension.

    HTML :

    <div id="wrapper">
        <input id="fileUpload" type="file" />
        <br />
        <div id="image-holder"></div>
    </div> 
    

    jQuery :

    $("#fileUpload").on('change', function () {
    
        var imgPath = $(this)[0].value;
        var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
    
        if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
            if (typeof (FileReader) != "undefined") {
    
                var image_holder = $("#image-holder");
                image_holder.empty();
    
                var reader = new FileReader();
                reader.onload = function (e) {
                    $("<img />", {
                        "src": e.target.result,
                            "class": "thumb-image"
                    }).appendTo(image_holder);
    
                }
                image_holder.show();
                reader.readAsDataURL($(this)[0].files[0]);
            } else {
                alert("This browser does not support FileReader.");
            }
        } else {
            alert("Pls select only images");
        }
    });
    

    For detail understanding of FileReader()

    Check this Article : Using FileReader() preview image before uploading.

    "Cannot update paths and switch to branch at the same time"

    This simple thing worked for me!

    If it says it can't do 2 things at same time, separate them.

    git branch branch_name origin/branch_name 
    
    git checkout branch_name
    

    Correct way to integrate jQuery plugins in AngularJS

    i have alreay 2 situations where directives and services/factories didnt play well.

    the scenario is that i have (had) a directive that has dependency injection of a service, and from the directive i ask the service to make an ajax call (with $http).

    in the end, in both cases the ng-Repeat did not file at all, even when i gave the array an initial value.

    i even tried to make a directive with a controller and an isolated-scope

    only when i moved everything to a controller and it worked like magic.

    example about this here Initialising jQuery plugin (RoyalSlider) in Angular JS

    SQL - Rounding off to 2 decimal places

    DECLARE @porcentaje FLOAT
    
    SET @porcentaje = (CONVERT(DECIMAL,ABS(8700)) * 100) / CONVERT(DECIMAL,ABS(37020))
    
    SELECT @porcentaje
    

    Finding longest string in array

    If your string is already split into an array, you'll not need the split part.

    function findLongestWord(str) {
      str = str.split(' ');
      var longest = 0;
    
      for(var i = 0; i < str.length; i++) {
         if(str[i].length >= longest) {
           longest = str[i].length;
            } 
         }
      return longest;
    }
    findLongestWord("The quick brown fox jumped over the lazy dog");
    

    CSS Disabled scrolling

    Try using the following code snippet. This should solve your issue.

    body, html { 
        overflow-x: hidden; 
        overflow-y: auto;
    }
    

    How do I deserialize a complex JSON object in C# .NET?

    First install newtonsoft.json package to Visual Studio using NuGet Package Manager then add the following code:

    ClassName ObjectName = JsonConvert.DeserializeObject < ClassName > (jsonObject);
    

    How can I trigger a Bootstrap modal programmatically?

    You should't write data-toggle="modal" in the element which triggered the modal (like a button), and you manually can show the modal with:

    $('#myModal').modal('show');
    

    and hide with:

    $('#myModal').modal('hide');
    

    Correct way to initialize HashMap and can HashMap hold different value types?

    The 2nd one is using generics which came in with Java 1.5. It will reduce the number of casts in your code & can help you catch errors at compiletime instead of runtime. That said, it depends on what you are coding. A quick & dirty map to hold a few objects of various types doesn't need generics. But if the map is holding objects all descending from a type other than Object, it can be worth it.

    The prior poster is incorrect about the array in a map. An array is actually an object, so it is a valid value.

    Map<String,Object> map = new HashMap<String,Object>();
    map.put("one",1); // autoboxed to an object
    map.put("two", new int[]{1,2} ); // array of ints is an object
    map.put("three","hello"); // string is an object
    

    Also, since HashMap is an object, it can also be a value in a HashMap.

    com.google.android.gms:play-services-measurement-base is being requested by various other libraries

    Only solution that work for me (found some where in SOF)(don't have the link) is :

    in top main build.grale

    allprojects {
    
    subprojects {
        project.configurations.all {
            resolutionStrategy.eachDependency { details ->
                if (details.requested.group == 'com.google.android.gms'
                        && !details.requested.name.contains('multidex')) {
                    details.useVersion "x.y.z"
                }
            }
        }
    }
    

    Error - is not marked as serializable

    You need to add a Serializable attribute to the class which you want to serialize.

    [Serializable]
    public class OrgPermission
    

    How to remove an id attribute from a div using jQuery?

    I'm not sure what jQuery api you're looking at, but you should only have to specify id.

    $('#thumb').removeAttr('id');
    

    Converting an integer to a string in PHP

    You can either use the period operator and concatenate a string to it (and it will be type casted to a string):

    $integer = 93;
    $stringedInt = $integer . "";
    

    Or, more correctly, you can just type cast the integer to a string:

    $integer = 93;
    $stringedInt = (string) $integer;
    

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

    You can use String.Format function to add second class based on condition:

    <div class="@String.Format("details {0}", Details.Count > 0 ? "show" : "hide")">
    

    How can foreign key constraints be temporarily disabled using T-SQL?

    You can temporarily disable constraints on your tables, do work, then rebuild them.

    Here is an easy way to do it...

    Disable all indexes, including the primary keys, which will disable all foreign keys, then re-enable just the primary keys so you can work with them...

    DECLARE @sql AS NVARCHAR(max)=''
    select @sql = @sql +
        'ALTER INDEX ALL ON [' + t.[name] + '] DISABLE;'+CHAR(13)
    from  
        sys.tables t
    where type='u'
    
    select @sql = @sql +
        'ALTER INDEX ' + i.[name] + ' ON [' + t.[name] + '] REBUILD;'+CHAR(13)
    from  
        sys.key_constraints i
    join
        sys.tables t on i.parent_object_id=t.object_id
    where
        i.type='PK'
    
    
    exec dbo.sp_executesql @sql;
    go
    

    [Do something, like loading data]

    Then re-enable and rebuild the indexes...

    DECLARE @sql AS NVARCHAR(max)=''
    select @sql = @sql +
        'ALTER INDEX ALL ON [' + t.[name] + '] REBUILD;'+CHAR(13)
    from  
        sys.tables t
    where type='u'
    
    exec dbo.sp_executesql @sql;
    go
    

    SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?

    Here is a simple example for others visiting this old post, but is confused by the example in the question and the other answer:

    Delivery -> Package (One -> Many)

    CREATE TABLE Delivery(
        Id INT IDENTITY PRIMARY KEY,
        NoteNumber NVARCHAR(255) NOT NULL
    )
    
    CREATE TABLE Package(
        Id INT IDENTITY PRIMARY KEY,
        Status INT NOT NULL DEFAULT 0,
        Delivery_Id INT NOT NULL,
        CONSTRAINT FK_Package_Delivery_Id FOREIGN KEY (Delivery_Id) REFERENCES Delivery (Id) ON DELETE CASCADE
    )
    

    The entry with the foreign key Delivery_Id (Package) is deleted with the referenced entity in the FK relationship (Delivery).

    So when a Delivery is deleted the Packages referencing it will also be deleted. If a Package is deleted nothing happens to any deliveries.

    Removing space from dataframe columns in pandas

    • To remove white spaces:

    1) To remove white space everywhere:

    df.columns = df.columns.str.replace(' ', '')
    

    2) To remove white space at the beginning of string:

    df.columns = df.columns.str.lstrip()
    

    3) To remove white space at the end of string:

    df.columns = df.columns.str.rstrip()
    

    4) To remove white space at both ends:

    df.columns = df.columns.str.strip()
    
    • To replace white spaces with other characters (underscore for instance):

    5) To replace white space everywhere

    df.columns = df.columns.str.replace(' ', '_')
    

    6) To replace white space at the beginning:

    df.columns = df.columns.str.replace('^ +', '_')
    

    7) To replace white space at the end:

    df.columns = df.columns.str.replace(' +$', '_')
    

    8) To replace white space at both ends:

    df.columns = df.columns.str.replace('^ +| +$', '_')
    

    All above applies to a specific column as well, assume you have a column named col, then just do:

    df[col] = df[col].str.strip()  # or .replace as above
    

    How to check python anaconda version installed on Windows 10 PC?

    The folder containing your Anaconda installation contains a subfolder called conda-meta with json files for all installed packages, including one for Anaconda itself. Look for anaconda-<version>-<build>.json.

    My file is called anaconda-5.0.1-py27hdb50712_1.json, and at the bottom is more info about the version:

    "installed_by": "Anaconda2-5.0.1-Windows-x86_64.exe", 
    "link": { "source": "C:\\ProgramData\\Anaconda2\\pkgs\\anaconda-5.0.1-py27hdb50712_1" }, 
    "name": "anaconda", 
    "platform": "win", 
    "subdir": "win-64", 
    "url": "https://repo.continuum.io/pkgs/main/win-64/anaconda-5.0.1-py27hdb50712_1.tar.bz2", 
    "version": "5.0.1"
    

    (Slightly edited for brevity.)

    The output from conda -V is the conda version.

    How can I capture packets in Android?

    It's probably worth mentioning that for http/https some people proxy their browser traffic through Burp/ZAP or another intercepting "attack proxy". A thread that covers options for this on Android devices can be found here: https://android.stackexchange.com/questions/32366/which-browser-does-support-proxies

    Material UI and Grid system

    I hope this is not too late to give a response.

    I was also looking for a simple, robust, flexible and highly customizable bootstrap like react grid system to use in my projects.

    The best I know of is react-pure-grid https://www.npmjs.com/package/react-pure-grid

    react-pure-grid gives you the power to customize every aspect of your grid system, while at the same time it has built in defaults which probably suits any project

    Usage

    npm install react-pure-grid --save
    

    -

    import {Container, Row, Col} from 'react-pure-grid';
    
    const App = () => (
          <Container>
            <Row>
              <Col xs={6} md={4} lg={3}>Hello, world!</Col>
            </Row>
            <Row>
                <Col xsOffset={5} xs={7}>Welcome!</Col>
            </Row>
          </Container>
    );
    

    Combine [NgStyle] With Condition (if..else)

    I have used the below code in my existing project

    <div class="form-group" [ngStyle]="{'border':isSubmitted && form_data.controls.first_name.errors?'1px solid red':'' }">
    </div>
    

    Can grep show only words that match search pattern?

    ripgrep

    Here are the example using ripgrep:

    rg -o "(\w+)?th(\w+)?"
    

    It'll match all words matching th.

    Correct way to work with vector of arrays

    There is no error in the following piece of code:

    float arr[4];
    arr[0] = 6.28;
    arr[1] = 2.50;
    arr[2] = 9.73;
    arr[3] = 4.364;
    std::vector<float*> vec = std::vector<float*>();
    vec.push_back(arr);
    float* ptr = vec.front();
    for (int i = 0; i < 3; i++)
        printf("%g\n", ptr[i]);
    

    OUTPUT IS:

    6.28

    2.5

    9.73

    4.364

    IN CONCLUSION:

    std::vector<double*>
    

    is another possibility apart from

    std::vector<std::array<double, 4>>
    

    that James McNellis suggested.

    How to round to 2 decimals with Python?

    You can use the round function, which takes as its first argument the number and the second argument is the precision after the decimal point.

    In your case, it would be:

    answer = str(round(answer, 2))
    

    How to get the date 7 days earlier date from current date in Java

    Use the Calendar-API:

    // get Calendar instance
    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    
    // substract 7 days
    // If we give 7 there it will give 8 days back
    cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)-6);
    
    // convert to date
    Date myDate = cal.getTime();
    

    Hope this helps. Have Fun!

    ORA-01036: illegal variable name/number when running query through C#

    The Oracle error ORA-01036 means that the query uses an undefined variable somewhere. From the query we can determine which variables are in use, namely all that start with @. However, if you're inputting this into an advanced query, it's important to confirm that all variables have a matching input parameter, including the same case as in the variable name, if your Oracle database is Case Sensitive.

    Selecting distinct values from a JSON

    This is a great spot for a reduce

    var uniqueArray = o.DATA.reduce(function (a, d) {
           if (a.indexOf(d.name) === -1) {
             a.push(d.name);
           }
           return a;
        }, []);
    

    How to compare two NSDates: Which is more recent?

    Let's assume two dates:

    NSDate *date1;
    NSDate *date2;
    

    Then the following comparison will tell which is earlier/later/same:

    if ([date1 compare:date2] == NSOrderedDescending) {
        NSLog(@"date1 is later than date2");
    } else if ([date1 compare:date2] == NSOrderedAscending) {
        NSLog(@"date1 is earlier than date2");
    } else {
        NSLog(@"dates are the same");
    }
    

    Please refer to the NSDate class documentation for more details.

    Passing a method parameter using Task.Factory.StartNew

    Construct the first parameter as an instance of Action, e.g.

    var inputID = 123;
    var col = new BlockingDataCollection();
    var task = Task.Factory.StartNew(
        () => CheckFiles(inputID, col),
        cancelCheckFile.Token,
        TaskCreationOptions.LongRunning,
        TaskScheduler.Default);
    

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

    kubectl describe pods <name of pod> will give you some information including the IP

    Retina displays, high-res background images

    Here's a solution that also includes High(er)DPI (MDPI) devices > ~160 dots per inch like quite a few non-iOS Devices (f.e.: Google Nexus 7 2012):

    .box {
        background: url( 'img/box-bg.png' ) no-repeat top left;
        width: 200px;
        height: 200px;
    }
    @media only screen and ( -webkit-min-device-pixel-ratio: 1.3 ),
           only screen and (    min--moz-device-pixel-ratio: 1.3 ),
           only screen and (      -o-min-device-pixel-ratio: 2.6/2 ), /* returns 1.3, see Dev.Opera */
           only screen and (         min-device-pixel-ratio: 1.3 ),
           only screen and ( min-resolution: 124.8dpi ),
           only screen and ( min-resolution: 1.3dppx ) {
    
           .box {
               background: url( 'img/[email protected]' ) no-repeat top left / 200px 200px;
           }
    
    }
    

    As @3rror404 included in his edit after receiving feedback from the comments, there's a world beyond Webkit/iPhone. One thing that bugs me with most solutions around so far like the one referenced as source above at CSS-Tricks, is that this isn't taken fully into account.
    The original source went already further.

    As an example the Nexus 7 (2012) screen is a TVDPI screen with a weird device-pixel-ratio of 1.325. When loading the images with normal resolution they are upscaled via interpolation and therefore blurry. For me applying this rule in the media query to include those devices succeeded in best customer feedback.

    JWT refresh token flow

    Based in this implementation with Node.js of JWT with refresh token:

    1) In this case they use a uid and it's not a JWT. When they refresh the token they send the refresh token and the user. If you implement it as a JWT, you don't need to send the user, because it would inside the JWT.

    2) They implement this in a separated document (table). It has sense to me because a user can be logged in in different client applications and it could have a refresh token by app. If the user lose a device with one app installed, the refresh token of that device could be invalidated without affecting the other logged in devices.

    3) In this implementation it response to the log in method with both, access token and refresh token. It seams correct to me.

    How to iterate (keys, values) in JavaScript?

    using swagger-ui.js

    you can do this -

    _.forEach({ 'a': 1, 'b': 2 }, function(n, key) {
        console.log(n, key);
     });
    

    How to find if directory exists in Python

    We can check with 2 built in functions

    os.path.isdir("directory")
    

    It will give boolean true the specified directory is available.

    os.path.exists("directoryorfile")
    

    It will give boolead true if specified directory or file is available.

    To check whether the path is directory;

    os.path.isdir("directorypath")

    will give boolean true if the path is directory

    Get protocol + host name from URL

    Here is a slightly improved version:

    urls = [
        "http://stackoverflow.com:8080/some/folder?test=/questions/9626535/get-domain-name-from-url",
        "Stackoverflow.com:8080/some/folder?test=/questions/9626535/get-domain-name-from-url",
        "http://stackoverflow.com/some/folder?test=/questions/9626535/get-domain-name-from-url",
        "https://StackOverflow.com:8080?test=/questions/9626535/get-domain-name-from-url",
        "stackoverflow.com?test=questions&v=get-domain-name-from-url"]
    for url in urls:
        spltAr = url.split("://");
        i = (0,1)[len(spltAr)>1];
        dm = spltAr[i].split("?")[0].split('/')[0].split(':')[0].lower();
        print dm
    

    Output

    stackoverflow.com
    stackoverflow.com
    stackoverflow.com
    stackoverflow.com
    stackoverflow.com
    

    Fiddle: https://pyfiddle.io/fiddle/23e4976e-88d2-4757-993e-532aa41b7bf0/?i=true

    How to call javascript function on page load in asp.net

    <html>
    <head>
    <script type="text/javascript">
    function GetTimeZoneOffset() {
        var d = new Date()
        var gmtOffSet = -d.getTimezoneOffset();
        var gmtHours = Math.floor(gmtOffSet / 60);
        var GMTMin = Math.abs(gmtOffSet % 60);
        var dot = ".";
        var retVal = "" + gmtHours + dot + GMTMin;
        document.getElementById('<%= offSet.ClientID%>').value = retVal;
    }
    
    </script>
    </head>
    <body onload="GetTimeZoneOffset()">
        <asp:HiddenField ID="clientDateTime" runat="server" />
        <asp:HiddenField ID="offSet" runat="server" />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </body>
    </html>
    

    key point to notice here is,body has an attribute onload. Just give it a function name and that function will be called on page load.


    Alternatively, you can also call the function on page load event like this

    <html>
    <head>
    <script type="text/javascript">
    
    window.onload = load();
    
    function load() {
        var d = new Date()
        var gmtOffSet = -d.getTimezoneOffset();
        var gmtHours = Math.floor(gmtOffSet / 60);
        var GMTMin = Math.abs(gmtOffSet % 60);
        var dot = ".";
        var retVal = "" + gmtHours + dot + GMTMin;
        document.getElementById('<%= offSet.ClientID%>').value = retVal;
    }
    
    </script>
    </head>
    <body >
        <asp:HiddenField ID="clientDateTime" runat="server" />
        <asp:HiddenField ID="offSet" runat="server" />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></body>
    </body>
    </html>
    

    How to get twitter bootstrap modal to close (after initial launch)

    If you have few modal shown simultaneously you can specify target modal for in-modal button with attributes data-toggle and data-target:

    <div class="modal fade in" id="sendMessageModal" tabindex="-1" role="dialog" aria-hidden="true">
          <div class="modal-dialog modal-sm">
               <div class="modal-content">
                    <div class="modal-header text-center">
                         <h4 class="modal-title">Modal Title</h4>
                         <small>Modal Subtitle</small>
                    </div>
                    <div class="modal-body">
                         <p>Modal content text</p>
                    </div>
                    <div class="modal-footer">
                         <button type="button" class="btn btn-default pull-left" data-toggle="modal" data-target="#sendMessageModal">Close</button>
                         <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#sendMessageModal">Send</button>
                    </div>
               </div>
          </div>
     </div>
    

    Somewhere outside the modal code you can have another toggle button:

    <a href="index.html#" class="btn btn-default btn-xs" data-toggle="modal" data-target="#sendMessageModal">Resend Message</a>
    

    User can't click in-modal toggle button while these button hidden and it correct works with option "modal" for attribute data-toggle. This scheme works automagicaly!

    Drop all the tables, stored procedures, triggers, constraints and all the dependencies in one sql statement

    Seems like a rather dangerous feature to me. If you'd implement something like this I would make sure to properly secure it in a way you won't be able to run this per accident.

    As suggested before you could make some sort of stored procedure yourself. In SQL Server 2005 you could have a look this system table to determine and find the objects you would like to drop.

    select * from sys.objects
    

    Boolean Field in Oracle

    Oracle itself uses Y/N for Boolean values. For completeness it should be noted that pl/sql has a boolean type, it is only tables that do not.

    If you are using the field to indicate whether the record needs to be processed or not you might consider using Y and NULL as the values. This makes for a very small (read fast) index that takes very little space.

    C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send

    Your project supports .Net Framework 4.0 and .Net Framework 4.5. If you have upgrade issues

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    

    instead of can use;

    ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
    

    How do I find the index of a character in a string in Ruby?

    index(substring [, offset]) ? fixnum or nil
    index(regexp [, offset]) ? fixnum or nil
    

    Returns the index of the first occurrence of the given substring or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search.

    "hello".index('e')             #=> 1
    "hello".index('lo')            #=> 3
    "hello".index('a')             #=> nil
    "hello".index(?e)              #=> 1
    "hello".index(/[aeiou]/, -3)   #=> 4
    

    Check out ruby documents for more information.

    What is the difference between dynamic programming and greedy approach?

    With the reference of Biswajit Roy: Dynamic Programming firstly plans then Go. and Greedy algorithm uses greedy choice, it firstly Go then continuously Plans.

    How to see log files in MySQL?

    In my (I have LAMP installed) /etc/mysql/my.cnf file I found following, commented lines in [mysqld] section:

    general_log_file        = /var/log/mysql/mysql.log
    general_log             = 1
    

    I had to open this file as superuser, with terminal:

    sudo geany /etc/mysql/my.cnf
    

    (I prefer to use Geany instead of gedit or VI, it doesn't matter)

    I just uncommented them & save the file then restart MySQL with

    sudo service MySQL restart
    

    Run several queries, open the above file (/var/log/mysql/mysql.log) and the log was there :)

    CAST DECIMAL to INT

    There's also ROUND() if your numbers don't necessarily always end with .00. ROUND(20.6) will give 21, and ROUND(20.4) will give 20.

    Setting up a JavaScript variable from Spring model by using Thymeleaf

    If you need to display your variable unescaped, use this format:

    <script th:inline="javascript">
    /*<![CDATA[*/
    
        var message = /*[(${message})]*/ 'default';
    
    /*]]>*/
    </script>
    

    Note the [( brackets which wrap the variable.

    MySQL Nested Select Query?

    You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t below) and alias the columns as well.

    The DISTINCT can also be safely removed as the internal GROUP BY makes it redundant:

    SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
    FROM (
        SELECT MIN(`date`) AS `date`, `player_name`
        FROM `player_playtime`
        GROUP BY `player_name`
    ) AS t
    GROUP BY DATE( `date`) DESC LIMIT 60 ;
    

    Since the COUNT is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*) and further simplify the query:

    SELECT t.date , COUNT(*) AS player_count
    FROM (
        SELECT DATE(MIN(`date`)) AS date
        FROM player_playtime
        GROUP BY player_name
    ) AS t
    GROUP BY t.date DESC LIMIT 60 ;
    

    check if a file is open in Python

    If all you care about is the current process, an easy way is to use the file object attribute "closed"

    f = open('file.py')
    if f.closed:
      print 'file is closed'
    

    This will not detect if the file is open by other processes!

    source: http://docs.python.org/2.4/lib/bltin-file-objects.html

    I am not able launch JNLP applications using "Java Web Start"?

    In my case, Netbeans automatically creates a .jnlp file that doesn't work and my problem was due to an accidental overwriting of the launch.jnlp file on the server (by the inadequate and incorrect version from Netbeans). This caused a mismatch between the local .jnlp file and the remote .jnlp file, resulting in Java Web Start just quitting after "Verifying application."

    So no one else has to waste an hour finding a bug that should be communicated adequately (but isn't) by Java WS.

    Get URL query string parameters

    Here is my function to rebuild parts of the REFERRER's query string.

    If the calling page already had a query string in its own URL, and you must go back to that page and want to send back some, not all, of that $_GET vars (e.g. a page number).

    Example: Referrer's query string was ?foo=1&bar=2&baz=3 calling refererQueryString( 'foo' , 'baz' ) returns foo=1&baz=3":

    function refererQueryString(/* var args */) {
    
        //Return empty string if no referer or no $_GET vars in referer available:
        if (!isset($_SERVER['HTTP_REFERER']) ||
            empty( $_SERVER['HTTP_REFERER']) ||
            empty(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY ))) {
    
            return '';
        }
    
        //Get URL query of referer (something like "threadID=7&page=8")
        $refererQueryString = parse_url(urldecode($_SERVER['HTTP_REFERER']), PHP_URL_QUERY);
    
        //Which values do you want to extract? (You passed their names as variables.)
        $args = func_get_args();
    
        //Get '[key=name]' strings out of referer's URL:
        $pairs = explode('&',$refererQueryString);
    
        //String you will return later:
        $return = '';
    
        //Analyze retrieved strings and look for the ones of interest:
        foreach ($pairs as $pair) {
            $keyVal = explode('=',$pair);
            $key = &$keyVal[0];
            $val = urlencode($keyVal[1]);
            //If you passed the name as arg, attach current pair to return string:
            if(in_array($key,$args)) {
                $return .= '&'. $key . '=' .$val;
            }
        }
    
        //Here are your returned 'key=value' pairs glued together with "&":
        return ltrim($return,'&');
    }
    
    //If your referer was 'page.php?foo=1&bar=2&baz=3'
    //and you want to header() back to 'page.php?foo=1&baz=3'
    //(no 'bar', only foo and baz), then apply:
    
    header('Location: page.php?'.refererQueryString('foo','baz'));
    

    Android EditText Max Length

    If you want to see a counter label you can use app:counterEnabled and android:maxLength, like:

    <android.support.design.widget.TextInputLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      app:counterEnabled="true">
    
      <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:maxLength="420" />
    
    </android.support.design.widget.TextInputLayout>
    

    DO NOT set app:counterMaxLength on TextInputLayout because it will conflict with android:maxLength resulting into the issue of invisible chars after the text hits the size limit.

    how to loop through each row of dataFrame in pyspark

    above

    tupleList = [{name:x["name"], age:x["age"], city:x["city"]} 
    

    should be

    tupleList = [{'name':x["name"], 'age':x["age"], 'city':x["city"]} 
    

    for name, age, and city are not variables but simply keys of the dictionary.

    Adding asterisk to required fields in Bootstrap 3

    This CSS worked for me:

    .form-group.required.control-label:before{
       color: red;
       content: "*";
       position: absolute;
       margin-left: -10px;
    }
    

    and this HTML:

    <div class="form-group required control-label">
      <label for="emailField">Email</label>
      <input type="email" class="form-control" id="emailField" placeholder="Type Your Email Address Here" />
    </div>
    

    Return Bit Value as 1/0 and NOT True/False in SQL Server

    This can be changed to 0/1 through using CASE WHEN like this example:

    SELECT 
     CASE WHEN SchemaName.TableName.BitFieldName = 'true' THEN 1 ELSE 0 END AS 'bit Value' 
     FROM SchemaName.TableName
    

    Convert list of dictionaries to a pandas DataFrame

    The easiest way I have found to do it is like this:

    dict_count = len(dict_list)
    df = pd.DataFrame(dict_list[0], index=[0])
    for i in range(1,dict_count-1):
        df = df.append(dict_list[i], ignore_index=True)
    

    How can I remove file extension from a website address?

    You have different choices. One on them is creating a folder named "profile" and rename your "profile.php" to "default.php" and put it into "profile" folder. and you can give orders to this page in this way:

    Old page: http://something.com/profile.php?id=a&abc=1

    New page: http://something.com/profile/?id=a&abc=1

    If you are not satisfied leave a comment for complicated methods.

    How to connect to a docker container from outside the host (same network) [Windows]

    TL;DR Check the network mode of your VirtualBox host - it should be bridged if you want the virtual machine (and the Docker container it's hosting) accessible on your local network.


    It sounds like your confusion lies in which host to connect to in order to access your application via HTTP. You haven't really spelled out what your configuration is - I'm going to make some guesses, based on the fact that you've got "Windows" and "VirtualBox" in your tags.

    I'm guessing that you have Docker running on some flavour of Linux running in VirtualBox on a Windows host. I'm going to label the IP addresses as follows:

    D = the IP address of the Docker container

    L = the IP address of the Linux host running in VirtualBox

    W = the IP address of the Windows host

    When you run your Go application on your Windows host, you can connect to it with http://W:8080/ from anywhere on your local network. This works because the Go application binds the port 8080 on the Windows machine and anybody who tries to access port 8080 at the IP address W will get connected.

    And here's where it becomes more complicated:

    VirtualBox, when it sets up a virtual machine (VM), can configure the network in one of several different modes. I don't remember what all the different options are, but the one you want is bridged. In this mode, VirtualBox connects the virtual machine to your local network as if it were a stand-alone machine on the network, just like any other machine that was plugged in to your network. In bridged mode, the virtual machine appears on your network like any other machine. Other modes set things up differently and the machine will not be visible on your network.

    So, assuming you set up networking correctly for the Linux host (bridged), the Linux host will have an IP address on your local network (something like 192.168.0.x) and you will be able to access your Docker container at http://L:8080/.

    If the Linux host is set to some mode other than bridged, you might be able to access from the Windows host, but this is going to depend on exactly what mode it's in.

    EDIT - based on the comments below, it sounds very much like the situation I've described above is correct.

    Let's back up a little: here's how Docker works on my computer (Ubuntu Linux).

    Imagine I run the same command you have: docker run -p 8080:8080 dockertest. What this does is start a new container based on the dockertest image and forward (connect) port 8080 on the Linux host (my PC) to port 8080 on the container. Docker sets up it's own internal networking (with its own set of IP addresses) to allow the Docker daemon to communicate and to allow containers to communicate with one another. So basically what you're doing with that -p 8080:8080 is connecting Docker's internal networking with the "external" network - ie. the host's network adapter - on a particular port.

    With me so far? OK, now let's take a step back and look at your system. Your machine is running Windows - Docker does not (currently) run on Windows, so the tool you're using has set up a Linux host in a VirtualBox virtual machine. When you do the docker run in your environment, exactly the same thing is happening - port 8080 on the Linux host is connected to port 8080 on the container. The big difference here is that your Windows host is not the Linux host on which the container is running, so there's another layer here and it's communication across this layer where you are running into problems.

    What you need is one of two things:

    1. to connect port 8080 on the VirtualBox VM to port 8080 on the Windows host, just like you connect the Docker container to the host port.

    2. to connect the VirtualBox VM directly to your local network with the bridged network mode I described above.

    If you go for the first option, you will be able to access the container at http://W:8080 where W is the IP address or hostname of the Windows host. If you opt for the second, you will be able to access the container at http://L:8080 where L is the IP address or hostname of the Linux VM.

    So that's all the higher-level explanation - now you need to figure out how to change the configuration of the VirtualBox VM. And here's where I can't really help you - I don't know what tool you're using to do all this on your Windows machine and I'm not at all familiar with using Docker on Windows.

    If you can get to the VirtualBox configuration window, you can make the changes described below. There is also a command line client that will modify VMs, but I'm not familiar with that.

    For bridged mode (and this really is the simplest choice), shut down your VM, click the "Settings" button at the top, and change the network mode to bridged, then restart the VM and you're good to go. The VM should pick up an IP address on your local network via DHCP and should be visible to other computers on the network at that IP address.

    Content-Disposition:What are the differences between "inline" and "attachment"?

    Because when I use one or another I get a window prompt asking me to download the file for both of them.

    This behavior depends on the browser and the file you are trying to serve. With inline, the browser will try to open the file within the browser.

    For example, if you have a PDF file and Firefox/Adobe Reader, an inline disposition will open the PDF within Firefox, whereas attachment will force it to download.

    If you're serving a .ZIP file, browsers won't be able to display it inline, so for inline and attachment dispositions, the file will be downloaded.

    Git add all files modified, deleted, and untracked?

    I authored the G2 project, a friendly environment for the command line git lover.
    Please get the project from github - G2 https://github.com/orefalo/g2

    It has a bunch of handy commands, one of them being exactly what your are looking for: freeze

    freeze - Freeze all files in the repository (additions, deletions, modifications) to the staging area, thus staging that content for inclusion in the next commit. Also accept a specific path as parameter

    JavaScript ES6 promise for loop

    Based on the excellent answer by trincot, I wrote a reusable function that accepts a handler to run over each item in an array. The function itself returns a promise that allows you to wait until the loop has finished and the handler function that you pass may also return a promise.

    loop(items, handler) : Promise

    It took me some time to get it right, but I believe the following code will be usable in a lot of promise-looping situations.

    Copy-paste ready code:

    // SEE https://stackoverflow.com/a/46295049/286685
    const loop = (arr, fn, busy, err, i=0) => {
      const body = (ok,er) => {
        try {const r = fn(arr[i], i, arr); r && r.then ? r.then(ok).catch(er) : ok(r)}
        catch(e) {er(e)}
      }
      const next = (ok,er) => () => loop(arr, fn, ok, er, ++i)
      const run  = (ok,er) => i < arr.length ? new Promise(body).then(next(ok,er)).catch(er) : ok()
      return busy ? run(busy,err) : new Promise(run)
    }
    

    Usage

    To use it, call it with the array to loop over as the first argument and the handler function as the second. Do not pass parameters for the third, fourth and fifth arguments, they are used internally.

    _x000D_
    _x000D_
    const loop = (arr, fn, busy, err, i=0) => {_x000D_
      const body = (ok,er) => {_x000D_
        try {const r = fn(arr[i], i, arr); r && r.then ? r.then(ok).catch(er) : ok(r)}_x000D_
        catch(e) {er(e)}_x000D_
      }_x000D_
      const next = (ok,er) => () => loop(arr, fn, ok, er, ++i)_x000D_
      const run  = (ok,er) => i < arr.length ? new Promise(body).then(next(ok,er)).catch(er) : ok()_x000D_
      return busy ? run(busy,err) : new Promise(run)_x000D_
    }_x000D_
    _x000D_
    const items = ['one', 'two', 'three']_x000D_
    _x000D_
    loop(items, item => {_x000D_
      console.info(item)_x000D_
    })_x000D_
    .then(() => console.info('Done!'))
    _x000D_
    _x000D_
    _x000D_

    Advanced use cases

    Let's look at the handler function, nested loops and error handling.

    handler(current, index, all)

    The handler gets passed 3 arguments. The current item, the index of the current item and the complete array being looped over. If the handler function needs to do async work, it can return a promise and the loop function will wait for the promise to resolve before starting the next iteration. You can nest loop invocations and all works as expected.

    _x000D_
    _x000D_
    const loop = (arr, fn, busy, err, i=0) => {_x000D_
      const body = (ok,er) => {_x000D_
        try {const r = fn(arr[i], i, arr); r && r.then ? r.then(ok).catch(er) : ok(r)}_x000D_
        catch(e) {er(e)}_x000D_
      }_x000D_
      const next = (ok,er) => () => loop(arr, fn, ok, er, ++i)_x000D_
      const run  = (ok,er) => i < arr.length ? new Promise(body).then(next(ok,er)).catch(er) : ok()_x000D_
      return busy ? run(busy,err) : new Promise(run)_x000D_
    }_x000D_
    _x000D_
    const tests = [_x000D_
      [],_x000D_
      ['one', 'two'],_x000D_
      ['A', 'B', 'C']_x000D_
    ]_x000D_
    _x000D_
    loop(tests, (test, idx, all) => new Promise((testNext, testFailed) => {_x000D_
      console.info('Performing test ' + idx)_x000D_
      return loop(test, (testCase) => {_x000D_
        console.info(testCase)_x000D_
      })_x000D_
      .then(testNext)_x000D_
      .catch(testFailed)_x000D_
    }))_x000D_
    .then(() => console.info('All tests done'))
    _x000D_
    _x000D_
    _x000D_

    Error handling

    Many promise-looping examples I looked at break down when an exception occurs. Getting this function to do the right thing was pretty tricky, but as far as I can tell it is working now. Make sure to add a catch handler to any inner loops and invoke the rejection function when it happens. E.g.:

    _x000D_
    _x000D_
    const loop = (arr, fn, busy, err, i=0) => {_x000D_
      const body = (ok,er) => {_x000D_
        try {const r = fn(arr[i], i, arr); r && r.then ? r.then(ok).catch(er) : ok(r)}_x000D_
        catch(e) {er(e)}_x000D_
      }_x000D_
      const next = (ok,er) => () => loop(arr, fn, ok, er, ++i)_x000D_
      const run  = (ok,er) => i < arr.length ? new Promise(body).then(next(ok,er)).catch(er) : ok()_x000D_
      return busy ? run(busy,err) : new Promise(run)_x000D_
    }_x000D_
    _x000D_
    const tests = [_x000D_
      [],_x000D_
      ['one', 'two'],_x000D_
      ['A', 'B', 'C']_x000D_
    ]_x000D_
    _x000D_
    loop(tests, (test, idx, all) => new Promise((testNext, testFailed) => {_x000D_
      console.info('Performing test ' + idx)_x000D_
      loop(test, (testCase) => {_x000D_
        if (idx == 2) throw new Error()_x000D_
        console.info(testCase)_x000D_
      })_x000D_
      .then(testNext)_x000D_
      .catch(testFailed)  //  <--- DON'T FORGET!!_x000D_
    }))_x000D_
    .then(() => console.error('Oops, test should have failed'))_x000D_
    .catch(e => console.info('Succesfully caught error: ', e))_x000D_
    .then(() => console.info('All tests done'))
    _x000D_
    _x000D_
    _x000D_

    UPDATE: NPM package

    Since writing this answer, I turned the above code in an NPM package.

    for-async

    Install

    npm install --save for-async
    

    Import

    var forAsync = require('for-async');  // Common JS, or
    import forAsync from 'for-async';
    

    Usage (async)

    var arr = ['some', 'cool', 'array'];
    forAsync(arr, function(item, idx){
      return new Promise(function(resolve){
        setTimeout(function(){
          console.info(item, idx);
          // Logs 3 lines: `some 0`, `cool 1`, `array 2`
          resolve(); // <-- signals that this iteration is complete
        }, 25); // delay 25 ms to make async
      })
    })
    

    See the package readme for more details.

    Which is best data type for phone number in MySQL and what should Java type mapping for it be?

    1. String
    2. Varchar

    This is my opinion for my database as recommended by my mentor

    HTML button onclick event

    You should all know this is inline scripting and is not a good practice at all...with that said you should definitively use javascript or jQuery for this type of thing:

    HTML

    <!DOCTYPE html> 
    <html> 
     <head> 
        <meta charset="ISO-8859-1"> 
        <title>Online Student Portal</title> 
     </head> 
     <body> 
        <form action="">
             <input type="button" id="myButton" value="Add"/>
        </form> 
     </body> 
    </html>
    

    JQuery

    var button_my_button = "#myButton";
    $(button_my_button).click(function(){
     window.location.href='Students.html';
    });
    

    Javascript

      //get a reference to the element
      var myBtn = document.getElementById('myButton');
    
      //add event listener
      myBtn.addEventListener('click', function(event) {
        window.location.href='Students.html';
      });
    

    See comments why avoid inline scripting and also why inline scripting is bad

    How can I find out which server hosts LDAP on my windows domain?

    AD registers Service Location (SRV) resource records in its DNS server which you can query to get the port and the hostname of the responsible LDAP server in your domain.

    Just try this on the command-line:

    C:\> nslookup 
    > set types=all
    > _ldap._tcp.<<your.AD.domain>>
    _ldap._tcp.<<your.AD.domain>>  SRV service location:
          priority       = 0
          weight         = 100
          port           = 389
          svr hostname   = <<ldap.hostname>>.<<your.AD.domain>>
    

    (provided that your nameserver is the AD nameserver which should be the case for the AD to function properly)

    Please see Active Directory SRV Records and Windows 2000 DNS white paper for more information.

    jQuery '.each' and attaching '.click' event

    No need to use .each. click already binds to all div occurrences.

    $('div').click(function(e) {
        ..    
    });
    

    See Demo

    Note: use hard binding such as .click to make sure dynamically loaded elements don't get bound.

    Handling urllib2's timeout? - Python

    There are very few cases where you want to use except:. Doing this captures any exception, which can be hard to debug, and it captures exceptions including SystemExit and KeyboardInterupt, which can make your program annoying to use..

    At the very simplest, you would catch urllib2.URLError:

    try:
        urllib2.urlopen("http://example.com", timeout = 1)
    except urllib2.URLError, e:
        raise MyException("There was an error: %r" % e)
    

    The following should capture the specific error raised when the connection times out:

    import urllib2
    import socket
    
    class MyException(Exception):
        pass
    
    try:
        urllib2.urlopen("http://example.com", timeout = 1)
    except urllib2.URLError, e:
        # For Python 2.6
        if isinstance(e.reason, socket.timeout):
            raise MyException("There was an error: %r" % e)
        else:
            # reraise the original error
            raise
    except socket.timeout, e:
        # For Python 2.7
        raise MyException("There was an error: %r" % e)
    

    MySQL Insert query doesn't work with WHERE clause

    Insert into = Adding rows to a table

    Upate = update specific rows.

    What would the where clause describe in your insert? It doesn't have anything to match, the row doesn't exist (yet)...

    Python: 'ModuleNotFoundError' when trying to import module from imported package

    FIRST, if you want to be able to access man1.py from man1test.py AND manModules.py from man1.py, you need to properly setup your files as packages and modules.

    Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A.

    ...

    When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.

    The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

    You need to set it up to something like this:

    man
    |- __init__.py
    |- Mans
       |- __init__.py
       |- man1.py
    |- MansTest
       |- __init.__.py
       |- SoftLib
          |- Soft
             |- __init__.py
             |- SoftWork
                |- __init__.py
                |- manModules.py
          |- Unittests
             |- __init__.py
             |- man1test.py
    

    SECOND, for the "ModuleNotFoundError: No module named 'Soft'" error caused by from ...Mans import man1 in man1test.py, the documented solution to that is to add man1.py to sys.path since Mans is outside the MansTest package. See The Module Search Path from the Python documentation. But if you don't want to modify sys.path directly, you can also modify PYTHONPATH:

    sys.path is initialized from these locations:

    • The directory containing the input script (or the current directory when no file is specified).
    • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
    • The installation-dependent default.

    THIRD, for from ...MansTest.SoftLib import Soft which you said "was to facilitate the aforementioned import statement in man1.py", that's now how imports work. If you want to import Soft.SoftLib in man1.py, you have to setup man1.py to find Soft.SoftLib and import it there directly.

    With that said, here's how I got it to work.

    man1.py:

    from Soft.SoftWork.manModules import *
    # no change to import statement but need to add Soft to PYTHONPATH
    
    def foo():
        print("called foo in man1.py")
        print("foo call module1 from manModules: " + module1())
    

    man1test.py

    # no need for "from ...MansTest.SoftLib import Soft" to facilitate importing..
    from ...Mans import man1
    
    man1.foo()
    

    manModules.py

    def module1():
        return "module1 in manModules"
    

    Terminal output:

    $ python3 -m man.MansTest.Unittests.man1test
    Traceback (most recent call last):
      ...
        from ...Mans import man1
      File "/temp/man/Mans/man1.py", line 2, in <module>
        from Soft.SoftWork.manModules import *
    ModuleNotFoundError: No module named 'Soft'
    
    $ PYTHONPATH=$PYTHONPATH:/temp/man/MansTest/SoftLib
    $ export PYTHONPATH
    $ echo $PYTHONPATH
    :/temp/man/MansTest/SoftLib
    $ python3 -m man.MansTest.Unittests.man1test
    called foo in man1.py
    foo called module1 from manModules: module1 in manModules 
    

    As a suggestion, maybe re-think the purpose of those SoftLib files. Is it some sort of "bridge" between man1.py and man1test.py? The way your files are setup right now, I don't think it's going to work as you expect it to be. Also, it's a bit confusing for the code-under-test (man1.py) to be importing stuff from under the test folder (MansTest).

    Failing to run jar file from command line: “no main manifest attribute”

    The -jar option only works if the JAR file is an executable JAR file, which means it must have a manifest file with a Main-Class attribute in it.

    If it's not an executable JAR, then you'll need to run the program with something like:

    java -cp app.jar com.somepackage.SomeClass
    

    where com.somepackage.SomeClass is the class that contains the main method to run the program.

    What does it mean to have an index to scalar variable error? python

    exponent is a 1D array. This means that exponent[0] is a scalar, and exponent[0][i] is trying to access it as if it were an array.

    Did you mean to say:

    L = identity(len(l))
    for i in xrange(len(l)):
        L[i][i] = exponent[i]
    

    or even

    L = diag(exponent)
    

    ?

    How do I validate a date in rails?

    Here's a non-chronic answer..

    class Pimping < ActiveRecord::Base
    
    validate :valid_date?
    
    def valid_date?
      if scheduled_on.present?
        unless scheduled_on.is_a?(Time)
          errors.add(:scheduled_on, "Is an invalid date.")
        end
      end
    end
    

    Dealing with timestamps in R

    You want the (standard) POSIXt type from base R that can be had in 'compact form' as a POSIXct (which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt (which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)

    Quick example:

    R> now <- Sys.time()
    R> now
    [1] "2009-12-25 18:39:11 CST"
    R> as.numeric(now)
    [1] 1.262e+09
    R> now + 10  # adds 10 seconds
    [1] "2009-12-25 18:39:21 CST"
    R> as.POSIXlt(now)
    [1] "2009-12-25 18:39:11 CST"
    R> str(as.POSIXlt(now))
     POSIXlt[1:9], format: "2009-12-25 18:39:11"
    R> unclass(as.POSIXlt(now))
    $sec
    [1] 11.79
    
    $min
    [1] 39
    
    $hour
    [1] 18
    
    $mday
    [1] 25
    
    $mon
    [1] 11
    
    $year
    [1] 109
    
    $wday
    [1] 5
    
    $yday
    [1] 358
    
    $isdst
    [1] 0
    
    attr(,"tzone")
    [1] "America/Chicago" "CST"             "CDT"            
    R> 
    

    As for reading them in, see help(strptime)

    As for difference, easy too:

    R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
    R> difftime(now, Jan1, unit="week")
    Time difference of 51.25 weeks
    R> 
    

    Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.

    WiX tricks and tips

    Before deploying an install package I always control the content of it.

    It's just a simple call at the command line (according to Terrences post) open command line and enter

    msiexec /a Package.msi /qb TARGETDIR="%CD%\Extract" /l*vx "%CD\install.log%"
    

    This will extract package contents to an subdir 'Extract' with the current path.

    How to import a module given its name as string?

    For example, my module names are like jan_module/feb_module/mar_module.

    month = 'feb'
    exec 'from %s_module import *'%(month)
    

    Using Mysql in the command line in osx - command not found?

    That means /usr/local/mysql/bin/mysql is not in the PATH variable..

    Either execute /usr/local/mysql/bin/mysql to get your mysql shell,

    or type this in your terminal:

    PATH=$PATH:/usr/local/mysql/bin
    

    to add that to your PATH variable so you can just run mysql without specifying the path

    Why did a network-related or instance-specific error occur while establishing a connection to SQL Server?

    I've resolved the issue. It was due to the SQL browser service.

    Solution to such problem is one among below -

    • Check the spelling of the SQL Server instance name that is specified in the connection string.

    • Use the SQL Server Surface Area Configuration tool to enable SQL Server to accept remote connections over the TCP or named pipes protocols. For more information about the SQL Server Surface Area Configuration Tool, see Surface Area Configuration for Services and Connections.

    • Make sure that you have configured the firewall on the server instance of SQL Server to open ports for SQL Server and the SQL Server Browser port (UDP 1434).

    • Make sure that the SQL Server Browser service is started on the server.

    link - http://www.microsoft.com/products/ee/transform.aspx?ProdName=Microsoft+SQL+Server&EvtSrc=MSSQLServer&EvtID=-1

    Close Bootstrap modal on form submit

    give id to submit button

    <button id="btnSave" type="submit" class="btn btn-success"><i class="glyphicon glyphicon-trash"></i> Save</button>
    
    $('#btnSave').click(function() {
       $('#StudentModal').modal('hide');
    });
    

    Also you forgot to close last div.

    </div>
    

    Hope this helps.

    What is the difference between i++ and ++i?

    The way the operator works is that it gets incremented at the same time, but if it is before a variable, the expression will evaluate with the incremented/decremented variable:

    int x = 0;   //x is 0
    int y = ++x; //x is 1 and y is 1
    

    If it is after the variable the current statement will get executed with the original variable, as if it had not yet been incremented/decremented:

    int x = 0;   //x is 0
    int y = x++; //'y = x' is evaluated with x=0, but x is still incremented. So, x is 1, but y is 0
    

    I agree with dcp in using pre-increment/decrement (++x) unless necessary. Really the only time I use the post-increment/decrement is in while loops or loops of that sort. These loops are the same:

    while (x < 5)  //evaluates conditional statement
    {
        //some code
        ++x;       //increments x
    }
    

    or

    while (x++ < 5) //evaluates conditional statement with x value before increment, and x is incremented
    {
        //some code
    }
    

    You can also do this while indexing arrays and such:

    int i = 0;
    int[] MyArray = new int[2];
    MyArray[i++] = 1234; //sets array at index 0 to '1234' and i is incremented
    MyArray[i] = 5678;   //sets array at index 1 to '5678'
    int temp = MyArray[--i]; //temp is 1234 (becasue of pre-decrement);
    

    Etc, etc...

    List of strings to one string

    My vote is string.Join

    No need for lambda evaluations and temporary functions to be created, fewer function calls, less stack pushing and popping.

    How to convert a negative number to positive?

    >>> n = -42
    >>> -n       # if you know n is negative
    42
    >>> abs(n)   # for any n
    42
    

    Don't forget to check the docs.

    PHPUnit assert that an exception was thrown?

    public function testException() {
        try {
            $this->methodThatThrowsException();
            $this->fail("Expected Exception has not been raised.");
        } catch (Exception $ex) {
            $this->assertEquals($ex->getMessage(), "Exception message");
        }
    
    }
    

    Git SSH error: "Connect to host: Bad file number"

    I just had the same problem and tried every solution that I could find, but none worked. Eventually, I tried quitting Git Bash and re-opening it, and everything worked perfectly.

    So, try quitting Git Bash and re-opening it.

    Trying to detect browser close event

    <script type="text/javascript">
    window.addEventListener("beforeunload", function (e) {
    
      var confirmationMessage = "Are you sure you want to leave this page without placing the order ?";
      (e || window.event).returnValue = confirmationMessage;
      return confirmationMessage;
    
    });
    </script>
    

    Please try this code, this is working fine for me. This custom message is coming into Chrome browser but in Mozilla this message is not showing.

    How to import RecyclerView for Android L-preview

    I used this one is working for me. One thing needs to be consider that what appcompat version you are using. I am using appcompat-v7:26.+ so this is working for me.

    implementation 'com.android.support:recyclerview-v7:26.+'
    

    javascript getting my textbox to display a variable

    _x000D_
    _x000D_
    function myfunction() {_x000D_
      var first = document.getElementById("textbox1").value;_x000D_
      var second = document.getElementById("textbox2").value;_x000D_
      var answer = parseFloat(first) + parseFloat(second);_x000D_
    _x000D_
      var textbox3 = document.getElementById('textbox3');_x000D_
      textbox3.value = answer;_x000D_
    }
    _x000D_
    <input type="text" name="textbox1" id="textbox1" /> + <input type="text" name="textbox2" id="textbox2" />_x000D_
    <input type="submit" name="button" id="button1" onclick="myfunction()" value="=" />_x000D_
    <br/> Your answer is:--_x000D_
    <input type="text" name="textbox3" id="textbox3" readonly="true" />
    _x000D_
    _x000D_
    _x000D_

    Create an array or List of all dates between two dates

    public static IEnumerable<DateTime> GetDateRange(DateTime startDate, DateTime endDate)
    {
        if (endDate < startDate)
            throw new ArgumentException("endDate must be greater than or equal to startDate");
    
        while (startDate <= endDate)
        {
            yield return startDate;
            startDate = startDate.AddDays(1);
        }
    }
    

    Why does range(start, end) not include end?

    Exclusive ranges do have some benefits:

    For one thing each item in range(0,n) is a valid index for lists of length n.

    Also range(0,n) has a length of n, not n+1 which an inclusive range would.

    How to list all the files in a commit?

    I'll just assume that gitk is not desired for this. In that case, try git show --name-only <sha>.

    SQL query to find third highest salary in company

    I found a very good explanation in

    http://www.programmerinterview.com/index.php/database-sql/find-nth-highest-salary-sql/

    This query should give nth highest salary

    SELECT *
    FROM Employee Emp1
    WHERE (N-1) = (
        SELECT COUNT(DISTINCT(Emp2.Salary))
        FROM Employee Emp2
        WHERE Emp2.Salary > Emp1.Salary)
    

    How to check if std::map contains a key without doing insert?

    Use my_map.count( key ); it can only return 0 or 1, which is essentially the Boolean result you want.

    Alternately my_map.find( key ) != my_map.end() works too.

    What does localhost:8080 mean?

    the localhost:8080 means your explicitly targeting port 8080.

    How to kill a process in MacOS?

    If you're trying to kill -9 it, you have the correct PID, and nothing happens, then you don't have permissions to kill the process.

    Solution:

    $ sudo kill -9 PID
    

    Okay, sure enough Mac OS/X does give an error message for this case:

    $ kill -9 196
    -bash: kill: (196) - Operation not permitted
    

    So, if you're not getting an error message, you somehow aren't getting the right PID.

    Dynamically updating plot in matplotlib

    Is there a way in which I can update the plot just by adding more point[s] to it...

    There are a number of ways of animating data in matplotlib, depending on the version you have. Have you seen the matplotlib cookbook examples? Also, check out the more modern animation examples in the matplotlib documentation. Finally, the animation API defines a function FuncAnimation which animates a function in time. This function could just be the function you use to acquire your data.

    Each method basically sets the data property of the object being drawn, so doesn't require clearing the screen or figure. The data property can simply be extended, so you can keep the previous points and just keep adding to your line (or image or whatever you are drawing).

    Given that you say that your data arrival time is uncertain your best bet is probably just to do something like:

    import matplotlib.pyplot as plt
    import numpy
    
    hl, = plt.plot([], [])
    
    def update_line(hl, new_data):
        hl.set_xdata(numpy.append(hl.get_xdata(), new_data))
        hl.set_ydata(numpy.append(hl.get_ydata(), new_data))
        plt.draw()
    

    Then when you receive data from the serial port just call update_line.

    How to import CSV file data into a PostgreSQL table?

    Most other solutions here require that you create the table in advance/manually. This may not be practical in some cases (e.g., if you have a lot of columns in the destination table). So, the approach below may come handy.

    Providing the path and column count of your csv file, you can use the following function to load your table to a temp table that will be named as target_table:

    The top row is assumed to have the column names.

    create or replace function data.load_csv_file
    (
        target_table text,
        csv_path text,
        col_count integer
    )
    
    returns void as $$
    
    declare
    
    iter integer; -- dummy integer to iterate columns with
    col text; -- variable to keep the column name at each iteration
    col_first text; -- first column name, e.g., top left corner on a csv file or spreadsheet
    
    begin
        create table temp_table ();
    
        -- add just enough number of columns
        for iter in 1..col_count
        loop
            execute format('alter table temp_table add column col_%s text;', iter);
        end loop;
    
        -- copy the data from csv file
        execute format('copy temp_table from %L with delimiter '','' quote ''"'' csv ', csv_path);
    
        iter := 1;
        col_first := (select col_1 from temp_table limit 1);
    
        -- update the column names based on the first row which has the column names
        for col in execute format('select unnest(string_to_array(trim(temp_table::text, ''()''), '','')) from temp_table where col_1 = %L', col_first)
        loop
            execute format('alter table temp_table rename column col_%s to %s', iter, col);
            iter := iter + 1;
        end loop;
    
        -- delete the columns row
        execute format('delete from temp_table where %s = %L', col_first, col_first);
    
        -- change the temp table name to the name given as parameter, if not blank
        if length(target_table) > 0 then
            execute format('alter table temp_table rename to %I', target_table);
        end if;
    
    end;
    
    $$ language plpgsql;
    

    How do I execute a command and get the output of the command within C++ using POSIX?

    You can get the output after running a script using a pipe. We use pipes when we want the output of the child process.

    int my_func() {
        char ch;
        FILE *fpipe;
        FILE *copy_fp;
        FILE *tmp;
        char *command = (char *)"/usr/bin/my_script my_arg";
        copy_fp = fopen("/tmp/output_file_path", "w");
        fpipe = (FILE *)popen(command, "r");
        if (fpipe) {
            while ((ch = fgetc(fpipe)) != EOF) {
                fputc(ch, copy_fp);
            }
        }
        else {
            if (copy_fp) {
                fprintf(copy_fp, "Sorry there was an error opening the file");
            }
        }
        pclose(fpipe);
        fclose(copy_fp);
        return 0;
    }
    

    So here is the script, which you want to run. Put it in a command variable with the arguments your script takes (nothing if no arguments). And the file where you want to capture the output of the script, put it in copy_fp.

    So the popen runs your script and puts the output in fpipe and then you can just copy everything from that to your output file.

    In this way you can capture the outputs of child processes.

    And another process is you can directly put the > operator in the command only. So if we will put everything in a file while we run the command, you won't have to copy anything.

    In that case, there isn't any need to use pipes. You can use just system, and it will run the command and put the output in that file.

    int my_func(){
        char *command = (char *)"/usr/bin/my_script my_arg > /tmp/my_putput_file";
        system(command);
        printf("everything saved in my_output_file");
        return 0;
    }
    

    You can read YoLinux Tutorial: Fork, Exec and Process control for more information.

    Getting the difference between two sets

    Adding a solution which I've recently used myself and haven't seen mentioned here. If you have Apache Commons Collections available then you can use the SetUtils#difference method:

    // Returns all the elements of test2 which are not in test1
    SetUtils.difference(test2, test1) 
    

    Note that according to the documentation the returned set is an unmodifiable view:

    Returns a unmodifiable view containing the difference of the given Sets, denoted by a \ b (or a - b). The returned view contains all elements of a that are not a member of b.

    Full documentation: https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/SetUtils.html#difference-java.util.Set-java.util.Set-

    Have a div cling to top of screen if scrolled down past it

    Use position:fixed; and set the top:0;left:0;right:0;height:100px; and you should be able to have it "stick" to the top of the page.

    <div style="position:fixed;top:0;left:0;right:0;height:100px;">Some buttons</div>
    

    How can I submit form on button click when using preventDefault()?

    Change the submit button to a normal button and handle submitting in its onClick event.

    As far as I know, there is no way to tell if the form was submitted by Enter Key or the submit button.

    Cannot set content-type to 'application/json' in jQuery.ajax

    I recognized those screens, I'm using CodeFluentEntities, and I've got solution that worked for me as well.

    I'm using that construction:

    $.ajax({
       url: path,
       type: "POST",
       contentType: "text/plain",
       data: {"some":"some"}
    }
    

    as you can see, if I use

    contentType: "",
    

    or

    contentType: "text/plain", //chrome
    

    Everything works fine.

    I'm not 100% sure that it's all that you need, cause I've also changed headers.

    HTML5 Pre-resize images before uploading

    fd.append("image", dataurl);
    

    This will not work. On PHP side you can not save file with this.

    Use this code instead:

    var blobBin = atob(dataurl.split(',')[1]);
    var array = [];
    for(var i = 0; i < blobBin.length; i++) {
      array.push(blobBin.charCodeAt(i));
    }
    var file = new Blob([new Uint8Array(array)], {type: 'image/png', name: "avatar.png"});
    
    fd.append("image", file); // blob file
    

    Understanding __getitem__ method

    The magic method __getitem__ is basically used for accessing list items, dictionary entries, array elements etc. It is very useful for a quick lookup of instance attributes.

    Here I am showing this with an example class Person that can be instantiated by 'name', 'age', and 'dob' (date of birth). The __getitem__ method is written in a way that one can access the indexed instance attributes, such as first or last name, day, month or year of the dob, etc.

    import copy
    
    # Constants that can be used to index date of birth's Date-Month-Year
    D = 0; M = 1; Y = -1
    
    class Person(object):
        def __init__(self, name, age, dob):
            self.name = name
            self.age = age
            self.dob = dob
    
        def __getitem__(self, indx):
            print ("Calling __getitem__")
            p = copy.copy(self)
    
            p.name = p.name.split(" ")[indx]
            p.dob = p.dob[indx] # or, p.dob = p.dob.__getitem__(indx)
            return p
    

    Suppose one user input is as follows:

    p = Person(name = 'Jonab Gutu', age = 20, dob=(1, 1, 1999))
    

    With the help of __getitem__ method, the user can access the indexed attributes. e.g.,

    print p[0].name # print first (or last) name
    print p[Y].dob  # print (Date or Month or ) Year of the 'date of birth'
    

    Using SED with wildcard

    The asterisk (*) means "zero or more of the previous item".

    If you want to match any single character use

    sed -i 's/string-./string-0/g' file.txt
    

    If you want to match any string (i.e. any single character zero or more times) use

    sed -i 's/string-.*/string-0/g' file.txt
    

    Form Submit Execute JavaScript Best Practice?

    Use the onsubmit event to execute JavaScript code when the form is submitted. You can then return false or call the passed event's preventDefault method to disable the form submission.

    For example:

    <script>
    function doSomething() {
        alert('Form submitted!');
        return false;
    }
    </script>
    
    <form onsubmit="return doSomething();" class="my-form">
        <input type="submit" value="Submit">
    </form>
    

    This works, but it's best not to litter your HTML with JavaScript, just as you shouldn't write lots of inline CSS rules. Many Javascript frameworks facilitate this separation of concerns. In jQuery you bind an event using JavaScript code like so:

    <script>
    $('.my-form').on('submit', function () {
        alert('Form submitted!');
        return false;
    });
    </script>
    
    <form class="my-form">
        <input type="submit" value="Submit">
    </form>
    

    How can one use multi threading in PHP applications

    As of the writing of my current comment, I don't know about the PHP threads. I came to look for the answer here myself, but one workaround is that the PHP program that receives the request from the web server delegates the whole answer formulation to a console application that stores its output, the answer to the request, to a binary file and the PHP program that launched the console application returns that binary file byte-by-byte as the answer to the received request. The console application can be written in any programming language that runs on the server, including those that have proper threading support, including C++ programs that use OpenMP.

    One unreliable, dirty, trick is to use PHP for executing a console application, "uname",

    uname -a
    

    and print the output of that console command to the HTML output to find out the exact version of the server software. Then install the exact same version of the software to a VirtualBox instance, compile/assemble whatever fully self-contained, preferably static, binaries that one wants and then upload those to the server. From that point onwards the PHP application can use those binaries in the role of the console application that has proper multi-threading. It's a dirty, unreliable, workaround to a situation, when the server administrator has not installed all needed programming language implementations to the server. The thing to watch out for is that at every request that the PHP application receives the console application(s) terminates/exit/get_killed.

    As to what the hosting service administrators think of such server usage patterns, I guess it boils down to culture. In Northern Europe the service provider HAS TO DELIVER WHAT WAS ADVERTISED and if execution of console commands was allowed and uploading of non-malware files was allowed and the service provider has a right to kill any server process after a few minutes or even after 30 seconds, then the hosting service administrators lack any arguments for forming a proper complaint. In United States and Western Europe the situation/culture is very different and I believe that there's a great chance that in U.S. and/or Western Europe the hosting service provider will refuse to serve hosting service clients that use the above described trick. That's just my guess, given my personal experience with U.S. hosting services and given what I have heard from others about Western European hosting services. As of the writing of my current comment(2018_09_01) I do not know anything about the cultural norms of the Southern-European hosting service providers, Southern-European network administrators.

    How many threads can a Java VM support?

    This depends on the CPU you're using, on the OS, on what other processes are doing, on what Java release you're using, and other factors. I've seen a Windows server have > 6500 Threads before bringing the machine down. Most of the threads were not doing anything, of course. Once the machine hit around 6500 Threads (in Java), the whole machine started to have problems and become unstable.

    My experience shows that Java (recent versions) can happily consume as many Threads as the computer itself can host without problems.

    Of course, you have to have enough RAM and you have to have started Java with enough memory to do everything that the Threads are doing and to have a stack for each Thread. Any machine with a modern CPU (most recent couple generations of AMD or Intel) and with 1 - 2 Gig of memory (depending on OS) can easily support a JVM with thousands of Threads.

    If you need a more specific answer than this, your best bet is to profile.

    correct quoting for cmd.exe for multiple arguments

    Note the "" at the beginning and at the end!

    Run a program and pass a Long Filename

    cmd /c write.exe "c:\sample documents\sample.txt"
    

    Spaces in Program Path

    cmd /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""
    

    Spaces in Program Path + parameters

    cmd /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
    

    Spaces in Program Path + parameters with spaces

    cmd /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""
    

    Launch Demo1 and then Launch Demo2

    cmd /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""
    

    CMD.exe (Command Shell)

    The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

    There are two possible scenario, in my case I used 2nd point.

    1. If you are facing this issue in production environment and you can easily deploy new code to the production then you can use of below solution.

      You can add below line of code before making api call,

      ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // .NET 4.5

    2. If you cannot deploy new code and you want to resolve with the same code which is present in the production, then this issue can be done by changing some configuration setting file. You can add either of one in your config file.

    <runtime>
        <AppContextSwitchOverrides value="Switch.System.Net.DontEnableSchUseStrongCrypto=false"/>
      </runtime>
    

    or

    <runtime>
      <AppContextSwitchOverrides value="Switch.System.Net.DontEnableSystemDefaultTlsVersions=false"
    </runtime>
    

    Model Binding to a List MVC 4

    A clean solution could be create a generic class to handle the list, so you don't need to create a different class each time you need it.

    public class ListModel<T>
    {
        public List<T> Items { get; set; }
    
        public ListModel(List<T> list) {
            Items = list;
        }
    }
    

    and when you return the View you just need to simply do:

    List<customClass> ListOfCustomClass = new List<customClass>();
    //Do as needed...
    return View(new ListModel<customClass>(ListOfCustomClass));
    

    then define the list in the model:

    @model ListModel<customClass>
    

    and ready to go:

    @foreach(var element in Model.Items) {
      //do as needed...
    }
    

    TypeScript error: Type 'void' is not assignable to type 'boolean'

    It means that the callback function you passed to this.dataStore.data.find should return a boolean and have 3 parameters, two of which can be optional:

    • value: Conversations
    • index: number
    • obj: Conversation[]

    However, your callback function does not return anything (returns void). You should pass a callback function with the correct return value:

    this.dataStore.data.find((element, index, obj) => {
        // ...
    
        return true; // or false
    });
    

    or:

    this.dataStore.data.find(element => {
        // ...
    
        return true; // or false
    });
    

    Reason why it's this way: the function you pass to the find method is called a predicate. The predicate here defines a boolean outcome based on conditions defined in the function itself, so that the find method can determine which value to find.

    In practice, this means that the predicate is called for each item in data, and the first item in data for which your predicate returns true is the value returned by find.

    How to catch SQLServer timeout exceptions

    I am not sure but when we have execute time out or command time out The client sends an "ABORT" to SQL Server then simply abandons the query processing. No transaction is rolled back, no locks are released. to solve this problem I Remove transaction in Stored-procedure and use SQL Transaction in my .Net Code To manage sqlException

    Oracle: Import CSV file

    Another solution you can use is SQL Developer.

    With it, you have the ability to import from a csv file (other delimited files are available).

    Just open the table view, then:

    • choose actions
    • import data
    • find your file
    • choose your options.

    You have the option to have SQL Developer do the inserts for you, create an sql insert script, or create the data for a SQL Loader script (have not tried this option myself).

    Of course all that is moot if you can only use the command line, but if you are able to test it with SQL Developer locally, you can always deploy the generated insert scripts (for example).

    Just adding another option to the 2 already very good answers.

    HTML5 Audio stop function

    I believe it would be good to check if the audio is playing state and reset the currentTime property.

    if (sound.currentTime !== 0 && (sound.currentTime > 0 && sound.currentTime < sound.duration) {
        sound.currentTime = 0;
    }
    sound.play();
    

    How to force addition instead of concatenation in javascript

    Should also be able to do this:

    total += eval(myInt1) + eval(myInt2) + eval(myInt3);
    

    This helped me in a different, but similar, situation.

    Upgrade python without breaking yum

    pythonz, an active fork of pythonbrew, makes this a breeze. You can install a version with:

    # pythonz install 2.7.3
    

    Then set up a symlink with:

    # ln -s /usr/local/pythonz/pythons/CPython-2.7.3/bin/python2.7 /usr/local/bin/python2.7
    # python2.7 --version
    Python 2.7.3
    

    Access item in a list of lists

    for l in list1:
        val = 50 - l[0] + l[1] - l[2]
        print "val:", val
    

    Loop through list and do operation on the sublist as you wanted.

    Is it good practice to use the xor operator for boolean checks?

    You could always just wrap it in a function to give it a verbose name:

    public static boolean XOR(boolean A, boolean B) {
        return A ^ B;
    }
    

    But, it seems to me that it wouldn't be hard for anyone who didn't know what the ^ operator is for to Google it really quick. It's not going to be hard to remember after the first time. Since you asked for other uses, its common to use the XOR for bit masking.

    You can also use XOR to swap the values in two variables without using a third temporary variable.

    // Swap the values in A and B
    A ^= B;
    B ^= A;
    A ^= B;
    

    Here's a Stackoverflow question related to XOR swapping.

    Laravel Eloquent Join vs Inner Join?

    I'm sure there are other ways to accomplish this, but one solution would be to use join through the Query Builder.

    If you have tables set up something like this:

    users
        id
        ...
    
    friends
        id
        user_id
        friend_id
        ...
    
    votes, comments and status_updates (3 tables)
        id
        user_id
        ....
    

    In your User model:

    class User extends Eloquent {
        public function friends()
        {
            return $this->hasMany('Friend');
        }
    }
    

    In your Friend model:

    class Friend extends Eloquent {
        public function user()
        {
            return $this->belongsTo('User');
        }
    }
    

    Then, to gather all the votes for the friends of the user with the id of 1, you could run this query:

    $user = User::find(1);
    $friends_votes = $user->friends()
        ->with('user') // bring along details of the friend
        ->join('votes', 'votes.user_id', '=', 'friends.friend_id')
        ->get(['votes.*']); // exclude extra details from friends table
    

    Run the same join for the comments and status_updates tables. If you would like votes, comments, and status_updates to be in one chronological list, you can merge the resulting three collections into one and then sort the merged collection.


    Edit

    To get votes, comments, and status updates in one query, you could build up each query and then union the results. Unfortunately, this doesn't seem to work if we use the Eloquent hasMany relationship (see comments for this question for a discussion of that problem) so we have to modify to queries to use where instead:

    $friends_votes = 
        DB::table('friends')->where('friends.user_id','1')
        ->join('votes', 'votes.user_id', '=', 'friends.friend_id');
    
    $friends_comments = 
        DB::table('friends')->where('friends.user_id','1')
        ->join('comments', 'comments.user_id', '=', 'friends.friend_id');
    
    $friends_status_updates = 
        DB::table('status_updates')->where('status_updates.user_id','1')
        ->join('friends', 'status_updates.user_id', '=', 'friends.friend_id');
    
    $friends_events = 
        $friends_votes
        ->union($friends_comments)
        ->union($friends_status_updates)
        ->get();
    

    At this point, though, our query is getting a bit hairy, so a polymorphic relationship with and an extra table (like DefiniteIntegral suggests below) might be a better idea.

    Angular 4 img src is not found

    in your component assign a variable like,

    export class AppComponent {
      netImage:any = "../assets/network.jpg";
      title = 'app';
    }
    

    use this netImage in your src to get the image, as given below,

    <figure class="figure">
      <img [src]="netImage" class="figure-img img-fluid rounded" alt="A generic square placeholder image with rounded corners in a figure.">
      <figcaption class="figure-caption">A caption for the above image.</figcaption>
    </figure>
    

    "No Content-Security-Policy meta tag found." error in my phonegap application

    After adding the cordova-plugin-whitelist, you must tell your application to allow access all the web-page links or specific links, if you want to keep it specific.

    You can simply add this to your config.xml, which can be found in your application's root directory:

    Recommended in the documentation:

    <allow-navigation href="http://example.com/*" />
    

    or:

    <allow-navigation href="http://*/*" />
    

    From the plugin's documentation:

    Navigation Whitelist

    Controls which URLs the WebView itself can be navigated to. Applies to top-level navigations only.

    Quirks: on Android it also applies to iframes for non-http(s) schemes.

    By default, navigations only to file:// URLs, are allowed. To allow other other URLs, you must add tags to your config.xml:

    <!-- Allow links to example.com -->
    <allow-navigation href="http://example.com/*" />
    
    <!-- Wildcards are allowed for the protocol, as a prefix
         to the host, or as a suffix to the path -->
    <allow-navigation href="*://*.example.com/*" />
    
    <!-- A wildcard can be used to whitelist the entire network,
         over HTTP and HTTPS.
         *NOT RECOMMENDED* -->
    <allow-navigation href="*" />
    
    <!-- The above is equivalent to these three declarations -->
    <allow-navigation href="http://*/*" />
    <allow-navigation href="https://*/*" />
    <allow-navigation href="data:*" />
    

    How to store and retrieve a dictionary with redis

    you can pickle your dict and save as string.

    import pickle
    import redis
    
    r = redis.StrictRedis('localhost')
    mydict = {1:2,2:3,3:4}
    p_mydict = pickle.dumps(mydict)
    r.set('mydict',p_mydict)
    
    read_dict = r.get('mydict')
    yourdict = pickle.loads(read_dict)
    

    Difference between DataFrame, Dataset, and RDD in Spark

    Spark RDD (resilient distributed dataset) :

    RDD is the core data abstraction API and is available since very first release of Spark (Spark 1.0). It is a lower-level API for manipulating distributed collection of data. The RDD APIs exposes some extremely useful methods which can be used to get very tight control over underlying physical data structure. It is an immutable (read only) collection of partitioned data distributed on different machines. RDD enables in-memory computation on large clusters to speed up big data processing in a fault tolerant manner. To enable fault tolerance, RDD uses DAG (Directed Acyclic Graph) which consists of a set of vertices and edges. The vertices and edges in DAG represent the RDD and the operation to be applied on that RDD respectively. The transformations defined on RDD are lazy and executes only when an action is called

    Spark DataFrame :

    Spark 1.3 introduced two new data abstraction APIs – DataFrame and DataSet. The DataFrame APIs organizes the data into named columns like a table in relational database. It enables programmers to define schema on a distributed collection of data. Each row in a DataFrame is of object type row. Like an SQL table, each column must have same number of rows in a DataFrame. In short, DataFrame is lazily evaluated plan which specifies the operations needs to be performed on the distributed collection of the data. DataFrame is also an immutable collection.

    Spark DataSet :

    As an extension to the DataFrame APIs, Spark 1.3 also introduced DataSet APIs which provides strictly typed and object-oriented programming interface in Spark. It is immutable, type-safe collection of distributed data. Like DataFrame, DataSet APIs also uses Catalyst engine in order to enable execution optimization. DataSet is an extension to the DataFrame APIs.

    Other Differences -

    enter image description here

    Accessing localhost (xampp) from another computer over LAN network - how to?

    These are the steps to follow when you want your PHP application to be installed on a LAN server (not on web)

    1. Get the internal IP or Static IP of the server (Ex: 192.168.1.193)
    2. Open XAMPP>apache>conf>httpd.conf file in notepad
    3. Search for Listen 80
    4. Above line would read like- #Listen 0.0.0.0:80 / 12.34.56.78:80
    5. Change the IP address and replace it with the static IP
    6. Save the httpd.conf file ensuring that the server is pointed to #Listen 192.168.1.193:80
    7. In the application root config.php (db connection) replace localhost with IP address of the server

    Note: If firewall is installed, ensure that you add the http port 80 and 8080 to exceptions and allow to listen. Go to Control Panel>Windows Firewall>Allow a program to communicate through windows firewall>Add another program Name: http Port: 80 Add one more as http - 8080

    If IIS (Microsoft .Net Application Internet Information Server) is installed with any Microsoft .Net application already on server, then it would have already occupied 80 port. In that case change the #Listen 192.168.1.193:80 to #Listen 192.168.1.193:8080

    Hope this helps! :)

    vba: get unique values from array

    There is no VBA built in functionality for removing duplicates from an array, however you could use the next function:

    Function RemoveDuplicates(MyArray As Variant) As Variant
        With CreateObject("scripting.dictionary")
            For Each item In MyArray
                c00 = .Item(item)
            Next
            sn = .keys ' the array .keys contains all unique keys
            MsgBox Join(.keys, vbLf) ' you can join the array into a string
            RemoveDuplicates = .keys ' return an array without duplicates
        End With
    End Function
    

    Visual Studio Error: (407: Proxy Authentication Required)

    I got this error when running dotnet publish while connected to the company VPN. Once I disconnected from the VPN, it worked.

    How to randomize (or permute) a dataframe rowwise and columnwise?

    This is another way to shuffle the data.frame using package dplyr:

    row-wise:

    df2 <- slice(df1, sample(1:n()))
    

    or

    df2 <- sample_frac(df1, 1L)
    

    column-wise:

    df2 <- select(df1, one_of(sample(names(df1)))) 
    

    How to convert a string to lower or upper case in Ruby

    You can find out all the methods available on a String by opening irb and running:

    "MyString".methods.sort
    

    And for a list of the methods available for strings in particular:

    "MyString".own_methods.sort
    

    I use this to find out new and interesting things about objects which I might not otherwise have known existed.

    How to highlight a selected row in ngRepeat?

    Each row has an ID. All you have to do is to send this ID to the function setSelected(), store it (in $scope.idSelectedVote for instance), and then check for each row if the selected ID is the same as the current one. Here is a solution (see the documentation for ngClass, if needed):

    $scope.idSelectedVote = null;
    $scope.setSelected = function (idSelectedVote) {
       $scope.idSelectedVote = idSelectedVote;
    };
    
    <ul ng-repeat="vote in votes" ng-click="setSelected(vote.id)" ng-class="{selected: vote.id === idSelectedVote}">
        ...
    </ul>
    

    Plunker

    Sorting an array of objects by property values

     function compareValues(key, order = 'asc') {
      return function innerSort(a, b) {
        if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
          // property doesn't exist on either object
          return 0;
        }
    
        const varA = (typeof a[key] === 'string')
          ? a[key].toUpperCase() : a[key];
        const varB = (typeof b[key] === 'string')
          ? b[key].toUpperCase() : b[key];
    
        let comparison = 0;
        if (varA > varB) {
          comparison = 1;
        } else if (varA < varB) {
          comparison = -1;
        }
        return (
          (order === 'desc') ? (comparison * -1) : comparison
        );
      };
    }
    

    http://yazilimsozluk.com/sort-array-in-javascript-by-asc-or-desc

    Using XAMPP, how do I swap out PHP 5.3 for PHP 5.2?

    For OSX it's even easier. Your machine should come with a version of Apache already installed. All you need to do is locate the php lib for that version (which is likely 5.2.x) and swap it out.

    This is the command you'd run from terminal*

    cp /usr/libexec/apache2/libphp5.so /Applications/XAMPP/xamppfiles/modules/libphp5.so
    

    I tested this on 10.5 (Leopard), so ymmv. * all the caveats about this might break your system, make a backup, blah blah blah.

    Edit: On 10.4 (Tiger), Xampp 1.73, using the libphp5.so-files found at Mamp, this does not work at all.

    Convert pyQt UI to python

    For Ubuntu it works for following commands; If you want individual files to contain main method to run the files individually, may be for testing purpose,

    pyuic5 filename.ui -o filename.py -x
    

    No main method in file, cannot run individually... try

    pyuic5 filename.ui -o filename.py
    

    Consider, I'm using PyQT5.

    How to maximize the browser window in Selenium WebDriver (Selenium 2) using C#?

    The below line of code would maximize IE, Chrome and Mozilla

    driver.manage().window().maximize();
    

    The above line of code and other workarounds mentioned in the post did not work for NodeWebKit browser, so as a workaround i had to use native C# code as mentioned below:

    public static void MaximiseNWKBrowser(IWebDriver d)
            {
                var body = UICommon.GetElement(By.TagName("body"), d);
                body.Click();
                string alt = "%";
                string space = " ";
                string down = "{DOWN}";
                string enter = "{ENTER}";
                SendKeys.SendWait(alt + space);
                for(var i = 1; i <= 6; i++)
                {
                    SendKeys.SendWait(down);
                }
                SendKeys.SendWait(enter);            
            }
    

    So this workaround basically uses "ALT+SPACE" to bring up the browser action menu to select "MAXIMIZE" from the options and presses "ENTER"

    How do I install PIL/Pillow for Python 3.6?

    For python version 2.x you can simply use

    • pip install pillow

    But for python version 3.X you need to specify

    • (sudo) pip3 install pillow

    when you enter pip in bash hit tab and you will see what options you have

    How to give the background-image path in CSS?

    Your css is here: Project/Web/Support/Styles/file.css

    1 time ../ means Project/Web/Support and 2 times ../ i.e. ../../ means Project/Web

    Try:

    background-image: url('../../images/image.png');
    

    How to delete row based on cell value

    You could copy down a formula like the following in a new column...

    =IF(ISNUMBER(FIND("-",A1)),1,0)
    

    ... then sort on that column, highlight all the rows where the value is 1 and delete them.

    Mockito How to mock and assert a thrown exception?

    Make the exception happen like this:

    when(obj.someMethod()).thenThrow(new AnException());
    

    Verify it has happened either by asserting that your test will throw such an exception:

    @Test(expected = AnException.class)
    

    Or by normal mock verification:

    verify(obj).someMethod();
    

    The latter option is required if your test is designed to prove intermediate code handles the exception (i.e. the exception won't be thrown from your test method).

    Modify the legend of pandas bar plot

    If you need to call plot multiply times, you can also use the "label" argument:

    ax = df1.plot(label='df1', y='y_var')
    ax = df2.plot(label='df2', y='y_var')
    

    While this is not the case in the OP question, this can be helpful if the DataFrame is in long format and you use groupby before plotting.

    Convert.ToDateTime: how to set format

    You should probably use either DateTime.ParseExact or DateTime.TryParseExact instead. They allow you to specify specific formats. I personally prefer the Try-versions since I think they produce nicer code for the error cases.

    How can I declare a two dimensional string array?

    There are 2 types of multidimensional arrays in C#, called Multidimensional and Jagged.

    For multidimensional you can by:

    string[,] multi = new string[3, 3];

    For jagged array you have to write a bit more code:

    string[][] jagged = new string[3][];
                for (int i = 0; i < jagged.Length; i++)
                {
                    jagged[i] = new string[3];
                }
    

    In short jagged array is both faster and has intuitive syntax. For more information see: this Stackoverflow question

    How do I install an R package from source?

    You can install directly from the repository (note the type="source"):

    install.packages("RJSONIO", repos = "http://www.omegahat.org/R", type="source")
    

    UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples

    The accepted answer explains already well why the warning occurs. If you simply want to control the warnings, one could use precision_recall_fscore_support. It offers a (semi-official) argument warn_for that could be used to mute the warnings.

    (_, _, f1, _) = metrics.precision_recall_fscore_support(y_test, y_pred,
                                                            average='weighted', 
                                                            warn_for=tuple())
    

    As mentioned already in some comments, use this with care.

    How do I link to part of a page? (hash?)

    You have two options:

    You can either put an anchor in your document as follows:

    <a name="ref"></a>
    

    Or else you give an id to a any HTML element:

    <h1 id="ref">Heading</h1>
    

    Then simply append the hash #ref to the URL of your link to jump to the desired reference. Example:

    <a href="document.html#ref">Jump to ref in document.html</a>
    

    Select values of checkbox group with jQuery

    Use .map() (adapted from the example at http://api.jquery.com/map/):

    var values = $("input[name='user_group[]']:checked").map(function(index,domElement) {
        return $(domElement).val();
    });
    

    Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/JDBC_DBO]]

    all i found solution for whatever you all get the exception like.. org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]..

    the problem with bulid path of the jars..

    To over come this problem.. place all jars in "WebContent/lib" whatever you need to in your project. i hope it will useful to you...

    How to make shadow on border-bottom?

    I'm a little late on the party, but its actualy possible to emulate borders using a box-shadow

    _x000D_
    _x000D_
    .border {_x000D_
      background-color: #ededed;_x000D_
      padding: 10px;_x000D_
      margin-bottom: 5px;_x000D_
    }_x000D_
    _x000D_
    .border-top {_x000D_
      box-shadow: inset 0 3px 0 0 cornflowerblue;_x000D_
    }_x000D_
    _x000D_
    .border-right {_x000D_
      box-shadow: inset -3px 0 0 cornflowerblue;_x000D_
    }_x000D_
    _x000D_
    .border-bottom {_x000D_
      box-shadow: inset 0 -3px 0 0 cornflowerblue;_x000D_
    }_x000D_
    _x000D_
    .border-left {_x000D_
      box-shadow: inset 3px 0 0 cornflowerblue;_x000D_
    }
    _x000D_
    <div class="border border-top">border-top</div>_x000D_
    <div class="border border-right">border-right</div>_x000D_
    <div class="border border-bottom">border-bottom</div>_x000D_
    <div class="border border-left">border-left</div>
    _x000D_
    _x000D_
    _x000D_

    EDIT: I understood this question wrong, but I will leave the awnser as more people might misunderstand the question and came for the awnser I supplied.

    Emulate Samsung Galaxy Tab

    What resolution and density should I set?

    • 1024x600

    How can I indicate that this is large screen device?

    • you can't really (not that i know of)

    What hardware does this tablet support?

    What is max heap size?

    • not sure

    Which Android version?

    • 2.2

    Hope that helps - check the spec page for all unanswered questions.

    How to send 100,000 emails weekly?

    People have recommended MailChimp which is a good vendor for bulk email. If you're looking for a good vendor for transactional email, I might be able to help.

    Over the past 6 months, we used four different SMTP vendors with the goal of figuring out which was the best one.

    Here's a summary of what we found...

    AuthSMTP

    • Cheapest around
    • No analysis/reporting
    • No tracking for opens/clicks
    • Had slight hesitation on some sends

    Postmark

    • Very cheap, but not as cheap as AuthSMTP
    • Beautiful cpanel but no tracking on opens/clicks
    • Send-level activity tracking so you can open a single email that was sent and look at how it looked and the delivery data.
    • Have to use API. Sending by SMTP was recently introduced but it's buggy. For instance, we noticed that quotes (") in the subject line are stripped.
    • Cannot send any attachment you want. Must be on approved list of file types and under a certain size. (10 MB I think)
    • Requires a set list of from names/addresses.

    JangoSMTP

    • Expensive in relation to the others – more than 10 times in some cases
    • Ugly cpanel but great tracking on opens/clicks with email-level detail
    • Had hesitation, at times, when sending. On two occasions, sends took an hour to be delivered
    • Requires a set list of from name/addresses.

    SendGrid

    • Not quite a cheap as AuthSMTP but still very cheap. Many customers can exist on 200 free sends per day.
    • Decent cpanel but no in-depth detail on open/click tracking
    • Lots of API options. Options (open/click tracking, etc) can be custom defined on an email-by-email basis. Inbound (reply) email can be posted to our HTTP end point.
    • Absolutely zero hesitation on sends. Every email sent landed in the inbox almost immediately.
    • Can send from any from name/address.

    Conclusion

    SendGrid was the best with Postmark coming in second place. We never saw any hesitation in send times with either of those two - in some cases we sent several hundred emails at once - and they both have the best ROI, given a solid featureset.

    How do I horizontally center a span element inside a div

    Spans can get a bit tricky to deal with. if you set the width of teach span you can use

    margin: 0 auto;
    

    to center them, but they then end up on different lines. I would suggest trying a different approach to your structure.

    Here is the jsfiddle I cam e up with off the top of my head: jsFiddle

    EDIT:

    Adrift's answer is the easiest solution :)

    How can I listen for a click-and-hold in jQuery?

        var _timeoutId = 0;
    
        var _startHoldEvent = function(e) {
          _timeoutId = setInterval(function() {
             myFunction.call(e.target);
          }, 1000);
        };
    
        var _stopHoldEvent = function() {
          clearInterval(_timeoutId );
        };
    
        $('#myElement').on('mousedown', _startHoldEvent).on('mouseup mouseleave', _stopHoldEvent);
    

    Java balanced expressions check {[()]}

    I hope this code can help:

    import java.util.Stack;
    
    public class BalancedParenthensies {
    
        public static void main(String args[]) {
    
            System.out.println(balancedParenthensies("{(a,b)}"));
            System.out.println(balancedParenthensies("{(a},b)"));
            System.out.println(balancedParenthensies("{)(a,b}"));
        }
    
        public static boolean balancedParenthensies(String s) {
            Stack<Character> stack  = new Stack<Character>();
            for(int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if(c == '[' || c == '(' || c == '{' ) {     
                    stack.push(c);
                } else if(c == ']') {
                    if(stack.isEmpty() || stack.pop() != '[') {
                        return false;
                    }
                } else if(c == ')') {
                    if(stack.isEmpty() || stack.pop() != '(') {
                        return false;
                    }           
                } else if(c == '}') {
                    if(stack.isEmpty() || stack.pop() != '{') {
                        return false;
                    }
                }
    
            }
            return stack.isEmpty();
        }
    }
    

    How to pass argument to Makefile from command line?

    Few years later, want to suggest just for this: https://github.com/casey/just

    action v1 v2=default:
        @echo 'take action on {{v1}} and {{v2}}...'
    

    Dynamic constant assignment

    Constants in ruby cannot be defined inside methods. See the notes at the bottom of this page, for example

    How can I get last characters of a string

    Getting the last character is easy, as you can treat strings as an array:

    var lastChar = id[id.length - 1];
    

    To get a section of a string, you can use the substr function or the substring function:

    id.substr(id.length - 1); //get the last character
    id.substr(2);             //get the characters from the 3rd character on
    id.substr(2, 1);          //get the 3rd character
    id.substr(2, 2);          //get the 3rd and 4th characters
    

    The difference between substr and substring is how the second (optional) parameter is treated. In substr, it's the amount of characters from the index (the first parameter). In substring, it's the index of where the character slicing should end.

    Angular2 - TypeScript : Increment a number after timeout in AppComponent

    You should put your processing into the class constructor or an OnInit hook method.

    Transform char array into String

    May you should try creating a temp string object and then add to existing item string. Something like this.

    for(int k=0; k<bufferPos; k++){
          item += String(buffer[k]);
          }
    

    How to open this .DB file?

    I don't think there is a way to tell which program to use from just the .db extension. It could even be an encrypted database which can't be opened. You can MS Access, or a sqlite manager.

    Edit: Try to rename the file to .txt and open it with a text editor. The first couple of words in the file could tell you the DB Type.

    If it is a SQLite database, it will start with "SQLite format 3"

    Calling a php function by onclick event

    onclick event to call a function

      <strike> <input type="button" value="NEXT"  onclick="document.write('<?php //call a function here ex- 'fun();' ?>');" />    </strike>
    

    it will surely help you

    it take a little more time than normal but wait it will work

    How to exit when back button is pressed?

    Why wouldn't the user just hit the home button? Then they can exit your app from any of your activities, not just a specific one.

    If you are worried about your application continuing to do something in the background. Make sure to stop it in the relevant onPause and onStop commands (which will get triggered when the user presses Home).

    If your issue is that you want the next time the user clicks on your app for it to start back at the beginning, I recommend putting some kind of menu item or UI button on the screen that takes the user back to the starting activity of your app. Like the twitter bird in the official twitter app, etc.

    Convert .pem to .crt and .key

    If you asked this question because you're using mkcert then the trick is that the .pem file is the cert and the -key.pem file is the key.

    (You don't need to convert, just run mkcert yourdomain.dev otherdomain.dev )

    Android Studio 3.0 Flavor Dimension Issue

    I have used flavorDimensions for my application in build.gradle (Module: app)

    flavorDimensions "tier"
    
    productFlavors {
        production {
            flavorDimensions "tier"
            //manifestPlaceholders = [appName: APP_NAME]
            //signingConfig signingConfigs.config
        }
        staging {
            flavorDimensions "tier"
            //manifestPlaceholders = [appName: APP_NAME_STAGING]
            //applicationIdSuffix ".staging"
            //versionNameSuffix "-staging"
            //signingConfig signingConfigs.config
        }
    }
    

    Check this link for more info

    // Specifies two flavor dimensions.
    flavorDimensions "tier", "minApi"
    
    productFlavors {
         free {
                // Assigns this product flavor to the "tier" flavor dimension. Specifying
                // this property is optional if you are using only one dimension.
                dimension "tier"
                ...
         }
    
         paid {
                dimension "tier"
                ...
         }
    
         minApi23 {
                dimension "minApi"
                ...
         }
    
         minApi18 {
                dimension "minApi"
                ...
         }
    }
    

    How to send a POST request with BODY in swift

    You're close. The parameters dictionary formatting doesn't look correct. You should try the following:

    let parameters: [String: AnyObject] = [
        "IdQuiz" : 102,
        "IdUser" : "iosclient",
        "User" : "iosclient",
        "List": [
            [
                "IdQuestion" : 5,
                "IdProposition": 2,
                "Time" : 32
            ],
            [
                "IdQuestion" : 4,
                "IdProposition": 3,
                "Time" : 9
            ]
        ]
    ]
    
    Alamofire.request(.POST, "http://myserver.com", parameters: parameters, encoding: .JSON)
        .responseJSON { request, response, JSON, error in
            print(response)
            print(JSON)
            print(error)
        }
    

    Hopefully that fixed your issue. If it doesn't, please reply and I'll adjust my answer accordingly.

    What is the max size of localStorage values?

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

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

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

    Github pages:

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

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

    enter image description here

    And half smaller result in safari ~2Mbytes

    enter image description here

    I forgot the password I entered during postgres installation

    For Windows installation, a Windows user is created. And "psql" use this user for connection to the port. If you change the PostgreSQL user's password, it won't change the Windows one. The commandline juste below works only if you have access to commandline.

    Instead you could use Windows GUI application "c:\Windows\system32\lusrmgr.exe". This app manage users created by Windows. So you can now modify the password.