Programs & Examples On #Sp msforeachdb

Updating address bar with new URL without hash or reloading the page

You can now do this in most "modern" browsers!

Here is the original article I read (posted July 10, 2010): HTML5: Changing the browser-URL without refreshing page.

For a more in-depth look into pushState/replaceState/popstate (aka the HTML5 History API) see the MDN docs.

TL;DR, you can do this:

window.history.pushState("object or string", "Title", "/new-url");

See my answer to Modify the URL without reloading the page for a basic how-to.

ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response

the problem can because of MVC MW.you must set formatterType in MVC options:

services.AddMvc(options =>
            {
                options.UseCustomStringModelBinder();
                options.AllowEmptyInputInBodyModelBinding = true;
                foreach (var formatter in options.InputFormatters)
                {
                    if (formatter.GetType() == typeof(SystemTextJsonInputFormatter))
                        ((SystemTextJsonInputFormatter)formatter).SupportedMediaTypes.Add(
                            Microsoft.Net.Http.Headers.MediaTypeHeaderValue.Parse("text/plain"));
                }
            }).AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
            });

How to do a "Save As" in vba code, saving my current Excel workbook with datestamp?

Dim NuevoLibro As Workbook
Dim NombreLibro As String
    NombreLibro = "LibroPrueba"
'---Creamos nuevo libro y lo guardamos
    Set NuevoLibro = Workbooks.Add
        With NuevoLibro
            .SaveAs Filename:=NuevaRuta & NombreLibro, FileFormat:=52
        End With
                                                    '*****************************
                                                        'valores para FileFormat
                                                        '.xlsx = 51 '(52 for Mac)
                                                        '.xlsm = 52 '(53 for Mac)
                                                        '.xlsb = 50 '(51 for Mac)
                                                        '.xls = 56 '(57 for Mac)
                                                    '*****************************

How to determine a Python variable's type?

print type(variable_name)

I also highly recommend the IPython interactive interpreter when dealing with questions like this. It lets you type variable_name? and will return a whole list of information about the object including the type and the doc string for the type.

e.g.

In [9]: var = 123

In [10]: var?
Type:       int
Base Class: <type 'int'>
String Form:    123
Namespace:  Interactive
Docstring:
    int(x[, base]) -> integer

Convert a string or number to an integer, if possible. A floating point argument will be truncated towards zero (this does not include a string representation of a floating point number!) When converting a string, use the optional base. It is an error to supply a base when converting a non-string. If the argument is outside the integer range a long object will be returned instead.

How can I remove space (margin) above HTML header?

I solved the space issue by adding a border and removing is by setting a negative margin. Do not know what the underlying problem is though.

header {
  border-top: 1px solid gold !important;
  margin-top: -1px !important;
}

Spring MVC: Error 400 The request sent by the client was syntactically incorrect

Based on the error:

Required String parameter 'action' is not present

There needs to be a request parameter named action present in the request for Spring to map the request to your handler handleSave.

The HTML that you pasted shows no such parameter.

Return HTTP status code 201 in flask

Ripping off Luc's comment here, but to return a blank response, like a 201 the simplest option is to use the following return in your route.

return "", 201

So for example:

    @app.route('/database', methods=["PUT"])
    def database():
        update_database(request)
        return "", 201

Removing leading zeroes from a field in a SQL statement

You can try this - it takes special care to only remove leading zeroes if needed:

DECLARE @LeadingZeros    VARCHAR(10) ='-000987000'

SET @LeadingZeros =
      CASE WHEN PATINDEX('%-0', @LeadingZeros) = 1   THEN 
           @LeadingZeros
      ELSE 
           CAST(CAST(@LeadingZeros AS INT) AS VARCHAR(10)) 
      END   

SELECT @LeadingZeros

Or you can simply call

CAST(CAST(@LeadingZeros AS INT) AS VARCHAR(10)) 

What's causing my java.net.SocketException: Connection reset?

The javadoc for SocketException states that it is

Thrown to indicate that there is an error in the underlying protocol such as a TCP error

In your case it seems that the connection has been closed by the server end of the connection. This could be an issue with the request you are sending or an issue at their end.

To aid debugging you could look at using a tool such as Wireshark to view the actual network packets. Also, is there an alternative client to your Java code that you could use to test the web service? If this was successful it could indicate a bug in the Java code.

As you are using Commons HTTP Client have a look at the Common HTTP Client Logging Guide. This will tell you how to log the request at the HTTP level.

why $(window).load() is not working in jQuery?

You're using jQuery version 3.1.0 and the load event is deprecated for use since jQuery version 1.8. The load event is removed from jQuery 3.0. Instead you can use on method and bind the JavaScript load event:

 $(window).on('load', function () {
      alert("Window Loaded");
 });

How to set a cron job to run at a exact time?

My use case is that I'm on a metered account. Data transfer is limited on weekdays, Mon - Fri, from 6am - 6pm. I am using bandwidth limiting, but somehow, data still slips through, about 1GB per day!

I strongly suspected it's sickrage or sickbeard, doing a high amount of searches. My download machine is called "download." The following was my solution, using the above,for starting, and stopping the download VM, using KVM:

# Stop download Mon-Fri, 6am
0 6 * * 1,2,3,4,5 root          virsh shutdown download
# Start download Mon-Fri, 6pm
0 18 * * 1,2,3,4,5 root         virsh start download

I think this is correct, and hope it helps someone else too.

How to delete items from a dictionary while iterating over it?

There is a way that may be suitable if the items you want to delete are always at the "beginning" of the dict iteration

while mydict:
    key, value = next(iter(mydict.items()))
    if should_delete(key, value):
       del mydict[key]
    else:
       break

The "beginning" is only guaranteed to be consistent for certain Python versions/implementations. For example from What’s New In Python 3.7

the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec.

This way avoids a copy of the dict that a lot of the other answers suggest, at least in Python 3.

Quantile-Quantile Plot using SciPy

You can use bokeh

from bokeh.plotting import figure, show
from scipy.stats import probplot
# pd_series is the series you want to plot
series1 = probplot(pd_series, dist="norm")
p1 = figure(title="Normal QQ-Plot", background_fill_color="#E8DDCB")
p1.scatter(series1[0][0],series1[0][1], fill_color="red")
show(p1)

sys.stdin.readline() reads without prompt, returning 'nothing in between'

stdin.read(1)

will not return when you press one character - it will wait for '\n'. The problem is that the second character is buffered in standard input, and the moment you call another input - it will return immediately because it gets its input from buffer.

Correctly Parsing JSON in Swift 3

{
    "User":[
      {
        "FirstUser":{
        "name":"John"
        },
       "Information":"XY",
        "SecondUser":{
        "name":"Tom"
      }
     }
   ]
}

If I create model using previous json Using this link [blog]: http://www.jsoncafe.com to generate Codable structure or Any Format

Model

import Foundation
struct RootClass : Codable {
    let user : [Users]?
    enum CodingKeys: String, CodingKey {
        case user = "User"
    }

    init(from decoder: Decoder) throws {
        let values = try? decoder.container(keyedBy: CodingKeys.self)
        user = try? values?.decodeIfPresent([Users].self, forKey: .user)
    }
}

struct Users : Codable {
    let firstUser : FirstUser?
    let information : String?
    let secondUser : SecondUser?
    enum CodingKeys: String, CodingKey {
        case firstUser = "FirstUser"
        case information = "Information"
        case secondUser = "SecondUser"
    }
    init(from decoder: Decoder) throws {
        let values = try? decoder.container(keyedBy: CodingKeys.self)
        firstUser = try? FirstUser(from: decoder)
        information = try? values?.decodeIfPresent(String.self, forKey: .information)
        secondUser = try? SecondUser(from: decoder)
    }
}
struct SecondUser : Codable {
    let name : String?
    enum CodingKeys: String, CodingKey {
        case name = "name"
    }
    init(from decoder: Decoder) throws {
        let values = try? decoder.container(keyedBy: CodingKeys.self)
        name = try? values?.decodeIfPresent(String.self, forKey: .name)
    }
}
struct FirstUser : Codable {
    let name : String?
    enum CodingKeys: String, CodingKey {
        case name = "name"
    }
    init(from decoder: Decoder) throws {
        let values = try? decoder.container(keyedBy: CodingKeys.self)
        name = try? values?.decodeIfPresent(String.self, forKey: .name)
    }
}

Parse

    do {
        let res = try JSONDecoder().decode(RootClass.self, from: data)
        print(res?.user?.first?.firstUser?.name ?? "Yours optional value")
    } catch {
        print(error)
    }

Change application's starting activity

Yes, you use the AndroidManifest.xml file. You can actually even have more than one launcher activity specified in your application manifest. To make an activity seen on the launcher you add these attributes to your activity in the manifest:

<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

How to detect if javascript files are loaded?

When they say "The bottom of the page" they don't literally mean the bottom: they mean just before the closing </body> tag. Place your scripts there and they will be loaded before the DOMReady event; place them afterwards and the DOM will be ready before they are loaded (because it's complete when the closing </html> tag is parsed), which as you have found will not work.

If you're wondering how I know that this is what they mean: I have worked at Yahoo! and we put our scripts just before the </body> tag :-)

EDIT: also, see T.J. Crowder's reply and make sure you have things in the correct order.

The SELECT permission was denied on the object 'sysobjects', database 'mssqlsystemresource', schema 'sys'

I had the same error and SOLVED by removing the DB roles db_denydatawriter and db_denydatreader of the DB user. For that, select the appropriate DB user on logins >> properties >> user mappings >> find out DB and select it >> uncheck the mentioned Db user roles. Thats it !!

What is the intended use-case for git stash?

The main idea is

Stash the changes in a dirty working directory away

So Basicallly Stash command keep your some changes that you don't need them or want them at the moment; but you may need them.

Use git stash when you want to record the current state of the working directory and the index, but want to go back to a clean working directory. The command saves your local modifications away and reverts the working directory to match the HEAD commit.

Run javascript function when user finishes typing instead of on key up?

You guys have heard of closures in javascript ?!

it's very simple and straightforward just compare you current input value with the old value that the setTimeOut function closes over, and voila, you're done.

let timer;
$('#myInput').on('keyup', function() {
  window.clearTimeout(timer);
  // here is the closures javascript magic happens.
  const value = $(this).val();
  timer = setTimeout(() => {
    if(value === $(this).val() && $(this).val()!== ''){
        alert($(this).val());
    }
  }, 500);
})

How to set image in imageview in android?

The images your put into res/drawable are handled by Android. There is no need for you to get the image the way you did. in your case you could simply call iv.setImageRessource(R.drawable.apple)

to just get the image (and not adding it to the ImageView directly), you can call Context.getRessources().getDrawable(R.drawable.apple) to get the image

Is it possible to send a variable number of arguments to a JavaScript function?

The splat and spread operators are part of ES6, the planned next version of Javascript. So far only Firefox supports them. This code works in FF16+:

var arr = ['quick', 'brown', 'lazy'];

var sprintf = function(str, ...args)
{
    for (arg of args) {
        str = str.replace(/%s/, arg);
    }
    return str;
}

sprintf.apply(null, ['The %s %s fox jumps over the %s dog.', ...arr]);
sprintf('The %s %s fox jumps over the %s dog.', 'slow', 'red', 'sleeping');

Note the awkard syntax for spread. The usual syntax of sprintf('The %s %s fox jumps over the %s dog.', ...arr); is not yet supported. You can find an ES6 compatibility table here.

Note also the use of for...of, another ES6 addition. Using for...in for arrays is a bad idea.

Arduino COM port doesn't work

Abstract: Steps of How to resolve "Serial port 'COM1' not found" in fedora 17.

Today install the packages for Arduino in Fedora 17. (yum install arduino) and I have the same problem: I decided to upload an example to the chip. and got the same error "Serial port 'COM1' not found".

In this case when I run Arduino program, some banner appears which warns me that my user is not in 'dialout' and 'lock' group. Do you want add your user in this groups? I click in add button, but for some reason the program fail and not say nothing.

Step1: recognize the Arduino device unplug your Arduino and list /dev files:

#ls -l /dev

plug your Arduino and go and list /dev files

#ls -l /dev

Find the new file (device) that was not before plugging, for example:

ttyACM0 or ttyUSB1

Read this properties:

ls -l /dev/ttyACM0

crw-rw---- 1 root dialout 166, 0 Dec 24 19:25 /dev/ttyACM0

the first c mean that Arduino is a character device.

user owner: root

group owner: dialout

mayor number: 166

minor number: 0

Step2: set your user as group owner.

If you do:

groups <yourUser>

And you are not in 'dialout' and/or 'lock' group. Add yourself in this groups run as root:

usermod -aG lock <yourUser>
usermod -aG dialout <yourUser>

