Programs & Examples On #Saxparseexception

The Java exception which encapsulates an XML parse error or warning.

Content is not allowed in Prolog SAXParserException

This error can come if there is validation error either in your wsdl or xsd file. For instance I too got the same issue while running wsdl2java to convert my wsdl file to generate the client. In one of my xsd it was defined as below

<xs:import schemaLocation="" namespace="http://MultiChoice.PaymentService/DataContracts" />

Where the schemaLocation was empty. By providing the proper data in schemaLocation resolved my problem.

<xs:import schemaLocation="multichoice.paymentservice.DataContracts.xsd" namespace="http://MultiChoice.PaymentService/DataContracts" />

"Cannot send session cache limiter - headers already sent"

"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.

Check that you don't send ANY content before calling session_start. Better yet, just make session_start the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).

Best way to get user GPS location in background in Android

None of the rest of the answers use:

com.google.android.gms.location.FusedLocationProviderClient

Which is the Fused Location Provider and the main entry point for interacting with the fused location provider by Google, and it is very hard to find a good example. This was released mid 2017 by Google.

Google Play services location APIs are preferred over the Android framework location APIs (android.location)

If you are currently using the Android framework location APIs, you are strongly encouraged to switch to the Google Play services location APIs as soon as possible.

For you to use the Google Location API, first add this to your build.gradle

compile 'com.google.android.gms:play-services:11.0.0'

Then you can use this class Wherebouts.java:

import android.location.Location;
import android.os.Looper;
import android.util.Log;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;

/**
 * Uses Google Play API for obtaining device locations
 * Created by alejandro.tkachuk 
 * [email protected]
 * www.calculistik.com Mobile Development
 */

public class Wherebouts {

    private static final Wherebouts instance = new Wherebouts();

    private static final String TAG = Wherebouts.class.getSimpleName();

    private FusedLocationProviderClient mFusedLocationClient;
    private LocationCallback locationCallback;
    private LocationRequest locationRequest;
    private LocationSettingsRequest locationSettingsRequest;

    private Workable<GPSPoint> workable;

    private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 1000;
    private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 1000;

    private Wherebouts() {
        this.locationRequest = new LocationRequest();
        this.locationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
        this.locationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
        this.locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
        builder.addLocationRequest(this.locationRequest);
        this.locationSettingsRequest = builder.build();

        this.locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult); // why? this. is. retarded. Android.
                Location currentLocation = locationResult.getLastLocation();

                GPSPoint gpsPoint = new GPSPoint(currentLocation.getLatitude(), currentLocation.getLongitude());
                Log.i(TAG, "Location Callback results: " + gpsPoint);
                if (null != workable)
                    workable.work(gpsPoint);
            }
        };

        this.mFusedLocationClient = LocationServices.getFusedLocationProviderClient(MainApplication.getAppContext());
        this.mFusedLocationClient.requestLocationUpdates(this.locationRequest,
                this.locationCallback, Looper.myLooper());
    }

    public static Wherebouts instance() {
        return instance;
    }

    public void onChange(Workable<GPSPoint> workable) {
        this.workable = workable;
    }

    public LocationSettingsRequest getLocationSettingsRequest() {
        return this.locationSettingsRequest;
    }

    public void stop() {
        Log.i(TAG, "stop() Stopping location tracking");
        this.mFusedLocationClient.removeLocationUpdates(this.locationCallback);
    }

}

From your Activity, you can use it like this, by passing a Workable object. A Workable object is nothing more than a custom Callback alike object.

 Wherebouts.instance().onChange(workable);

By using a callback like Workable, you will write UI related code in your Activity and leave the hustle of working with GPS to a helper class, like Wherebouts.

    new Workable<GPSPoint>() {
        @Override
        public void work(GPSPoint gpsPoint) {
            // draw something in the UI with this new data
        }
    };

Of course you would need to ask for the corresponding permissions to the Android OS for your App to use. You can read the following documentation for more info about that or do some research.

How can I fix "Design editor is unavailable until a successful build" error?

Go online before starting android studio. Then go file->New project Follow onscreen steps. Then wait It will download the necessary files over internet. And that should fix it.

How to find the location of the Scheduled Tasks folder

Looks like TaskCache registry data is in ...

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache

... on my Windows 10 PC (i.e. add Schedule before TaskCache and TaskCache has an upper case C).

Check if a parameter is null or empty in a stored procedure

I recommend checking for invalid dates too:

set @PreviousStartDate=case ISDATE(@PreviousStartDate) 
    when 1 then @PreviousStartDate 
        else '1/1/2010'
    end

What are database constraints?

  1. UNIQUE constraint (of which a PRIMARY KEY constraint is a variant). Checks that all values of a given field are unique across the table. This is X-axis constraint (records)

  2. CHECK constraint (of which a NOT NULL constraint is a variant). Checks that a certain condition holds for the expression over the fields of the same record. This is Y-axis constraint (fields)

  3. FOREIGN KEY constraint. Checks that a field's value is found among the values of a field in another table. This is Z-axis constraint (tables).

endforeach in loops?

It's mainly so you can make start and end statements clearer when creating HTML in loops:

<table>
<? while ($record = mysql_fetch_assoc($rs)): ?>
    <? if (!$record['deleted']): ?>
        <tr>
        <? foreach ($display_fields as $field): ?>
            <td><?= $record[$field] ?></td>
        <? endforeach; ?>
        <td>
        <select name="action" onChange="submit">
        <? foreach ($actions as $action): ?>
            <option value="<?= $action ?>"><?= $action ?>
        <? endforeach; ?>
        </td>
        </tr>
    <? else: ?>
         <tr><td colspan="<?= array_count($display_fields) ?>"><i>record <?= $record['id'] ?> has been deleted</i></td></tr>
    <? endif; ?>
<? endwhile; ?>
</table>

versus

<table>
<? while ($record = mysql_fetch_assoc($rs)) { ?>
    <? if (!$record['deleted']) { ?>
        <tr>
        <? foreach ($display_fields as $field) { ?>
            <td><?= $record[$field] ?></td>
        <? } ?>
        <td>
        <select name="action" onChange="submit">
        <? foreach ($actions as $action) { ?>
            <option value="<?= $action ?>"><?= action ?>
        <? } ?>
        </td>
        </tr>
    <? } else { ?>
         <tr><td colspan="<?= array_count($display_fields) ?>"><i>record <?= $record['id'] ?> has been deleted</i></td></tr>
    <? } ?>
<? } ?>
</table>

Hopefully my example is sufficient to demonstrate that once you have several layers of nested loops, and the indenting is thrown off by all the PHP open/close tags and the contained HTML (and maybe you have to indent the HTML a certain way to get your page the way you want), the alternate syntax (endforeach) form can make things easier for your brain to parse. With the normal style, the closing } can be left on their own and make it hard to tell what they're actually closing.

How do I pass JavaScript values to Scriptlet in JSP?

I can provide two ways,

a.jsp,

<html>
    <script language="javascript" type="text/javascript">
        function call(){
            var name = "xyz";
            window.location.replace("a.jsp?name="+name);
        }
    </script>
    <input type="button" value="Get" onclick='call()'>
    <%
        String name=request.getParameter("name");
        if(name!=null){
            out.println(name);
        }
    %>
</html>

b.jsp,

<script>
    var v="xyz";
</script>
<% 
    String st="<script>document.writeln(v)</script>";
    out.println("value="+st); 
%>

Can we have functions inside functions in C++?

No.

What are you trying to do?

workaround:

int main(void)
{
  struct foo
  {
    void operator()() { int a = 1; }
  };

  foo b;
  b(); // call the operator()

}

CSS: center element within a <div> element

I believe the modern way to go is place-items: center in the parent container

An example can be found here: https://1linelayouts.glitch.me

Can I give the col-md-1.5 in bootstrap?

Create new classes to overwrite the width. See jFiddle for working code.

<div class="row">
  <div class="col-xs-1 col-xs-1-5">
    <div class="box">
      box 1
    </div>
  </div>
  <div class="col-xs-3 col-xs-3-5">
    <div class="box">
      box 2
    </div>
  </div>
  <div class="col-xs-3 col-xs-3-5">
    <div class="box">
      box 3
    </div>
  </div>
  <div class="col-xs-3 col-xs-3-5">
    <div class="box">
      box 4
    </div>
  </div>
</div>

.col-xs-1-5 {
  width: 12.49995%;
}
.col-xs-3-5 {
  width: 29.16655%;
}
.box {
  border: 1px solid #000;
  text-align: center;
}

What can MATLAB do that R cannot do?

As a user of both MATLAB and R, I think they are very different applications. I myself have a background in computer science, etc. and I can't help thinking that R is by statisticians for statisticians whereas MATLAB is by programmers for programmers.

R makes it very easy to visualize and compute all sorts of statistical stuff but I wouldn't use it to implement anything signal processing related if it was up to me.

To sum up, if you want to do statistics, use R. If you want to program, use MATLAB or some programming language.

Is there a standardized method to swap two variables in Python?

I know three ways to swap variables, but a, b = b, a is the simplest. There is

XOR (for integers)

x = x ^ y
y = y ^ x
x = x ^ y

Or concisely,

x ^= y
y ^= x
x ^= y

Temporary variable

w = x
x = y
y = w
del w

Tuple swap

x, y = y, x

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer in java 1.6

The number of results can (theoretically) be greater than the range of an integer. I would refactor the code and work with the returned long value instead.

Why is it said that "HTTP is a stateless protocol"?

HTTP is called as a stateless protocol because each request is executed independently, without any knowledge of the requests that were executed before it, which means once the transaction ends the connection between the browser and the server is also lost.

What makes the protocol stateless is that in its original design, HTTP is a relatively simple file transfer protocol:

  1. make a request for a file named by a URL,
  2. get the file in response,
  3. disconnect.

There was no relationship maintained between one connection and another, even from the same client. This simplifies the contract between client and server, and in many cases minimizes the amount of data that needs to be transferred.

Read and write a text file in typescript

believe there should be a way in accessing file system.

Include node.d.ts using npm i @types/node. And then create a new tsconfig.json file (npx tsc --init) and create a .ts file as followed:

import fs from 'fs';
fs.readFileSync('foo.txt','utf8');

You can use other functions in fs as well : https://nodejs.org/api/fs.html

More

Node quick start : https://basarat.gitbooks.io/typescript/content/docs/node/nodejs.html

Conversion of a datetime2 data type to a datetime data type results out-of-range value

The Entity Framework 4 works with the datetime2 data type so in db the corresponding field must be datetime2 for SQL Server 2008.

To achive the solution there are two ways.

  1. To use the datetime data type in Entity Framwork 4 you have to switch the ProviderManifestToken in the edmx-file to "2005".
  2. If you set corresponding field as Allow Null (it converts it to NULLABLE) so then EF automatically uses date objects as datetime.

Python - Move and overwrite files and folders

I had a similar problem. I wanted to move files and folder structures and overwrite existing files, but not delete anything which is in the destination folder structure.

I solved it by using os.walk(), recursively calling my function and using shutil.move() on files which I wanted to overwrite and folders which did not exist.

It works like shutil.move(), but with the benefit that existing files are only overwritten, but not deleted.

import os
import shutil

def moverecursively(source_folder, destination_folder):
    basename = os.path.basename(source_folder)
    dest_dir = os.path.join(destination_folder, basename)
    if not os.path.exists(dest_dir):
        shutil.move(source_folder, destination_folder)
    else:
        dst_path = os.path.join(destination_folder, basename)
        for root, dirs, files in os.walk(source_folder):
            for item in files:
                src_path = os.path.join(root, item)
                if os.path.exists(dst_file):
                    os.remove(dst_file)
                shutil.move(src_path, dst_path)
            for item in dirs:
                src_path = os.path.join(root, item)
                moverecursively(src_path, dst_path)

how to create a list of lists

Just came across the same issue today...

In order to create a list of lists you will have firstly to store your data, array, or other type of variable into a list. Then, create a new empty list and append to it the lists that you just created. At the end you should end up with a list of lists:

list_1=data_1.tolist()
list_2=data_2.tolist()
listoflists = []
listoflists.append(list_1)
listoflists.append(list_2)

Getting an element from a Set

Quick helper method that might address this situation:

<T> T onlyItem(Collection<T> items) {
    if (items.size() != 1)
        throw new IllegalArgumentException("Collection must have single item; instead it has " + items.size());

    return items.iterator().next();
}

Use of "this" keyword in formal parameters for static methods in C#

This is an extension method. See here for an explanation.

Extension methods allow developers to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original type. Extension Methods help blend the flexibility of "duck typing" support popular within dynamic languages today with the performance and compile-time validation of strongly-typed languages.

Extension Methods enable a variety of useful scenarios, and help make possible the really powerful LINQ query framework... .

it means that you can call

MyClass myClass = new MyClass();
int i = myClass.Foo();

rather than

MyClass myClass = new MyClass();
int i = Foo(myClass);

This allows the construction of fluent interfaces as stated below.

Good tutorial for using HTML5 History API (Pushstate?)

Here is a great screen-cast on the topic by Ryan Bates of railscasts. At the end he simply disables the ajax functionality if the history.pushState method is not available:

http://railscasts.com/episodes/246-ajax-history-state

MongoDB relationships: embed or reference?

I came across this small presentation while researching this question on my own. I was surprised at how well it was laid out, both the info and the presentation of it.

http://openmymind.net/Multiple-Collections-Versus-Embedded-Documents

It summarized:

As a general rule, if you have a lot of [child documents] or if they are large, a separate collection might be best.

Smaller and/or fewer documents tend to be a natural fit for embedding.

QR Code encoding and decoding using zxing

For what it's worth, my groovy spike seems to work with both UTF-8 and ISO-8859-1 character encodings. Not sure what will happen when a non zxing decoder tries to decode the UTF-8 encoded image though... probably varies depending on the device.

// ------------------------------------------------------------------------------------
// Requires: groovy-1.7.6, jdk1.6.0_03, ./lib with zxing core-1.7.jar, javase-1.7.jar 
// Javadocs: http://zxing.org/w/docs/javadoc/overview-summary.html
// Run with: groovy -cp "./lib/*" zxing.groovy
// ------------------------------------------------------------------------------------

import com.google.zxing.*
import com.google.zxing.common.*
import com.google.zxing.client.j2se.*

import java.awt.image.BufferedImage
import javax.imageio.ImageIO

def class zxing {
    def static main(def args) {
        def filename = "./qrcode.png"
        def data = "This is a test to see if I can encode and decode this data..."
        def charset = "UTF-8" //"ISO-8859-1" 
        def hints = new Hashtable<EncodeHintType, String>([(EncodeHintType.CHARACTER_SET): charset])

        writeQrCode(filename, data, charset, hints, 100, 100)

        assert data == readQrCode(filename, charset, hints)
    }

    def static writeQrCode(def filename, def data, def charset, def hints, def width, def height) {
        BitMatrix matrix = new MultiFormatWriter().encode(new String(data.getBytes(charset), charset), BarcodeFormat.QR_CODE, width, height, hints)
        MatrixToImageWriter.writeToFile(matrix, filename.substring(filename.lastIndexOf('.')+1), new File(filename))
    }

    def static readQrCode(def filename, def charset, def hints) {
        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(ImageIO.read(new FileInputStream(filename)))))
        Result result = new MultiFormatReader().decode(binaryBitmap, hints)

        result.getText()        
    }

}

How to solve "Could not establish trust relationship for the SSL/TLS secure channel with authority"

I encountered the same problem and I was able to resolve it with two solutions: First, I used the MMC snap-in "Certificates" for the "Computer account" and dragged the self-signed certificate into the "Trusted Root Certification Authorities" folder. This means the local computer (the one that generated the certificate) will now trust that certificate. Secondly I noticed that the certificate was generated for some internal computer name, but the web service was being accessed using another name. This caused a mismatch when validating the certificate. We generated the certificate for computer.operations.local, but accessed the web service using https://computer.internaldomain.companydomain.com. When we switched the URL to the one used to generate the certificate we got no more errors.

Maybe just switching URLs would have worked, but by making the certificate trusted you also avoid the red screen in Internet Explorer where it tells you it doesn't trust the certificate.

Retrieve the maximum length of a VARCHAR column in SQL Server

Use the built-in functions for length and max on the description column:

SELECT MAX(LEN(DESC)) FROM table_name;

Note that if your table is very large, there can be performance issues.

What does the Java assert keyword do, and when should it be used?

Here's the most common use case. Suppose you're switching on an enum value:

switch (fruit) {
  case apple:
    // do something
    break;
  case pear:
    // do something
    break;
  case banana:
    // do something
    break;
}

As long as you handle every case, you're fine. But someday, somebody will add fig to your enum and forget to add it to your switch statement. This produces a bug that may get tricky to catch, because the effects won't be felt until after you've left the switch statement. But if you write your switch like this, you can catch it immediately:

switch (fruit) {
  case apple:
    // do something
    break;
  case pear:
    // do something
    break;
  case banana:
    // do something
    break;
  default:
    assert false : "Missing enum value: " + fruit;
}

Redirect all output to file in Bash

Command:

foo >> output.txt 2>&1

appends to the output.txt file, without replacing the content.

How to select the first row for each group in MySQL?

You should use some aggregate function to get the value of AnotherColumn that you want. That is, if you want the lowest value of AnotherColumn for each value of SomeColumn (either numerically or lexicographically), you can use:

SELECT SomeColumn, MIN(AnotherColumn)
FROM YourTable
GROUP BY SomeColumn

Some hopefully helpful links:

http://dev.mysql.com/doc/refman/5.1/en/group-by-functions.html

http://www.oreillynet.com/databases/blog/2007/05/debunking_group_by_myths.html

Laravel blade check empty foreach

You should use empty()

@if (!empty($status->replies)) 

<div class="media-body reply-body">
    @foreach ($status->replies as $reply)
        <p>{{ $reply->body }}</p>
    @endforeach
</div>

@endif

You can use count, but if the array is larger it takes longer, if you only need to know if its empty, empty is the better one to use.

Send cookies with curl

if you have Firebug installed on Firefox, just open the url. In the network panel, right-click and select Copy as cURL. You can see all curl parameters for this web call.

How to use ADB to send touch events to device using sendevent command?

Consider using Android's uiautomator, with adb shell uiautomator [...] or directly using the .jar that comes with the SDK.

How can you run a command in bash over and over until success?

until passwd
do
  echo "Try again"
done

or

while ! passwd
do
  echo "Try again"
done

apt-get for Cygwin?

Update: you can read the more complex answer, which contains more methods and information.

There exists a couple of scripts, which can be used as simple package managers. But as far as I know, none of them allows you to upgrade packages, because it’s not an easy task on Windows since there is not possible to overwrite files in use. So you have to close all Cygwin instances first and then you can use Cygwin’s native setup.exe (which itself does the upgrade via “replace after reboot” method, when files are in use).


apt-cyg

The best one for me. Simply because it’s one of the most recent. It works correctly for both platforms - x86 and x86_64. There exists a lot of forks with some additional features. For example the kou1okada fork is one of improved versions.


Cygwin’s setup.exe

It has also command line mode. Moreover it allows you to upgrade all installed packages at once.

setup.exe-x86_64.exe -q --packages=bash,vim

Example use:

setup.exe-x86_64.exe -q --packages="bash,vim"

You can create an alias for easier use, for example:

alias cyg-get="/cygdrive/d/path/to/cygwin/setup-x86_64.exe -q -P"

Then you can for example install the Vim package with:

cyg-get vim

Giving my function access to outside variable

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


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

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

For more informations, see Variable scope.

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


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

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

And call the function like this :

$result = someFunction();


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

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

Then, call the function like this :

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

With this :

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


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

Delete all rows in table

You can rename the table in question, create a table with an identical schema, and then drop the original table at your leisure.

See the MySQL 5.1 Reference Manual for the [RENAME TABLE][1] and [CREATE TABLE][2] commands.

RENAME TABLE tbl TO tbl_old;

CREATE TABLE tbl LIKE tbl_old;

DROP TABLE tbl_old; -- at your leisure

This approach can help minimize application downtime.

refresh both the External data source and pivot tables together within a time schedule

Under the connection properties, uncheck "Enable background refresh". This will make the connection refresh when told to, not in the background as other processes happen.

With background refresh disabled, your VBA procedure will wait for your external data to refresh before moving to the next line of code.

Then you just modify the following code:

ActiveWorkbook.Connections("CONNECTION_NAME").Refresh
Sheets("SHEET_NAME").PivotTables("PIVOT_TABLE_NAME").PivotCache.Refresh

You can also turn off background refresh in VBA:

ActiveWorkbook.Connections("CONNECTION_NAME").ODBCConnection.BackgroundQuery = False

LINQ's Distinct() on a particular property

You could also use query syntax if you want it to look all LINQ-like:

var uniquePeople = from p in people
                   group p by new {p.ID} //or group by new {p.ID, p.Name, p.Whatever}
                   into mygroup
                   select mygroup.FirstOrDefault();

What is a NullReferenceException, and how do I fix it?

What is the cause?

Bottom Line

You are trying to use something that is null (or Nothing in VB.NET). This means you either set it to null, or you never set it to anything at all.

Like anything else, null gets passed around. If it is null in method "A", it could be that method "B" passed a null to method "A".

null can have different meanings:

  1. Object variables which are uninitialized and hence point to nothing. In this case, if you access properties or methods of such objects, it causes a NullReferenceException.
  2. The developer is using null intentionally to indicate there is no meaningful value available. Note that C# has the concept of nullable datatypes for variables (like database tables can have nullable fields) - you can assign null to them to indicate there is no value stored in it, for example int? a = null; where the question mark indicates it is allowed to store null in variable a. You can check that either with if (a.HasValue) {...} or with if (a==null) {...}. Nullable variables, like a this example, allow to access the value via a.Value explicitly, or just as normal via a.
    Note that accessing it via a.Value throws an InvalidOperationException instead of a NullReferenceException if a is null - you should do the check beforehand, i.e. if you have another on-nullable variable int b; then you should do assignments like if (a.HasValue) { b = a.Value; } or shorter if (a != null) { b = a; }.

The rest of this article goes into more detail and shows mistakes that many programmers often make which can lead to a NullReferenceException.

More Specifically

The runtime throwing a NullReferenceException always means the same thing: you are trying to use a reference, and the reference is not initialized (or it was once initialized, but is no longer initialized).

This means the reference is null, and you cannot access members (such as methods) through a null reference. The simplest case:

string foo = null;
foo.ToUpper();

This will throw a NullReferenceException at the second line because you can't call the instance method ToUpper() on a string reference pointing to null.

Debugging

How do you find the source of a NullReferenceException? Apart from looking at the exception itself, which will be thrown exactly at the location where it occurs, the general rules of debugging in Visual Studio apply: place strategic breakpoints and inspect your variables, either by hovering the mouse over their names, opening a (Quick)Watch window or using the various debugging panels like Locals and Autos.

If you want to find out where the reference is or isn't set, right-click its name and select "Find All References". You can then place a breakpoint at every found location and run your program with the debugger attached. Every time the debugger breaks on such a breakpoint, you need to determine whether you expect the reference to be non-null, inspect the variable, and verify that it points to an instance when you expect it to.

By following the program flow this way, you can find the location where the instance should not be null, and why it isn't properly set.

Examples

Some common scenarios where the exception can be thrown:

Generic

ref1.ref2.ref3.member

If ref1 or ref2 or ref3 is null, then you'll get a NullReferenceException. If you want to solve the problem, then find out which one is null by rewriting the expression to its simpler equivalent:

var r1 = ref1;
var r2 = r1.ref2;
var r3 = r2.ref3;
r3.member

Specifically, in HttpContext.Current.User.Identity.Name, the HttpContext.Current could be null, or the User property could be null, or the Identity property could be null.

Indirect

public class Person 
{
    public int Age { get; set; }
}
public class Book 
{
    public Person Author { get; set; }
}
public class Example 
{
    public void Foo() 
    {
        Book b1 = new Book();
        int authorAge = b1.Author.Age; // You never initialized the Author property.
                                       // there is no Person to get an Age from.
    }
}

If you want to avoid the child (Person) null reference, you could initialize it in the parent (Book) object's constructor.

Nested Object Initializers

The same applies to nested object initializers:

Book b1 = new Book 
{ 
   Author = { Age = 45 } 
};

This translates to:

Book b1 = new Book();
b1.Author.Age = 45;

While the new keyword is used, it only creates a new instance of Book, but not a new instance of Person, so the Author the property is still null.

Nested Collection Initializers

public class Person 
{
    public ICollection<Book> Books { get; set; }
}
public class Book 
{
    public string Title { get; set; }
}

The nested collection Initializers behave the same:

Person p1 = new Person 
{
    Books = {
         new Book { Title = "Title1" },
         new Book { Title = "Title2" },
    }
};

This translates to:

Person p1 = new Person();
p1.Books.Add(new Book { Title = "Title1" });
p1.Books.Add(new Book { Title = "Title2" });

The new Person only creates an instance of Person, but the Books collection is still null. The collection Initializer syntax does not create a collection for p1.Books, it only translates to the p1.Books.Add(...) statements.

Array

int[] numbers = null;
int n = numbers[0]; // numbers is null. There is no array to index.

Array Elements

Person[] people = new Person[5];
people[0].Age = 20 // people[0] is null. The array was allocated but not
                   // initialized. There is no Person to set the Age for.

Jagged Arrays

long[][] array = new long[1][];
array[0][0] = 3; // is null because only the first dimension is yet initialized.
                 // Use array[0] = new long[2]; first.

Collection/List/Dictionary

Dictionary<string, int> agesForNames = null;
int age = agesForNames["Bob"]; // agesForNames is null.
                               // There is no Dictionary to perform the lookup.

Range Variable (Indirect/Deferred)

public class Person 
{
    public string Name { get; set; }
}
var people = new List<Person>();
people.Add(null);
var names = from p in people select p.Name;
string firstName = names.First(); // Exception is thrown here, but actually occurs
                                  // on the line above.  "p" is null because the
                                  // first element we added to the list is null.

Events (C#)

public class Demo
{
    public event EventHandler StateChanged;
    
    protected virtual void OnStateChanged(EventArgs e)
    {        
        StateChanged(this, e); // Exception is thrown here 
                               // if no event handlers have been attached
                               // to StateChanged event
    }
}

(Note: The VB.NET compiler inserts null checks for event usage, so it's not necessary to check events for Nothing in VB.NET.)

Bad Naming Conventions:

If you named fields differently from locals, you might have realized that you never initialized the field.

public class Form1
{
    private Customer customer;
    
    private void Form1_Load(object sender, EventArgs e) 
    {
        Customer customer = new Customer();
        customer.Name = "John";
    }
    
    private void Button_Click(object sender, EventArgs e)
    {
        MessageBox.Show(customer.Name);
    }
}

This can be solved by following the convention to prefix fields with an underscore:

    private Customer _customer;

ASP.NET Page Life cycle:

public partial class Issues_Edit : System.Web.UI.Page
{
    protected TestIssue myIssue;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
             // Only called on first load, not when button clicked
             myIssue = new TestIssue(); 
        }
    }
        
    protected void SaveButton_Click(object sender, EventArgs e)
    {
        myIssue.Entry = "NullReferenceException here!";
    }
}

ASP.NET Session Values

// if the "FirstName" session value has not yet been set,
// then this line will throw a NullReferenceException
string firstName = Session["FirstName"].ToString();

ASP.NET MVC empty view models

If the exception occurs when referencing a property of @Model in an ASP.NET MVC View, you need to understand that the Model gets set in your action method, when you return a view. When you return an empty model (or model property) from your controller, the exception occurs when the views access it:

// Controller
public class Restaurant:Controller
{
    public ActionResult Search()
    {
        return View();  // Forgot the provide a Model here.
    }
}

// Razor view 
@foreach (var restaurantSearch in Model.RestaurantSearch)  // Throws.
{
}
    
<p>@Model.somePropertyName</p> <!-- Also throws -->

WPF Control Creation Order and Events

WPF controls are created during the call to InitializeComponent in the order they appear in the visual tree. A NullReferenceException will be raised in the case of early-created controls with event handlers, etc. , that fire during InitializeComponent which reference late-created controls.

For example:

<Grid>
    <!-- Combobox declared first -->
    <ComboBox Name="comboBox1" 
              Margin="10"
              SelectedIndex="0" 
              SelectionChanged="comboBox1_SelectionChanged">
       <ComboBoxItem Content="Item 1" />
       <ComboBoxItem Content="Item 2" />
       <ComboBoxItem Content="Item 3" />
    </ComboBox>
        
    <!-- Label declared later -->
    <Label Name="label1" 
           Content="Label"
           Margin="10" />
</Grid>