restart the pc, and set /dev/<yourDeviceFile> as your serial port before upload.

Enable ASP.NET ASMX web service for HTTP POST / GET requests

Try to declare UseHttpGet over your method.

[ScriptMethod(UseHttpGet = true)]
public string HelloWorld()
{
    return "Hello World";
}

How to put a Scanner input into an array... for example a couple of numbers

import  java.util.Scanner;

class Array {
public static void main(String a[]){

    Scanner input = new Scanner(System.in);

    System.out.println("Enter the size of an Array");

    int num = input.nextInt();

    System.out.println("Enter the Element "+num+" of an Array");

    double[] numbers = new double[num];

    for (int i = 0; i < numbers.length; i++)
    {

        System.out.println("Please enter number");

        numbers[i] = input.nextDouble();

    }

    for (int i = 0; i < numbers.length; i++)
    {

        if ( (i%3) !=0){

            System.out.print("");

            System.out.print(numbers[i]+"\t");

        } else {
            System.out.println("");

            System.out.print(numbers[i]+"\t");
        }

    }

}

Spring MVC: Complex object as GET @RequestParam

Yes, You can do it in a simple way. See below code of lines.

URL - http://localhost:8080/get/request/multiple/param/by/map?name='abc' & id='123'

 @GetMapping(path = "/get/request/header/by/map")
    public ResponseEntity<String> getRequestParamInMap(@RequestParam Map<String,String> map){
        // Do your business here 
        return new ResponseEntity<String>(map.toString(),HttpStatus.OK);
    } 

How do I extract Month and Year in a MySQL date and compare them?

in Mysql Doku: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_extract

SELECT EXTRACT( YEAR_MONTH FROM `date` ) 
FROM `Table` WHERE Condition = 'Condition';

HTML5 placeholder css padding

Setting line-height: 0px; fixed it for me in Chrome

Cut off text in string after/before separator in powershell

I had a dir full of files including some that were named invoice no-product no.pdf and wanted to sort these by product no, so...

get-childitem *.pdf | sort-object -property @{expression={$\_.name.substring($\_.name.indexof("-")+1)}}

Note that in the absence of a - this sorts by $_.name

how to read certain columns from Excel using Pandas - Python

You can use column indices (letters) like this:

import pandas as pd
import numpy as np
file_loc = "path.xlsx"
df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], usecols = "A,C:AA")
print(df)

[Corresponding documentation][1]:

usecolsint, str, list-like, or callable default None

  • If None, then parse all columns.
  • If str, then indicates comma separated list of Excel column letters and column ranges (e.g. “A:E” or “A,C,E:F”). Ranges are inclusive of both sides.
  • If list of int, then indicates list of column numbers to be parsed.
  • If list of string, then indicates list of column names to be parsed.

    New in version 0.24.0.

  • If callable, then evaluate each column name against it and parse the column if the callable returns True.

Returns a subset of the columns according to behavior above.

New in version 0.24.0.

What languages are Windows, Mac OS X and Linux written in?

You're right MacOSX has Objective-C in the core.

Windows C++

Linux C

About the scripting languages, no, they pretty much high level.

How to Insert Double or Single Quotes

If you save the Excel file as a CSV format file, you might find that the result is convenient to inserting into a database, though I'm not sure all of the fields would be quoted.

iterate through a map in javascript

The callback to $.each() is passed the property name and the value, in that order. You're therefore trying to iterate over the property names in the inner call to $.each(). I think you want:

$.each(myMap, function (i, val) {
  $.each(val, function(innerKey, innerValue) {
    // ...
  });
});

In the inner loop, given an object like your map, the values are arrays. That's OK, but note that the "innerKey" values will all be numbers.

edit — Now once that's straightened out, here's the next problem:

    setTimeout(function () {

      // ...

    }, i * 6000);

The first time through that loop, "i" will be the string "partnr1". Thus, that multiplication attempt will result in a NaN. You can keep an external counter to keep track of the property count of the outer map:

var pcount = 1;
$.each(myMap, function(i, val) {
  $.each(val, function(innerKey, innerValue) {
    setTimeout(function() {
      // ...
    }, pcount++ * 6000);
  });
});

How to use mongoose findOne

Found the problem, need to use function(err,obj) instead:

Auth.findOne({nick: 'noname'}, function(err,obj) { console.log(obj); });

node.js - how to write an array to file

Remember you can access good old ECMAScript APIs, in this case, JSON.stringify().

For simple arrays like the one in your example:

require('fs').writeFile(

    './my.json',

    JSON.stringify(myArray),

    function (err) {
        if (err) {
            console.error('Crap happens');
        }
    }
);

Error: could not find function ... in R

If this occurs while you check your package (R CMD check), take a look at your NAMESPACE.

You can solve this by adding the following statement to the NAMESPACE:

exportPattern("^[^\\\\.]")

This exports everything that doesn't start with a dot ("."). This allows you to have your hidden functions, starting with a dot:

.myHiddenFunction <- function(x) cat("my hidden function")

Operator overloading in Java

Just use Xtend along with your Java code. It supports Operator Overloading:

    package com.example;

@SuppressWarnings("all")
public class Test {
  protected int wrapped;

  public Test(final int value) {
    this.wrapped = value;
  }

  public int operator_plus(final Test e2) {
    return (this.wrapped + e2.wrapped);
  }
}

package com.example

class Test2 {

    new() {
        val t1 = new Test(3)
        val t2 = new Test(5)
        val t3 = t1 + t2
    }

}

On the official website, there is a list of the methods to implement for each operator !

npm command to uninstall or prune unused packages in Node.js

Note: Recent npm versions do this automatically when package-locks are enabled, so this is not necessary except for removing development packages with the --production flag.


Run npm prune to remove modules not listed in package.json.

From npm help prune:

This command removes "extraneous" packages. If a package name is provided, then only packages matching one of the supplied names are removed.

Extraneous packages are packages that are not listed on the parent package's dependencies list.

If the --production flag is specified, this command will remove the packages specified in your devDependencies.

com.sun.jdi.InvocationException occurred invoking method

Removing hashCode() and equals() solved my issue. In my case, I used Apache's commons-lang hash code and equals builders for creating non-static classes manually, so the compiler didn't throw any exception. But at runtime it caused the invocation exception.

SQL Server NOLOCK and joins

I was pretty sure that you need to specify the NOLOCK for each JOIN in the query. But my experience was limited to SQL Server 2005.

When I looked up MSDN just to confirm, I couldn't find anything definite. The below statements do seem to make me think, that for 2008, your two statements above are equivalent though for 2005 it is not the case:

[SQL Server 2008 R2]

All lock hints are propagated to all the tables and views that are accessed by the query plan, including tables and views referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.

[SQL Server 2005]

In SQL Server 2005, all lock hints are propagated to all the tables and views that are referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.

Additionally, point to note - and this applies to both 2005 and 2008:

The table hints are ignored if the table is not accessed by the query plan. This may be caused by the optimizer choosing not to access the table at all, or because an indexed view is accessed instead. In the latter case, accessing an indexed view can be prevented by using the OPTION (EXPAND VIEWS) query hint.

Tomcat Servlet: Error 404 - The requested resource is not available

this is may be due to the thing that you have created your .jsp or the .html file in the WEB-INF instead of the WebContent folder.

Solution: Just replace the files that are there in the WEB-INF folder to the Webcontent folder and try executing the same - You will get the appropriate output

Producing a new line in XSLT

I've noticed from my experience that producing a new line INSIDE a <xsl:variable> clause doesn't work. I was trying to do something like:

<xsl:variable name="myVar">
  <xsl:choose>
    <xsl:when test="@myValue != ''">
      <xsl:text>My value: </xsl:text>
      <xsl:value-of select="@myValue" />
      <xsl:text></xsl:text> <!--NEW LINE-->
      <xsl:text>My other value: </xsl:text>
      <xsl:value-of select="@myOtherValue" />
    </xsl:when>
  </xsl:choose>
<xsl:variable>

<div>
  <xsl:value-of select="$myVar"/>
</div>

Anything I tried to put in that "new line" (the empty <xsl:text> node) just didn't work (including most of the simpler suggestions in this page), not to mention the fact that HTML just won't work there, so eventually I had to split it to 2 variables, call them outside the <xsl:variable> scope and put a simple <br/> between them, i.e:

<xsl:variable name="myVar1">
  <xsl:choose>
    <xsl:when test="@myValue != ''">
      <xsl:text>My value: </xsl:text>
      <xsl:value-of select="@myValue" />
    </xsl:when>
  </xsl:choose>
<xsl:variable>

<xsl:variable name="myVar2">
  <xsl:choose>
    <xsl:when test="@myValue != ''">
      <xsl:text>My other value: </xsl:text>
      <xsl:value-of select="@myOtherValue" />
    </xsl:when>
  </xsl:choose>
<xsl:variable>

<div>
  <xsl:value-of select="$myVar1"/>
  <br/>
  <xsl:value-of select="$myVar2"/>
</div>

Yeah, I know, it's not the most sophisticated solution but it works, just sharing my frustration experience with XSLs ;)

ASP.NET GridView RowIndex As CommandArgument

void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    Button b = (Button)e.CommandSource;
    b.CommandArgument = ((GridViewRow)sender).RowIndex.ToString();
}

What does \d+ mean in regular expression terms?

\d is called a character class and will match digits. It is equal to [0-9].

+ matches 1 or more occurrences of the character before.

So \d+ means match 1 or more digits.

How to change the bootstrap primary color?

  • You cannot change the color in cdn file.
  • Download the bootstrap file.
  • Search For bootstrap.css file.
  • open this(bootstrsap.css) file and search for 'primary'.
  • change it to the colour you desire.

How do I do redo (i.e. "undo undo") in Vim?

In command mode, use the U key to undo and Ctrl + r to redo. Have a look at http://www.vim.org/htmldoc/undo.html.

plot with custom text for x axis points

You can manually set xticks (and yticks) using pyplot.xticks:

import matplotlib.pyplot as plt
import numpy as np

x = np.array([0,1,2,3])
y = np.array([20,21,22,23])
my_xticks = ['John','Arnold','Mavis','Matt']
plt.xticks(x, my_xticks)
plt.plot(x, y)
plt.show()

How to get the week day name from a date?

SQL> SELECT TO_CHAR(date '1982-03-09', 'DAY') day FROM dual;

DAY
---------
TUESDAY

SQL> SELECT TO_CHAR(date '1982-03-09', 'DY') day FROM dual;

DAY
---
TUE

SQL> SELECT TO_CHAR(date '1982-03-09', 'Dy') day FROM dual;

DAY
---
Tue

(Note that the queries use ANSI date literals, which follow the ISO-8601 date standard and avoid date format ambiguity.)

A column-vector y was passed when a 1d array was expected

format_train_y=[]
for n in train_y:
    format_train_y.append(n[0])

Headers and client library minor version mismatch

I got same php warring in my wordpress site...

Err: Warning: mysql_connect(): Headers and client library minor version mismatch. Headers:50547 Library:50628 in /home/lhu/public_html/innovacarrentalschennai.com/wp-includes/wp-db.php on line 1515

Cause: I updated wp 4.2 to 4.5 version (PHP and MySql mismatch )

I changed wp-db.php on line 1515

$this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );

to

if ( WP_DEBUG ) {
    $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
} else {
    $this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
}

Its got without warring err on my wordpress site

how to run two commands in sudo?

On the terminal, type:

$ sudo bash

Then write as many commands as you want. Type exit when you done.

If you need to automate it, create a script.sh file and run it:

$ sudo ./script.sh

Unable to verify leaf signature

For Create React App (where this error occurs too and this question is the #1 Google result), you are probably using HTTPS=true npm start and a proxy (in package.json) which goes to some HTTPS API which itself is self-signed, when in development.

If that's the case, consider changing proxy like this:

"proxy": {
  "/api": {
    "target": "https://localhost:5001",
    "secure": false
  }
}

secure decides whether the WebPack proxy checks the certificate chain or not and disabling that ensures the API self-signed certificate is not verified so that you get your data.

retrieve data from db and display it in table in php .. see this code whats wrong with it?

<html>
    <head>
        <meta charset="UTF-8">
        <title>LoginDB</title>
    </head>
    <body>

        <?php
        $con=  mysqli_connect("localhost", "root", "", "detail");
<!-- detail is the database in MySqli Database -->
        if(!$con)
       {
           die('not connected');
       }
            $con=  mysqli_query($con, "select * from signup");
<!-- signup is the table in the detail_Database -->
       ?>
        <div>
            <td>Login Page Database</td>
         <table border="1">
            <th> First Name</th>
                    <th>Last Name</th>
                    <th>UserName</th>
                     <th>Password</th>
                    <th>Gender</th>
                    <th>D.O.B.</th>
                    <th>Phone Number</th>
                    <th>Address</th>

            </tr>

        <?php

             while($row=  mysqli_fetch_array($con))
<!-- Fetch each row from signup Table  -->
             {
                 ?>
            <tr>
                <td><?php echo $row['FirstName']; ?></td>
                <td><?php echo $row['LastName']; ?></td>
                <td><?php echo $row['Username']; ?></td>
                <td><?php echo $row['Password'] ;?></td>
                <td><?php echo $row['Gender'] ;?></td>
                <td><?php echo $row['DOB'] ;?></td>
                <td><?php echo $row['PhoneNumber'] ;?></td>
                <td><?php echo $row['Address'] ;?></td>
            </tr>
        <?php
             }
             ?>
             </table>
            </div>
    </body>
</html>

Using CSS to insert text

Also check out the attr() function of the CSS content attribute. It outputs a given attribute of the element as a text node. Use it like so:

<div class="Owner Joe" />

div:before {
  content: attr(class);
}

Or even with the new HTML5 custom data attributes:

<div data-employeename="Owner Joe" />

div:before {
  content: attr(data-employeename);
}

mongodb, replicates and error: { "$err" : "not master and slaveOk=false", "code" : 13435 }

You have to set "secondary okay" mode to let the mongo shell know that you're allowing reads from a secondary. This is to protect you and your applications from performing eventually consistent reads by accident. You can do this in the shell with:

rs.secondaryOk()

After that you can query normally from secondaries.

A note about "eventual consistency": under normal circumstances, replica set secondaries have all the same data as primaries within a second or less. Under very high load, data that you've written to the primary may take a while to replicate to the secondaries. This is known as "replica lag", and reading from a lagging secondary is known as an "eventually consistent" read, because, while the newly written data will show up at some point (barring network failures, etc), it may not be immediately available.

Edit: You only need to set secondaryOk when querying from secondaries, and only once per session.

Pointers in C: when to use the ampersand and the asterisk?

There is a pattern when dealing with arrays and functions; it's just a little hard to see at first.

When dealing with arrays, it's useful to remember the following: when an array expression appears in most contexts, the type of the expression is implicitly converted from "N-element array of T" to "pointer to T", and its value is set to point to the first element in the array. The exceptions to this rule are when the array expression appears as an operand of either the & or sizeof operators, or when it is a string literal being used as an initializer in a declaration.

Thus, when you call a function with an array expression as an argument, the function will receive a pointer, not an array:

int arr[10];
...
foo(arr);
...

void foo(int *arr) { ... }

This is why you don't use the & operator for arguments corresponding to "%s" in scanf():

char str[STRING_LENGTH];
...
scanf("%s", str);

Because of the implicit conversion, scanf() receives a char * value that points to the beginning of the str array. This holds true for any function called with an array expression as an argument (just about any of the str* functions, *scanf and *printf functions, etc.).

In practice, you will probably never call a function with an array expression using the & operator, as in:

int arr[N];
...
foo(&arr);

void foo(int (*p)[N]) {...}

Such code is not very common; you have to know the size of the array in the function declaration, and the function only works with pointers to arrays of specific sizes (a pointer to a 10-element array of T is a different type than a pointer to a 11-element array of T).

When an array expression appears as an operand to the & operator, the type of the resulting expression is "pointer to N-element array of T", or T (*)[N], which is different from an array of pointers (T *[N]) and a pointer to the base type (T *).

When dealing with functions and pointers, the rule to remember is: if you want to change the value of an argument and have it reflected in the calling code, you must pass a pointer to the thing you want to modify. Again, arrays throw a bit of a monkey wrench into the works, but we'll deal with the normal cases first.

Remember that C passes all function arguments by value; the formal parameter receives a copy of the value in the actual parameter, and any changes to the formal parameter are not reflected in the actual parameter. The common example is a swap function:

void swap(int x, int y) { int tmp = x; x = y; y = tmp; }
...
int a = 1, b = 2;
printf("before swap: a = %d, b = %d\n", a, b);
swap(a, b);
printf("after swap: a = %d, b = %d\n", a, b);

You'll get the following output:

before swap: a = 1, b = 2
after swap: a = 1, b = 2

The formal parameters x and y are distinct objects from a and b, so changes to x and y are not reflected in a and b. Since we want to modify the values of a and b, we must pass pointers to them to the swap function:

void swap(int *x, int *y) {int tmp = *x; *x = *y; *y = tmp; }
...
int a = 1, b = 2;
printf("before swap: a = %d, b = %d\n", a, b);
swap(&a, &b);
printf("after swap: a = %d, b = %d\n", a, b);

Now your output will be

before swap: a = 1, b = 2
after swap: a = 2, b = 1

Note that, in the swap function, we don't change the values of x and y, but the values of what x and y point to. Writing to *x is different from writing to x; we're not updating the value in x itself, we get a location from x and update the value in that location.

This is equally true if we want to modify a pointer value; if we write

int myFopen(FILE *stream) {stream = fopen("myfile.dat", "r"); }
...
FILE *in;
myFopen(in);

then we're modifying the value of the input parameter stream, not what stream points to, so changing stream has no effect on the value of in; in order for this to work, we must pass in a pointer to the pointer:

int myFopen(FILE **stream) {*stream = fopen("myFile.dat", "r"); }
...
FILE *in;
myFopen(&in);

Again, arrays throw a bit of a monkey wrench into the works. When you pass an array expression to a function, what the function receives is a pointer. Because of how array subscripting is defined, you can use a subscript operator on a pointer the same way you can use it on an array:

int arr[N];
init(arr, N);
...
void init(int *arr, int N) {size_t i; for (i = 0; i < N; i++) arr[i] = i*i;}

Note that array objects may not be assigned; i.e., you can't do something like

int a[10], b[10];
...
a = b;

so you want to be careful when you're dealing with pointers to arrays; something like

void (int (*foo)[N])
{
  ...
  *foo = ...;
}

won't work.

How to filter JSON Data in JavaScript or jQuery?

I know the question explicitly says JS or jQuery, but anyway using lodash is always on the table for other searchers I suppose.

From the source docs:

var users = [
  { 'user': 'barney', 'age': 36, 'active': true },
  { 'user': 'fred',   'age': 40, 'active': false }
];

_.filter(users, function(o) { return !o.active; });
// => objects for ['fred']

// The `_.matches` iteratee shorthand.
_.filter(users, { 'age': 36, 'active': true });
// => objects for ['barney']

// The `_.matchesProperty` iteratee shorthand.
_.filter(users, ['active', false]);
// => objects for ['fred']

// The `_.property` iteratee shorthand.
_.filter(users, 'active');
// => objects for ['barney']

So the solution for the original question would be just one liner:

var result = _.filter(data, ['website', 'yahoo']);

css label width not taking effect

Make it a block first, then float left to stop pushing the next block in to a new line.

#report-upload-form label {
                           padding-left:26px;
                           width:125px;
                           text-transform: uppercase;
                           display:block;
                           float:left
}

When I catch an exception, how do I get the type, file, and line number?

Without any imports, but also incompatible with imported modules:

try:
    raise TypeError("Hello, World!")  # line 2
except Exception as e:
    print(
        type(e).__name__,          # TypeError
        __file__,                  # /tmp/example.py
        e.__traceback__.tb_lineno  # 2
    )

$ python3 /tmp/example.py
TypeError /tmp/example.py 2

To reiterate, this does not work across imports or modules, so if you do import X; try: X.example(); then the filename and line number will point to the line containing X.example() instead of the line where it went wrong within X.example(). If anyone knows how to easily get the file name and line number from the last stack trace line (I expected something like e[-1].filename, but no such luck), please improve this answer.

Angular 4 - Select default value in dropdown [Reactive Forms]

I was struggling and Found this Easy and Effective way from IntelliJ IDEA suggestion

<select id="country" formControlName="country"  >
  <option [defaultSelected]=true [value]="default" >{{default}}</option>
  <option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
</select> 

And On your ts file assign the values

 countries = ['USA', 'UK', 'Canada'];
 default = 'UK'

Just make sure your formControlName accepts string, because you already assigned it as a string.

Custom HTTP Authorization Header

No, that is not a valid production according to the "credentials" definition in RFC 2617. You give a valid auth-scheme, but auth-param values must be of the form token "=" ( token | quoted-string ) (see section 1.2), and your example doesn't use "=" that way.

How to get primary key column in Oracle?

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

Make sure that 'TABLE_NAME' is in upper case since Oracle stores table names in upper case.

std::string length() and size() member functions

As per the documentation, these are just synonyms. size() is there to be consistent with other STL containers (like vector, map, etc.) and length() is to be consistent with most peoples' intuitive notion of character strings. People usually talk about a word, sentence or paragraph's length, not its size, so length() is there to make things more readable.

How do I download/extract font from chrome developers tools?

To get .woff fonts first open the chrome dev tools panel (Ctrl+Shift+i) go to Network and reload the page. There you will see everything the page downloads. Find the .woff file, right click and select Copy response.

The response will be a url so paste it in the navigation bar. A file will be downloaded, just add the .woff extension to it and voila.

Easiest way to parse a comma delimited string to some kind of object I can loop through to access the individual values?

Use Linq, it is a very quick and easy way.

string mystring = "0, 10, 20, 30, 100, 200";

var query = from val in mystring.Split(',')
            select int.Parse(val);
foreach (int num in query)
{
     Console.WriteLine(num);
}

Lambda expression to convert array/List of String to array/List of Integers

You can also use,

List<String> list = new ArrayList<>();
    list.add("1");
    list.add("2");
    list.add("3");

    Integer[] array = list.stream()
        .map( v -> Integer.valueOf(v))
        .toArray(Integer[]::new);

If Cell Starts with Text String... Formula

As of Excel 2019 you could do this. The "Error" at the end is the default.

SWITCH(LEFT(A1,1), "A", "Pick Up", "B", "Collect", "C", "Prepaid", "Error")

Microsoft Excel Switch Documentation

adding onclick event to dynamically added button?

Try this:

var inputTag = document.createElement("div");              
inputTag.innerHTML = "<input type = 'button' value = 'oooh' onClick = 'your_function_name()'>";    
document.body.appendChild(inputTag);

This creates a button inside a DIV which works perfectly!

Netbeans 8.0.2 The module has not been deployed

Try to change Tomcat version, in my case tomcat "8.0.41" and "8.5.8" didn't work. But "8.5.37" worked fine.

How to add multiple columns to pandas dataframe in one assignment?

I would have expected your syntax to work too. The problem arises because when you create new columns with the column-list syntax (df[[new1, new2]] = ...), pandas requires that the right hand side be a DataFrame (note that it doesn't actually matter if the columns of the DataFrame have the same names as the columns you are creating).

Your syntax works fine for assigning scalar values to existing columns, and pandas is also happy to assign scalar values to a new column using the single-column syntax (df[new1] = ...). So the solution is either to convert this into several single-column assignments, or create a suitable DataFrame for the right-hand side.

Here are several approaches that will work:

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'col_1': [0, 1, 2, 3],
    'col_2': [4, 5, 6, 7]
})

Then one of the following:

1) Three assignments in one, using list unpacking:

df['column_new_1'], df['column_new_2'], df['column_new_3'] = [np.nan, 'dogs', 3]

2) DataFrame conveniently expands a single row to match the index, so you can do this:

df[['column_new_1', 'column_new_2', 'column_new_3']] = pd.DataFrame([[np.nan, 'dogs', 3]], index=df.index)

3) Make a temporary data frame with new columns, then combine with the original data frame later:

df = pd.concat(
    [
        df,
        pd.DataFrame(
            [[np.nan, 'dogs', 3]], 
            index=df.index, 
            columns=['column_new_1', 'column_new_2', 'column_new_3']
        )
    ], axis=1
)

4) Similar to the previous, but using join instead of concat (may be less efficient):

df = df.join(pd.DataFrame(
    [[np.nan, 'dogs', 3]], 
    index=df.index, 
    columns=['column_new_1', 'column_new_2', 'column_new_3']
))

5) Using a dict is a more "natural" way to create the new data frame than the previous two, but the new columns will be sorted alphabetically (at least before Python 3.6 or 3.7):

df = df.join(pd.DataFrame(
    {
        'column_new_1': np.nan,
        'column_new_2': 'dogs',
        'column_new_3': 3
    }, index=df.index
))

6) Use .assign() with multiple column arguments.

I like this variant on @zero's answer a lot, but like the previous one, the new columns will always be sorted alphabetically, at least with early versions of Python:

df = df.assign(column_new_1=np.nan, column_new_2='dogs', column_new_3=3)