Here comboBox1 is created before label1. If comboBox1_SelectionChanged attempts to reference `label1, it will not yet have been created.

private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    label1.Content = comboBox1.SelectedIndex.ToString(); // NullReference here!!
}

Changing the order of the declarations in the XAML (i.e., listing label1 before comboBox1, ignoring issues of design philosophy, would at least resolve the NullReferenceException here.

Cast with as

var myThing = someObject as Thing;

This doesn't throw an InvalidCastException but returns a null when the cast fails (and when someObject is itself null). So be aware of that.

LINQ FirstOrDefault() and SingleOrDefault()

The plain versions First() and Single() throw exceptions when there is nothing. The "OrDefault" versions return null in that case. So be aware of that.

foreach

foreach throws when you try to iterate null collection. Usually caused by unexpected null result from methods that return collections.

List<int> list = null;    
foreach(var v in list) { } // exception

More realistic example - select nodes from XML document. Will throw if nodes are not found but initial debugging shows that all properties valid:

foreach (var node in myData.MyXml.DocumentNode.SelectNodes("//Data"))

Ways to Avoid

Explicitly check for null and ignore null values.

If you expect the reference sometimes to be null, you can check for it being null before accessing instance members:

void PrintName(Person p)
{
    if (p != null) 
    {
        Console.WriteLine(p.Name);
    }
}

Explicitly check for null and provide a default value.

Methods call you expect to return an instance can return null, for example when the object being sought cannot be found. You can choose to return a default value when this is the case:

string GetCategory(Book b) 
{
    if (b == null)
        return "Unknown";
    return b.Category;
}

Explicitly check for null from method calls and throw a custom exception.

You can also throw a custom exception, only to catch it in the calling code:

string GetCategory(string bookTitle) 
{
    var book = library.FindBook(bookTitle);  // This may return null
    if (book == null)
        throw new BookNotFoundException(bookTitle);  // Your custom exception
    return book.Category;
}

Use Debug.Assert if a value should never be null, to catch the problem earlier than the exception occurs.

When you know during development that a method maybe can, but never should return null, you can use Debug.Assert() to break as soon as possible when it does occur:

string GetTitle(int knownBookID) 
{
    // You know this should never return null.
    var book = library.GetBook(knownBookID);  

    // Exception will occur on the next line instead of at the end of this method.
    Debug.Assert(book != null, "Library didn't return a book for known book ID.");

    // Some other code

    return book.Title; // Will never throw NullReferenceException in Debug mode.
}

Though this check will not end up in your release build, causing it to throw the NullReferenceException again when book == null at runtime in release mode.

Use GetValueOrDefault() for nullable value types to provide a default value when they are null.

DateTime? appointment = null;
Console.WriteLine(appointment.GetValueOrDefault(DateTime.Now));
// Will display the default value provided (DateTime.Now), because appointment is null.

appointment = new DateTime(2022, 10, 20);
Console.WriteLine(appointment.GetValueOrDefault(DateTime.Now));
// Will display the appointment date, not the default

Use the null coalescing operator: ?? [C#] or If() [VB].

The shorthand to providing a default value when a null is encountered:

IService CreateService(ILogger log, Int32? frobPowerLevel)
{
   var serviceImpl = new MyService(log ?? NullLog.Instance);
 
   // Note that the above "GetValueOrDefault()" can also be rewritten to use
   // the coalesce operator:
   serviceImpl.FrobPowerLevel = frobPowerLevel ?? 5;
}

Use the null condition operator: ?. or ?[x] for arrays (available in C# 6 and VB.NET 14):

This is also sometimes called the safe navigation or Elvis (after its shape) operator. If the expression on the left side of the operator is null, then the right side will not be evaluated, and null is returned instead. That means cases like this:

var title = person.Title.ToUpper();

If the person does not have a title, this will throw an exception because it is trying to call ToUpper on a property with a null value.

In C# 5 and below, this can be guarded with:

var title = person.Title == null ? null : person.Title.ToUpper();

Now the title variable will be null instead of throwing an exception. C# 6 introduces a shorter syntax for this:

var title = person.Title?.ToUpper();

This will result in the title variable being null, and the call to ToUpper is not made if person.Title is null.

Of course, you still have to check title for null or use the null condition operator together with the null coalescing operator (??) to supply a default value:

// regular null check
int titleLength = 0;
if (title != null)
    titleLength = title.Length; // If title is null, this would throw NullReferenceException
    
// combining the `?` and the `??` operator
int titleLength = title?.Length ?? 0;

Likewise, for arrays you can use ?[i] as follows:

int[] myIntArray = null;
var i = 5;
int? elem = myIntArray?[i];
if (!elem.HasValue) Console.WriteLine("No value");

This will do the following: If myIntArray is null, the expression returns null and you can safely check it. If it contains an array, it will do the same as: elem = myIntArray[i]; and returns the i<sup>th</sup> element.

Use null context (available in C# 8):

Introduced in C# 8 there null context's and nullable reference types perform static analysis on variables and provides a compiler warning if a value can be potentially null or have been set to null. The nullable reference types allows types to be explicitly allowed to be null.

The nullable annotation context and nullable warning context can be set for a project using the Nullable element in your csproj file. This element configures how the compiler interprets the nullability of types and what warnings are generated. Valid settings are:

  • enable: The nullable annotation context is enabled. The nullable warning context is enabled. Variables of a reference type, string for example, are non-nullable. All nullability warnings are enabled.
  • disable: The nullable annotation context is disabled. The nullable warning context is disabled. Variables of a reference type are oblivious, just like earlier versions of C#. All nullability warnings are disabled.
  • safeonly: The nullable annotation context is enabled. The nullable warning context is safeonly. Variables of a reference type are nonnullable. All safety nullability warnings are enabled.
  • warnings: The nullable annotation context is disabled. The nullable warning context is enabled. Variables of a reference type are oblivious. All nullability warnings are enabled.
  • safeonlywarnings: The nullable annotation context is disabled. The nullable warning context is safeonly. Variables of a reference type are oblivious. All safety nullability warnings are enabled.

A nullable reference type is noted using the same syntax as nullable value types: a ? is appended to the type of the variable.

Special techniques for debugging and fixing null derefs in iterators

C# supports "iterator blocks" (called "generators" in some other popular languages). Null dereference exceptions can be particularly tricky to debug in iterator blocks because of deferred execution:

public IEnumerable<Frob> GetFrobs(FrobFactory f, int count)
{
    for (int i = 0; i < count; ++i)
    yield return f.MakeFrob();
}
...
FrobFactory factory = whatever;
IEnumerable<Frobs> frobs = GetFrobs();
...
foreach(Frob frob in frobs) { ... }

If whatever results in null then MakeFrob will throw. Now, you might think that the right thing to do is this:

// DON'T DO THIS
public IEnumerable<Frob> GetFrobs(FrobFactory f, int count)
{
   if (f == null) 
      throw new ArgumentNullException("f", "factory must not be null");
   for (int i = 0; i < count; ++i)
      yield return f.MakeFrob();
}

Why is this wrong? Because the iterator block does not actually run until the foreach! The call to GetFrobs simply returns an object which when iterated will run the iterator block.

By writing a null check like this you prevent the null dereference, but you move the null argument exception to the point of the iteration, not to the point of the call, and that is very confusing to debug.

The correct fix is:

// DO THIS
public IEnumerable<Frob> GetFrobs(FrobFactory f, int count)
{
   // No yields in a public method that throws!
   if (f == null) 
       throw new ArgumentNullException("f", "factory must not be null");
   return GetFrobsForReal(f, count);
}
private IEnumerable<Frob> GetFrobsForReal(FrobFactory f, int count)
{
   // Yields in a private method
   Debug.Assert(f != null);
   for (int i = 0; i < count; ++i)
        yield return f.MakeFrob();
}

That is, make a private helper method that has the iterator block logic, and a public surface method that does the null check and returns the iterator. Now when GetFrobs is called, the null check happens immediately, and then GetFrobsForReal executes when the sequence is iterated.

If you examine the reference source for LINQ to Objects you will see that this technique is used throughout. It is slightly more clunky to write, but it makes debugging nullity errors much easier. Optimize your code for the convenience of the caller, not the convenience of the author.

A note on null dereferences in unsafe code

C# has an "unsafe" mode which is, as the name implies, extremely dangerous because the normal safety mechanisms which provide memory safety and type safety are not enforced. You should not be writing unsafe code unless you have a thorough and deep understanding of how memory works.

In unsafe mode, you should be aware of two important facts:

  • dereferencing a null pointer produces the same exception as dereferencing a null reference
  • dereferencing an invalid non-null pointer can produce that exception in some circumstances

To understand why that is, it helps to understand how .NET produces null dereference exceptions in the first place. (These details apply to .NET running on Windows; other operating systems use similar mechanisms.)

Memory is virtualized in Windows; each process gets a virtual memory space of many "pages" of memory that are tracked by the operating system. Each page of memory has flags set on it which determine how it may be used: read from, written to, executed, and so on. The lowest page is marked as "produce an error if ever used in any way".

Both a null pointer and a null reference in C# are internally represented as the number zero, and so any attempt to dereference it into its corresponding memory storage causes the operating system to produce an error. The .NET runtime then detects this error and turns it into the null dereference exception.

That's why dereferencing both a null pointer and a null reference produces the same exception.

What about the second point? Dereferencing any invalid pointer that falls in the lowest page of virtual memory causes the same operating system error, and thereby the same exception.

Why does this make sense? Well, suppose we have a struct containing two ints, and an unmanaged pointer equal to null. If we attempt to dereference the second int in the struct, the CLR will not attempt to access the storage at location zero; it will access the storage at location four. But logically this is a null dereference because we are getting to that address via the null.

If you are working with unsafe code and you get a null dereference exception, just be aware that the offending pointer need not be null. It can be any location in the lowest page, and this exception will be produced.

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

You can find your sample code completely here: http://www.java2s.com/Code/Java/Hibernate/OneToManyMappingbasedonSet.htm

Have a look and check the differences. specially the even_id in :

<set name="attendees" cascade="all">
    <key column="event_id"/>
    <one-to-many class="Attendee"/>
</set> 

Set Memory Limit in htaccess

In your .htaccess you can add:

PHP 5.x

<IfModule mod_php5.c>
    php_value memory_limit 64M
</IfModule>

PHP 7.x

<IfModule mod_php7.c>
    php_value memory_limit 64M
</IfModule>

If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.

If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.

Read more on http://support.tigertech.net/php-value

How to capitalize the first letter of text in a TextView in an Android Application

Following does not apply to TextView, but works with EditText; even then, it applies to the text entered from the keyboard, not the text loaded with setText(). To be more specific, it turns the Caps on in the keyboard, and the user can override this at her will.

android:inputType="textCapSentences"

or

TV.sname.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);

This will CAP the first letter.

or

compile 'org.apache.commons:commons-lang3:3.4' //in build.gradle module(app)

tv.setText(StringUtils.capitalize(myString.toLowerCase().trim()));

AngularJS: how to implement a simple file upload with multipart form?

A real working solution with no other dependencies than angularjs (tested with v.1.0.6)

html

<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files)"/>

Angularjs (1.0.6) not support ng-model on "input-file" tags so you have to do it in a "native-way" that pass the all (eventually) selected files from the user.

controller

$scope.uploadFile = function(files) {
    var fd = new FormData();
    //Take the first selected file
    fd.append("file", files[0]);

    $http.post(uploadUrl, fd, {
        withCredentials: true,
        headers: {'Content-Type': undefined },
        transformRequest: angular.identity
    }).success( ...all right!... ).error( ..damn!... );

};

The cool part is the undefined content-type and the transformRequest: angular.identity that give at the $http the ability to choose the right "content-type" and manage the boundary needed when handling multipart data.

Working with huge files in VIM

This has been a recurring question for many years. (The numbers keep changing, but the concept is the same: how do I view or edit files that are larger than memory?)

Obviously more or less are good approaches to merely reading the files --- less even offers vi like keybindings for scrolling and searching.

A Freshmeat search on "large files" suggests that two editors would be particularly suited to your needs.

One would be: lfhex ... a large file hex editor (which depends on Qt). That one, obviously, entails using a GUI.

Another would seem to be suited to console use: hed ... and it claims to have a vim-like interface (including an ex mode?).

I'm sure I've seen other editors for Linux/UNIX that were able to page through files without loading their entirety into memory. However, I don't recall any of their names. I'm making this response a "wiki" entry to encourage others to add their links to such editors. (Yes, I am familiar with ways to work around the issue using split and cat; but I'm thinking of editors, especially console/curses editors which can dispense with that and save us the time/latencies and disk space overhead that such approaches entail).

Send form data using ajax

can you try this :

function f (){
fname  = $("input[name='fname']").val();
lname  = $("input[name='fname']").val();
att=form.attr("action") ;
$.post(att ,{fname : fname , lname :lname}).done(function(data){
alert(data);
});
return true;
}

How to commit changes to a new branch

git checkout -b your-new-branch

git add <files>

git commit -m <message>

First, checkout your new branch. Then add all the files you want to commit to staging. Lastly, commit all the files you just added. You might want to do a git push origin your-new-branch afterward so your changes show up on the remote.

Show a popup/message box from a Windows batch file

Might display a little flash, but no temp files required. Should work all the way back to somewhere in the (IIRC) IE5 era.

mshta javascript:alert("Message\n\nMultiple\nLines\ntoo!");close();

Don't forget to escape your parentheses if you're using if:

if 1 == 1 (
   mshta javascript:alert^("1 is equal to 1, amazing."^);close^(^);
)

If Cell Starts with Text String... Formula

I know this is a really old post, but I found it in searching for a solution to the same problem. I don't want a nested if-statement, and Switch is apparently newer than the version of Excel I'm using. I figured out what was going wrong with my code, so I figured I'd share here in case it helps someone else.

I remembered that VLOOKUP requires the source table to be sorted alphabetically/numerically for it to work. I was initially trying to do this...

=LOOKUP(LOWER(LEFT($T$3, 1)),  {"s","l","m"}, {-1,1,0})

and it started working when I did this...

=LOOKUP(LOWER(LEFT($T$3, 1)),  {"l","m","s"}, {1,0,-1})

I was initially thinking the last value might turn out to be a default, so I wanted the zero at the last place. That doesn't seem to be the behavior anyway, so I just put the possible matches in order, and it worked.

Edit: As a final note, I see that the example in the original post has letters in alphabetical order, but I imagine the real use case might have been different if the error was happening and the letters A, B, and C were just examples.

How to pass params with history.push/Link/Redirect in react-router v4?

you can use,

this.props.history.push("/template", { ...response }) or this.props.history.push("/template", { response: response })

then you can access the parsed data from /template component by following code,

const state = this.props.location.state

Read more about React Session History Management

Currently running queries in SQL Server

Depending on your privileges, this query might work:

SELECT sqltext.TEXT,
req.session_id,
req.status,
req.command,
req.cpu_time,
req.total_elapsed_time
FROM sys.dm_exec_requests req
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext

Ref: http://blog.sqlauthority.com/2009/01/07/sql-server-find-currently-running-query-t-sql

Setting UILabel text to bold

Use font property of UILabel:

label.font = UIFont(name:"HelveticaNeue-Bold", size: 16.0)

or use default system font to bold text:

label.font = UIFont.boldSystemFont(ofSize: 16.0)

How to get ASCII value of string in C#

byte[] asciiBytes = Encoding.ASCII.GetBytes("Y");
foreach (byte b in asciiBytes)
{
    MessageBox.Show("" + b);
}

Manipulate a url string by adding GET parameters

$data = array('foo'=>'bar',
              'baz'=>'boom',
              'cow'=>'milk',
              'php'=>'hypertext processor');

$queryString =  http_build_query($data);
//$queryString = foo=bar&baz=boom&cow=milk&php=hypertext+processor

echo 'http://domain.com?'.$queryString;
//output: http://domain.com?foo=bar&baz=boom&cow=milk&php=hypertext+processor

How to query the permissions on an Oracle directory?

With Oracle 11g R2 (at least with 11.2.02) there is a view named datapump_dir_objs.

SELECT * FROM datapump_dir_objs;

The view shows the NAME of the directory object, the PATH as well as READ and WRITE permissions for the currently connected user. It does not show any directory objects which the current user has no permission to read from or write to, though.

jQuery Set Select Index

NB:

$('#selectBox option')[3].attr('selected', 'selected') 

is incorrect, the array deference gets you the dom object, not a jquery object, so it will fail with a TypeError, for instance in FF with: "$('#selectBox option')[3].attr() not a function."

Excel function to get first word from sentence in other cell

If you want to cater to 1-word cell, use this... based upon astander's

=IFERROR(LEFT(A1,SEARCH(" ",A1)-1),A1)

Set HTML element's style property in javascript

The DOM element style "property" is a readonly collection of all the style attributes defined on the element. (The collection property is readonly, not necessarily the items within the collection.)

You would be better off using the className "property" on the elements.

inherit from two classes in C#

Make two interfaces IA and IB:

public interface IA
{
    public void methodA(int value);
}

public interface IB
{
    public void methodB(int value);
}

Next make A implement IA and B implement IB.

public class A : IA
{
    public int fooA { get; set; }
    public void methodA(int value) { fooA = value; }
}

public class B : IB
{
    public int fooB { get; set; }
    public void methodB(int value) { fooB = value; }
}

Then implement your C class as follows:

public class C : IA, IB
{
    private A _a;
    private B _b;

    public C(A _a, B _b)
    {
        this._a = _a;
        this._b = _b;
    }

    public void methodA(int value) { _a.methodA(value); }
    public void methodB(int value) { _b.methodB(value); }
}

Generally this is a poor design overall because you can have both A and B implement a method with the same name and variable types such as foo(int bar) and you will need to decide how to implement it, or if you just call foo(bar) on both _a and _b. As suggested elsewhere you should consider a .A and .B properties instead of combining the two classes.

Drop rows containing empty cells from a pandas DataFrame

There's a situation where the cell has white space, you can't see it, use

df['col'].replace('  ', np.nan, inplace=True)

to replace white space as NaN, then

df= df.dropna(subset=['col'])

How to return a custom object from a Spring Data JPA GROUP BY query

This SQL query return List< Object[] > would.

You can do it this way:

 @RestController
 @RequestMapping("/survey")
 public class SurveyController {

   @Autowired
   private SurveyRepository surveyRepository;

     @RequestMapping(value = "/find", method =  RequestMethod.GET)
     public Map<Long,String> findSurvey(){
       List<Object[]> result = surveyRepository.findSurveyCount();
       Map<Long,String> map = null;
       if(result != null && !result.isEmpty()){
          map = new HashMap<Long,String>();
          for (Object[] object : result) {
            map.put(((Long)object[0]),object[1]);
          }
       }
     return map;
     }
 }

Static way to get 'Context' in Android?

If you're open to using RoboGuice, you can have the context injected into any class you want. Here's a small sample of how to do it with RoboGuice 2.0 (beta 4 at time of this writing)

import android.content.Context;
import android.os.Build;
import roboguice.inject.ContextSingleton;

import javax.inject.Inject;

@ContextSingleton
public class DataManager {
    @Inject
    public DataManager(Context context) {
            Properties properties = new Properties();
            properties.load(context.getResources().getAssets().open("data.properties"));
        } catch (IOException e) {
        }
    }
}

Case insensitive string as HashMap key

Subclass HashMap and create a version that lower-cases the key on put and get (and probably the other key-oriented methods).

Or composite a HashMap into the new class and delegate everything to the map, but translate the keys.

If you need to keep the original key you could either maintain dual maps, or store the original key along with the value.

How can I send an xml body using requests library?

Pass in the straight XML instead of a dictionary.

Counting the number of non-NaN elements in a numpy ndarray in Python

An alternative, but a bit slower alternative is to do it over indexing.

np.isnan(data)[np.isnan(data) == False].size

In [30]: %timeit np.isnan(data)[np.isnan(data) == False].size
1 loops, best of 3: 498 ms per loop 

The double use of np.isnan(data) and the == operator might be a bit overkill and so I posted the answer only for completeness.

What's the fastest way to loop through an array in JavaScript?

If you want a faster for loop, define your variables outside the loop and use below syntax

  const iMax = lengthOftheLoop;
  var i = 0;
  for (; i < iMax; i++) {
    console.log("loop"+i);
  }

reference: https://medium.com/kbdev/voyage-to-the-most-efficient-loop-in-nodejs-and-a-bit-js-5961d4524c2e

Understanding the Gemfile.lock file

You can find more about it in the bundler website (emphasis added below for your convenience):

After developing your application for a while, check in the application together with the Gemfile and Gemfile.lock snapshot. Now, your repository has a record of the exact versions of all of the gems that you used the last time you know for sure that the application worked...

This is important: the Gemfile.lock makes your application a single package of both your own code and the third-party code it ran the last time you know for sure that everything worked. Specifying exact versions of the third-party code you depend on in your Gemfile would not provide the same guarantee, because gems usually declare a range of versions for their dependencies.

Is it possible to set the stacking order of pseudo-elements below their parent element?

Pseudo-elements are treated as descendants of their associated element. To position a pseudo-element below its parent, you have to create a new stacking context to change the default stacking order.
Positioning the pseudo-element (absolute) and assigning a z-index value other than “auto” creates the new stacking context.

_x000D_
_x000D_
#element { _x000D_
    position: relative;  /* optional */_x000D_
    width: 100px;_x000D_
    height: 100px;_x000D_
    background-color: blue;_x000D_
}_x000D_
_x000D_
#element::after {_x000D_
    content: "";_x000D_
    width: 150px;_x000D_
    height: 150px;_x000D_
    background-color: red;_x000D_
_x000D_
    /* create a new stacking context */_x000D_
    position: absolute;_x000D_
    z-index: -1;  /* to be below the parent element */_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <title>Position a pseudo-element below its parent</title>_x000D_
</head>_x000D_
<body>_x000D_
  <div id="element">_x000D_
  </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Virtualbox shared folder permissions

In my personal experience, it's difficult to enable shared folders in VirtualBox but it Is posible. I have a debian Buster guest virtual machine installed in my Windows 10 host.

I don't recognize exactly what did it, but I remember I went to Windows defender, my antivirus to see if they recognize VirtualBox as a program and not as a virus. After that, I press right click on the document file and allowed to share the folder and I gave click to some buttons there and accepted to share with groups and with muy user in Windows 10.

Also, I found a webpage of Windows about something like virtual machines that I don't remember well, but it took me to a panel and I had to change three things double clicking so when I update Windows, it recognizes my virtual machine. Also, in muy debian, in the terminal, using some command lines, muy VirtualBox recognized my user giving permissions, I based on some info in the Ubuntu forums. I put all what I remember.

How do I list all cron jobs for all users?

I like the simple one-liner answer above:

for user in $(cut -f1 -d: /etc/passwd); do crontab -u $user -l; done

But Solaris which does not have the -u flag and does not print the user it's checking, you can modify it like so:

for user in $(cut -f1 -d: /etc/passwd); do echo User:$user; crontab -l $user 2>&1 | grep -v crontab; done

You will get a list of users without the errors thrown by crontab when an account is not allowed to use cron etc. Be aware that in Solaris, roles can be in /etc/passwd too (see /etc/user_attr).

MongoDB vs. Cassandra

Why choose between a traditional database and a NoSQL data store? Use both! The problem with NoSQL solutions (beyond the initial learning curve) is the lack of transactions -- you do all updates to MySQL and have MySQL populate a NoSQL data store for reads -- you then benefit from each technology's strengths. This does add more complexity, but you already have the MySQL side -- just add MongoDB, Cassandra, etc to the mix.

NoSQL datastores generally scale way better than a traditional DB for the same otherwise specs -- there is a reason why Facebook, Twitter, Google, and most start-ups are using NoSQL solutions. It's not just geeks getting high on new tech.

Java collections maintaining insertion order

Okay ... so these posts are old as compared to now, but insertion order is needed depending on your need or application requirements, so just use the right type of collection. For most part, it is not needed, but in a situation where you need to utilize objects in the order they were stored, I see a definite need. I think order matters when you are creating for instance a wizard or a flow engine or something of that nature where you need to go from state to state or something. In that sense you can read off stuff from the list without having it keep track of what you need next or traverse a list to find what you want. It does help with performance in that sense. It does matter or else these collections would not make much sense.

Git: can't undo local changes (error: path ... is unmerged)

You did it the wrong way around. You are meant to reset first, to unstage the file, then checkout, to revert local changes.

Try this:

$ git reset foo/bar.txt
$ git checkout foo/bar.txt

Git: add vs push vs commit

git add selects changes

git commit records changes LOCALLY

git push shares changes

build failed with: ld: duplicate symbol _OBJC_CLASS_$_Algebra5FirstViewController

In my case I had a reference to a library in Other Linker Flags. Removing it got rid of the error.

enter image description here

enter image description here

No default constructor found; nested exception is java.lang.NoSuchMethodException with Spring MVC?

Spring cannot instantiate your TestController because its only constructor requires a parameter. You can add a no-arg constructor or you add @Autowired annotation to the constructor:

@Autowired
public TestController(KeeperClient testClient) {
    TestController.testClient = testClient;
}

In this case, you are explicitly telling Spring to search the application context for a KeeperClient bean and inject it when instantiating the TestControlller.

Cast Object to Generic Type for returning

If you do not want to depend on throwing exception (which you probably should not) you can try this:

public static <T> T cast(Object o, Class<T> clazz) {
    return clazz.isInstance(o) ? clazz.cast(o) : null;
}

How to change default text color using custom theme?

Check if your activity layout overrides the theme, look for your activity layout located at layout/*your_activity*.xml and look for TextView that contains android:textColor="(some hex code") something like that on activity layout, and remove it. Then run your code again.

Get viewport/window height in ReactJS

class AppComponent extends React.Component {

  constructor(props) {
    super(props);
    this.state = {height: props.height};
  }

  componentWillMount(){
    this.setState({height: window.innerHeight + 'px'});
  }

  render() {
    // render your component...
  }
}

Set the props

AppComponent.propTypes = {
 height:React.PropTypes.string
};

AppComponent.defaultProps = {
 height:'500px'
};

viewport height is now available as {this.state.height} in rendering template

Elasticsearch: Failed to connect to localhost port 9200 - Connection refused

After utilizing some of the answers above, don't forget that after an apt install, a total reboot might be in order.

set serveroutput on in oracle procedure

Actually, you need to call SET SERVEROUTPUT ON; before the BEGIN call.

Everyone suggested this but offers no advice where to actually place the line:

SET SERVEROUTPUT ON;

BEGIN
    FOR rec in (SELECT * FROM EMPLOYEES) LOOP
        DBMS_OUTPUT.PUT_LINE(rec.EmployeeName);
    ENDLOOP;
END;

Otherwise, you won't see any output.

How to select first child with jQuery?

Use the :first-child selector.

In your example...

$('div.alldivs div:first-child')

This will also match any first child descendents that meet the selection criteria.

While :first matches only a single element, the :first-child selector can match more than one: one for each parent. This is equivalent to :nth-child(1).

For the first matched only, use the :first selector.

Alternatively, Felix Kling suggested using the direct descendent selector to get only direct children...

$('div.alldivs > div:first-child')

How to add text to an existing div with jquery

Very easy from My side:-

<html>
<head>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        $("input").click(function() {
            $('<input type="text" name="name" value="value"/>').appendTo('#testdiv');
        });

    });
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <div id="testdiv"></div>
    <input type="button" value="Add" />
</body>
</html>

How to return a part of an array in Ruby?

I like ranges for this:

def first_half(list)
  list[0...(list.length / 2)]
end

def last_half(list)
  list[(list.length / 2)..list.length]
end

However, be very careful about whether the endpoint is included in your range. This becomes critical on an odd-length list where you need to choose where you're going to break the middle. Otherwise you'll end up double-counting the middle element.

The above example will consistently put the middle element in the last half.

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

I found some issue about that kind of error

  1. Database username or password not match in the mysql or other other database. Please set application.properties like this

  

# =============================== # = DATA SOURCE # =============================== # Set here configurations for the database connection # Connection url for the database please let me know "[email protected]" spring.datasource.url = jdbc:mysql://localhost:3306/bookstoreapiabc # Username and secret spring.datasource.username = root spring.datasource.password = # Keep the connection alive if idle for a long time (needed in production) spring.datasource.testWhileIdle = true spring.datasource.validationQuery = SELECT 1 # =============================== # = JPA / HIBERNATE # =============================== # Use spring.jpa.properties.* for Hibernate native properties (the prefix is # stripped before adding them to the entity manager). # Show or not log for each sql query spring.jpa.show-sql = true # Hibernate ddl auto (create, create-drop, update): with "update" the database # schema will be automatically updated accordingly to java entities found in # the project spring.jpa.hibernate.ddl-auto = update # Allows Hibernate to generate SQL optimized for a particular DBMS spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

Issue no 2.

Your local server has two database server and those database server conflict. this conflict like this mysql server & xampp or lampp or wamp server. Please one of the database like mysql server because xampp or lampp server automatically install mysql server on this machine

HTML not loading CSS file

Add

type="text/css"

to your link tag

While this may no longer be necessary in modern browsers the HTML4 specification declared this a required attribute.

type = content-type [CI]

This attribute specifies the style sheet language of the element's contents and overrides the default style sheet language. The style sheet language is specified as a content type (e.g., "text/css"). Authors must supply a value for this attribute; there is no default value for this attribute.

HTTP Error 500.19 and error code : 0x80070021

In my case, there were rules for IIS URL Rewrite module but I didn't have that module installed. You should check your web.config if there are any modules included but not installed.

Renaming a branch in GitHub

You can do that without the terminal. You just need to create a branch with the new name, and remove the old after.

Create a branch

In your repository’s branch selector, just start typing a new branch name. It’ll give you the option to create a new branch:

Create a branch

It’ll branch off of your current context. For example, if you’re on the bugfix branch, it’ll create a new branch from bugfix instead of master. Looking at a commit or a tag instead? It’ll branch your code from that specific revision.

Delete a branch

You’ll also see a delete button in your repository’s Branches page:

Delete a branch

As an added bonus, it’ll also give you a link to the branch’s Pull Request, if it has one.

I just copied this content from: Create and delete branches

Invalidating JSON Web Tokens

I just save token to users table, when user login I will update new token, and when auth equal to the user current jwt.

I think this is not the best solution but that work for me.

case-insensitive matching in xpath?

for selenium xpath lower-case will not work ... Translate will help Case 1 :

  1. using Attribute //*[translate(@id,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='login_field']
  2. Using any attribute //[translate(@,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='login_field']

Case 2 : (with contains) //[contains(translate(@id,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz'),'login_field')]

case 3 : for Text property //*[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'),'username')]


QA Automator is automation management tool on cloud platform , where you can create, execute and maintenance the automation test scripts https://www.youtube.com/watch?v=iFk1Na_627U&t=53s

Repeat each row of data.frame the number of times specified in a column

in fact. use the methods of vector and index. we can also achieve the same result, and more easier to understand:

rawdata <- data.frame('time' = 1:3, 
           'x1' = 4:6,
           'x2' = 7:9,
           'x3' = 10:12)

rawdata[rep(1, time=2), ] %>% remove_rownames()
#  time x1 x2 x3
# 1    1  4  7 10
# 2    1  4  7 10


Fiddler not capturing traffic from browsers

I had the same problem with a Chrome extension called GeoProxy - even though proxy was disabled, it still took the traffic away and stopped fiddler from seeing it. Disabling the extension resolved the issue. I'm guessing this will be an issue with any proxy extension.

(This was meant just as a comment for Claus' response above, which set me on the right path - but apparently I have enough reputation to answer, but not to comment...)

Angular 2 Dropdown Options Default Value

just set the value of the model to the default you want like this:

selectedWorkout = 'back'

I created a fork of @Douglas' plnkr here to demonstrate the various ways to get the desired behavior in angular2.

bootstrap 4 responsive utilities visible / hidden xs sm lg not working

Screen Size Class

-

  1. Hidden on all .d-none

  2. Hidden only on xs .d-none .d-sm-block

  3. Hidden only on sm .d-sm-none .d-md-block

  4. Hidden only on md .d-md-none .d-lg-block

  5. Hidden only on lg .d-lg-none .d-xl-block

  6. Hidden only on xl .d-xl-none

  7. Visible on all .d-block

  8. Visible only on xs .d-block .d-sm-none

  9. Visible only on sm .d-none .d-sm-block .d-md-none

  10. Visible only on md .d-none .d-md-block .d-lg-none

  11. Visible only on lg .d-none .d-lg-block .d-xl-none

  12. Visible only on xl .d-none .d-xl-block

Refer this link http://getbootstrap.com/docs/4.0/utilities/display/#hiding-elements

4.5 link: https://getbootstrap.com/docs/4.5/utilities/display/#hiding-elements

Permission denied for relation

Connect to the right database first, then run:

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO jerry;

How do you send an HTTP Get Web Request in Python?

In Python, you can use urllib2 (http://docs.python.org/2/library/urllib2.html) to do all of that work for you.

Simply enough:

import urllib2
f =  urllib2.urlopen(url)
print f.read() 

Will print the received HTTP response.

To pass GET/POST parameters the urllib.urlencode() function can be used. For more information, you can refer to the Official Urllib2 Tutorial

How do you change the formatting options in Visual Studio Code?

At the VS code

press Ctrl+Shift+P

then type Format Document With...

At the end of the list click on Configure Default Formatter...

Now you can choose your favorite beautifier from the list.

Update 2021

if "Format Document With..." didn't exist any more, go to file => preferences => settings then navigate to Extensions => Vetur scroll a little bit then you will see format > defaultFormatter:css, now you can pick any document formatter that you installed bofer for different file type extensions.

Asserting successive calls to a mock method

Usually, I don't care about the order of the calls, only that they happened. In that case, I combine assert_any_call with an assertion about call_count.

>>> import mock
>>> m = mock.Mock()
>>> m(1)
<Mock name='mock()' id='37578160'>
>>> m(2)
<Mock name='mock()' id='37578160'>
>>> m(3)
<Mock name='mock()' id='37578160'>
>>> m.assert_any_call(1)
>>> m.assert_any_call(2)
>>> m.assert_any_call(3)
>>> assert 3 == m.call_count
>>> m.assert_any_call(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "[python path]\lib\site-packages\mock.py", line 891, in assert_any_call
    '%s call not found' % expected_string
AssertionError: mock(4) call not found

I find doing it this way to be easier to read and understand than a large list of calls passed into a single method.

If you do care about order or you expect multiple identical calls, assert_has_calls might be more appropriate.

Edit

Since I posted this answer, I've rethought my approach to testing in general. I think it's worth mentioning that if your test is getting this complicated, you may be testing inappropriately or have a design problem. Mocks are designed for testing inter-object communication in an object oriented design. If your design is not objected oriented (as in more procedural or functional), the mock may be totally inappropriate. You may also have too much going on inside the method, or you might be testing internal details that are best left unmocked. I developed the strategy mentioned in this method when my code was not very object oriented, and I believe I was also testing internal details that would have been best left unmocked.

How can I customize the tab-to-space conversion factor?

If you use the prettier extension in Visual Studio Code, try adding this to the settings.json file:

"editor.insertSpaces": false,
"editor.tabSize": 4,
"editor.detectIndentation": false,

"prettier.tabWidth": 4,
"prettier.useTabs": true  // This made it finally work for me

How to do an update + join in PostgreSQL?

Here's a simple SQL that updates Mid_Name on the Name3 table using the Middle_Name field from Name:

update name3
set mid_name = name.middle_name
from name
where name3.person_id = name.person_id;

Finding the Eclipse Version Number

Based on Neeme Praks' answer, the below code should give you the version of eclipse ide you're running within.

In my case, I was running in an eclipse-derived product, so Neeme's answer just gave me the version of that product. The OP asked how to find the Eclipse version, whih is what I was after. Therefore I needed to make a couple of changes, leading me to this:

    /**
     * Attempts to get the version of the eclipse ide we're running in.
     * @return the version, or null if it couldn't be detected.
     */
    static Version getEclipseVersion() {
        String product = "org.eclipse.platform.ide";
        IExtensionRegistry registry = Platform.getExtensionRegistry();
        IExtensionPoint point = registry.getExtensionPoint("org.eclipse.core.runtime.products");
        if (point != null) {
            IExtension[] extensions = point.getExtensions();
            for (IExtension ext : extensions) {
                if (product.equals(ext.getUniqueIdentifier())) {
                    IContributor contributor = ext.getContributor();
                    if (contributor != null) {
                        Bundle bundle = Platform.getBundle(contributor.getName());
                        if (bundle != null) {
                            return bundle.getVersion();
                        }
                    }
                }
            }
        }
        return null;
    }

This will return you a convenient Version, which can be compared thus:

    private static final Version DESIRED_MINIMUM_VERSION = new Version("4.9"); //other constructors are available
    boolean haveAtLeastMinimumDesiredVersion()
        Version thisVersion = getEclipseVersion();
        if (thisVersion == null) {
            //we might have a problem
        }
        //returns a positive number if thisVersion is greater than the given parameter (desiredVersion)
        return thisVersion.compareTo(DESIRED_MINIMUM_VERSION) >= 0;
    }

Remove Duplicates from range of cells in excel vba

To remove duplicates from a single column

 Sub removeDuplicate()
 'removeDuplicate Macro
 Columns("A:A").Select
 ActiveSheet.Range("$A$1:$A$117").RemoveDuplicates Columns:=Array(1), _ 
 Header:=xlNo 
 Range("A1").Select
 End Sub

if you have header then use Header:=xlYes

Increase your range as per your requirement.
you can make it to 1000 like this :

ActiveSheet.Range("$A$1:$A$1000")

More info here here

How to set up Spark on Windows?

Here's the fixes to get it to run in Windows without rebuilding everything - such as if you do not have a recent version of MS-VS. (You will need a Win32 C++ compiler, but you can install MS VS Community Edition free.)

I've tried this with Spark 1.2.2 and mahout 0.10.2 as well as with the latest versions in November 2015. There are a number of problems including the fact that the Scala code tries to run a bash script (mahout/bin/mahout) which does not work of course, the sbin scripts have not been ported to windows, and the winutils are missing if hadoop is not installed.

(1) Install scala, then unzip spark/hadoop/mahout into the root of C: under their respective product names.

(2) Rename \mahout\bin\mahout to mahout.sh.was (we will not need it)

(3) Compile the following Win32 C++ program and copy the executable to a file named C:\mahout\bin\mahout (that's right - no .exe suffix, like a Linux executable)

#include "stdafx.h"
#define BUFSIZE 4096
#define VARNAME TEXT("MAHOUT_CP")
int _tmain(int argc, _TCHAR* argv[]) {
    DWORD dwLength;     LPTSTR pszBuffer;
    pszBuffer = (LPTSTR)malloc(BUFSIZE*sizeof(TCHAR));
    dwLength = GetEnvironmentVariable(VARNAME, pszBuffer, BUFSIZE);
    if (dwLength > 0) { _tprintf(TEXT("%s\n"), pszBuffer); return 0; }
    return 1;
}

(4) Create the script \mahout\bin\mahout.bat and paste in the content below, although the exact names of the jars in the _CP class paths will depend on the versions of spark and mahout. Update any paths per your installation. Use 8.3 path names without spaces in them. Note that you cannot use wildcards/asterisks in the classpaths here.

set SCALA_HOME=C:\Progra~2\scala
set SPARK_HOME=C:\spark
set HADOOP_HOME=C:\hadoop
set MAHOUT_HOME=C:\mahout
set SPARK_SCALA_VERSION=2.10
set MASTER=local[2]
set MAHOUT_LOCAL=true
set path=%SCALA_HOME%\bin;%SPARK_HOME%\bin;%PATH%
cd /D %SPARK_HOME%
set SPARK_CP=%SPARK_HOME%\conf\;%SPARK_HOME%\lib\xxx.jar;...other jars...
set MAHOUT_CP=%MAHOUT_HOME%\lib\xxx.jar;...other jars...;%MAHOUT_HOME%\xxx.jar;...other jars...;%SPARK_CP%;%MAHOUT_HOME%\lib\spark\xxx.jar;%MAHOUT_HOME%\lib\hadoop\xxx.jar;%MAHOUT_HOME%\src\conf;%JAVA_HOME%\lib\tools.jar
start "master0" "%JAVA_HOME%\bin\java" -cp "%SPARK_CP%" -Xms1g -Xmx1g org.apache.spark.deploy.master.Master --ip localhost --port 7077 --webui-port 8082 >>out-master0.log 2>>out-master0.err
start "worker1" "%JAVA_HOME%\bin\java" -cp "%SPARK_CP%" -Xms1g -Xmx1g org.apache.spark.deploy.worker.Worker spark://localhost:7077 --webui-port 8083 >>out-worker1.log 2>>out-worker1.err
...you may add more workers here...
cd /D %MAHOUT_HOME%
"%JAVA_HOME%\bin\java" -Xmx4g -classpath "%MAHOUT_CP%" "org.apache.mahout.sparkbindings.shell.Main"

The name of the variable MAHOUT_CP should not be changed, as it is referenced in the C++ code.

Of course you can comment-out the code that launches the Spark master and worker because Mahout will run Spark as-needed; I just put it in the batch job to show you how to launch it if you wanted to use Spark without Mahout.

(5) The following tutorial is a good place to begin:

https://mahout.apache.org/users/sparkbindings/play-with-shell.html

You can bring up the Mahout Spark instance at:

"C:\Program Files (x86)\Google\Chrome\Application\chrome" --disable-web-security http://localhost:4040

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

As of Oct 2019, SQL Server Management Studio, they did not upgraded the SSMS to add create ER Diagram feature.

I would suggest try using DBWeaver from here :

https://dbeaver.io/download/

I am using Mac and Windows both and I was able to download the community edition and logged into my SQL server database and was able to create the ER diagram using the DB Weaver.

ER Diagram using the Community Version Db Viewer

Using BeautifulSoup to extract text without tags

I think you can get it using subc1.text.

>>> html = """
<p>
    <strong class="offender">YOB:</strong> 1987<br />
    <strong class="offender">RACE:</strong> WHITE<br />
    <strong class="offender">GENDER:</strong> FEMALE<br />
    <strong class="offender">HEIGHT:</strong> 5'05''<br />
    <strong class="offender">WEIGHT:</strong> 118<br />
    <strong class="offender">EYE COLOR:</strong> GREEN<br />
    <strong class="offender">HAIR COLOR:</strong> BROWN<br />
</p>
"""
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(html)
>>> print soup.text


YOB: 1987
RACE: WHITE
GENDER: FEMALE
HEIGHT: 5'05''
WEIGHT: 118
EYE COLOR: GREEN
HAIR COLOR: BROWN

Or if you want to explore it, you can use .contents :

>>> p = soup.find('p')
>>> from pprint import pprint
>>> pprint(p.contents)
[u'\n',
 <strong class="offender">YOB:</strong>,
 u' 1987',
 <br/>,
 u'\n',
 <strong class="offender">RACE:</strong>,
 u' WHITE',
 <br/>,
 u'\n',
 <strong class="offender">GENDER:</strong>,
 u' FEMALE',
 <br/>,
 u'\n',
 <strong class="offender">HEIGHT:</strong>,
 u" 5'05''",
 <br/>,
 u'\n',
 <strong class="offender">WEIGHT:</strong>,
 u' 118',
 <br/>,
 u'\n',
 <strong class="offender">EYE COLOR:</strong>,
 u' GREEN',
 <br/>,
 u'\n',
 <strong class="offender">HAIR COLOR:</strong>,
 u' BROWN',
 <br/>,
 u'\n']

and filter out the necessary items from the list:

>>> data = dict(zip([x.text for x in p.contents[1::4]], [x.strip() for x in p.contents[2::4]]))
>>> pprint(data)
{u'EYE COLOR:': u'GREEN',
 u'GENDER:': u'FEMALE',
 u'HAIR COLOR:': u'BROWN',
 u'HEIGHT:': u"5'05''",
 u'RACE:': u'WHITE',
 u'WEIGHT:': u'118',
 u'YOB:': u'1987'}

How to make GREP select only numeric values?

function getPercentUsed() {
    $sys = system("df -h /dev/sda6 --output=pcent | grep -o '[0-9]*'", $val);
    return $val[0];
}

setOnItemClickListener on custom ListView

Sorry for coding with Kotlin. But I faced the same problem. I solved with the code below.

list.setOnItemClickListener{ _, view, _, _ ->
        val text1 = view.find<TextView>(R.id.~~).text

        }

You can put an id which shows a TextView that you want in "~~".

Hope it'll help someone!

How to pass parameter to a promise function

Wrap your Promise inside a function or it will start to do its job right away. Plus, you can pass parameters to the function:

var some_function = function(username, password)
{
 return new Promise(function(resolve, reject)
 {
  /*stuff using username, password*/
  if ( /* everything turned out fine */ )
  {
   resolve("Stuff worked!");
  }
  else
  {
   reject(Error("It broke"));
  }
 });
}

Then, use it:

some_module.some_function(username, password).then(function(uid)
{
 // stuff
})

 

ES6:

const some_function = (username, password) =>
{
 return new Promise((resolve, reject) =>
 {
  /*stuff using username, password*/

  if ( /* everything turned out fine */ )
  {
   resolve("Stuff worked!");
  }
  else
  {
   reject(Error("It broke"));
  }
 });
};

Use:

some_module.some_function(username, password).then(uid =>
{
 // stuff
});

How to stop Python closing immediately when executed in Microsoft Windows

If you just want a delay

from time import *

sleep(20)

REST API error code 500 handling

The real question is why does it generate a 500 error. If it is related to any input parameters, then I would argue that it should be handled internally and returned as a 400 series error. Generally a 400, 404 or 406 would be appropriate to reflect bad input since the general convention is that a RESTful resource is uniquely identified by the URL and a URL that cannot generate a valid response is a bad request (400) or similar.

If the error is caused by anything other than the inputs explicitly or implicitly supplied by the request, then I would say a 500 error is likely appropriate. So a failed database connection or other unpredictable error is accurately represented by a 500 series error.

What does 'x packages are looking for funding' mean when running `npm install`?

First of all, try to support open source developers when you can, they invest quite a lot of their (free) time into these packages. But if you want to get rid of funding messages, you can configure NPM to turn these off. The command to do this is:

npm config set fund false --global

... or if you just want to turn it off for a particular project, run this in the project directory:

npm config set fund false 

For details why this was implemented, see @Stokely's and @ArunPratap's answers.

SQL Server CTE and recursion example

I haven't tested your code, just tried to help you understand how it operates in comment;

WITH
  cteReports (EmpID, FirstName, LastName, MgrID, EmpLevel)
  AS
  (
-->>>>>>>>>>Block 1>>>>>>>>>>>>>>>>>
-- In a rCTE, this block is called an [Anchor]
-- The query finds all root nodes as described by WHERE ManagerID IS NULL
    SELECT EmployeeID, FirstName, LastName, ManagerID, 1
    FROM Employees
    WHERE ManagerID IS NULL
-->>>>>>>>>>Block 1>>>>>>>>>>>>>>>>>
    UNION ALL
-->>>>>>>>>>Block 2>>>>>>>>>>>>>>>>>    
-- This is the recursive expression of the rCTE
-- On the first "execution" it will query data in [Employees],
-- relative to the [Anchor] above.
-- This will produce a resultset, we will call it R{1} and it is JOINed to [Employees]
-- as defined by the hierarchy
-- Subsequent "executions" of this block will reference R{n-1}
    SELECT e.EmployeeID, e.FirstName, e.LastName, e.ManagerID,
      r.EmpLevel + 1
    FROM Employees e
      INNER JOIN cteReports r
        ON e.ManagerID = r.EmpID
-->>>>>>>>>>Block 2>>>>>>>>>>>>>>>>>
  )
SELECT
  FirstName + ' ' + LastName AS FullName,
  EmpLevel,
  (SELECT FirstName + ' ' + LastName FROM Employees
    WHERE EmployeeID = cteReports.MgrID) AS Manager
FROM cteReports
ORDER BY EmpLevel, MgrID

The simplest example of a recursive CTE I can think of to illustrate its operation is;

;WITH Numbers AS
(
    SELECT n = 1
    UNION ALL
    SELECT n + 1
    FROM Numbers
    WHERE n+1 <= 10
)
SELECT n
FROM Numbers

Q 1) how value of N is getting incremented. if value is assign to N every time then N value can be incremented but only first time N value was initialize.

A1: In this case, N is not a variable. N is an alias. It is the equivalent of SELECT 1 AS N. It is a syntax of personal preference. There are 2 main methods of aliasing columns in a CTE in T-SQL. I've included the analog of a simple CTE in Excel to try and illustrate in a more familiar way what is happening.

--  Outside
;WITH CTE (MyColName) AS
(
    SELECT 1
)
-- Inside
;WITH CTE AS
(
    SELECT 1 AS MyColName
    -- Or
    SELECT MyColName = 1  
    -- Etc...
)

Excel_CTE

Q 2) now here about CTE and recursion of employee relation the moment i add two manager and add few more employee under second manager then problem start. i want to display first manager detail and in the next rows only those employee details will come those who are subordinate of that manager

A2:

Does this code answer your question?

--------------------------------------------
-- Synthesise table with non-recursive CTE
--------------------------------------------
;WITH Employee (ID, Name, MgrID) AS 
(
    SELECT 1,      'Keith',      NULL   UNION ALL
    SELECT 2,      'Josh',       1      UNION ALL
    SELECT 3,      'Robin',      1      UNION ALL
    SELECT 4,      'Raja',       2      UNION ALL
    SELECT 5,      'Tridip',     NULL   UNION ALL
    SELECT 6,      'Arijit',     5      UNION ALL
    SELECT 7,      'Amit',       5      UNION ALL
    SELECT 8,      'Dev',        6   
)
--------------------------------------------
-- Recursive CTE - Chained to the above CTE
--------------------------------------------
,Hierarchy AS
(
    --  Anchor
    SELECT   ID
            ,Name
            ,MgrID
            ,nLevel = 1
            ,Family = ROW_NUMBER() OVER (ORDER BY Name)
    FROM Employee
    WHERE MgrID IS NULL

    UNION ALL
    --  Recursive query
    SELECT   E.ID
            ,E.Name
            ,E.MgrID
            ,H.nLevel+1
            ,Family
    FROM Employee   E
    JOIN Hierarchy  H ON E.MgrID = H.ID
)
SELECT *
FROM Hierarchy
ORDER BY Family, nLevel

Another one sql with tree structure

SELECT ID,space(nLevel+
                    (CASE WHEN nLevel > 1 THEN nLevel ELSE 0 END)
                )+Name
FROM Hierarchy
ORDER BY Family, nLevel

Whitespaces in java

Why don't you check if text.trim() has a different length? :

if(text.length() == text.trim().length() || otherConditions){
    //your code
}

Clear Cache in Android Application programmatically

The answer from dhams is correct (after having been edited several times), but as the many edits of the code shows, it is difficult to write correct and robust code for deleting a directory (with sub-dirs) yourself. So I strongly suggest using Apache Commons IO, or some other API that does this for you:

import org.apache.commons.io.FileUtils;

...

// Delete local cache dir (ignoring any errors):
FileUtils.deleteQuietly(context.getCacheDir());

PS: Also delete the directory returned by context.getExternalCacheDir() if you use that.

To be able to use Apache Commons IO, add this to your build.gradle file, in the dependencies part:

compile 'commons-io:commons-io:2.4'

Command line tool to dump Windows DLL version?

You can use PowerShell to get the information you want.

(Get-Item C:\Path\To\MyFile.dll).VersionInfo

By default this will display ProductVersion and FileVersion But the full VERSIONINFO is available. I.e. to return Comments

(Get-Item C:\Path\To\MyFile.dll).VersionInfo.Comments

How can I completely uninstall nodejs, npm and node in Ubuntu

Note: This will completely remove nodejs from your system; then you can make a fresh install from the below commands.

Removing Nodejs and Npm

sudo apt-get remove nodejs npm node
sudo apt-get purge nodejs

Now remove .node and .npm folders from your system

sudo rm -rf /usr/local/bin/npm 
sudo rm -rf /usr/local/share/man/man1/node* 
sudo rm -rf /usr/local/lib/dtrace/node.d 
sudo rm -rf ~/.npm 
sudo rm -rf ~/.node-gyp 
sudo rm -rf /opt/local/bin/node 
sudo rm -rf opt/local/include/node 
sudo rm -rf /opt/local/lib/node_modules  

sudo rm -rf /usr/local/lib/node*
sudo rm -rf /usr/local/include/node*
sudo rm -rf /usr/local/bin/node*

Go to home directory and remove any node or node_modules directory, if exists.

You can verify your uninstallation by these commands; they should not output anything.

which node
which nodejs
which npm

Installing NVM (Node Version Manager) by downloading and running a script

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | bash

The command above will clone the NVM repository from Github to the ~/.nvm directory:

Close and reopen your terminal to start using nvm or run the following to use it now:

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

As the output above says, you should either close and reopen the terminal or run the commands to add the path to nvm script to the current shell session. You can do whatever is easier for you.

Once the script is in your PATH, verify that nvm was properly installed by typing:

nvm --version

which should give this output:

0.34.0

Installing Node.js and npm

nvm install node
nvm install --lts

Once the installation is completed, verify it by printing the Node.js version:

node --version

should give this output:

v12.8.1

Npm should also be installed with node, verify it using

npm -v

should give:

6.13.4

Extra - [Optional] You can also use two different versions of node using nvm easily

nvm install 8.10.0 # just put the node version number Now switch between node versions

$ nvm ls
->     v12.14.1
        v13.7.0
default -> lts/* (-> v12.14.1)
node -> stable (-> v13.7.0) (default)
stable -> 13.7 (-> v13.7.0) (default)
iojs -> N/A (default)
unstable -> N/A (default)
lts/* -> lts/erbium (-> v12.14.1)
lts/argon -> v4.9.1 (-> N/A)
lts/boron -> v6.17.1 (-> N/A)
lts/carbon -> v8.17.0 (-> N/A)
lts/dubnium -> v10.18.1 (-> N/A)

In my case v12.14.1 and v13.7.0 both are installed, to switch I have to just use

nvm use 12.14.1

Configuring npm for global installations In your home directory, create a directory for global installations:

mkdir ~/.npm-global

Configure npm to use the new directory path:

npm config set prefix '~/.npm-global'

In your preferred text editor, open or create a ~/.profile file if does not exist and add this line:

PATH="$HOME/.npm-global/bin:$PATH"

On the command line, update your system variables:

source ~/.profile

That's all

jquery-ui-dialog - How to hook into dialog close event

I have found it!

You can catch the close event using the following code:

 $('div#popup_content').on('dialogclose', function(event) {
     alert('closed');
 });

Obviously I can replace the alert with whatever I need to do.
Edit: As of Jquery 1.7, the bind() has become on()

Determining complexity for recursive functions (Big O notation)

One of the best ways I find for approximating the complexity of the recursive algorithm is drawing the recursion tree. Once you have the recursive tree:

Complexity = length of tree from root node to leaf node * number of leaf nodes
  1. The first function will have length of n and number of leaf node 1 so complexity will be n*1 = n
  2. The second function will have the length of n/5 and number of leaf nodes again 1 so complexity will be n/5 * 1 = n/5. It should be approximated to n

  3. For the third function, since n is being divided by 5 on every recursive call, length of recursive tree will be log(n)(base 5), and number of leaf nodes again 1 so complexity will be log(n)(base 5) * 1 = log(n)(base 5)

  4. For the fourth function since every node will have two child nodes, the number of leaf nodes will be equal to (2^n) and length of the recursive tree will be n so complexity will be (2^n) * n. But since n is insignificant in front of (2^n), it can be ignored and complexity can be only said to be (2^n).

  5. For the fifth function, there are two elements introducing the complexity. Complexity introduced by recursive nature of function and complexity introduced by for loop in each function. Doing the above calculation, the complexity introduced by recursive nature of function will be ~ n and complexity due to for loop n. Total complexity will be n*n.

Note: This is a quick and dirty way of calculating complexity(nothing official!). Would love to hear feedback on this. Thanks.

How to check if a file is empty in Bash?

[[ -s file ]] --> Checks if file has size greater than 0

if [[ -s diff.txt ]]; then echo "file has something"; else echo "file is empty"; fi

If needed, this checks all the *.txt files in the current directory; and reports all the empty file:

for file in *.txt; do if [[ ! -s $file ]]; then echo $file; fi; done

How to get logged-in user's name in Access vba?

In a Form, Create a text box, with in text box properties select data tab

Default value =CurrentUser()

Current source "select table field name"

It will display current user log on name in text box / label as well as saves the user name in the table field

How to load data from a text file in a PostgreSQL database?

Let consider that your data are in the file values.txt and that you want to import them in the database table myTable then the following query does the job

COPY myTable FROM 'value.txt' (DELIMITER('|'));

https://www.postgresql.org/docs/current/static/sql-copy.html

How do I autoindent in Netbeans?

Select the lines you want to reformat (indenting), then hit Alt+Shift+F. Only the selected lines will be reformatted.

OAuth 2.0 Authorization Header

You can still use the Authorization header with OAuth 2.0. There is a Bearer type specified in the Authorization header for use with OAuth bearer tokens (meaning the client app simply has to present ("bear") the token). The value of the header is the access token the client received from the Authorization Server.

It's documented in this spec: https://tools.ietf.org/html/rfc6750#section-2.1

E.g.:

   GET /resource HTTP/1.1
   Host: server.example.com
   Authorization: Bearer mF_9.B5f-4.1JqM

Where mF_9.B5f-4.1JqM is your OAuth access token.

How to escape double quotes in a title attribute

The escape code &#34; can also be used instead of &quot;.

Initialization of all elements of an array to one default value in C++?

Using the syntax that you used,

int array[100] = {-1};

says "set the first element to -1 and the rest to 0" since all omitted elements are set to 0.

In C++, to set them all to -1, you can use something like std::fill_n (from <algorithm>):

std::fill_n(array, 100, -1);

In portable C, you have to roll your own loop. There are compiler-extensions or you can depend on implementation-defined behavior as a shortcut if that's acceptable.

Find a value in DataTable

AFAIK, there is nothing built in for searching all columns. You can use Find only against the primary key. Select needs specified columns. You can perhaps use LINQ, but ultimately this just does the same looping. Perhaps just unroll it yourself? It'll be readable, at least.

VueJS conditionally add an attribute for an element

Simplest form:

<input :required="test">   // if true
<input :required="!test">  // if false
<input :required="!!test"> // test ? true : false

INSERT INTO...SELECT for all MySQL columns

For the syntax, it looks like this (leave out the column list to implicitly mean "all")

INSERT INTO this_table_archive
SELECT *
FROM this_table
WHERE entry_date < '2011-01-01 00:00:00'

For avoiding primary key errors if you already have data in the archive table

INSERT INTO this_table_archive
SELECT t.*
FROM this_table t
LEFT JOIN this_table_archive a on a.id=t.id
WHERE t.entry_date < '2011-01-01 00:00:00'
  AND a.id is null  # does not yet exist in archive

Self-reference for cell, column and row in worksheet functions

For a non-volatile solution, how about for 2007+:

for cell    =INDEX($A$1:$XFC$1048576,ROW(),COLUMN())
for column  =INDEX($A$1:$XFC$1048576,0,COLUMN())
for row     =INDEX($A$1:$XFC$1048576,ROW(),0)

I have weird bug on Excel 2010 where it won't accept the very last row or column for these formula (row 1048576 & column XFD), so you may need to reference these one short. Not sure if that's the same for any other versions so appreciate feedback and edit.

and for 2003 (INDEX became non-volatile in '97):

for cell    =INDEX($A$1:$IV$65536,ROW(),COLUMN())
for column  =INDEX($A$1:$IV$65536,0,COLUMN())
for row     =INDEX($A$1:$IV$65536,ROW(),0)

git checkout master error: the following untracked working tree files would be overwritten by checkout

Try git checkout -f master.

-f or --force

Source: https://www.kernel.org/pub/software/scm/git/docs/git-checkout.html

When switching branches, proceed even if the index or the working tree differs from HEAD. This is used to throw away local changes.

When checking out paths from the index, do not fail upon unmerged entries; instead, unmerged entries are ignored.

Add a border outside of a UIView (instead of inside)

Ok, there already is an accepted answer but I think there is a better way to do it, you just have to had a new layer a bit larger than your view and do not mask it to the bounds of the view's layer (which actually is the default behaviour). Here is the sample code :

CALayer * externalBorder = [CALayer layer];
externalBorder.frame = CGRectMake(-1, -1, myView.frame.size.width+2, myView.frame.size.height+2);
externalBorder.borderColor = [UIColor blackColor].CGColor;
externalBorder.borderWidth = 1.0;

[myView.layer addSublayer:externalBorder];
myView.layer.masksToBounds = NO;

Of course this is if you want your border to be 1 unity large, if you want more you adapt the borderWidth and the frame of the layer accordingly. This is better than using a second view a bit larger as a CALayer is lighter than a UIView and you don't have do modify the frame of myView, which is good for instance if myView is aUIImageView

N.B : For me the result was not perfect on simulator (the layer was not exactly at the right position so the layer was thicker on one side sometimes) but was exactly what is asked for on real device.

EDIT

Actually the problem I talk about in the N.B was just because I had reduced the screen of the simulator, on normal size there is absolutely no issue

Hope it helps

Redirect HTTP to HTTPS on default virtual host without ServerName

Try adding this in your vhost config:

RewriteEngine On
RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L]

include antiforgerytoken in ajax post ASP.NET MVC

I know this is an old question. But I will add my answer anyway, might help someone like me.

If you dont want to process the result from the controller's post action, like calling the LoggOff method of Accounts controller, you could do as the following version of @DarinDimitrov 's answer:

@using (Html.BeginForm("LoggOff", "Accounts", FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
{
    @Html.AntiForgeryToken()
}

<!-- this could be a button -->
<a href="#" id="ajaxSubmit">Submit</a>

<script type="text/javascript">
    $('#ajaxSubmit').click(function () {

        $('#__AjaxAntiForgeryForm').submit();

        return false;
    });
</script>

An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module

Enable this option in VS: Just My Code option

Tools -> Options -> Debugging -> General -> Enable Just My Code (Managed only)

jQuery Scroll To bottom of the page

function scrollToBottom() {
     $("#mContainer").animate({ scrollTop: $("#mContainer")[0].scrollHeight }, 1000);
}

This is the solution work from me and you find, I'm sure

How to increase heap size for jBoss server

Look in your JBoss bin folder for the file run.bat (run.sh on Unix)

look for the line set JAVA_OPTS, (or just JAVA_OPTS on Unix) at the end of that line add -Xmx512m. Change the number to the amount of memory you want to allocate to JBoss.

If you are using a custom script to start your jboss instance, you can add the set JAVA_OPTS option there as well.

Dart SDK is not configured

In my machine, flutter was installed in

C:\src\flutter

I set dart sdk path as

C:\src\flutter\bin\cache\dart-sdk

This solved my problem

Selenium Webdriver: Entering text into text field

I had a case where I was entering text into a field after which the text would be removed automatically. Turned out it was due to some site functionality where you had to press the enter key after entering the text into the field. So, after sending your barcode text with sendKeys method, send 'enter' directly after it. Note that you will have to import the selenium Keys class. See my code below.

import org.openqa.selenium.Keys;

String barcode="0000000047166";
WebElement element_enter = driver.findElement(By.xpath("//*[@id='div-barcode']"));
element_enter.findElement(By.xpath("your xpath")).sendKeys(barcode);

element_enter.sendKeys(Keys.RETURN); // this will result in the return key being pressed upon the text field

I hope it helps..

Let JSON object accept bytes or let urlopen output strings

Python’s wonderful standard library to the rescue…

import codecs

reader = codecs.getreader("utf-8")
obj = json.load(reader(response))

Works with both py2 and py3.

Docs: Python 2, Python3

What is the difference between Serialization and Marshaling?

I think that the main difference is that Marshalling supposedly also involves the codebase. In other words, you would not be able to marshal and unmarshal an object into a state-equivalent instance of a different class. .

Serialization just means that you can store the object and reobtain an equivalent state, even if it is an instance of another class.

That being said, they are typically synonyms.

Can't find SDK folder inside Android studio path, and SDK manager not opening

For me it was :

C:\Users\{your-user-name}\AppData\Local\Android\Sdk\tools\bin

Hope it helps!

What does <? php echo ("<pre>"); ..... echo("</pre>"); ?> mean?

The <pre> is used to define pre-formatted text.
The text within <pre> tag is displayed in a fixed-width font and it preserves both spaces and line breaks that are present in the text.
Here I'm printing a JSON FILE without <pre> tag and then with <pre> tag.

Without <pre> tag
https://i.stack.imgur.com/ofRn8.jpg
With <pre> tag
https://i.stack.imgur.com/XzDVg.jpg

List of strings to one string

I would go with option A:

String.Join(String.Empty, los.ToArray());

My reasoning is because the Join method was written for that purpose. In fact if you look at Reflector, you'll see that unsafe code was used to really optimize it. The other two also WORK, but I think the Join function was written for this purpose, and I would guess, the most efficient. I could be wrong though...

As per @Nuri YILMAZ without .ToArray(), but this is .NET 4+:

String.Join(String.Empty, los);

104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?

Don't use wsgiref for production. Use Apache and mod_wsgi, or something else.

We continue to see these connection resets, sometimes frequently, with wsgiref (the backend used by the werkzeug test server, and possibly others like the Django test server). Our solution was to log the error, retry the call in a loop, and give up after ten failures. httplib2 tries twice, but we needed a few more. They seem to come in bunches as well - adding a 1 second sleep might clear the issue.

We've never seen a connection reset when running through Apache and mod_wsgi. I don't know what they do differently, (maybe they just mask them), but they don't appear.

When we asked the local dev community for help, someone confirmed that they see a lot of connection resets with wsgiref that go away on the production server. There's a bug there, but it is going to be hard to find it.

How do you round a floating point number in Perl?

If you decide to use printf or sprintf, note that they use the Round half to even method.

foreach my $i ( 0.5, 1.5, 2.5, 3.5 ) {
    printf "$i -> %.0f\n", $i;
}
__END__
0.5 -> 0
1.5 -> 2
2.5 -> 2
3.5 -> 4

How to create duplicate table with new name in SQL Server 2008

In SSMS right click on a desired table > script as > create to > new query
-change the name of the table (ex. table2)
-change the PK key for the table (ex. PK_table2)

USE [NAMEDB]
GO
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[table_2](
[id] [int] NOT NULL,
[name] [varchar](50) NULL,
CONSTRAINT [PK_table_2] PRIMARY KEY CLUSTERED 
(
[reference] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = 
OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, 
ALLOW_PAGE_LOCKS = ON, 
OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO

Date validation with ASP.NET validator

I think the following is the easiest way to do it.

<asp:TextBox ID="DateControl" runat="server" Visible="False"></asp:TextBox>
<asp:RangeValidator ID ="rvDate" runat ="server" ControlToValidate="DateControl" ErrorMessage="Invalid Date" Type="Date" MinimumValue="01/01/1900" MaximumValue="01/01/2100" Display="Dynamic"></asp:RangeValidator>

What is the difference between required and ng-required?

The HTML attribute required="required" is a statement telling the browser that this field is required in order for the form to be valid. (required="required" is the XHTML form, just using required is equivalent)

The Angular attribute ng-required="yourCondition" means 'isRequired(yourCondition)' and sets the HTML attribute dynamically for you depending on your condition.

Also note that the HTML version is confusing, it is not possible to write something conditional like required="true" or required="false", only the presence of the attribute matters (present means true) ! This is where Angular helps you out with ng-required.

Executing a command stored in a variable from PowerShell

Here is yet another way without Invoke-Expression but with two variables (command:string and parameters:array). It works fine for me. Assume 7z.exe is in the system path.

$cmd = '7z.exe'
$prm = 'a', '-tzip', 'c:\temp\with space\test1.zip', 'C:\TEMP\with space\changelog'

& $cmd $prm

If the command is known (7z.exe) and only parameters are variable then this will do

$prm = 'a', '-tzip', 'c:\temp\with space\test1.zip', 'C:\TEMP\with space\changelog'

& 7z.exe $prm

BTW, Invoke-Expression with one parameter works for me, too, e.g. this works

$cmd = '& 7z.exe a -tzip "c:\temp\with space\test2.zip" "C:\TEMP\with space\changelog"'

Invoke-Expression $cmd

P.S. I usually prefer the way with a parameter array because it is easier to compose programmatically than to build an expression for Invoke-Expression.

Run php function on button click

I tried the code of William, Thanks brother.

but it's not working as a simple button I have to add form with method="post". Also I have to write submit instead of button.

here is my code below..

<form method="post">
    <input type="submit" name="test" id="test" value="RUN" /><br/>
</form>

<?php

function testfun()
{
   echo "Your test function on button click is working";
}

if(array_key_exists('test',$_POST)){
   testfun();
}

?>

What is the "continue" keyword and how does it work in Java?

If you think of the body of a loop as a subroutine, continue is sort of like return. The same keyword exists in C, and serves the same purpose. Here's a contrived example:

for(int i=0; i < 10; ++i) {
  if (i % 2 == 0) {
    continue;
  }
  System.out.println(i);
}

This will print out only the odd numbers.

How can I get the count of line in a file in an efficient way?

All previous answers suggest to read though the whole file and count the amount of newlines you find while doing this. You commented some as "not effective" but thats the only way you can do that. A "line" is nothing else as a simple character inside the file. And to count that character you must have a look at every single character within the file.

I'm sorry, but you have no choice. :-)

Put spacing between divs in a horizontal row?

This is because width when provided a % doesn't account for padding/margins. You will need to reduce the amount to possibly 24% or 24.5%. Once this is done you should be good, but you will need to provide different options based on the screen size if you want this to always work correct since you have a hardcoded margin, but a relative size.

Show/hide forms using buttons and JavaScript

Use the following code fragment to hide the form on button click.

document.getElementById("your form id").style.display="none";

And the following code to display it:

document.getElementById("your form id").style.display="block";

Or you can use the same function for both purposes:

function asd(a)
{
    if(a==1)
        document.getElementById("asd").style.display="none";
    else
        document.getElementById("asd").style.display="block";
}

And the HTML:

<form id="asd">form </form>
<button onclick="asd(1)">Hide</button>
<button onclick="asd(2)">Show</button>

Parse usable Street Address, City, State, Zip from a string

For ruby or rails developers there is a nice gem available called street_address. I have been using this on one of my project and it does the work I need.

The only Issue I had was whenever an address is in this format P. O. Box 1410 Durham, NC 27702 it returned nil and therefore I had to replace "P. O. Box" with '' and after this it were able to parse it.

Visual Studio SignTool.exe Not Found

Here is a solution for Visual Studio 2017. The installer looks a littlebit different from the VS 2015 version and the name of the installation packages are different.

__FILE__, __LINE__, and __FUNCTION__ usage in C++

Personally, I'm reluctant to use these for anything but debugging messages. I have done it, but I try not to show that kind of information to customers or end users. My customers are not engineers and are sometimes not computer savvy. I might log this info to the console, but, as I said, reluctantly except for debug builds or for internal tools. I suppose it does depend on the customer base you have, though.

Compiling a C++ program with gcc

By default, gcc selects the language based on the file extension, but you can force gcc to select a different language backend with the -x option thus:

gcc -x c++

More options are detailed in the gcc man page under "Options controlling the kind of output". See e.g. http://linux.die.net/man/1/gcc (search on the page for the text -x language).

This facility is very useful in cases where gcc can't guess the language using a file extension, for example if you're generating code and feeding it to gcc via stdin.

how to overlap two div in css?

I edited you fiddle you just need to add z-index to the front element and position it accordingly.

Regular expression to match any character being repeated more than 10 times

use the {10,} operator:

$: cat > testre
============================
==
==============

$: grep -E '={10,}' testre
============================
==============

Equivalent of Oracle's RowID in SQL Server

Check out the new ROW_NUMBER function. It works like this:

SELECT ROW_NUMBER() OVER (ORDER BY EMPID ASC) AS ROWID, * FROM EMPLOYEE

Delete duplicate records from a SQL table without a primary key

You could create a temporary table #tempemployee containing a select distinct of your employee table. Then delete from employee. Then insert into employee select from #tempemployee.

Like Josh said - even if you know the duplicates, deleting them will be impossile since you cannot actually refer to a specific record if it is an exact duplicate of another record.

Why is Spring's ApplicationContext.getBean considered bad?

The motivation is to write code that doesn't depend explicitly on Spring. That way, if you choose to switch containers, you don't have to rewrite any code.

Think of the container as something is invisible to your code, magically providing for its needs, without being asked.

Dependency injection is a counterpoint to the "service locator" pattern. If you are going to lookup dependencies by name, you might as well get rid of the DI container and use something like JNDI.

How to declare std::unique_ptr and what is the use of it?

There is no difference in working in both the concepts of assignment to unique_ptr.

int* intPtr = new int(3);
unique_ptr<int> uptr (intPtr);

is similar to

unique_ptr<int> uptr (new int(3));

Here unique_ptr automatically deletes the space occupied by uptr.


how pointers, declared in this way will be different from the pointers declared in a "normal" way.

If you create an integer in heap space (using new keyword or malloc), then you will have to clear that memory on your own (using delete or free respectively).

In the below code,

int* heapInt = new int(5);//initialize int in heap memory
.
.//use heapInt
.
delete heapInt;

Here, you will have to delete heapInt, when it is done using. If it is not deleted, then memory leakage occurs.

In order to avoid such memory leaks unique_ptr is used, where unique_ptr automatically deletes the space occupied by heapInt when it goes out of scope. So, you need not do delete or free for unique_ptr.

How can I convert a zero-terminated byte array to string?

Though not extremely performant, the only readable solution is:

  // Split by separator and pick the first one.
  // This has all the characters till null, excluding null itself.
  retByteArray := bytes.Split(byteArray[:], []byte{0}) [0]

  // OR

  // If you want a true C-like string, including the null character
  retByteArray := bytes.SplitAfter(byteArray[:], []byte{0}) [0]

A full example to have a C-style byte array:

package main

import (
    "bytes"
    "fmt"
)

func main() {
    var byteArray = [6]byte{97,98,0,100,0,99}

    cStyleString := bytes.SplitAfter(byteArray[:], []byte{0}) [0]
    fmt.Println(cStyleString)
}

A full example to have a Go style string excluding the nulls:

package main

import (
    "bytes"
    "fmt"
)

func main() {
    var byteArray = [6]byte{97, 98, 0, 100, 0, 99}

    goStyleString := string(bytes.Split(byteArray[:], []byte{0}) [0])
    fmt.Println(goStyleString)
}

This allocates a slice of slice of bytes. So keep an eye on performance if it is used heavily or repeatedly.

Python sum() function with list parameter

numbers = [1, 2, 3]
numsum = sum(list(numbers))
print(numsum)

This would work, if your are trying to Sum up a list.

How to update a git clone --mirror?

Regarding commits, refs, branches and "et cetera", Magnus answer just works (git remote update).

But unfortunately there is no way to clone / mirror / update the hooks, as I wanted...

I have found this very interesting thread about cloning/mirroring the hooks:

http://kerneltrap.org/mailarchive/git/2007/8/28/256180/thread

I learned:

  • The hooks are not considered part of the repository contents.

  • There is more data, like the .git/description folder, which does not get cloned, just as the hooks.

  • The default hooks that appear in the hooks dir comes from the TEMPLATE_DIR

  • There is this interesting template feature on git.

So, I may either ignore this "clone the hooks thing", or go for a rsync strategy, given the purposes of my mirror (backup + source for other clones, only).

Well... I will just forget about hooks cloning, and stick to the git remote update way.

  • Sehe has just pointed out that not only "hooks" aren't managed by the clone / update process, but also stashes, rerere, etc... So, for a strict backup, rsync or equivalent would really be the way to go. As this is not really necessary in my case (I can afford not having hooks, stashes, and so on), like I said, I will stick to the remote update.

Thanks! Improved a bit of my own "git-fu"... :-)

Best way to specify whitespace in a String.Split operation

So don't copy and paste! Extract a function to do your splitting and reuse it.

public static string[] SplitWhitespace (string input)
{
    char[] whitespace = new char[] { ' ', '\t' };
    return input.Split(whitespace);
}

Code reuse is your friend.

What's the "average" requests per second for a production web application?

personally, I like both analysis done every time....requests/second and average time/request and love seeing the max request time as well on top of that. it is easy to flip if you have 61 requests/second, you can then just flip it to 1000ms / 61 requests.

To answer your question, we have been doing a huge load test ourselves and find it ranges on various amazon hardware we use(best value was the 32 bit medium cpu when it came down to $$ / event / second) and our requests / seconds ranged from 29 requests / second / node up to 150 requests/second/node.

Giving better hardware of course gives better results but not the best ROI. Anyways, this post was great as I was looking for some parallels to see if my numbers where in the ballpark and shared mine as well in case someone else is looking. Mine is purely loaded as high as I can go.

NOTE: thanks to requests/second analysis(not ms/request) we found a major linux issue that we are trying to resolve where linux(we tested a server in C and java) freezes all the calls into socket libraries when under too much load which seems very odd. The full post can be found here actually.... http://ubuntuforums.org/showthread.php?p=11202389

We are still trying to resolve that as it gives us a huge performance boost in that our test goes from 2 minutes 42 seconds to 1 minute 35 seconds when this is fixed so we see a 33% performancce improvement....not to mention, the worse the DoS attack is the longer these pauses are so that all cpus drop to zero and stop processing...in my opinion server processing should continue in the face of a DoS but for some reason, it freezes up every once in a while during the Dos sometimes up to 30 seconds!!!

ADDITION: We found out it was actually a jdk race condition bug....hard to isolate on big clusters but when we ran 1 server 1 data node but 10 of those, we could reproduce it every time then and just looked at the server/datanode it occurred on. Switching the jdk to an earlier release fixed the issue. We were on jdk1.6.0_26 I believe.

SQL Server query to find all permissions/access for all users in a database

Here is a complete version of Jeremy's Aug 2011 query with the changes suggested by Brad (Oct 2011) and iw.kuchin (May 2012) incorporated:

  1. Brad: Correct [ObjectType] and [ObjectName] for schemas.
  2. iw.kuchin: For [ObjectType] it's better to use obj.type_desc only for OBJECT_OR_COLUMN permission class. For all other cases use perm.[class_desc].
  3. iw.kuchin: Handle IMPERSONATE permissions.
  4. iw.kuchin: Replace sys.login_token with sys.server_principals as it will show also SQL Logins, not only Windows ones.
  5. iw.kuchin: Include Windows groups.
  6. iw.kuchin: Exclude users sys and INFORMATION_SCHEMA.

Hopefully this saves someone else an hour or two of their lives. :)

/*
Security Audit Report
1) List all access provisioned to a SQL user or Windows user/group directly
2) List all access provisioned to a SQL user or Windows user/group through a database or application role
3) List all access provisioned to the public role

Columns Returned:
UserType        : Value will be either 'SQL User', 'Windows User', or 'Windows Group'.
                  This reflects the type of user/group defined for the SQL Server account.
DatabaseUserName: Name of the associated user as defined in the database user account.  The database user may not be the
                  same as the server user.
LoginName       : SQL or Windows/Active Directory user account.  This could also be an Active Directory group.
Role            : The role name.  This will be null if the associated permissions to the object are defined at directly
                  on the user account, otherwise this will be the name of the role that the user is a member of.
PermissionType  : Type of permissions the user/role has on an object. Examples could include CONNECT, EXECUTE, SELECT
                  DELETE, INSERT, ALTER, CONTROL, TAKE OWNERSHIP, VIEW DEFINITION, etc.
                  This value may not be populated for all roles.  Some built in roles have implicit permission
                  definitions.
PermissionState : Reflects the state of the permission type, examples could include GRANT, DENY, etc.
                  This value may not be populated for all roles.  Some built in roles have implicit permission
                  definitions.
ObjectType      : Type of object the user/role is assigned permissions on.  Examples could include USER_TABLE,
                  SQL_SCALAR_FUNCTION, SQL_INLINE_TABLE_VALUED_FUNCTION, SQL_STORED_PROCEDURE, VIEW, etc.
                  This value may not be populated for all roles.  Some built in roles have implicit permission
                  definitions.
Schema          : Name of the schema the object is in.
ObjectName      : Name of the object that the user/role is assigned permissions on.
                  This value may not be populated for all roles.  Some built in roles have implicit permission
                  definitions.
ColumnName      : Name of the column of the object that the user/role is assigned permissions on. This value
                  is only populated if the object is a table, view or a table value function.
*/

    --1) List all access provisioned to a SQL user or Windows user/group directly
    SELECT
        [UserType] = CASE princ.[type]
                         WHEN 'S' THEN 'SQL User'
                         WHEN 'U' THEN 'Windows User'
                         WHEN 'G' THEN 'Windows Group'
                     END,
        [DatabaseUserName] = princ.[name],
        [LoginName]        = ulogin.[name],
        [Role]             = NULL,
        [PermissionType]   = perm.[permission_name],
        [PermissionState]  = perm.[state_desc],
        [ObjectType] = CASE perm.[class]
                           WHEN 1 THEN obj.[type_desc]        -- Schema-contained objects
                           ELSE perm.[class_desc]             -- Higher-level objects
                       END,
        [Schema] = objschem.[name],
        [ObjectName] = CASE perm.[class]
                           WHEN 3 THEN permschem.[name]       -- Schemas
                           WHEN 4 THEN imp.[name]             -- Impersonations
                           ELSE OBJECT_NAME(perm.[major_id])  -- General objects
                       END,
        [ColumnName] = col.[name]
    FROM
        --Database user
        sys.database_principals            AS princ
        --Login accounts
        LEFT JOIN sys.server_principals    AS ulogin    ON ulogin.[sid] = princ.[sid]
        --Permissions
        LEFT JOIN sys.database_permissions AS perm      ON perm.[grantee_principal_id] = princ.[principal_id]
        LEFT JOIN sys.schemas              AS permschem ON permschem.[schema_id] = perm.[major_id]
        LEFT JOIN sys.objects              AS obj       ON obj.[object_id] = perm.[major_id]
        LEFT JOIN sys.schemas              AS objschem  ON objschem.[schema_id] = obj.[schema_id]
        --Table columns
        LEFT JOIN sys.columns              AS col       ON col.[object_id] = perm.[major_id]
                                                           AND col.[column_id] = perm.[minor_id]
        --Impersonations
        LEFT JOIN sys.database_principals  AS imp       ON imp.[principal_id] = perm.[major_id]
    WHERE
        princ.[type] IN ('S','U','G')
        -- No need for these system accounts
        AND princ.[name] NOT IN ('sys', 'INFORMATION_SCHEMA')

UNION

    --2) List all access provisioned to a SQL user or Windows user/group through a database or application role
    SELECT
        [UserType] = CASE membprinc.[type]
                         WHEN 'S' THEN 'SQL User'
                         WHEN 'U' THEN 'Windows User'
                         WHEN 'G' THEN 'Windows Group'
                     END,
        [DatabaseUserName] = membprinc.[name],
        [LoginName]        = ulogin.[name],
        [Role]             = roleprinc.[name],
        [PermissionType]   = perm.[permission_name],
        [PermissionState]  = perm.[state_desc],
        [ObjectType] = CASE perm.[class]
                           WHEN 1 THEN obj.[type_desc]        -- Schema-contained objects
                           ELSE perm.[class_desc]             -- Higher-level objects
                       END,
        [Schema] = objschem.[name],
        [ObjectName] = CASE perm.[class]
                           WHEN 3 THEN permschem.[name]       -- Schemas
                           WHEN 4 THEN imp.[name]             -- Impersonations
                           ELSE OBJECT_NAME(perm.[major_id])  -- General objects
                       END,
        [ColumnName] = col.[name]
    FROM
        --Role/member associations
        sys.database_role_members          AS members
        --Roles
        JOIN      sys.database_principals  AS roleprinc ON roleprinc.[principal_id] = members.[role_principal_id]
        --Role members (database users)
        JOIN      sys.database_principals  AS membprinc ON membprinc.[principal_id] = members.[member_principal_id]
        --Login accounts
        LEFT JOIN sys.server_principals    AS ulogin    ON ulogin.[sid] = membprinc.[sid]
        --Permissions
        LEFT JOIN sys.database_permissions AS perm      ON perm.[grantee_principal_id] = roleprinc.[principal_id]
        LEFT JOIN sys.schemas              AS permschem ON permschem.[schema_id] = perm.[major_id]
        LEFT JOIN sys.objects              AS obj       ON obj.[object_id] = perm.[major_id]
        LEFT JOIN sys.schemas              AS objschem  ON objschem.[schema_id] = obj.[schema_id]
        --Table columns
        LEFT JOIN sys.columns              AS col       ON col.[object_id] = perm.[major_id]
                                                           AND col.[column_id] = perm.[minor_id]
        --Impersonations
        LEFT JOIN sys.database_principals  AS imp       ON imp.[principal_id] = perm.[major_id]
    WHERE
        membprinc.[type] IN ('S','U','G')
        -- No need for these system accounts
        AND membprinc.[name] NOT IN ('sys', 'INFORMATION_SCHEMA')

UNION

    --3) List all access provisioned to the public role, which everyone gets by default
    SELECT
        [UserType]         = '{All Users}',
        [DatabaseUserName] = '{All Users}',
        [LoginName]        = '{All Users}',
        [Role]             = roleprinc.[name],
        [PermissionType]   = perm.[permission_name],
        [PermissionState]  = perm.[state_desc],
        [ObjectType] = CASE perm.[class]
                           WHEN 1 THEN obj.[type_desc]        -- Schema-contained objects
                           ELSE perm.[class_desc]             -- Higher-level objects
                       END,
        [Schema] = objschem.[name],
        [ObjectName] = CASE perm.[class]
                           WHEN 3 THEN permschem.[name]       -- Schemas
                           WHEN 4 THEN imp.[name]             -- Impersonations
                           ELSE OBJECT_NAME(perm.[major_id])  -- General objects
                       END,
        [ColumnName] = col.[name]
    FROM
        --Roles
        sys.database_principals            AS roleprinc
        --Role permissions
        LEFT JOIN sys.database_permissions AS perm      ON perm.[grantee_principal_id] = roleprinc.[principal_id]
        LEFT JOIN sys.schemas              AS permschem ON permschem.[schema_id] = perm.[major_id]
        --All objects
        JOIN      sys.objects              AS obj       ON obj.[object_id] = perm.[major_id]
        LEFT JOIN sys.schemas              AS objschem  ON objschem.[schema_id] = obj.[schema_id]
        --Table columns
        LEFT JOIN sys.columns              AS col       ON col.[object_id] = perm.[major_id]
                                                           AND col.[column_id] = perm.[minor_id]
        --Impersonations
        LEFT JOIN sys.database_principals  AS imp       ON imp.[principal_id] = perm.[major_id]
    WHERE
        roleprinc.[type] = 'R'
        AND roleprinc.[name] = 'public'
        AND obj.[is_ms_shipped] = 0

ORDER BY
    [UserType],
    [DatabaseUserName],
    [LoginName],
    [Role],
    [Schema],
    [ObjectName],
    [ColumnName],
    [PermissionType],
    [PermissionState],
    [ObjectType]

Postgresql - change the size of a varchar column to lower length

Try run following alter table:

ALTER TABLE public.users 
ALTER COLUMN "password" TYPE varchar(300) 
USING "password"::varchar;

Remove characters from a String in Java

Can't you use

id = id.substring(0, id.length()-4);

And what Eric said, ofcourse.

Render Content Dynamically from an array map function in React Native

lapsList() {

    return this.state.laps.map((data) => {
      return (
        <View><Text>{data.time}</Text></View>
      )
    })
}

You forgot to return the map. this code will resolve the issue.

How to run shell script on host from docker container?

The solution I use is to connect to the host over SSH and execute the command like this:

ssh -l ${USERNAME} ${HOSTNAME} "${SCRIPT}"

UPDATE

As this answer keeps getting up votes, I would like to remind (and highly recommend), that the account which is being used to invoke the script should be an account with no permissions at all, but only executing that script as sudo (that can be done from sudoers file).

Convert .class to .java

I used the http://www.javadecompilers.com but in some classes it gives you the message "could not load this classes..."

INSTEAD download Android Studio, navigate to the folder containing the java class file and double click it. The code will show in the right pane and I guess you can copy it an save it as a java file from there

Find and replace with a newline in Visual Studio Code

A possible workaround would be to use the multi-cursor. select the >< part of your example use Ctrl+Shift+L or select all occurrences. Then use the arrow keys to move all the cursors between the tags and press enter to insert a newline everywhere.

This won't work in all situations.

You can also use Ctrl+D for select next match, which adds the next match to the selection and adds a cursor. And use Ctrl+K Ctrl+D to skip a selection.

How to check if a string contains a substring in Bash

You should remember that shell scripting is less of a language and more of a collection of commands. Instinctively you think that this "language" requires you to follow an if with a [ or a [[. Both of those are just commands that return an exit status indicating success or failure (just like every other command). For that reason I'd use grep, and not the [ command.

Just do:

if grep -q foo <<<"$string"; then
    echo "It's there"
fi

Now that you are thinking of if as testing the exit status of the command that follows it (complete with semi-colon), why not reconsider the source of the string you are testing?

## Instead of this
filetype="$(file -b "$1")"
if grep -q "tar archive" <<<"$filetype"; then
#...

## Simply do this
if file -b "$1" | grep -q "tar archive"; then
#...

The -q option makes grep not output anything, as we only want the return code. <<< makes the shell expand the next word and use it as the input to the command, a one-line version of the << here document (I'm not sure whether this is standard or a Bashism).

How to extract the n-th elements from a list of tuples?

Timings for Python 3.6 for extracting the second element from a 2-tuple list.

Also, added numpy array method, which is simpler to read (but arguably simpler than the list comprehension).

from operator import itemgetter
elements = [(1,1) for _ in range(100000)]

%timeit second = [x[1] for x in elements]
%timeit second = list(map(itemgetter(1), elements))
%timeit second = dict(elements).values()
%timeit second = list(zip(*elements))[1]
%timeit second = np.array(elements)[:,1]

and the timings:

list comprehension:  4.73 ms ± 206 µs per loop
list(map):           5.3 ms ± 167 µs per loop
dict:                2.25 ms ± 103 µs per loop
list(zip)            5.2 ms ± 252 µs per loop
numpy array:        28.7 ms ± 1.88 ms per loop

Note that map() and zip() do not return a list anymore, hence the explicit conversion.

.crx file install in chrome

In case Chrome tells you "This can only be added from the Chrome Web Store", you can try the following:

  • Go to the webstore and try to add the extension
  • It will fail and give you a download instead
  • Rename the downloaded file to .zip and unpack it to a directory (you might get a warning about a corrupt zip header, but most unpacker will continue anyway)
  • Go to Settings -> Tools -> Extensions
  • Enable developer mode
  • Click "Load unpacked extention"
  • Browse to the unpacked folder and install your extention

HTML5 Canvas background image

Why don't you style it out:

<canvas id="canvas" width="800" height="600" style="background: url('./images/image.jpg')">
  Your browser does not support the canvas element.
</canvas>

Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources

**

bundle install --no-deployment

**

$ jekyll help

jekyll 4.0.0 -- Jekyll is a blog-aware, static site generator in Ruby

Bootstrap 3 scrollable div for table

You can use too

style="overflow-y: scroll; height:150px; width: auto;"

It's works for me

What is AF_INET, and why do I need it?

The primary purpose of AF_INET was to allow for other possible network protocols or address families (AF is for address family; PF_INET is for the (IPv4) internet protocol family). For example, there probably are a few Netware SPX/IPX networks around still; there were other network systems like DECNet, StarLAN and SNA, not to mention the ill-begotten ISO OSI (Open Systems Interconnection), and these did not necessarily use the now ubiquitous IP address to identify the peer host in network connections.

The ubiquitous alternative to AF_INET (which, in retrospect, should have been named AF_INET4) is AF_INET6, for the IPv6 address family. IPv4 uses 32-bit addresses; IPv6 uses 128-bit addresses.

You may see some other values - but they are unusual. It is there to allow for alternatives and future directions. The sockets interface is actually very general indeed - which is one of the reasons it has thrived where other networking interfaces have withered.

Life has (mostly) gotten simpler - be grateful.

Integrating Dropzone.js into existing HTML form with other fields

Here is my sample, is based on Django + Dropzone. View has select(required) and submit.

<form action="/share/upload/" class="dropzone" id="uploadDropzone">
    {% csrf_token %}
        <select id="warehouse" required>
            <option value="">Select a warehouse</option>
                {% for warehouse in warehouses %}
                    <option value={{forloop.counter0}}>{{warehouse.warehousename}}</option>
                {% endfor %}
        </select>
    <button id="submit-upload btn" type="submit">upload</button>
</form>

<script src="{% static '/js/libs/dropzone/dropzone.js' %}"></script>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script>
    var filename = "";

    Dropzone.options.uploadDropzone = {
        paramName: "file",  // The name that will be used to transfer the file,
        maxFilesize: 250,   // MB
        autoProcessQueue: false,
        accept: function(file, done) {
            console.log(file.name);
            filename = file.name;
            done();    // !Very important
        },
        init: function() {
            var myDropzone = this,
            submitButton = document.querySelector("[type=submit]");

            submitButton.addEventListener('click', function(e) {
                var isValid = document.querySelector('#warehouse').reportValidity();
                e.preventDefault();
                e.stopPropagation();
                if (isValid)
                    myDropzone.processQueue();
            });

            this.on('sendingmultiple', function(data, xhr, formData) {
                formData.append("warehouse", jQuery("#warehouse option:selected").val());
            });
        }
    };
</script>

React onClick function fires on render

JSX will evaluate JavaScript expressions in curly braces

In this case, this.props.removeTaskFunction(todo) is invoked and the return value is assigned to onClick

What you have to provide for onClick is a function. To do this, you can wrap the value in an anonymous function.

export const samepleComponent = ({todoTasks, removeTaskFunction}) => {
    const taskNodes = todoTasks.map(todo => (
                <div>
                    {todo.task}
                    <button type="submit" onClick={() => removeTaskFunction(todo)}>Submit</button>
                </div>
            );
    return (
        <div className="todo-task-list">
            {taskNodes}
        </div>
        );
    }
});

Check if a value is an object in JavaScript

If you are already using AngularJS then it has a built in method which will check if its an object (without accepting null).

angular.isObject(...)

Security of REST authentication schemes

Or you could use the known solution to this problem and use SSL. Self-signed certs are free and its a personal project right?

What do >> and << mean in Python?

I verified the following on both Python 2.7 and Python 3.8

I did print(100<<3) Converting 100 to Binary gives 1100100. What I did is I droped the first 3 bits and added 3 bits with the value '0' at the end. So it should result as 0100000, and I converted this to Decimal and the answer was 32.

For my suprise when I executed print(100<<3) the answer was 800. I was puzzled. I converted 800 to Binary to check whats going on. And this is what I got 1100100000.

If you see how 800 was Python answer, they did not shift or drop the first 3 bits but they added value '0' to last 3 bits.

Where as print(100>>3) , worked perfect. I did manual calculation and cheked the print result from python. It worked correctly. Dropped last 3 bits and added value '0' to first 3 bits.

Looks like (100<<3) , left shift operator has a bug on Python.

Python and pip, list all versions of a package that's available?

You can try to install package version that does to exist. Then pip will list available versions

pip install hell==99999
ERROR: Could not find a version that satisfies the requirement hell==99999
(from versions: 0.1.0, 0.2.0, 0.2.1, 0.2.2, 0.2.3, 0.2.4, 0.3.0,
0.3.1, 0.3.2, 0.3.3, 0.3.4, 0.4.0, 0.4.1)
ERROR: No matching distribution found for hell==99999

What's the difference between "end" and "exit sub" in VBA?

This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End and End Sub are not the same. They don't perform the same task.

End puts a stop to ALL code execution and you should almost always use Exit Sub (or Exit Function, respectively).

End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)

See also the MSDN dox for the End Statement

When executed, the End statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables.

Note The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

Nor is End Sub and Exit Sub the same. End Sub can't be called in the same way Exit Sub can be, because the compiler doesn't allow it.

enter image description here

This again means you have to Exit Sub, which is a perfectly legal operation:

Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.

Additionally, and once you get the feel for how procedures work, obviously, End Sub does not clear any global variables. But it does clear local (Dim'd) variables:

End Sub
Terminates the definition of this procedure.

Is it possible to indent JavaScript code in Notepad++?

JSTool is the best for stability.

Steps:

  1. Select menu Plugins>Plugin Manager>Show Plugin Manager
  2. Check to JSTool checkbox > Install > Restart Notepad++
  3. Open js file > Plugins > JSTool > JSFormat
    screenshot

Reference:

Delete files in subfolder using batch script

Moved from the closed topic

del /s d:\test\archive*.txt

This should get you all of your text files

Alternatively,

I modified a script I already wrote to look for certain files to move them, this one should go and find files and delete them. It allows you to just choose to which folder by a selection screen.

Please test this on your system before using it though.

@echo off
Title DeleteFilesInSubfolderList
color 0A
SETLOCAL ENABLEDELAYEDEXPANSION

REM ---------------------------
REM   *** EDIT VARIABLES BELOW ***
REM ---------------------------

set targetFolder=
REM targetFolder is the location you want to delete from    
REM ---------------------------
REM  *** DO NOT EDIT BELOW ***
REM ---------------------------

IF NOT DEFINED targetFolder echo.Please type in the full BASE Symform Offline Folder (I.E. U:\targetFolder)
IF NOT DEFINED targetFolder set /p targetFolder=:
cls
echo.Listing folders for: %targetFolder%\^*
echo.-------------------------------
set Index=1
for /d %%D in (%targetFolder%\*) do (
  set "Subfolders[!Index!]=%%D"
  set /a Index+=1
)
set /a UBound=Index-1
for /l %%i in (1,1,%UBound%) do echo. %%i. !Subfolders[%%i]!

:choiceloop
echo.-------------------------------
set /p Choice=Search for ERRORS in: 
if "%Choice%"=="" goto chioceloop
if %Choice% LSS 1 goto choiceloop
if %Choice% GTR %UBound% goto choiceloop
set Subfolder=!Subfolders[%Choice%]!
goto start

:start
TITLE Delete Text Files - %Subfolder%
IF NOT EXIST %ERRPATH% goto notExist
IF EXIST %ERRPATH% echo.%ERRPATH% Exists - Beginning to test-delete files...
echo.Searching for .txt files...
pushd %ERRPATH%
for /r %%a in (*.txt) do (
echo "%%a" "%Subfolder%\%%~nxa"
)
popd
echo.
echo.
verIFy >nul
echo.Execute^?
choice /C:YNX /N /M "(Y)Yes or (N)No:"
IF '%ERRORLEVEL%'=='1' set question1=Y
IF '%ERRORLEVEL%'=='2' set question1=N
IF /I '%question1%'=='Y' goto execute
IF /I '%question1%'=='N' goto end

:execute
echo.%ERRPATH% Exists - Beginning to delete files...
echo.Searching for .txt files...
pushd %ERRPATH%
for /r %%a in (*.txt) do (
del "%%a" "%Subfolder%\%%~nxa"
)
popd
goto end

:end
echo.
echo.
echo.Finished deleting files from %subfolder%
pause
goto choiceloop
ENDLOCAL
exit


REM Created by Trevor Giannetti
REM An unpublished work
REM (October 2012)

If you change the

set targetFolder= 

to the folder you want you won't get prompted for the folder. *Remember when putting the base path in, the format does not include a '\' on the end. e.g. d:\test c:\temp

Hope this helps

Style input type file?

After looking around on Google for a long time, trying out several solutions, both CSS, JavaScript and JQuery, i found that most of them were using an Image as the button. Some of them were hard to use, but i did manage to piece together something that ended out working out for me.

The important parts for me was:

  • The Browse button had to be a Button (not an image).
  • The button had to have a hover effect (to make it look nice).
  • The Width of both the Text and the button had to be easy to adjust.
  • The solution had to work in IE8, FF, Chrome and Safari.

This is the solution i came up with. And hope it can be of use to others as well.

Change the width of .file_input_textbox to change the width of the textbox.

Change the width of both .file_input_div, .file_input_button and .file_input_button_hover to change the width of the button. You might need to tweak a bit on the positions also. I never figured out why...

To test this solution, make a new html file and paste the content into it.

<html>
<head>

<style type="text/css">

.file_input_textbox {height:25px;width:200px;float:left; }
.file_input_div     {position: relative;width:80px;height:26px;overflow: hidden; }
.file_input_button  {width: 80px;position:absolute;top:0px;
                     border:1px solid #F0F0EE;padding:2px 8px 2px 8px; font-weight:bold; height:25px; margin:0px; margin-right:5px; }
.file_input_button_hover{width:80px;position:absolute;top:0px;
                     border:1px solid #0A246A; background-color:#B2BBD0;padding:2px 8px 2px 8px; height:25px; margin:0px; font-weight:bold; margin-right:5px; }
.file_input_hidden  {font-size:45px;position:absolute;right:0px;top:0px;cursor:pointer;
                     opacity:0;filter:alpha(opacity=0);-ms-filter:"alpha(opacity=0)";-khtml-opacity:0;-moz-opacity:0; }
</style>
</head>
<body>
    <input type="text" id="fileName" class="file_input_textbox" readonly="readonly">
 <div class="file_input_div">
  <input id="fileInputButton" type="button" value="Browse" class="file_input_button" />
  <input type="file" class="file_input_hidden" 
      onchange="javascript: document.getElementById('fileName').value = this.value" 
      onmouseover="document.getElementById('fileInputButton').className='file_input_button_hover';"
      onmouseout="document.getElementById('fileInputButton').className='file_input_button';" />
</div>
</body>
</html>

Get the value of checked checkbox?

<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="3" name="mailId[]">

<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="1" name="mailId[]">
function getValue(value){
    alert(value);
}

How to add elements of a Java8 stream into an existing List

I would concatenate the old list and new list as streams and save the results to destination list. Works well in parallel, too.

I will use the example of accepted answer given by Stuart Marks:

List<String> destList = Arrays.asList("foo");
List<String> newList = Arrays.asList("0", "1", "2", "3", "4", "5");

destList = Stream.concat(destList.stream(), newList.stream()).parallel()
            .collect(Collectors.toList());
System.out.println(destList);

//output: [foo, 0, 1, 2, 3, 4, 5]

Hope it helps.

How to print a string in C++

You need #include<string> to use string AND #include<iostream> to use cin and cout. (I didn't get it when I read the answers). Here's some code which works:

#include<string>
#include<iostream>
using namespace std;

int main()
{
    string name;
    cin >> name;
    string message("hi");
    cout << name << message;
    return 0;
}

Objective-C for Windows

Expanding on the two previous answers, if you just want Objective-C but not any of the Cocoa frameworks, then gcc will work on any platform. You can use it through Cygwin or get MinGW. However, if you want the Cocoa frameworks, or at least a reasonable subset of them, then GNUStep and Cocotron are your best bets.

Cocotron implements a lot of stuff that GNUStep does not, such as CoreGraphics and CoreData, though I can't vouch for how complete their implementation is on a specific framework. Their aim is to keep Cocotron up to date with the latest version of OS X so that any viable OS X program can run on Windows. Because GNUStep typically uses the latest version of gcc, they also add in support for Objective-C++ and a lot of the Objective-C 2.0 features.

I haven't tested those features with GNUStep, but if you use a sufficiently new version of gcc, you might be able to use them. I was not able to use Objective-C++ with GNUStep a few years ago. However, GNUStep does compile from just about any platform. Cocotron is a very mac-centric project. Although it is probably possible to compile it on other platforms, it comes XCode project files, not makefiles, so you can only compile its frameworks out of the box on OS X. It also comes with instructions on compiling Windows apps on XCode, but not any other platform. Basically, it's probably possible to set up a Windows development environment for Cocotron, but it's not as easy as setting one up for GNUStep, and you'll be on your own, so GNUStep is definitely the way to go if you're developing on Windows as opposed to just for Windows.

For what it's worth, Cocotron is licensed under the MIT license, and GNUStep is licensed under the LGPL.

HTML5 Audio stop function

It don't work sometimes in chrome,

sound.pause();
sound.currentTime = 0;

just change like that,

sound.currentTime = 0;
sound.pause();