7) This is interesting (based on https://stackoverflow.com/a/44951376/3830997), but I don't know when it would be worth the trouble:

new_cols = ['column_new_1', 'column_new_2', 'column_new_3']
new_vals = [np.nan, 'dogs', 3]
df = df.reindex(columns=df.columns.tolist() + new_cols)   # add empty cols
df[new_cols] = new_vals  # multi-column assignment works for existing cols

8) In the end it's hard to beat three separate assignments:

df['column_new_1'] = np.nan
df['column_new_2'] = 'dogs'
df['column_new_3'] = 3

Note: many of these options have already been covered in other answers: Add multiple columns to DataFrame and set them equal to an existing column, Is it possible to add several columns at once to a pandas DataFrame?, Add multiple empty columns to pandas DataFrame

How do I show running processes in Oracle DB?

Keep in mind that there are processes on the database which may not currently support a session.

If you're interested in all processes you'll want to look to v$process (or gv$process on RAC)

What's the difference between dependencies, devDependencies and peerDependencies in npm package.json file?

There are some modules and packages only necessary for development, which are not needed in production. Like it says it in the documentation:

If someone is planning on downloading and using your module in their program, then they probably don't want or need to download and build the external test or documentation framework that you use. In this case, it's best to list these additional items in a devDependencies hash.

NSURLSession/NSURLConnection HTTP load failed on iOS 9

Update:

As of Xcode 7.1, you don't need to manually enter the NSAppTransportSecurity Dictionary in the info.plist.

It will now autocomplete for you, realize it's a dictionary, and then autocomplete the Allows Arbitrary Loads as well. info.plist screenshot

Convert Mat to Array/Vector in OpenCV

If the memory of the Mat mat is continuous (all its data is continuous), you can directly get its data to a 1D array:

std::vector<uchar> array(mat.rows*mat.cols*mat.channels());
if (mat.isContinuous())
    array = mat.data;

Otherwise, you have to get its data row by row, e.g. to a 2D array:

uchar **array = new uchar*[mat.rows];
for (int i=0; i<mat.rows; ++i)
    array[i] = new uchar[mat.cols*mat.channels()];

for (int i=0; i<mat.rows; ++i)
    array[i] = mat.ptr<uchar>(i);

UPDATE: It will be easier if you're using std::vector, where you can do like this:

std::vector<uchar> array;
if (mat.isContinuous()) {
  // array.assign(mat.datastart, mat.dataend); // <- has problems for sub-matrix like mat = big_mat.row(i)
  array.assign(mat.data, mat.data + mat.total()*mat.channels());
} else {
  for (int i = 0; i < mat.rows; ++i) {
    array.insert(array.end(), mat.ptr<uchar>(i), mat.ptr<uchar>(i)+mat.cols*mat.channels());
  }
}

p.s.: For cv::Mats of other types, like CV_32F, you should do like this:

std::vector<float> array;
if (mat.isContinuous()) {
  // array.assign((float*)mat.datastart, (float*)mat.dataend); // <- has problems for sub-matrix like mat = big_mat.row(i)
  array.assign((float*)mat.data, (float*)mat.data + mat.total()*mat.channels());
} else {
  for (int i = 0; i < mat.rows; ++i) {
    array.insert(array.end(), mat.ptr<float>(i), mat.ptr<float>(i)+mat.cols*mat.channels());
  }
}

UPDATE2: For OpenCV Mat data continuity, it can be summarized as follows:

  • Matrices created by imread(), clone(), or a constructor will always be continuous.
  • The only time a matrix will not be continuous is when it borrows data (except the data borrowed is continuous in the big matrix, e.g. 1. single row; 2. multiple rows with full original width) from an existing matrix (i.e. created out of an ROI of a big mat).

Please check out this code snippet for demonstration.

How to add subject alernative name to ssl certs?

Although this question was more specifically about IP addresses in Subject Alt. Names, the commands are similar (using DNS entries for a host name and IP entries for IP addresses).

To quote myself:

If you're using keytool, as of Java 7, keytool has an option to include a Subject Alternative Name (see the table in the documentation for -ext): you could use -ext san=dns:www.example.com or -ext san=ip:10.0.0.1

Note that you only need Java 7's keytool to use this command. Once you've prepared your keystore, it should work with previous versions of Java.

(The rest of this answer also mentions how to do this with OpenSSL, but it doesn't seem to be what you're using.)

Set left margin for a paragraph in html

<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>

That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em' as the measurement, you may want to use other units, like 'px'.

EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:

In your HTML page, containing the <p> tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:

<head>
  <style type="text/css">
    p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>

So above, all <p> elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:

<head>
  <style type="text/css">
    .container p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <div class="container">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
  </div>
  <p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>

In the example above, only the <p> element inside the div, whose class name is 'container', will have the styles applied - and not the <p> element outside the container.

In addition to the above, you can collect your styles together and remove the style element from the <head> tag, replacing it with a <link> tag, which points to an external CSS file. This external file is where you'd now put your <p> tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.

Assigning the return value of new by reference is deprecated

Nitin is correct - the issue is actually in the MDB2 code.

According to Replacement for PEAR: MDB2 on PHP 5.3 you can update to the SVN version of MDB2 for a version which is PHP5.3 compatible.

As that answer was given in March 2010, and http://pear.php.net/package/MDB2/ shows a release some months later, I expect the current version of MDB2 will solve the issue also.

How to add a scrollbar to an HTML5 table?

@jogesh_pi answer is a good solution, i've created a example here http://jsfiddle.net/pqgaS/5/, check it, hope this help

<div id="listtableWrapperScroll">
    <table id="listtable">
        <tr>
            <td>Data Data</td>
            <td>Data Data</td>
            <td>Data Data</td>                
        </tr>
    </table>
</div>

#listtableWrapperScroll{
    height:100px;
    width:460px;
    overflow-y:scroll;
    border:1px solid #777777;
    background:#FFFFF2;
}
#listtableWrapperScroll #listtable{
    width:440px;       
}
#listtableWrapperScroll #listtable tr td{
    border-bottom:1px dashed #444;
}

"Cannot instantiate the type..."

Queue is an Interface so you can not initiate it directly. Initiate it by one of its implementing classes.

From the docs all known implementing classes:

  • AbstractQueue
  • ArrayBlockingQueue
  • ArrayDeque
  • ConcurrentLinkedQueue
  • DelayQueue
  • LinkedBlockingDeque
  • LinkedBlockingQueue
  • LinkedList
  • PriorityBlockingQueue
  • PriorityQueue
  • SynchronousQueue

You can use any of above based on your requirement to initiate a Queue object.

How do ACID and database transactions work?

ACID are desirable properties of any transaction processing engine.

A DBMS is (if it is any good) a particular kind of transaction processing engine that exposes, usually to a very large extent but not quite entirely, those properties.

But other engines exist that can also expose those properties. The kind of software that used to be called "TP monitors" being a case in point (nowadays' equivalent mostly being web servers).

Such TP monitors can access resources other than a DBMS (e.g. a printer), and still guarantee ACID toward their users. As an example of what ACID might mean when a printer is involved in a transaction:

  • Atomicity: an entire document gets printed or nothing at all
  • Consistency: at end-of-transaction, the paper feed is positioned at top-of-page
  • Isolation: no two documents get mixed up while printing
  • Durability: the printer can guarantee that it was not "printing" with empty cartridges.

ALTER TABLE on dependent column

If your constraint is on a user type, then don't forget to see if there is a Default Constraint, usually something like DF__TableName__ColumnName__6BAEFA67, if so then you will need to drop the Default Constraint, like this:

ALTER TABLE TableName DROP CONSTRAINT [DF__TableName__ColumnName__6BAEFA67]

For more info see the comments by the brilliant Aaron Bertrand on this answer.

EPPlus - Read Excel Table

Not sure why but none of the above solution work for me. So sharing what worked:

public void readXLS(string FilePath)
{
    FileInfo existingFile = new FileInfo(FilePath);
    using (ExcelPackage package = new ExcelPackage(existingFile))
    {
        //get the first worksheet in the workbook
        ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
        int colCount = worksheet.Dimension.End.Column;  //get Column Count
        int rowCount = worksheet.Dimension.End.Row;     //get row count
        for (int row = 1; row <= rowCount; row++)
        {
            for (int col = 1; col <= colCount; col++)
            {
                Console.WriteLine(" Row:" + row + " column:" + col + " Value:" + worksheet.Cells[row, col].Value?.ToString().Trim());
            }
        }
    }
}

Mobile Safari: Javascript focus() method on inputfield only works with click?

This solution works well, I tested on my phone:

document.body.ontouchend = function() { document.querySelector('[name="name"]').focus(); };

enjoy

How can I upload files asynchronously?

You can do it in vanilla JavaScript pretty easily. Here's a snippet from my current project:

var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e) {
    var percent = (e.position/ e.totalSize);
    // Render a pretty progress bar
};
xhr.onreadystatechange = function(e) {
    if(this.readyState === 4) {
        // Handle file upload complete
    }
};
xhr.open('POST', '/upload', true);
xhr.setRequestHeader('X-FileName',file.name); // Pass the filename along
xhr.send(file);

How to connect SQLite with Java?

You have to download and add the SQLite JDBC driver to your classpath.
You can download from here https://bitbucket.org/xerial/sqlite-jdbc/downloads

If you use Gradle, you will only have to add the SQLite dependency:

dependencies {
    compile 'org.xerial:sqlite-jdbc:3.8.11.2'
} 

Next thing you have to do is to initialize the driver:

try {
    Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException eString) {
    System.err.println("Could not init JDBC driver - driver not found");
}

How can I move all the files from one folder to another using the command line?

Be sure to use quotes if there are spaces in the file path:

move "C:\Users\MyName\My Old Folder\*" "C:\Users\MyName\My New Folder"

That will move the contents of C:\Users\MyName\My Old Folder\ to C:\Users\MyName\My New Folder

Can't perform a React state update on an unmounted component

I know that you're not using history, but in my case I was using the useHistory hook from React Router DOM, which unmounts the component before the state is persisted in my React Context Provider.

To fix this problem I have used the hook withRouter nesting the component, in my case export default withRouter(Login), and inside the component const Login = props => { ...; props.history.push("/dashboard"); .... I have also removed the other props.history.push from the component, e.g, if(authorization.token) return props.history.push('/dashboard') because this causes a loop, because the authorization state.

An alternative to push a new item to history.

MongoDB: How to find out if an array field contains an element?

It seems like the $in operator would serve your purposes just fine.

You could do something like this (pseudo-query):

if (db.courses.find({"students" : {"$in" : [studentId]}, "course" : courseId }).count() > 0) {
  // student is enrolled in class
}

Alternatively, you could remove the "course" : courseId clause and get back a set of all classes the student is enrolled in.

Convert char array to a int number in C

Why not just use atoi? For example:

char myarray[4] = {'-','1','2','3'};

int i = atoi(myarray);

printf("%d\n", i);

Gives me, as expected:

-123

Update: why not - the character array is not null terminated. Doh!

Fastest way to remove non-numeric characters from a VARCHAR in SQL Server

I'd use an Inline Function from performance perspective, see below: Note that symbols like '+','-' etc will not be removed

CREATE FUNCTION [dbo].[UDF_RemoveNumericStringsFromString]
 (
 @str varchar(100)
 )
 RETURNS TABLE AS RETURN
 WITH Tally (n) as 
  (
  -- 100 rows
   SELECT TOP (Len(@Str)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
   FROM (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) a(n)
   CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) b(n)
  )

  SELECT OutStr =  STUFF(
       (SELECT SUBSTRING(@Str, n,1) st
        FROM Tally
        WHERE ISNUMERIC(SUBSTRING(@Str, n,1)) = 1
        FOR XML PATH(''),type).value('.', 'varchar(100)'),1,0,'')
  GO

  /*Use it*/
  SELECT OutStr
  FROM dbo.UDF_RemoveNumericStringsFromString('fjkfhk759734977fwe9794t23')
  /*Result set
   759734977979423 */

You can define it with more than 100 characters...

Apply CSS rules to a nested class inside a div

Use Css Selector for this, or learn more about Css Selector just go here https://www.w3schools.com/cssref/css_selectors.asp

#main_text > .title {
  /* Style goes here */
}

#main_text .title {
  /* Style goes here */
}

sql - insert into multiple tables in one query

You can't. However, you CAN use a transaction and have both of them be contained within one transaction.

START TRANSACTION;
INSERT INTO table1 VALUES ('1','2','3');
INSERT INTO table2 VALUES ('bob','smith');
COMMIT;

http://dev.mysql.com/doc/refman/5.1/en/commit.html

Variable number of arguments in C++?

As others have said, C-style varargs. But you can also do something similar with default arguments.

batch file Copy files with certain extensions from multiple directories into one directory

Brandon, short and sweet. Also flexible.

set dSource=C:\Main directory\sub directory
set dTarget=D:\Documents
set fType=*.doc
for /f "delims=" %%f in ('dir /a-d /b /s "%dSource%\%fType%"') do (
    copy /V "%%f" "%dTarget%\" 2>nul
)

Hope this helps.

I would add some checks after the copy (using '||') but i'm not sure how "copy /v" reacts when it encounters an error.

you may want to try this:

copy /V "%%f" "%dTarget%\" 2>nul|| echo En error occured copying "%%F".&& exit /b 1

As the copy line. let me know if you get something out of it (in no position to test a copy failure atm..)

YAML Multi-Line Arrays

If what you are needing is an array of arrays, you can do this way:

key:
  - [ 'value11', 'value12', 'value13' ]
  - [ 'value21', 'value22', 'value23' ]

How to use a keypress event in AngularJS?

You can use ng-keydown ="myFunction($event)" as attribute.

<input ng-keydown="myFunction($event)" type="number">

myFunction(event) {
    if(event.keyCode == 13) {   // '13' is the key code for enter
        // do what you want to do when 'enter' is pressed :)
    }
}

ngModel cannot be used to register form controls with a parent formGroup directive

Expanding on @Avenir Çokaj's answer

Being a novice even I did not understand the error message clearly at first.

What the error message indicates is that in your formGroup you have an element that doesn't get accounted for in your formControl. (Intentionally/Accidentally)

If you intend on not validating this field but still want to use the ngModel on this input element please add the flag to indicate it's a standalone component without a need for validation as mentioned by @Avenir above.

Alternate background colors for list items

You can by hardcoding the sequence, like so:

li, li + li + li, li + li + li + li + li {
  background-color: black;
}

li + li, li + li + li + li {
  background-color: white;
}

Creating stored procedure and SQLite?

Yet, it is possible to fake it using a dedicated table, named for your fake-sp, with an AFTER INSERT trigger. The dedicated table rows contain the parameters for your fake sp, and if it needs to return results you can have a second (poss. temp) table (with name related to the fake-sp) to contain those results. It would require two queries: first to INSERT data into the fake-sp-trigger-table, and the second to SELECT from the fake-sp-results-table, which could be empty, or have a message-field if something went wrong.

onKeyDown event not working on divs in React

You're missing the binding of the method in the constructor. This is how React suggests that you do it:

class Whatever {
  constructor() {
    super();
    this.onKeyPressed = this.onKeyPressed.bind(this);
  }

  onKeyPressed(e) {
    // your code ...
  }

  render() {
    return (<div onKeyDown={this.onKeyPressed} />);
  }
}

There are other ways of doing this, but this will be the most efficient at runtime.

What is the best collation to use for MySQL with PHP?

Essentially, it depends on how you think of a string.

I always use utf8_bin because of the problem highlighted by Guus. In my opinion, as far as the database should be concerned, a string is still just a string. A string is a number of UTF-8 characters. A character has a binary representation so why does it need to know the language you're using? Usually, people will be constructing databases for systems with the scope for multilingual sites. This is the whole point of using UTF-8 as a character set. I'm a bit of a pureist but I think the bug risks heavily outweigh the slight advantage you may get on indexing. Any language related rules should be done at a much higher level than the DBMS.

In my books "value" should never in a million years be equal to "valúe".

If I want to store a text field and do a case insensitive search, I will use MYSQL string functions with PHP functions such as LOWER() and the php function strtolower().

How and where are Annotations used in Java?

It is useful for annotating your classes, either at the method, class, or field level, something about that class that is not quite related to the class.

You could have your own annotations, used to mark certain classes as test-use only. It could simply be for documentation purposes, or you could enforce it by filtering it out during your compile of a production release candidate.

You could use annotations to store some meta data, like in a plugin framework, e.g., name of the plugin.

Its just another tool, its has many purposes.

How to find index of STRING array in Java from a given value?

for (int i = 0; i < Types.length; i++) {
    if(TYPES[i].equals(userString)){
        return i;
    }
}
return -1;//not found

You can do this too:

return Arrays.asList(Types).indexOf(userSTring);

Use own username/password with git and bitbucket

Well, it's part of BitBucket philosophy and workflow:

  • Repository may have only one user: owner
  • For ordinary accounts (end-user's) collaboration expect "fork-pull request" workflow

i.e you can't (in usual case) commit into foreign repo under own credentials.

You have two possible solutions:

  1. "Classic" BB-way: fork repo (get owned by you repository), make changes, send pull request to origin repo
  2. Create "Team", add user-accounts as members of team, make Team owner of repository - it this case for this "Shared central" repository every team memeber can push under own credentials - inspect thg repository and TortoiseHg Team, owner of this repository, as samples

How to copy folders to docker image from Dockerfile?

the simplest way:

sudo docker cp path/on/your/machine adam_ubuntu:/root/path_in_container

Note putting into the root path if you are copying something that needs to be picked up by the root using ~.

Iterate over object attributes in python

The correct answer to this is that you shouldn't. If you want this type of thing either just use a dict, or you'll need to explicitly add attributes to some container. You can automate that by learning about decorators.

In particular, by the way, method1 in your example is just as good of an attribute.

Running Tensorflow in Jupyter Notebook

  1. install tensorflow by running these commands in anoconda shell or in console:

    conda create -n tensorflow python=3.5
    activate tensorflow
    conda install pandas matplotlib jupyter notebook scipy scikit-learn
    pip install tensorflow
    
  2. close the console and reopen it and type these commands:

    activate tensorflow 
    jupyter notebook 
    

How to replace string in Groovy

You need to escape the backslash \:

println yourString.replace("\\", "/")

Convert numpy array to tuple

I was not satisfied, so I finally used this:

>>> a=numpy.array([[1,2,3],[4,5,6]])
>>> a
array([[1, 2, 3],
       [4, 5, 6]])

>>> tuple(a.reshape(1, -1)[0])
(1, 2, 3, 4, 5, 6)

I don't know if it's quicker, but it looks more effective ;)

Run cmd commands through Java

Here the value adder is use of ampersands to batch commands and correct format for change drive with cd.

public class CmdCommander {

public static void main(String[] args) throws Exception {
    //easyway to start native windows command prompt from Intellij

    /*
    Rules are:
    1.baseStart must be dual start
    2.first command must not have &.
    3.subsequent commands must be prepended with &
    4.drive change needs extra &
    5.use quotes at start and end of command batch
    */
    String startQuote = "\"";
    String endQuote = "\"";
    //String baseStart_not_taking_commands = " cmd  /K start ";
    String baseStart = " cmd  /K start cmd /K ";//dual start is must

    String first_command_chcp = " chcp 1251 ";
    String dirList = " &dir ";//& in front of commands after first command means enter
    //change drive....to yours
    String changeDir = " &cd &I: ";//extra & makes changing drive happen

    String javaLaunch = " &java ";//just another command
    String javaClass = " Encodes ";//parameter for java needs no &

    String javaCommand = javaLaunch + javaClass;
    //build batch command
    String totalCommand =
            baseStart +
                    startQuote +
                    first_command_chcp +
                    //javaCommand +
                    changeDir +
                    dirList +
                    endQuote;

    System.out.println(totalCommand);//prints into Intellij terminal
    runCmd(totalCommand);
    //Thread t = Thread.currentThread();
    //t.sleep(3000);
    System.out.println("loppu hep");//prints into Intellij terminal

}


public static void runCmd(String command) throws Exception {

    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(command);


}

}

Delete commit on gitlab

Supose you have the following scenario:

* 1bd2200 (HEAD, master) another commit
* d258546 bad commit
* 0f1efa9 3rd commit
* bd8aa13 2nd commit
* 34c4f95 1st commit

Where you want to remove d258546 i.e. "bad commit".

You shall try an interactive rebase to remove it: git rebase -i 34c4f95

then your default editor will pop with something like this:

 pick bd8aa13 2nd commit
 pick 0f1efa9 3rd commit
 pick d258546 bad commit
 pick 1bd2200 another commit

 # Rebase 34c4f95..1bd2200 onto 34c4f95
 #
 # Commands:
 #  p, pick = use commit
 #  r, reword = use commit, but edit the commit message
 #  e, edit = use commit, but stop for amending
 #  s, squash = use commit, but meld into previous commit
 #  f, fixup = like "squash", but discard this commit's log message
 #  x, exec = run command (the rest of the line) using shell
 #
 # These lines can be re-ordered; they are executed from top to bottom.
 #
 # If you remove a line here THAT COMMIT WILL BE LOST.
 #
 # However, if you remove everything, the rebase will be aborted.
 #
 # Note that empty commits are commented out

just remove the line with the commit you want to strip and save+exit the editor:

 pick bd8aa13 2nd commit
 pick 0f1efa9 3rd commit
 pick 1bd2200 another commit
 ...

git will proceed to remove this commit from your history leaving something like this (mind the hash change in the commits descendant from the removed commit):

 * 34fa994 (HEAD, master) another commit
 * 0f1efa9 3rd commit
 * bd8aa13 2nd commit
 * 34c4f95 1st commit

Now, since I suppose that you already pushed the bad commit to gitlab, you'll need to repush your graph to the repository (but with the -f option to prevent it from being rejected due to a non fastforwardeable history i.e. git push -f <your remote> <your branch>)

Please be extra careful and make sure that none coworker is already using the history containing the "bad commit" in their branches.

Alternative option:

Instead of rewrite the history, you may simply create a new commit which negates the changes introduced by your bad commit, to do this just type git revert <your bad commit hash>. This option is maybe not as clean, but is far more safe (in case you are not fully aware of what are you doing with an interactive rebase).

Code for a simple JavaScript countdown timer?

So far the answers seem to rely on code being run instantly. If you set a timer for 1000ms, it will actually be around 1008 instead.

Here is how you should do it:

function timer(time,update,complete) {
    var start = new Date().getTime();
    var interval = setInterval(function() {
        var now = time-(new Date().getTime()-start);
        if( now <= 0) {
            clearInterval(interval);
            complete();
        }
        else update(Math.floor(now/1000));
    },100); // the smaller this number, the more accurate the timer will be
}

To use, call:

timer(
    5000, // milliseconds
    function(timeleft) { // called every step to update the visible countdown
        document.getElementById('timer').innerHTML = timeleft+" second(s)";
    },
    function() { // what to do after
        alert("Timer complete!");
    }
);

Windows Application has stopped working :: Event Name CLR20r3

Make sure the client computer has the same or higher version of the .NET framework that you built your program to.

How to return Json object from MVC controller to view

$.ajax({
    dataType: "json",
    type: "POST",
    url: "/Home/AutocompleteID",
    data: data,
    success: function (data) {
        $('#search').html('');
        $('#search').append(data[0].Scheme_Code);
        $('#search').append(data[0].Scheme_Name);
    }
});

Disabling enter key for form

Just add following code in <Head> Tag in your HTML Code. It will Form submission on Enter Key For all fields on form.

<script type="text/javascript">
    function stopEnterKey(evt) {
        var evt = (evt) ? evt : ((event) ? event : null);
        var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
        if ((evt.keyCode == 13) && (node.type == "text")) { return false; }
    }
    document.onkeypress = stopEnterKey;
</script>

How do I access properties of a javascript object if I don't know the names?

You can loop through keys like this:

for (var key in data) {
  console.log(key);
}

This logs "Name" and "Value".

If you have a more complex object type (not just a plain hash-like object, as in the original question), you'll want to only loop through keys that belong to the object itself, as opposed to keys on the object's prototype:

for (var key in data) {
  if (data.hasOwnProperty(key)) {
    console.log(key);
  }
}

As you noted, keys are not guaranteed to be in any particular order. Note how this differs from the following:

for each (var value in data) {
  console.log(value);
}

This example loops through values, so it would log Property Name and 0. N.B.: The for each syntax is mostly only supported in Firefox, but not in other browsers.

If your target browsers support ES5, or your site includes es5-shim.js (recommended), you can also use Object.keys:

var data = { Name: 'Property Name', Value: '0' };
console.log(Object.keys(data)); // => ["Name", "Value"]

and loop with Array.prototype.forEach:

Object.keys(data).forEach(function (key) {
  console.log(data[key]);
});
// => Logs "Property Name", 0

Key value pairs using JSON

var object = {
    key1 : {
        name : 'xxxxxx',
        value : '100.0'
    },
    key2 : {
        name : 'yyyyyyy',
        value : '200.0'
    },
    key3 : {
        name : 'zzzzzz',
        value : '500.0'
    },
}

If thats how your object looks and you want to loop each name and value then I would try and do something like.

$.each(object,function(key,innerjson){
    /*
        key would be key1,key2,key3
        innerjson would be the name and value **
    */

    //Alerts and logging of the variable.
    console.log(innerjson); //should show you the value    
    alert(innerjson.name); //Should say xxxxxx,yyyyyy,zzzzzzz
});

How to define multiple CSS attributes in jQuery?

Using a plain object, you can pair up strings that represent property names with their corresponding values. Changing the background color, and making text bolder, for instance would look like this:

$("#message").css({
    "background-color": "#0F0", 
    "font-weight"     : "bolder"
});

Alternatively, you can use the JavaScript property names too:

$("#message").css({
    backgroundColor: "rgb(128, 115, 94)",
    fontWeight     : "700"
});

More information can be found in jQuery's documentation.

Hibernate HQL Query : How to set a Collection as a named parameter of a Query?

In TorpedoQuery it look like this

Entity from = from(Entity.class);
where(from.getCode()).in("Joe", "Bob");
Query<Entity> select = select(from);

New line in Sql Query

use CHAR(10) for New Line in SQL
char(9) for Tab
and Char(13) for Carriage Return

What is the difference between DSA and RSA?

With reference to man ssh-keygen, the length of a DSA key is restricted to exactly 1024 bit to remain compliant with NIST's FIPS 186-2. Nonetheless, longer DSA keys are theoretically possible; FIPS 186-3 explicitly allows them. Furthermore, security is no longer guaranteed with 1024 bit long RSA or DSA keys.

In conclusion, a 2048 bit RSA key is currently the best choice.

MORE PRECAUTIONS TO TAKE

Establishing a secure SSH connection entails more than selecting safe encryption key pair technology. In view of Edward Snowden's NSA revelations, one has to be even more vigilant than what previously was deemed sufficient.

To name just one example, using a safe key exchange algorithm is equally important. Here is a nice overview of current best SSH hardening practices.

How to escape the equals sign in properties files

I've been able to input values within the character ":

db_user="postgresql"
db_passwd="this,is,my,password"

Override browser form-filling and input highlighting with HTML/CSS

Simple javascript solution for all browser:

setTimeout(function() {
    $(".parent input").each(function(){
        parent = $(this).parents(".parent");
        $(this).clone().appendTo(parent);   
        $(this).attr("id","").attr("name","").hide();
    }); 
}, 300 );

Clone input, reset attribute and hide original input. Timeout is needed for iPad

Serialize JavaScript object into JSON string

This might be useful. http://nanodeath.github.com/HydrateJS/ https://github.com/nanodeath/HydrateJS

Use hydrate.stringify to serialize the object and hydrate.parse to deserialize.

How to force view controller orientation in iOS 8?

I found that if it's a presented view controller, you can override preferredInterfaceOrientationForPresentation

Swift:

override func supportedInterfaceOrientations() -> Int {
  return Int(UIInterfaceOrientationMask.Landscape.rawValue)
}

override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
  return UIInterfaceOrientation.LandscapeLeft
}

override func shouldAutorotate() -> Bool {
  return false
}

INSERT INTO...SELECT for all MySQL columns

don't you need double () for the values bit? if not try this (although there must be a better way

insert into this_table_archive (id, field_1, field_2, field_3) 
values
((select id from this_table where entry_date < '2001-01-01'), 
((select field_1 from this_table where entry_date < '2001-01-01'), 
((select field_2 from this_table where entry_date < '2001-01-01'), 
((select field_3 from this_table where entry_date < '2001-01-01'));

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

Use Encoding.Convert to adjust the byte array before attempting to decode it into your destination encoding.

Encoding iso = Encoding.GetEncoding("ISO-8859-1");
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(Message);
byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes);
string msg = iso.GetString(isoBytes);

How do you fadeIn and animate at the same time?

For people still looking a couple of years later, things have changed a bit. You can now use the queue for .fadeIn() as well so that it will work like this:

$('.tooltip').fadeIn({queue: false, duration: 'slow'});
$('.tooltip').animate({ top: "-10px" }, 'slow');

This has the benefit of working on display: none elements so you don't need the extra two lines of code.

Can I get "&&" or "-and" to work in PowerShell?

Very old question, but for the newcomers: maybe the PowerShell version (similar but not equivalent) that the question is looking for, is to use -and as follows:

(build_command) -and (run_tests_command)

orderBy multiple fields in Angular

Make sure that the sorting is not to complicated for the end user. I always thought sorting on group and sub group is a little bit complicated to understand. If its a technical end user it might be OK.

Convert dictionary to list collection in C#

If you want to pass the Dictionary keys collection into one method argument.

List<string> lstKeys = Dict.Keys;
Methodname(lstKeys);
-------------------
void MethodName(List<String> lstkeys)
{
    `enter code here`
    //Do ur task
}

How to create a new text file using Python

# Method 1
f = open("Path/To/Your/File.txt", "w")   # 'r' for reading and 'w' for writing
f.write("Hello World from " + f.name)    # Write inside file 
f.close()                                # Close file 

# Method 2
with open("Path/To/Your/File.txt", "w") as f:   # Opens file and casts as f 
    f.write("Hello World form " + f.name)       # Writing
    # File closed automatically

There are many more methods but these two are most common. Hope this helped!

Creating self signed certificate for domain and subdomains - NET::ERR_CERT_COMMON_NAME_INVALID

I think it may be a bug in chrome. There was a similar issue long back: See this.

Try in a different browser. I think it should work fine.

SQL Query for Selecting Multiple Records

I strongly recommend using lowercase field|column names, it will make your life easier.

Let's assume you have a table called users with the following definition and records:

id|firstname|lastname|username             |password
1 |joe      |doe     |[email protected]   |1234
2 |jane     |doe     |[email protected]  |12345
3 |johnny   |doe     |[email protected]|123456

let's say you want to get all records from table users, then you do:

SELECT * FROM users;

Now let's assume you want to select all records from table users, but you're interested only in the fields id, firstname and lastname, thus ignoring username and password:

SELECT id, firstname, lastname FROM users;

Now we get at the point where you want to retrieve records based on condition(s), what you need to do is to add the WHERE clause, let's say we want to select from users only those that have username = [email protected] and password = 1234, what you do is:

SELECT * FROM users
WHERE ( ( username = '[email protected]' ) AND ( password = '1234' ) );

But what if you need only the id of a record with username = [email protected] and password = 1234? then you do:

SELECT id FROM users
WHERE ( ( username = '[email protected]' ) AND ( password = '1234' ) );

Now to get to your question, as others before me answered you can use the IN clause:

SELECT * FROM users
WHERE ( id IN (1,2,..,n) );

or, if you wish to limit to a list of records between id 20 and id 40, then you can easily write:

SELECT * FROM users
WHERE ( ( id >= 20 ) AND ( id <= 40 ) );

I hope this gives a better understanding.

SQL server ignore case in a where expression

You can force the case sensitive, casting to a varbinary like that:

SELECT * FROM myTable 
WHERE convert(varbinary, myField) = convert(varbinary, 'sOmeVal')

hash keys / values as array

look at the _.keys() and _.values() functions in either lodash or underscore

DateTime.ToString() format that can be used in a filename or extension?

Using interpolation string & format specifier:

var filename = $"{DateTime.Now:yyyy.dd.M HH-mm-ss}"

Example Output for January 1st, 2020 at 10:40:45AM:

2020.28.01 10-40-45


Or if you want a standard date format:

var filename = $"{DateTime.Now:yyyy.M.dd HH-mm-ss}"

2020.01.28 10-40-45


Note: this feature is available in C# 6 and later versions of the language.

C# DataTable.Select() - How do I format the filter criteria to include null?

Try this

myDataTable.Select("[Name] is NULL OR [Name] <> 'n/a'" )

Edit: Relevant sources:

CSS selector for disabled input type="submit"

As said by jensgram, IE6 does not support attribute selector. You could add a class="disabled" to select the disabled inputs so that this can work in IE6.

how does int main() and void main() work

Neither main() or void main() are standard C. The former is allowed as it has an implicit int return value, making it the same as int main(). The purpose of main's return value is to return an exit status to the operating system.

In standard C, the only valid signatures for main are:

int main(void)

and

int main(int argc, char **argv)

The form you're using: int main() is an old style declaration that indicates main takes an unspecified number of arguments. Don't use it - choose one of those above.

JavaScript hide/show element

I would like to suggest you the JQuery option.

$("#item").toggle();
$("#item").hide();
$("#item").show();

For example:

$(document).ready(function(){
   $("#item").click(function(event){
     //Your actions here
   });
 });

Is there are way to make a child DIV's width wider than the parent DIV using CSS?

To make child div as wide as the content, try this:

.child{
    position:absolute;
    left:0;
    overflow:visible;
    white-space:nowrap;
}

Is there Unicode glyph Symbol to represent "Search"

You can simply add this CSS to your header

<link href='http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css' rel='stylesheet' type='text/css'>

next add this code in place where you want to display a glyph symbol.

<div class="fa fa-search"></div> <!-- smaller -->
<div class="fa fa-search fa-2x"></div> <!-- bigger -->

Have fun.

Getting HTTP headers with Node.js

I had some problems with http.get; so I switched to the lib request:

var request = require('request');

var url = 'http://blog.mynotiz.de/';

var options = {
    url: url,
    method: 'HEAD'
};

request(options, function (error, response, body) {
        if (error) {
            return console.error('upload failed:', error);
        }

        if (response.headers['content-length']) {
            var file_size = response.headers['content-length'];
            console.log(file_size);
        }
    }
);

How to find sum of several integers input by user using do/while, While statement or For statement

You should do:

#include<iostream>
using namespace std;
int main ()
{

    int sum = 0;
    int number;
    int numberitems;


    cout << "Enter number of items: \n";
    cin >> numberitems;

    for(int i=0;i<numberitems;i++)
    {
        cout << "Enter number <<i<<":" \n";
        cin >> number; sum+=number;
    }
    cout<<"sum is: "<< sum<<endl;
}

And with a while statement

#include <iostream>
using namespace std;
int main ()
{
    int sum = 0;
    int number;
    int numberitems;
    cin>>numberitems;

    cout << "Enter number: \n";

    while (count <=numberitems)
    {
        cin >> number;
        sum+=number;
    }
    cout << sum << endl;
}

excel VBA run macro automatically whenever a cell is changed

In an attempt to find a way to make the target cell for the intersect method a name table array, I stumbled across a simple way to run something when ANY cell or set of cells on a particular sheet changes. This code is placed in the worksheet module as well:

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Cells.Count > 0 Then
'mycode here
end if
end sub

How to check if a variable is set in Bash?

I like auxiliary functions to hide the crude details of bash. In this case, doing so adds even more (hidden) crudeness:

# The first ! negates the result (can't use -n to achieve this)
# the second ! expands the content of varname (can't do ${$varname})
function IsDeclared_Tricky
{
  local varname="$1"
  ! [ -z ${!varname+x} ]
}

Because I first had bugs in this implementation (inspired by the answers of Jens and Lionel), I came up with a different solution:

# Ask for the properties of the variable - fails if not declared
function IsDeclared()
{
  declare -p $1 &>/dev/null
}

I find it to be more straight-forward, more bashy and easier to understand/remember. Test case shows it is equivalent:

function main()
{
  declare -i xyz
  local foo
  local bar=
  local baz=''

  IsDeclared_Tricky xyz; echo "IsDeclared_Tricky xyz: $?"
  IsDeclared_Tricky foo; echo "IsDeclared_Tricky foo: $?"
  IsDeclared_Tricky bar; echo "IsDeclared_Tricky bar: $?"
  IsDeclared_Tricky baz; echo "IsDeclared_Tricky baz: $?"

  IsDeclared xyz; echo "IsDeclared xyz: $?"
  IsDeclared foo; echo "IsDeclared foo: $?"
  IsDeclared bar; echo "IsDeclared bar: $?"
  IsDeclared baz; echo "IsDeclared baz: $?"
}

main

The test case also shows that local var does NOT declare var (unless followed by '='). For quite some time I thought i declared variables this way, just to discover now that i merely expressed my intention... It's a no-op, i guess.

IsDeclared_Tricky xyz: 1
IsDeclared_Tricky foo: 1
IsDeclared_Tricky bar: 0
IsDeclared_Tricky baz: 0
IsDeclared xyz: 1
IsDeclared foo: 1
IsDeclared bar: 0
IsDeclared baz: 0

BONUS: usecase

I mostly use this test to give (and return) parameters to functions in a somewhat "elegant" and safe way (almost resembling an interface...):

#auxiliary functions
function die()
{
  echo "Error: $1"; exit 1
}

function assertVariableDeclared()
{
  IsDeclared "$1" || die "variable not declared: $1"
}

function expectVariables()
{
  while (( $# > 0 )); do
    assertVariableDeclared $1; shift
  done
}

# actual example
function exampleFunction()
{
  expectVariables inputStr outputStr
  outputStr="$inputStr world!"
}

function bonus()
{
  local inputStr='Hello'
  local outputStr= # remove this to trigger error
  exampleFunction
  echo $outputStr
}

bonus

If called with all requires variables declared:

Hello world!

else:

Error: variable not declared: outputStr

Angular : Manual redirect to route

You should inject Router in your constructor like this;

constructor(private router: Router) { }

then you can do this anywhere you want;

this.router.navigate(['/product-list']);

Search for exact match of string in excel row using VBA Macro

Use worksheet.find (worksheet is your worksheet) and use the row-range for its range-object. You can get the rangeobject like: worksheet.rows(rowIndex) as example

Then give find the required parameters it should find it for you fine. If I recall correctly, find returns the first match per default. I have no Excel at hand, so you have to look up find for yourself, sorry

I would advise against using a for-loop it is more fragile and ages slower than find.

Easy way to export multiple data.frame to multiple Excel worksheets

Many good answers here, but some of them are a little dated. If you want to add further worksheets to a single file then this is the approach I find works for me. For clarity, here is the workflow for openxlsx version 4.0

# Create a blank workbook
OUT <- createWorkbook()

# Add some sheets to the workbook
addWorksheet(OUT, "Sheet 1 Name")
addWorksheet(OUT, "Sheet 2 Name")

# Write the data to the sheets
writeData(OUT, sheet = "Sheet 1 Name", x = dataframe1)
writeData(OUT, sheet = "Sheet 2 Name", x = dataframe2)

# Export the file
saveWorkbook(OUT, "My output file.xlsx")

EDIT

I've now trialled a few other answers, and I actually really like @Syed's. It doesn't exploit all the functionality of openxlsx but if you want a quick-and-easy export method then that's probably the most straightforward.

Disabling swap files creation in vim

create no vim swap file just for a particular file

autocmd bufenter  c:/aaa/Dropbox/TapNote/Todo.txt :set noswapfile

html cellpadding the left side of a cell

I use inline css all the time BECAUSE.... I want absolute control of the design and place different things aligned differently from cell to cell.

It is not hard to understand...

Anyway, I just put something like this inside my tag:

style='padding:5px 10px 5px 5px'

Where the order represents top, right, bottom and left.

How to use background thread in swift?

Dan Beaulieu's answer in swift5 (also working since swift 3.0.1).

Swift 5.0.1

extension DispatchQueue {

    static func background(delay: Double = 0.0, background: (()->Void)? = nil, completion: (() -> Void)? = nil) {
        DispatchQueue.global(qos: .background).async {
            background?()
            if let completion = completion {
                DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: {
                    completion()
                })
            }
        }
    }

}

Usage

DispatchQueue.background(delay: 3.0, background: {
    // do something in background
}, completion: {
    // when background job finishes, wait 3 seconds and do something in main thread
})

DispatchQueue.background(background: {
    // do something in background
}, completion:{
    // when background job finished, do something in main thread
})

DispatchQueue.background(delay: 3.0, completion:{
    // do something in main thread after 3 seconds
})

What’s the best way to get an HTTP response code from a URL?

Addressing @Niklas R's comment to @nickanor's answer:

from urllib.error import HTTPError
import urllib.request

def getResponseCode(url):
    try:
        conn = urllib.request.urlopen(url)
        return conn.getcode()
    except HTTPError as e:
        return e.code

If input value is blank, assign a value of "empty" with Javascript

I think the easiest way to solve this issue, if you only need it on 1 or 2 boxes is by using the HTML input's "onsubmit" function.

Check this out and i will explain what it does:

<input type="text" name="val" onsubmit="if(this == ''){$this.val('empty');}" />

So we have created the HTML text box, assigned it a name ("val" in this case) and then we added the onsubmit code, this code checks to see if the current input box is empty and if it is, then, upon form submit it will fill it with the words empty.

Please note, this code should also function perfectly when using the HTML "Placeholder" tag as the placeholder tag doesn't actually assign a value to the input box.

Creating instance list of different objects

How can I create a list without defining a class type? (<Employee>)

If I'm reading this correctly, you just want to avoid having to specify the type, correct?

In Java 7, you can do

List<Employee> list = new ArrayList<>();

but any of the other alternatives being discussed are just going to sacrifice type safety.

Why plt.imshow() doesn't display the image?

plt.imshow just finishes drawing a picture instead of printing it. If you want to print the picture, you just need to add plt.show.

Python Requests package: Handling xml response

requests does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward.

Python comes with built-in XML parsers. I recommend you use the ElementTree API:

import requests
from xml.etree import ElementTree

response = requests.get(url)

tree = ElementTree.fromstring(response.content)

or, if the response is particularly large, use an incremental approach:

    response = requests.get(url, stream=True)
    # if the server sent a Gzip or Deflate compressed response, decompress
    # as we read the raw stream:
    response.raw.decode_content = True

    events = ElementTree.iterparse(response.raw)
    for event, elem in events:
        # do something with `elem`

The external lxml project builds on the same API to give you more features and power still.

PHP json_encode json_decode UTF-8

This is an encoding issue. It looks like at some point, the data gets represented as ISO-8859-1.

Every part of your process needs to be UTF-8 encoded.

  • The database connection

  • The database tables

  • Your PHP file (if you are using special characters inside that file as shown in your example above)

  • The content-type headers that you output

Excel: Searching for multiple terms in a cell

This will do it for you:

=IF(OR(ISNUMBER(SEARCH("Gingrich",C3)),ISNUMBER(SEARCH("Obama",C3))),"1","")

Given this function in the column to the right of the names (which are in column C), the result is:

Romney  
Gingrich    1
Obama       1

How to initialize a two-dimensional array in Python?

from random import randint
l = []

for i in range(10):
    k=[]
    for j in range(10):
        a= randint(1,100)
        k.append(a)

    l.append(k)




print(l)
print(max(l[2]))

b = []
for i in range(10):
    a = l[i][5]
    b.append(a)

print(min(b))

Format certain floating dataframe columns into percentage in pandas

style.format is vectorized, so we can simply apply it to the entire df (or just its numerical columns):

df[num_cols].style.format('{:,.3f}')

Visual Studio 2017: Display method references

In previous posts I have read that this feature IS available on VS 2015 community if you FIRST install SQL Server express (free) and THEN install VS. I have tried it and it worked. I just had to reinstall Windows and am going thru the same procedure now and it did not work... so will try again :). I know it worked 6 months ago when I tried.

-Ed

The character encoding of the HTML document was not declared

I have same problem with the most basic situation and my problem was solved with inserting this meta in the head:

<meta charset="UTF-8">

the character encoding (which is actually UTF-8) of the html document was not declared

The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly

In case it helps, I've ran into this problem when passing null into a parameter for a generic TValue, to get around this you have to cast your null values:

(string)null

(int)null

etc.

String.Replace(char, char) method in C#

One caveat: in .NET the linefeed is "\r\n". So if you're loading your text from a file, you might have to use that instead of just "\n"

edit> as samuel pointed out in the comments, "\r\n" is not .NET specific, but is windows specific.

How can I show figures separately in matplotlib?

I think I am a bit late to the party but... In my opinion, what you need is the object oriented API of matplotlib. In matplotlib 1.4.2 and using IPython 2.4.1 with Qt4Agg backend, I can do the following:

import matplotlib.pyplot as plt
fig, ax = plt.subplots(1) # Creates figure fig and add an axes, ax.
fig2, ax2 = plt.subplots(1) # Another figure

ax.plot(range(20)) #Add a straight line to the axes of the first figure.
ax2.plot(range(100)) #Add a straight line to the axes of the first figure.

fig.show() #Only shows figure 1 and removes it from the "current" stack.
fig2.show() #Only shows figure 2 and removes it from the "current" stack.
plt.show() #Does not show anything, because there is nothing in the "current" stack.
fig.show() # Shows figure 1 again. You can show it as many times as you want.

In this case plt.show() shows anything in the "current" stack. You can specify figure.show() ONLY if you are using a GUI backend (e.g. Qt4Agg). Otherwise, I think you will need to really dig down into the guts of matplotlib to monkeypatch a solution.

Remember that most (all?) plt.* functions are just shortcuts and aliases for figure and axes methods. They are very useful for sequential programing, but you will find blocking walls very soon if you plan to use them in a more complex way.

Uploading multiple files using formData()

This one worked for me

_x000D_
_x000D_
//Javascript part_x000D_
//file_input is a file input id_x000D_
var formData = new FormData();_x000D_
var filesLength=document.getElementById('file_input').files.length;_x000D_
for(var i=0;i<filesLength;i++){_x000D_
 formData.append("file[]", document.getElementById('file_input').files[i]);_x000D_
}_x000D_
$.ajax({_x000D_
   url: 'upload.php',_x000D_
   type: 'POST',_x000D_
   data: formData,_x000D_
   contentType: false,_x000D_
   cache: false,_x000D_
   processData: false,_x000D_
   success: function (html) {_x000D_
   _x000D_
  }_x000D_
});
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
<?php_x000D_
//PHP part_x000D_
$file_names = $_FILES["file"]["name"];_x000D_
for ($i = 0; $i < count($file_names); $i++) {_x000D_
   $file_name=$file_names[$i];_x000D_
   $extension = end(explode(".", $file_name));_x000D_
   $original_file_name = pathinfo($file_name, PATHINFO_FILENAME);_x000D_
   $file_url = $original_file_name . "-" . date("YmdHis") . "." . $extension;_x000D_
 move_uploaded_file($_FILES["file"]["tmp_name"][$i], $absolute_destination . $file_url);_x000D_
}
_x000D_
_x000D_
_x000D_

git clone: Authentication failed for <URL>

In my case the error was some old username and password was stored in cache.

So I removed it by going to sourceTree and delete the existing account.

Now for the new clone then it will ask you for the password for the repo. enter image description here

shell script to remove a file if it already exist

Another one line command I used is:

[ -e file ] && rm file

Writing html form data to a txt file without the use of a webserver

I know this is old, but it's the first example of saving form data to a txt file I found in a quick search. So I've made a couple edits to the above code that makes it work more smoothly. It's now easier to add more fields, including the radio button as @user6573234 requested.

https://jsfiddle.net/cgeiser/m0j7Lwyt/1/

<!DOCTYPE html>
<html>
<head>
<style>
form * {
  display: block;
  margin: 10px;
}
</style>
<script language="Javascript" >
function download() {
  var filename = window.document.myform.docname.value;
  var name =  window.document.myform.name.value;
  var text =  window.document.myform.text.value;
  var problem =  window.document.myform.problem.value;
  
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 
    "Your Name: " + encodeURIComponent(name) + "\n\n" +
    "Problem: " + encodeURIComponent(problem) + "\n\n" +
    encodeURIComponent(text)); 

  pom.setAttribute('download', filename);

  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);
}
</script>
</head>
<body>
<form name="myform" method="post" >
  <input type="text" id="docname" value="test.txt" />
  <input type="text" id="name" placeholder="Your Name" />
  <div style="display:unblock">
    Option 1 <input type="radio" value="Option 1" onclick="getElementById('problem').value=this.value; getElementById('problem').show()" style="display:inline" />
    Option 2 <input type="radio" value="Option 2" onclick="getElementById('problem').value=this.value;" style="display:inline" />
    <input type="text" id="problem" />
  </div>
  <textarea rows=3 cols=50 id="text" />Please type in this box. 
When you click the Download button, the contents of this box will be downloaded to your machine at the location you specify. Pretty nifty. </textarea>
  
  <input id="download_btn" type="submit" class="btn" style="width: 125px" onClick="download();" />
  
</form>
</body>
</html>

Entity framework linq query Include() multiple children entities

Use extension methods. Replace NameOfContext with the name of your object context.

public static class Extensions{
   public static IQueryable<Company> CompleteCompanies(this NameOfContext context){
         return context.Companies
             .Include("Employee.Employee_Car")
             .Include("Employee.Employee_Country") ;
     }

     public static Company CompanyById(this NameOfContext context, int companyID){
         return context.Companies
             .Include("Employee.Employee_Car")
             .Include("Employee.Employee_Country")
             .FirstOrDefault(c => c.Id == companyID) ;
      }

}

Then your code becomes

     Company company = 
          context.CompleteCompanies().FirstOrDefault(c => c.Id == companyID);

     //or if you want even more
     Company company = 
          context.CompanyById(companyID);

In a javascript array, how do I get the last 5 elements, excluding the first element?

_x000D_
_x000D_
var y = [1,2,3,4,5,6,7,8,9,10];_x000D_
_x000D_
console.log(y.slice((y.length - 5), y.length))
_x000D_
_x000D_
_x000D_

you can do this!

SystemError: Parent module '' not loaded, cannot perform relative import

if you just run the main.py under the app, just import like

from mymodule import myclass

if you want to call main.py on other folder, use:

from .mymodule import myclass

for example:

+-- app
¦   +-- __init__.py
¦   +-- main.py
¦   +-- mymodule.py
+-- __init__.py
+-- run.py

main.py

from .mymodule import myclass

run.py

from app import main
print(main.myclass)

So I think the main question of you is how to call app.main.

The create-react-app imports restriction outside of src directory

Image inside public folder

  use image inside html extension
  <img src="%PUBLIC_URL%/resumepic.png"/>

  use image inside  js extension
  <img src={process.env.PUBLIC_URL+"/resumepic.png"}/>
  • use image inside js Extension

When to use a View instead of a Table?

According to Wikipedia,

Views can provide many advantages over tables:

  • Views can represent a subset of the data contained in a table.
  • Views can limit the degree of exposure of the underlying tables to the outer world: a given user may have permission to query the view, while denied access to the rest of the base table.

  • Views can join and simplify multiple tables into a single virtual table.

  • Views can act as aggregated tables, where the database engine aggregates data (sum, average, etc.) and presents the calculated results as part of the data.

  • Views can hide the complexity of data. For example, a view could appear as Sales2000 or Sales2001, transparently partitioning the actual underlying table.

  • Views take very little space to store; the database contains only the definition of a view, not a copy of all the data that it presents.

  • Views can provide extra security, depending on the SQL engine used.

how I can show the sum of in a datagridview column?

int sum = 0;
for (int i = 0; i < dataGridView1.Rows.Count; ++i)
{
    sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[1].Value);
}
label1.Text = sum.ToString();

How can I add an element after another element?

try using the after() method:

$('#bla').after('<div id="space"></div>');

Documentation

Performing user authentication in Java EE / JSF using j_security_check

I suppose you want form based authentication using deployment descriptors and j_security_check.

You can also do this in JSF by just using the same predefinied field names j_username and j_password as demonstrated in the tutorial.

E.g.

<form action="j_security_check" method="post">
    <h:outputLabel for="j_username" value="Username" />
    <h:inputText id="j_username" />
    <br />
    <h:outputLabel for="j_password" value="Password" />
    <h:inputSecret id="j_password" />
    <br />
    <h:commandButton value="Login" />
</form>

You could do lazy loading in the User getter to check if the User is already logged in and if not, then check if the Principal is present in the request and if so, then get the User associated with j_username.

package com.stackoverflow.q2206911;

import java.io.IOException;
import java.security.Principal;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

@ManagedBean
@SessionScoped
public class Auth {

    private User user; // The JPA entity.

    @EJB
    private UserService userService;

    public User getUser() {
        if (user == null) {
            Principal principal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
            if (principal != null) {
                user = userService.find(principal.getName()); // Find User by j_username.
            }
        }
        return user;
    }

}

The User is obviously accessible in JSF EL by #{auth.user}.

To logout do a HttpServletRequest#logout() (and set User to null!). You can get a handle of the HttpServletRequest in JSF by ExternalContext#getRequest(). You can also just invalidate the session altogether.

public String logout() {
    FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
    return "login?faces-redirect=true";
}

For the remnant (defining users, roles and constraints in deployment descriptor and realm), just follow the Java EE 6 tutorial and the servletcontainer documentation the usual way.


Update: you can also use the new Servlet 3.0 HttpServletRequest#login() to do a programmatic login instead of using j_security_check which may not per-se be reachable by a dispatcher in some servletcontainers. In this case you can use a fullworthy JSF form and a bean with username and password properties and a login method which look like this:

<h:form>
    <h:outputLabel for="username" value="Username" />
    <h:inputText id="username" value="#{auth.username}" required="true" />
    <h:message for="username" />
    <br />
    <h:outputLabel for="password" value="Password" />
    <h:inputSecret id="password" value="#{auth.password}" required="true" />
    <h:message for="password" />
    <br />
    <h:commandButton value="Login" action="#{auth.login}" />
    <h:messages globalOnly="true" />
</h:form>

And this view scoped managed bean which also remembers the initially requested page:

@ManagedBean
@ViewScoped
public class Auth {

    private String username;
    private String password;
    private String originalURL;

    @PostConstruct
    public void init() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        originalURL = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_REQUEST_URI);

        if (originalURL == null) {
            originalURL = externalContext.getRequestContextPath() + "/home.xhtml";
        } else {
            String originalQuery = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_QUERY_STRING);

            if (originalQuery != null) {
                originalURL += "?" + originalQuery;
            }
        }
    }

    @EJB
    private UserService userService;

    public void login() throws IOException {
        FacesContext context = FacesContext.getCurrentInstance();
        ExternalContext externalContext = context.getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();

        try {
            request.login(username, password);
            User user = userService.find(username, password);
            externalContext.getSessionMap().put("user", user);
            externalContext.redirect(originalURL);
        } catch (ServletException e) {
            // Handle unknown username/password in request.login().
            context.addMessage(null, new FacesMessage("Unknown login"));
        }
    }

    public void logout() throws IOException {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        externalContext.invalidateSession();
        externalContext.redirect(externalContext.getRequestContextPath() + "/login.xhtml");
    }

    // Getters/setters for username and password.
}

This way the User is accessible in JSF EL by #{user}.

How can I get a count of the total number of digits in a number?

Create a method that returns all digits, and another that counts them:

public static int GetNumberOfDigits(this long value)
{
    return value.GetDigits().Count();
}

public static IEnumerable<int> GetDigits(this long value)
{
    do
    {
        yield return (int)(value % 10);
        value /= 10;
    } while (value != 0);
}

This felt like the more intuitive approach to me when tackling this problem. I tried the Log10 method first due to its apparent simplicity, but it has an insane amount of corner cases and precision problems.

I also found the if-chain proposed in the other answer to a bit ugly to look at.

I know this is not the most efficient method, but it gives you the other extension to return the digits as well for other uses (you can just mark it private if you don't need to use it outside the class).

Keep in mind that it does not consider the negative sign as a digit.

How do I get the application exit code from a Windows command line?

It's worth noting that .BAT and .CMD files operate differently.

Reading https://ss64.com/nt/errorlevel.html it notes the following:

There is a key difference between the way .CMD and .BAT batch files set errorlevels:

An old .BAT batch script running the 'new' internal commands: APPEND, ASSOC, PATH, PROMPT, FTYPE and SET will only set ERRORLEVEL if an error occurs. So if you have two commands in the batch script and the first fails, the ERRORLEVEL will remain set even after the second command succeeds.

This can make debugging a problem BAT script more difficult, a CMD batch script is more consistent and will set ERRORLEVEL after every command that you run [source].

This was causing me no end of grief as I was executing successive commands, but the ERRORLEVEL would remain unchanged even in the event of a failure.

How do I create an average from a Ruby array?

You could try something like the following:

a = [1,2,3,4,5]
# => [1, 2, 3, 4, 5]
(a.sum/a.length).to_f
# => 3.0

npm install hangs

For anyone on MacOS (I'm on Mojave 10.14), the following helped me out: https://github.com/reactioncommerce/reaction/issues/1938#issuecomment-284207213

You'd run these commands

echo kern.maxfiles=65536 | sudo tee -a /etc/sysctl.conf
echo kern.maxfilesperproc=65536 | sudo tee -a /etc/sysctl.conf
sudo sysctl -w kern.maxfiles=65536
sudo sysctl -w kern.maxfilesperproc=65536
ulimit -n 65536

Then try npm install once more.

Detect when input has a 'readonly' attribute

Since JQuery 1.6, always use .prop() Read why here: http://api.jquery.com/prop/

if($('input').prop('readonly')){ }

.prop() can also be used to set the property

$('input').prop('readonly',true);

$('input').prop('readonly',false);

What data type to use in MySQL to store images?

Perfect answer for your question can be found on MYSQL site itself.refer their manual(without using PHP)

http://forums.mysql.com/read.php?20,17671,27914

According to them use LONGBLOB datatype. with that you can only store images less than 1MB only by default,although it can be changed by editing server config file.i would also recommend using MySQL workBench for ease of database management

Pandas: Subtracting two date columns and the result being an integer

How about:

df_test['Difference'] = (df_test['First_Date'] - df_test['Second Date']).dt.days

This will return difference as int if there are no missing values(NaT) and float if there is.

How to make html <select> element look like "disabled", but pass values?

Add a class .disabled and use this CSS:

?.disabled {border: 1px solid #999; color: #333; opacity: 0.5;}
.disabled option {color: #000; opacity: 1;}?

Demo: http://jsfiddle.net/ZCSRq/

How to sum up elements of a C++ vector?

C++0x only:

vector<int> v; // and fill with data
int sum {}; // or = 0 ... :)
for (int n : v) sum += n;

This is similar to the BOOST_FOREACH mentioned elsewhere and has the same benefit of clarity in more complex situations, compared to stateful functors used with accumulate or for_each.

MYSQL Truncated incorrect DOUBLE value

You don't need the AND keyword. Here's the correct syntax of the UPDATE statement:

UPDATE 
    shop_category 
SET 
    name = 'Secolul XVI - XVIII', 
    name_eng = '16th to 18th centuries' 
WHERE 
    category_id = 4768

How can I remove the top and right axis in matplotlib?

(This is more of an extension comment, in addition to the comprehensive answers here.)


Note that we can hide each of these three elements independently of each other:

  • To hide the border (aka "spine"): ax.set_frame_on(False) or ax.spines['top'].set_visible(False)

  • To hide the ticks: ax.tick_params(top=False)

  • To hide the labels: ax.tick_params(labeltop=False)

Clear Cache in Android Application programmatically

Try this

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    clearApplicationData();
}

public void clearApplicationData() {
    File cache = getCacheDir();
    File appDir = new File(cache.getParent());
    if (appDir.exists()) {
        String[] children = appDir.list();
        for (String s : children) {
            if (!s.equals("lib")) {
                deleteDir(new File(appDir, s));
                Log.i("EEEEEERRRRRROOOOOOORRRR", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
            }
        }
    }
}

public static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        int i = 0;
        while (i < children.length) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
            i++;
        }
    }

    assert dir != null;
    return dir.delete();
}

How can I open a link in a new window?

I just found an interesting solution to this issue. I was creating spans which contain information based on the return from a web service. I thought about trying to put a link around the span so that if I clicked on it, the "a" would capture the click.

But I was trying to capture the click with the span... so I thought why not do this when I created the span.

var span = $('<span id="something" data-href="'+url+'" />');

I then bound a click handler to the span which created a link based on the 'data-href' attribute:

span.click(function(e) {
    e.stopPropagation();
    var href = $(this).attr('data-href');
    var link = $('<a href="http://' + href + '" />');
    link.attr('target', '_blank');
    window.open(link.attr('href'));
});

This successfully allowed me to click on a span and open a new window with a proper url.

Converting HTML files to PDF

The Flying Saucer XHTML renderer project has support for outputting XHTML to PDF. Have a look at an example here.

Installing Python packages from local file system folder to virtualenv with pip

To install only from local you need 2 options:

  • --find-links: where to look for dependencies. There is no need for the file:// prefix mentioned by others.
  • --no-index: do not look in pypi indexes for missing dependencies (dependencies not installed and not in the --find-links path).

So you could run from any folder the following:

pip install --no-index --find-links /srv/pkg /path/to/mypackage-0.1.0.tar.gz

If your mypackage is setup properly, it will list all its dependencies, and if you used pip download to download the cascade of dependencies (ie dependencies of depencies etc), everything will work.

If you want to use the pypi index if it is accessible, but fallback to local wheels if not, you can remove --no-index and add --retries 0. You will see pip pause for a bit while it is try to check pypi for a missing dependency (one not installed) and when it finds it cannot reach it, will fall back to local. There does not seem to be a way to tell pip to "look for local ones first, then the index".

HashMap and int as key

I don't understand why I should add a dimension (ie: making the int into an array) since I only need to store a digit as key.

An array is also an Object, so HashMap<int[], MyObject> is a valid construct that uses int arrays as keys.

Compiler doesn't know what you want or what you need, it just sees a language construct that is almost correct, and warns what's missing for it to be fully correct.

What is the difference between background and background-color

There's a bug regarding with background and background-color

the difference of this, when using background, sometimes when your creating a webpage in CSS background: #fff // can over ride a block of Mask image("top item, text or image")) so its better to always use background-color for safe use, in your design if its individual