Programs & Examples On #Labels

A label is a placeholder for text, and other UI elements.

How to adjust the size of y axis labels only in R?

ucfagls is right, providing you use the plot() command. If not, please give us more detail.

In any case, you can control every axis seperately by using the axis() command and the xaxt/yaxt options in plot(). Using the data of ucfagls, this becomes :

plot(Y ~ X, data=foo,yaxt="n")
axis(2,cex.axis=2)

the option yaxt="n" is necessary to avoid that the plot command plots the y-axis without changing. For the x-axis, this works exactly the same :

plot(Y ~ X, data=foo,xaxt="n")
axis(1,cex.axis=2)

See also the help files ?par and ?axis


Edit : as it is for a barplot, look at the options cex.axis and cex.names :

tN <- table(sample(letters[1:5],100,replace=T,p=c(0.2,0.1,0.3,0.2,0.2)))

op <- par(mfrow=c(1,2))
barplot(tN, col=rainbow(5),cex.axis=0.5) # for the Y-axis
barplot(tN, col=rainbow(5),cex.names=0.5) # for the X-axis
par(op)

alt text

Label python data points on plot

I had a similar issue and ended up with this:

enter image description here

For me this has the advantage that data and annotation are not overlapping.

from matplotlib import pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)

# annotations at the side (ordered by B values)
x0,x1=ax.get_xlim()
y0,y1=ax.get_ylim()
for ii, ind in enumerate(np.argsort(B)):
    x = A[ind]
    y = B[ind]
    xPos = x1 + .02 * (x1 - x0)
    yPos = y0 + ii * (y1 - y0)/(len(B) - 1)
    ax.annotate('',#label,
          xy=(x, y), xycoords='data',
          xytext=(xPos, yPos), textcoords='data',
          arrowprops=dict(
                          connectionstyle="arc3,rad=0.",
                          shrinkA=0, shrinkB=10,
                          arrowstyle= '-|>', ls= '-', linewidth=2
                          ),
          va='bottom', ha='left', zorder=19
          )
    ax.text(xPos + .01 * (x1 - x0), yPos,
            '({:.2f}, {:.2f})'.format(x,y),
            transform=ax.transData, va='center')

plt.grid()
plt.show()

Using the text argument in .annotate ended up with unfavorable text positions. Drawing lines between a legend and the data points is a mess, as the location of the legend is hard to address.

How do I correctly upgrade angular 2 (npm) to the latest version?

Another nice package which I used for migrating form a beta version of Angular2 to Angular2 2.0.0 final is npm-check-updates

It shows the latest available version of all packages specified within your package.json. In contrast to npm outdated it is also capable to edit your package.json, enabling you to do a npm upgrade later.

Install

sudo npm install -g npm-check-updates

Usage

ncufor display

ncu -u for re-writing your package.json

Get the new record primary key ID from MySQL insert query?

I just want to share my approach to this in PHP, some of you may found it not an efficient way but this is a 100 better than other available options.

generate a random key and insert it into the table creating a new row. then you can use that key to retrieve the primary key. use the update to add data and do other stuff.

doing this way helps to secure a row and have the correct primary key.

I really don't recommend this unless you don't have any other options.

How to Use Content-disposition for force a file to download to the hard drive?

On the HTTP Response where you are returning the PDF file, ensure the content disposition header looks like:

Content-Disposition: attachment; filename=quot.pdf;

See content-disposition on the wikipedia MIME page.

.aspx vs .ashx MAIN difference

Page is a special case handler.

Generic Web handler (*.ashx, extension based processor) is the default HTTP handler for all Web handlers that do not have a UI and that include the @WebHandler directive.

ASP.NET page handler (*.aspx) is the default HTTP handler for all ASP.NET pages.

Among the built-in HTTP handlers there are also Web service handler (*.asmx) and Trace handler (trace.axd)

MSDN says:

An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler.

The image below illustrates this: request pipe line

As to your second question:

Does ashx handle more connections than aspx?

Don't think so (but for sure, at least not less than).

How to make responsive table

For make responsive table you can make 100% of each ‘td’ and insert related heading in the ‘td’ on the mobile(less the ’768px’ width).

See More:
http://wonderdesigners.com/?p=227

How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

Many things changed since 2009, but I can only find answers saying you need to use NamedParametersJDBCTemplate.

For me it works if I just do a

db.query(sql, new MyRowMapper(), StringUtils.join(listeParamsForInClause, ","));

using SimpleJDBCTemplate or JDBCTemplate

Get User's Current Location / Coordinates

Import library like:

import CoreLocation

set Delegate:

CLLocationManagerDelegate

Take variable like:

var locationManager:CLLocationManager!

On viewDidLoad() write this pretty code:

 locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()

    if CLLocationManager.locationServicesEnabled(){
        locationManager.startUpdatingLocation()
    }

Write CLLocation delegate methods:

    //MARK: - location delegate methods
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let userLocation :CLLocation = locations[0] as CLLocation

    print("user latitude = \(userLocation.coordinate.latitude)")
    print("user longitude = \(userLocation.coordinate.longitude)")

    self.labelLat.text = "\(userLocation.coordinate.latitude)"
    self.labelLongi.text = "\(userLocation.coordinate.longitude)"

    let geocoder = CLGeocoder()
    geocoder.reverseGeocodeLocation(userLocation) { (placemarks, error) in
        if (error != nil){
            print("error in reverseGeocode")
        }
        let placemark = placemarks! as [CLPlacemark]
        if placemark.count>0{
            let placemark = placemarks![0]
            print(placemark.locality!)
            print(placemark.administrativeArea!)
            print(placemark.country!)

            self.labelAdd.text = "\(placemark.locality!), \(placemark.administrativeArea!), \(placemark.country!)"
        }
    }

}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print("Error \(error)")
}

Now set permission for access the location, so add these key value into your info.plist file

 <key>NSLocationAlwaysUsageDescription</key>
<string>Will you allow this app to always know your location?</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Do you allow this app to know your current location?</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Do you allow this app to know your current location?</string>

enter image description here

100% working without any issue. TESTED

Passing Parameters JavaFX FXML

Why answer a 6 year old question ?
One the most fundamental concepts working with any programming language is how to navigate from one (window, form or page) to another. Also while doing this navigation the developer often wants to pass data from one (window, form or page) and display or use the data passed
While most of the answers here provide good to excellent examples how to accomplish this we thought we would kick it up a notch or two or three
We said three because we will navigate between three (window, form or page) and use the concept of static variables to pass data around the (window, form or page)
We will also include some decision making code while we navigate

public class Start extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        // This is MAIN Class which runs first
        Parent root = FXMLLoader.load(getClass().getResource("start.fxml"));
        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.setResizable(false);// This sets the value for all stages
        stage.setTitle("Start Page"); 
        stage.show();
        stage.sizeToScene();
    }

    public static void main(String[] args) {
        launch(args);
    } 
}

Start Controller

public class startController implements Initializable {

@FXML Pane startPane,pageonePane;
@FXML Button btnPageOne;
@FXML TextField txtStartValue;
public Stage stage;
public static int intSETonStartController;
String strSETonStartController;

@FXML
private void toPageOne() throws IOException{

    strSETonStartController = txtStartValue.getText().trim();


        // yourString != null && yourString.trim().length() > 0
        // int L = testText.length();
        // if(L == 0){
        // System.out.println("LENGTH IS "+L);
        // return;
        // }
        /* if (testText.matches("[1-2]") && !testText.matches("^\\s*$")) 
           Second Match is regex for White Space NOT TESTED !
        */

        String testText = txtStartValue.getText().trim();
        // NOTICE IF YOU REMOVE THE * CHARACTER FROM "[1-2]*"
        // NO NEED TO CHECK LENGTH it also permited 12 or 11 as valid entry 
        // =================================================================
        if (testText.matches("[1-2]")) {
            intSETonStartController = Integer.parseInt(strSETonStartController);
        }else{
            txtStartValue.setText("Enter 1 OR 2");
            return;
        }

        System.out.println("You Entered = "+intSETonStartController);
        stage = (Stage)startPane.getScene().getWindow();// pane you are ON
        pageonePane = FXMLLoader.load(getClass().getResource("pageone.fxml"));// pane you are GOING TO
        Scene scene = new Scene(pageonePane);// pane you are GOING TO
        stage.setScene(scene);
        stage.setTitle("Page One"); 
        stage.show();
        stage.sizeToScene();
        stage.centerOnScreen();  
}

private void doGET(){
    // Why this testing ?
    // strSENTbackFROMPageoneController is null because it is set on Pageone
    // =====================================================================
    txtStartValue.setText(strSENTbackFROMPageoneController);
    if(intSETonStartController == 1){
      txtStartValue.setText(str);  
    }
    System.out.println("== doGET WAS RUN ==");
    if(txtStartValue.getText() == null){
       txtStartValue.setText("");   
    }
}

@Override
public void initialize(URL url, ResourceBundle rb) {
    // This Method runs every time startController is LOADED
     doGET();
}    
}

Page One Controller

public class PageoneController implements Initializable {

@FXML Pane startPane,pageonePane,pagetwoPane;
@FXML Button btnOne,btnTwo;
@FXML TextField txtPageOneValue;
public static String strSENTbackFROMPageoneController;
public Stage stage;

    @FXML
private void onBTNONE() throws IOException{

        stage = (Stage)pageonePane.getScene().getWindow();// pane you are ON
        pagetwoPane = FXMLLoader.load(getClass().getResource("pagetwo.fxml"));// pane you are GOING TO
        Scene scene = new Scene(pagetwoPane);// pane you are GOING TO
        stage.setScene(scene);
        stage.setTitle("Page Two"); 
        stage.show();
        stage.sizeToScene();
        stage.centerOnScreen();
}

@FXML
private void onBTNTWO() throws IOException{
    if(intSETonStartController == 2){
        Alert alert = new Alert(AlertType.CONFIRMATION);
        alert.setTitle("Alert");
        alert.setHeaderText("YES to change Text Sent Back");
        alert.setResizable(false);
        alert.setContentText("Select YES to send 'Alert YES Pressed' Text Back\n"
                + "\nSelect CANCEL send no Text Back\r");// NOTE this is a Carriage return\r
        ButtonType buttonTypeYes = new ButtonType("YES");
        ButtonType buttonTypeCancel = new ButtonType("CANCEL", ButtonData.CANCEL_CLOSE);

        alert.getButtonTypes().setAll(buttonTypeYes, buttonTypeCancel);

        Optional<ButtonType> result = alert.showAndWait();
        if (result.get() == buttonTypeYes){
            txtPageOneValue.setText("Alert YES Pressed");
        } else {
            System.out.println("canceled");
            txtPageOneValue.setText("");
            onBack();// Optional
        }
    }
}

@FXML
private void onBack() throws IOException{

    strSENTbackFROMPageoneController = txtPageOneValue.getText();
    System.out.println("Text Returned = "+strSENTbackFROMPageoneController);
    stage = (Stage)pageonePane.getScene().getWindow();
    startPane = FXMLLoader.load(getClass().getResource("start.fxml")); 
    Scene scene = new Scene(startPane);
    stage.setScene(scene);
    stage.setTitle("Start Page"); 
    stage.show();
    stage.sizeToScene();
    stage.centerOnScreen(); 
}

private void doTEST(){
    String fromSTART = String.valueOf(intSETonStartController);
    txtPageOneValue.setText("SENT  "+fromSTART);
    if(intSETonStartController == 1){
       btnOne.setVisible(true);
       btnTwo.setVisible(false);
       System.out.println("INTEGER Value Entered = "+intSETonStartController);  
    }else{
       btnOne.setVisible(false);
       btnTwo.setVisible(true);
       System.out.println("INTEGER Value Entered = "+intSETonStartController); 
    }  
}

@Override
public void initialize(URL url, ResourceBundle rb) {
    doTEST();
}    

}

Page Two Controller

public class PagetwoController implements Initializable {

@FXML Pane startPane,pagetwoPane;
public Stage stage;
public static String str;

@FXML
private void toStart() throws IOException{

    str = "You ON Page Two";
    stage = (Stage)pagetwoPane.getScene().getWindow();// pane you are ON
    startPane = FXMLLoader.load(getClass().getResource("start.fxml"));// pane you are GOING TO
    Scene scene = new Scene(startPane);// pane you are GOING TO
    stage.setScene(scene);
    stage.setTitle("Start Page"); 
    stage.show();
    stage.sizeToScene();
    stage.centerOnScreen();  
}

@Override
public void initialize(URL url, ResourceBundle rb) {

}    

}

Below are all the FXML files

_x000D_
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
_x000D_
<?import javafx.scene.control.Button?>_x000D_
<?import javafx.scene.layout.AnchorPane?>_x000D_
<?import javafx.scene.text.Font?>_x000D_
_x000D_
<AnchorPane id="AnchorPane" fx:id="pagetwoPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" fx:controller="atwopage.PagetwoController">_x000D_
   <children>_x000D_
      <Button layoutX="227.0" layoutY="62.0" mnemonicParsing="false" onAction="#toStart" text="To Start Page">_x000D_
         <font>_x000D_
            <Font name="System Bold" size="18.0" />_x000D_
         </font>_x000D_
      </Button>_x000D_
   </children>_x000D_
</AnchorPane>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
_x000D_
<?import javafx.scene.control.Button?>_x000D_
<?import javafx.scene.control.Label?>_x000D_
<?import javafx.scene.control.TextField?>_x000D_
<?import javafx.scene.layout.AnchorPane?>_x000D_
<?import javafx.scene.text.Font?>_x000D_
_x000D_
<AnchorPane id="AnchorPane" fx:id="startPane" prefHeight="200.0" prefWidth="400.0" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" fx:controller="atwopage.startController">_x000D_
   <children>_x000D_
      <Label focusTraversable="false" layoutX="115.0" layoutY="47.0" text="This is the Start Pane">_x000D_
         <font>_x000D_
            <Font size="18.0" />_x000D_
         </font>_x000D_
      </Label>_x000D_
      <Button fx:id="btnPageOne" focusTraversable="false" layoutX="137.0" layoutY="100.0" mnemonicParsing="false" onAction="#toPageOne" text="To Page One">_x000D_
         <font>_x000D_
            <Font size="18.0" />_x000D_
         </font>_x000D_
      </Button>_x000D_
      <Label focusTraversable="false" layoutX="26.0" layoutY="150.0" text="Enter 1 OR 2">_x000D_
         <font>_x000D_
            <Font size="18.0" />_x000D_
         </font>_x000D_
      </Label>_x000D_
      <TextField fx:id="txtStartValue" layoutX="137.0" layoutY="148.0" prefHeight="28.0" prefWidth="150.0" />_x000D_
   </children>_x000D_
</AnchorPane>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
_x000D_
<?import javafx.scene.control.Button?>_x000D_
<?import javafx.scene.control.Label?>_x000D_
<?import javafx.scene.control.TextField?>_x000D_
<?import javafx.scene.layout.AnchorPane?>_x000D_
<?import javafx.scene.text.Font?>_x000D_
_x000D_
<AnchorPane id="AnchorPane" fx:id="pageonePane" prefHeight="200.0" prefWidth="400.0" xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" fx:controller="atwopage.PageoneController">_x000D_
   <children>_x000D_
      <Label focusTraversable="false" layoutX="111.0" layoutY="35.0" text="This is Page One Pane">_x000D_
         <font>_x000D_
            <Font size="18.0" />_x000D_
         </font>_x000D_
      </Label>_x000D_
      <Button focusTraversable="false" layoutX="167.0" layoutY="97.0" mnemonicParsing="false" onAction="#onBack" text="BACK">_x000D_
         <font>_x000D_
            <Font size="18.0" />_x000D_
         </font></Button>_x000D_
      <Button fx:id="btnOne" focusTraversable="false" layoutX="19.0" layoutY="97.0" mnemonicParsing="false" onAction="#onBTNONE" text="Button One" visible="false">_x000D_
         <font>_x000D_
            <Font size="18.0" />_x000D_
         </font>_x000D_
      </Button>_x000D_
      <Button fx:id="btnTwo" focusTraversable="false" layoutX="267.0" layoutY="97.0" mnemonicParsing="false" onAction="#onBTNTWO" text="Button Two">_x000D_
         <font>_x000D_
            <Font size="18.0" />_x000D_
         </font>_x000D_
      </Button>_x000D_
      <Label focusTraversable="false" layoutX="19.0" layoutY="152.0" text="Send Anything BACK">_x000D_
         <font>_x000D_
            <Font size="18.0" />_x000D_
         </font>_x000D_
      </Label>_x000D_
      <TextField fx:id="txtPageOneValue" layoutX="195.0" layoutY="150.0" prefHeight="28.0" prefWidth="150.0" />_x000D_
   </children>_x000D_
</AnchorPane>
_x000D_
_x000D_
_x000D_

Build project into a JAR automatically in Eclipse

This is possible by defining a custom Builder in eclipse (see the link in Peter's answer). However, unless your project is very small, it may slow down your workspace unacceptably. Autobuild for class files happens incrementally, i.e. only those classes affected by a change are recompiled, but the JAR file will have to be rebuilt and copied completely, every time you save a change.

How can I find out if an .EXE has Command-Line Options?

Just use IDA PRO (https://www.hex-rays.com/products/ida/index.shtml) to disassemble the file, and search for some known command line option (using Search...Text) - in that section you will then typically see all the command line options - for the program (LIB2NIST.exe) in the screenshot below, for example, it shows a documented command line option (/COM2TAG) but also some undocumented ones, like /L. Hope this helps?

enter image description here

Best way to store date/time in mongodb

The best way is to store native JavaScript Date objects, which map onto BSON native Date objects.

> db.test.insert({date: ISODate()})
> db.test.insert({date: new Date()})
> db.test.find()
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:42.389Z") }
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:57.240Z") }

The native type supports a whole range of useful methods out of the box, which you can use in your map-reduce jobs, for example.

If you need to, you can easily convert Date objects to and from Unix timestamps1), using the getTime() method and Date(milliseconds) constructor, respectively.

1) Strictly speaking, the Unix timestamp is measured in seconds. The JavaScript Date object measures in milliseconds since the Unix epoch.

How do synchronized static methods work in Java and can I use it for loading Hibernate entities?

To answer your question, yes it does: your synchronized method cannot be executed by more than one thread at a time.

How to get the dimensions of a tensor (in TensorFlow) at graph construction time?

Just print out the embed after construction graph (ops) without running:

import tensorflow as tf

...

train_dataset = tf.placeholder(tf.int32, shape=[128, 2])
embeddings = tf.Variable(
    tf.random_uniform([50000, 64], -1.0, 1.0))
embed = tf.nn.embedding_lookup(embeddings, train_dataset)
print (embed)

This will show the shape of the embed tensor:

Tensor("embedding_lookup:0", shape=(128, 2, 64), dtype=float32)

Usually, it's good to check shapes of all tensors before training your models.

Iterate over model instance field names and values in template

You can have a form do the work for you.

def my_model_view(request, mymodel_id):
    class MyModelForm(forms.ModelForm):
        class Meta:
            model = MyModel

    model = get_object_or_404(MyModel, pk=mymodel_id)
    form = MyModelForm(instance=model)
    return render(request, 'model.html', { 'form': form})

Then in the template:

<table>
    {% for field in form %}
        <tr>
            <td>{{ field.name }}</td>
            <td>{{ field.value }}</td>
        </tr>
    {% endfor %}
</table>

How to Convert UTC Date To Local time Zone in MySql Select Query

 select convert_tz(now(),@@session.time_zone,'+05:30')

replace '+05:30' with desired timezone. see here - https://stackoverflow.com/a/3984412/2359994

to format into desired time format, eg:

 select DATE_FORMAT(convert_tz(now(),@@session.time_zone,'+05:30') ,'%b %d %Y %h:%i:%s %p') 

you will get similar to this -> Dec 17 2014 10:39:56 AM

How to install mysql-connector via pip

If loading via pip install mysql-connector and leads an error Unable to find Protobuf include directory then this would be useful pip install mysql-connector==2.1.4

mysql-connector is obsolete, so use pip install mysql-connector-python. Same here

Multiple modals overlay

No script solutions , using only css given you have two layers of modals, set the 2nd modal to a higher z index

.second-modal { z-index: 1070 }

div.modal-backdrop + div.modal-backdrop {
   z-index: 1060; 
}

Cast object to T

First check to see if it can be cast.

if (readData is T) {
    return (T)readData;
} 
try {
   return (T)Convert.ChangeType(readData, typeof(T));
} 
catch (InvalidCastException) {
   return default(T);
}

Remove scrollbar from iframe

Add this in your css to hide just the horizontal scroll bar

iframe{
    overflow-x:hidden;
}

Invoking a jQuery function after .each() has completed

Maybe a late response but there is a package to handle this https://github.com/ACFBentveld/Await

 var myObject = { // or your array
        1 : 'My first item',
        2 : 'My second item',
        3 : 'My third item'
    }

    Await.each(myObject, function(key, value){
         //your logic here
    });

    Await.done(function(){
        console.log('The loop is completely done');
    });

Run Executable from Powershell script with parameters

Try quoting the argument list:

Start-Process -FilePath "C:\Program Files\MSBuild\test.exe" -ArgumentList "/genmsi/f $MySourceDirectory\src\Deployment\Installations.xml"

You can also provide the argument list as an array (comma separated args) but using a string is usually easier.

Making Enter key on an HTML form submit instead of activating button

You can use jQuery:

$(function() {
    $("form input").keypress(function (e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $('button[type=submit] .default').click();
            return false;
        } else {
            return true;
        }
    });
});

avrdude: stk500v2_ReceiveMessage(): timeout

I was running this code from Arduino setup , got same error resolve after changing
serial port to COM13
GO TO Option
tool>> serial port>> COM132

How to use XPath in Python?

If you are going to need it for html:

import lxml.html as html
root  = html.fromstring(string)
root.xpath('//meta')

isPrime Function for Python Language

With n**.5, you are not squaring n, but taking the square root.

Consider the number 20; the integer factors are 1, 2, 4, 5, 10, and 20. When you divide 20 by 2 and get 10, you know that it is also divisible by 10, without having to check. When you divide it by 4 and get 5, you know it is divisible by both 4 and 5, without having to check for 5.

After reaching this halfway point in the factors, you will have no more numbers to check which you haven't already recognized as factors earlier. Therefore, you only need to go halfway to see if something is prime, and this halfway point can be found by taking the number's square root.

Also, the reason 1 isn't a prime number is because prime numbers are defined as having 2 factors, 1 and itself. i.e 2 is 1*2, 3 is 1*3, 5 is 1*5. But 1 (1*1) only has 1 factor, itself. Therefore, it doesn't meet this definition.

set font size in jquery

Try:

$("#"+styleTarget).css({ 'font-size': $(this).val() });

By putting the value in quotes, it becomes a string, and "+$(this).val()+"px is definitely not close to a font value. There are a couple of ways of setting the style properties of an element:

Using a map:

$("#elem").css({
    fontSize: 20
});

Using key and value parameters:

All of these are valid.

$("#elem").css("fontSize", 20);
$("#elem").css("fontSize", "20px");
$("#elem").css("font-size", "20");
$("#elem").css("font-size", "20px");

You can replace "fontSize" with "font-size" but it will have to be quoted then.

How to get the start time of a long-running Linux process?

As a follow-up to Adam Matan's answer, the /proc/<pid> directory's time stamp as such is not necessarily directly useful, but you can use

awk -v RS=')' 'END{print $20}' /proc/12345/stat

to get the start time in clock ticks since system boot.1

This is a slightly tricky unit to use; see also convert jiffies to seconds for details.

awk -v ticks="$(getconf CLK_TCK)" 'NR==1 { now=$1; next }
    END { printf "%9.0f\n", now - ($20/ticks) }' /proc/uptime RS=')' /proc/12345/stat

This should give you seconds, which you can pass to strftime() to get a (human-readable, or otherwise) timestamp.

awk -v ticks="$(getconf CLK_TCK)" 'NR==1 { now=$1; next }
    END { print strftime("%c", systime() - (now-($20/ticks))) }' /proc/uptime RS=')' /proc/12345/stat

Updated with some fixes from Stephane Chazelas in the comments; thanks as always!

If you only have Mawk, maybe try

awk -v ticks="$(getconf CLK_TCK)" -v epoch="$(date +%s)" '
  NR==1 { now=$1; next }
  END { printf "%9.0f\n", epoch - (now-($20/ticks)) }' /proc/uptime RS=')' /proc/12345/stat |
xargs -i date -d @{}

1 man proc; search for starttime.

c# regex matches example

This pattern should work:

#\d

foreach(var match in System.Text.RegularExpressions.RegEx.Matches(input, "#\d"))
{
    Console.WriteLine(match.Value);
}

(I'm not in front of Visual Studio, but even if that doesn't compile as-is, it should be close enough to tweak into something that works).

Using Apache POI how to read a specific excel column

import java.io.*;

import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.ss.usermodel.*;
import java.text.*;

public class XSLXReader {
    static DecimalFormat df = new DecimalFormat("#####0");

    public static void main(String[] args) {
        FileWriter fostream;
        PrintWriter out = null;
        String strOutputPath = "H:\\BLR_Team\\Kavitha\\Excel-to-xml\\";
        String strFilePrefix = "Master_5.2-B";

        try {
            InputStream inputStream = new FileInputStream(new File("H:\\BLR_Team\\Kavitha\\Excel-to-xml\\Stack-up 20L pure storage 11-0039-01 ISU_USA-A 1-30-17-Rev_exm.xls"));
            Workbook wb = WorkbookFactory.create(inputStream);
           // Sheet sheet = wb.getSheet(0);
            Sheet sheet =null;
            Integer noOfSheets= wb.getNumberOfSheets();

            for(int i=0;i<noOfSheets;i++){
                sheet = wb.getSheetAt(i);
                System.out.println("Sheet : "+i + " " + sheet.getSheetName());
                System.out.println("Sheet : "+i + " " + sheet.getFirstRowNum());
                System.out.println("Sheet : "+i + " " + sheet.getLastRowNum());

            //Column 29
            fostream = new FileWriter(strOutputPath + "\\" + strFilePrefix+i+ ".xml");
            out = new PrintWriter(new BufferedWriter(fostream));

            out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            out.println("<Bin-code>");

            boolean firstRow = true;
            for (Row row : sheet) {
                if (firstRow == true) {
                    firstRow = false;
                    continue;
                }
                out.println("\t<DCT>");
                out.println(formatElement("\t\t", "ID", formatCell(row.getCell(0))));
                out.println(formatElement("\t\t", "Table_name", formatCell(row.getCell(1))));
                out.println(formatElement("\t\t", "isProddaten", formatCell(row.getCell(2))));
                out.println(formatElement("\t\t", "isR3P01Data", formatCell(row.getCell(3))));

                out.println(formatElement("\t\t", "LayerNo", formatCell(row.getCell(29))));
                out.println("\t</DCT>");
            }
            CellReference ref = new CellReference("A13");
          Row r = sheet.getRow(ref.getRow());
          if (r != null) {
             Cell c = r.getCell(ref.getCol());
           System.out.println(c.getRichStringCellValue().getString());
          }

            for (Row row : sheet) {
                  for (Cell cell : row) {

                      CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());


                      switch (cell.getCellType()) {
                      case Cell.CELL_TYPE_STRING:
                          System.out.println(cell.getRichStringCellValue().getString());
                          break;
                      case Cell.CELL_TYPE_NUMERIC:
                          if (DateUtil.isCellDateFormatted(cell)) {
                              System.out.println(cell.getDateCellValue());
                          } else {
                              System.out.println(cell.getNumericCellValue());
                          }
                          break;
                      case Cell.CELL_TYPE_BOOLEAN:
                          System.out.println(cell.getBooleanCellValue());
                          break;
                      case Cell.CELL_TYPE_FORMULA:
                          System.out.println(cell.getCellFormula());
                          break;
                      case Cell.CELL_TYPE_BLANK:
                          System.out.println();
                          break;
                      default:
                          System.out.println();
                  }
                  }

            }
            out.write("</Bin-code>");
            out.flush();
            out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String formatCell(Cell cell)
    {
        if (cell == null) {
            return "";
        }
        switch(cell.getCellType()) {
            case Cell.CELL_TYPE_BLANK:
                return "";
            case Cell.CELL_TYPE_BOOLEAN:
                return Boolean.toString(cell.getBooleanCellValue());
            case Cell.CELL_TYPE_ERROR:
                return "*error*";
            case Cell.CELL_TYPE_NUMERIC:
                return XSLXReader.df.format(cell.getNumericCellValue());
            case Cell.CELL_TYPE_STRING:
                return cell.getStringCellValue();
            default:
                return "<unknown value>";
        }
    }

    private static String formatElement(String prefix, String tag, String value) {
        StringBuilder sb = new StringBuilder(prefix);
        sb.append("<");
        sb.append(tag);
        if (value != null && value.length() > 0) {
            sb.append(">");
            sb.append(value);
            sb.append("</");
            sb.append(tag);
            sb.append(">");
        } else {
            sb.append("/>");
        }
        return sb.toString();
    }
}

This code does 3 things:

  1. Excel to XML file generation. Eng. Name Dong Kim
  2. Prints the content of a particular cell : A13
  3. Also print the excel content into normal text format. Jars to be imported: poi-3.9.jar,poi-ooxml-3.9.jar,poi-ooxml-schemas-3.9.jar,xbea??n-2.3.0.jar,xmlbeans??-xmlpublic-2.4.0.jar??,dom4j-1.5.jar

Postgresql 9.2 pg_dump version mismatch

** after install postgres version is match(9.2) Create a symbolic link or new shortcut

**- on '/usr/bin'

syntag is = sudo ln -s [path for use] [new shortcut name]

example

sudo ln -s /usr/lib/postgresql/9.2/bin/pg_dump new_pg_dump

-- how to call : new_pg_dump -h 192.168.9.88 -U postgres database

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

codes need to save UTF8 without BOM while recording. Sometimes, written codes with (Notepad++) or other coding tools and use UTF8 encode, this error occurs. I'm sorry, I do not know English. This is just my experience.

ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

If you use the WEB API with Claims, you can use this:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class AutorizeCompanyAttribute:  AuthorizationFilterAttribute
{
    public string Company { get; set; }

    public override void OnAuthorization(HttpActionContext actionContext)
    {
        var claims = ((ClaimsIdentity)Thread.CurrentPrincipal.Identity);
        var claim = claims.Claims.Where(x => x.Type == "Company").FirstOrDefault();

        string privilegeLevels = string.Join("", claim.Value);        

        if (privilegeLevels.Contains(this.Company)==false)
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "Usuario de Empresa No Autorizado");
        }
    }
}
[HttpGet]
[AutorizeCompany(Company = "MyCompany")]
[Authorize(Roles ="SuperAdmin")]
public IEnumerable MyAction()
{....
}

How to export query result to csv in Oracle SQL Developer?

Not exactly "exporting," but you can select the rows (or Ctrl-A to select all of them) in the grid you'd like to export, and then copy with Ctrl-C.

The default is tab-delimited. You can paste that into Excel or some other editor and manipulate the delimiters all you like.

Also, if you use Ctrl-Shift-C instead of Ctrl-C, you'll also copy the column headers.

How to find reason of failed Build without any error or warning

With Visual Studio 2019, I had to 'Run as as administrator' and it finally built ok. So open the application as admin (right mouse click- run as Administrator).

Difference between null and empty ("") Java String

Amazing answers, but I'd like to give from a different perspective.

String a = "StackOverflow";
String a1 = "StackOverflow" + "";
String a2 = "StackOverflow" + null;

System.out.println(a == a1); // true
System.out.println(a == a2); // false

So this can tell us "" and null point to the different object references.

HashMap to return default value for non-found keys?

In Java 8, use Map.getOrDefault. It takes the key, and the value to return if no matching key is found.

Python list of dictionaries search

Have you ever tried out the pandas package? It's perfect for this kind of search task and optimized too.

import pandas as pd

listOfDicts = [
{"name": "Tom", "age": 10},
{"name": "Mark", "age": 5},
{"name": "Pam", "age": 7}
]

# Create a data frame, keys are used as column headers.
# Dict items with the same key are entered into the same respective column.
df = pd.DataFrame(listOfDicts)

# The pandas dataframe allows you to pick out specific values like so:

df2 = df[ (df['name'] == 'Pam') & (df['age'] == 7) ]

# Alternate syntax, same thing

df2 = df[ (df.name == 'Pam') & (df.age == 7) ]

I've added a little bit of benchmarking below to illustrate pandas' faster runtimes on a larger scale i.e. 100k+ entries:

setup_large = 'dicts = [];\
[dicts.extend(({ "name": "Tom", "age": 10 },{ "name": "Mark", "age": 5 },\
{ "name": "Pam", "age": 7 },{ "name": "Dick", "age": 12 })) for _ in range(25000)];\
from operator import itemgetter;import pandas as pd;\
df = pd.DataFrame(dicts);'

setup_small = 'dicts = [];\
dicts.extend(({ "name": "Tom", "age": 10 },{ "name": "Mark", "age": 5 },\
{ "name": "Pam", "age": 7 },{ "name": "Dick", "age": 12 }));\
from operator import itemgetter;import pandas as pd;\
df = pd.DataFrame(dicts);'

method1 = '[item for item in dicts if item["name"] == "Pam"]'
method2 = 'df[df["name"] == "Pam"]'

import timeit
t = timeit.Timer(method1, setup_small)
print('Small Method LC: ' + str(t.timeit(100)))
t = timeit.Timer(method2, setup_small)
print('Small Method Pandas: ' + str(t.timeit(100)))

t = timeit.Timer(method1, setup_large)
print('Large Method LC: ' + str(t.timeit(100)))
t = timeit.Timer(method2, setup_large)
print('Large Method Pandas: ' + str(t.timeit(100)))

#Small Method LC: 0.000191926956177
#Small Method Pandas: 0.044392824173
#Large Method LC: 1.98827004433
#Large Method Pandas: 0.324505090714

How come I can't remove the blue textarea border in Twitter Bootstrap?

try this, I think this will help and your blue border will be removed:

outline:none;

Combine two tables for one output

You'll need to use UNION to combine the results of two queries. In your case:

SELECT ChargeNum, CategoryID, SUM(Hours)
FROM KnownHours
GROUP BY ChargeNum, CategoryID
UNION ALL
SELECT ChargeNum, 'Unknown' AS CategoryID, SUM(Hours)
FROM UnknownHours
GROUP BY ChargeNum

Note - If you use UNION ALL as in above, it's no slower than running the two queries separately as it does no duplicate-checking.

What is the difference between a "line feed" and a "carriage return"?

Both of these are primary from the old printing days.

Carriage return is from the days of the teletype printers/old typewriters, where literally the carriage would return to the next line, and push the paper up. This is what we now call \r.

Line feed LF signals the end of the line, it signals that the line has ended - but doesn't move the cursor to the next line. In other words, it doesn't "return" the cursor/printer head to the next line.

For more sundry details, the mighty wikipedia to the rescue.

Iteration ng-repeat only X times in AngularJs

This is the simplest workaround I could think of.

<span ng-repeat="n in [].constructor(5) track by $index">
{{$index}}
</span>

Here's a Plunker example.

PowerShell array initialization

Here's another typical way:

$array = for($i = 0; $i -le 4; $i++) { $false }

Choosing the correct upper and lower HSV boundaries for color detection with`cv::inRange` (OpenCV)

Here's a simple HSV color thresholder script to determine the lower/upper color ranges using trackbars for any image on the disk. Simply change the image path in cv2.imread()

enter image description here

import cv2
import numpy as np

def nothing(x):
    pass

# Load image
image = cv2.imread('1.jpg')

# Create a window
cv2.namedWindow('image')

# Create trackbars for color change
# Hue is from 0-179 for Opencv
cv2.createTrackbar('HMin', 'image', 0, 179, nothing)
cv2.createTrackbar('SMin', 'image', 0, 255, nothing)
cv2.createTrackbar('VMin', 'image', 0, 255, nothing)
cv2.createTrackbar('HMax', 'image', 0, 179, nothing)
cv2.createTrackbar('SMax', 'image', 0, 255, nothing)
cv2.createTrackbar('VMax', 'image', 0, 255, nothing)

# Set default value for Max HSV trackbars
cv2.setTrackbarPos('HMax', 'image', 179)
cv2.setTrackbarPos('SMax', 'image', 255)
cv2.setTrackbarPos('VMax', 'image', 255)

# Initialize HSV min/max values
hMin = sMin = vMin = hMax = sMax = vMax = 0
phMin = psMin = pvMin = phMax = psMax = pvMax = 0

while(1):
    # Get current positions of all trackbars
    hMin = cv2.getTrackbarPos('HMin', 'image')
    sMin = cv2.getTrackbarPos('SMin', 'image')
    vMin = cv2.getTrackbarPos('VMin', 'image')
    hMax = cv2.getTrackbarPos('HMax', 'image')
    sMax = cv2.getTrackbarPos('SMax', 'image')
    vMax = cv2.getTrackbarPos('VMax', 'image')

    # Set minimum and maximum HSV values to display
    lower = np.array([hMin, sMin, vMin])
    upper = np.array([hMax, sMax, vMax])

    # Convert to HSV format and color threshold
    hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    mask = cv2.inRange(hsv, lower, upper)
    result = cv2.bitwise_and(image, image, mask=mask)

    # Print if there is a change in HSV value
    if((phMin != hMin) | (psMin != sMin) | (pvMin != vMin) | (phMax != hMax) | (psMax != sMax) | (pvMax != vMax) ):
        print("(hMin = %d , sMin = %d, vMin = %d), (hMax = %d , sMax = %d, vMax = %d)" % (hMin , sMin , vMin, hMax, sMax , vMax))
        phMin = hMin
        psMin = sMin
        pvMin = vMin
        phMax = hMax
        psMax = sMax
        pvMax = vMax

    # Display result image
    cv2.imshow('image', result)
    if cv2.waitKey(10) & 0xFF == ord('q'):
        break

cv2.destroyAllWindows()

Why Would I Ever Need to Use C# Nested Classes

A nested class can have private, protected and protected internal access modifiers along with public and internal.

For example, you are implementing the GetEnumerator() method that returns an IEnumerator<T> object. The consumers wouldn't care about the actual type of the object. All they know about it is that it implements that interface. The class you want to return doesn't have any direct use. You can declare that class as a private nested class and return an instance of it (this is actually how the C# compiler implements iterators):

class MyUselessList : IEnumerable<int> {
    // ...
    private List<int> internalList;
    private class UselessListEnumerator : IEnumerator<int> {
        private MyUselessList obj;
        public UselessListEnumerator(MyUselessList o) {
           obj = o;
        }
        private int currentIndex = -1;
        public int Current {
           get { return obj.internalList[currentIndex]; }
        }
        public bool MoveNext() { 
           return ++currentIndex < obj.internalList.Count;
        }
    }
    public IEnumerator<int> GetEnumerator() {
        return new UselessListEnumerator(this);
    }
}

What is the difference between iterator and iterable and how to use them?

Question:Difference between Iterable and Iterator?
Ans:

iterable: It is related to forEach loop
iterator: Is is related to Collection

The target element of the forEach loop shouble be iterable.
We can use Iterator to get the object one by one from the Collection

Iterable present in java.?ang package
Iterator present in java.util package

Contains only one method iterator()
Contains three method hasNext(), next(), remove()

Introduced in 1.5 version
Introduced in 1.2 version

How to install JQ on Mac by command-line?

For most it is a breeze, however like you I had a difficult time installing jq

The best resources I found are: https://stedolan.github.io/jq/download/ and http://macappstore.org/jq/

However neither worked for me. I run python 2 & 3, and use brew in addition to pip, as well as Jupyter. I was only successful after brew uninstall jq then updating brew and rebooting my system

What worked for me was removing all previous installs then pip install jq

How do I toggle an element's class in pure JavaScript?

2014 answer: classList.toggle() is the standard and supported by most browsers.

Older browsers can use use classlist.js for classList.toggle():

var menu = document.querySelector('.menu') // Using a class instead, see note below.
menu.classList.toggle('hidden-phone');

As an aside, you shouldn't be using IDs (they leak globals into the JS window object).

In Bootstrap open Enlarge image in modal

    <div class="row" style="display:inline-block">

    <div class="col-lg-12">
        <h1 class="page-header">Thumbnail Gallery</h1>

            <div class="col-lg-3 col-md-4 col-xs-6 thumb">
            <a class="thumbnail" href="#" data-image-id="" data-toggle="modal" data-title="This is my title" data-caption="Some lovely red flowers" data-image="http://onelive.us/wp-content/uploads/2014/08/flower-delivery-online.jpg" data-target="#image-gallery">
                <img class="img-responsive" src="http://onelive.us/wp-content/uploads/2014/08/flower-delivery-online.jpg" alt="Short alt text">
            </a>
        </div>
            <div class="col-lg-3 col-md-4 col-xs-6 thumb">
            <a class="thumbnail" href="#" data-image-id="" data-toggle="modal" data-title="The car i dream about" data-caption="If you sponsor me, I can drive this car" data-image="http://www.picturesnew.com/media/images/car-image.jpg" data-target="#image-gallery">
                <img class="img-responsive" src="http://www.picturesnew.com/media/images/car-image.jpg" alt="A alt text">
            </a>
        </div>
            <div class="col-lg-3 col-md-4 col-xs-6 thumb">
            <a class="thumbnail" href="#" data-image-id="" data-toggle="modal" data-title="Im so nice" data-caption="And if there is money left, my girlfriend will receive this car" data-image="http://upload.wikimedia.org/wikipedia/commons/7/78/1997_Fiat_Panda.JPG" data-target="#image-gallery">
                <img class="img-responsive" src="http://upload.wikimedia.org/wikipedia/commons/7/78/1997_Fiat_Panda.JPG" alt="Another alt text">
            </a>
        </div>
</div>


<div class="modal fade" id="image-gallery" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title" id="image-gallery-title"></h4>
            </div>
            <div class="modal-body">
                <img id="image-gallery-image" class="img-responsive" src="">
            </div>
            <div class="modal-footer">

                <div class="col-md-2">
                    <button type="button" class="btn btn-primary" id="show-previous-image">Previous</button>
                </div>

                <div class="col-md-8 text-justify" id="image-gallery-caption">
                    This text will be overwritten by jQuery
                </div>

                <div class="col-md-2">
                    <button type="button" id="show-next-image" class="btn btn-default">Next</button>
                </div>
            </div>
        </div>
    </div>
</div>



<script>
$(document).ready(function(){

    loadGallery(true, 'a.thumbnail');

    //This function disables buttons when needed
    function disableButtons(counter_max, counter_current){
        $('#show-previous-image, #show-next-image').show();
        if(counter_max == counter_current){
            $('#show-next-image').hide();
        } else if (counter_current == 1){
            $('#show-previous-image').hide();
        }
    }

    /**
     *
     * @param setIDs        Sets IDs when DOM is loaded. If using a PHP counter, set to false.
     * @param setClickAttr  Sets the attribute for the click handler.
     */

    function loadGallery(setIDs, setClickAttr){
        var current_image,
            selector,
            counter = 0;

        $('#show-next-image, #show-previous-image').click(function(){
            if($(this).attr('id') == 'show-previous-image'){
                current_image--;
            } else {
                current_image++;
            }

            selector = $('[data-image-id="' + current_image + '"]');
            updateGallery(selector);
        });

        function updateGallery(selector) {
            var $sel = selector;
            current_image = $sel.data('image-id');
            $('#image-gallery-caption').text($sel.data('caption'));
            $('#image-gallery-title').text($sel.data('title'));
            $('#image-gallery-image').attr('src', $sel.data('image'));
            disableButtons(counter, $sel.data('image-id'));
        }

        if(setIDs == true){
            $('[data-image-id]').each(function(){
                counter++;
                $(this).attr('data-image-id',counter);
            });
        }
        $(setClickAttr).on('click',function(){
            updateGallery($(this));
        });
    }
});
</script>

how to remove only one style property with jquery

You can also replace "-moz-user-select:none" with "-moz-user-select:inherit". This will inherit the style value from any parent style or from the default style if no parent style was defined.

Loop structure inside gnuplot?

I have the script all.p

set ...
...
list=system('ls -1B *.dat')
plot for [file in list] file w l u 1:2 t file

Here the two last rows are literal, not heuristic. Then i run

$ gnuplot -p all.p

Change *.dat to the file type you have, or add file types.

Next step: Add to ~/.bashrc this line

alias p='gnuplot -p ~/./all.p'

and put your file all.p int your home directory and voila. You can plot all files in any directory by typing p and enter.

EDIT I changed the command, because it didn't work. Previously it contained list(i)=word(system(ls -1B *.dat),i).

SignalR Console app example

This is for dot net core 2.1 - after a lot of trial and error I finally got this to work flawlessly:

var url = "Hub URL goes here";

var connection = new HubConnectionBuilder()
    .WithUrl($"{url}")
    .WithAutomaticReconnect() //I don't think this is totally required, but can't hurt either
    .Build();

//Start the connection
var t = connection.StartAsync();

//Wait for the connection to complete
t.Wait();

//Make your call - but in this case don't wait for a response 
//if your goal is to set it and forget it
await connection.InvokeAsync("SendMessage", "User-Server", "Message from the server");

This code is from your typical SignalR poor man's chat client. The problem that I and what seems like a lot of other people have run into is establishing a connection before attempting to send a message to the hub. This is critical, so it is important to wait for the asynchronous task to complete - which means we are making it synchronous by waiting for the task to complete.

How should I do integer division in Perl?

Integer division $x divided by $y ...

$z = -1 & $x / $y

How does it work?

$x / $y

return the floating point division

&

perform a bit-wise AND

-1

stands for

&HFFFFFFFF

for the largest integer ... whence

$z = -1 & $x / $y

gives the integer division ...

How to call a method after a delay in Android

If you have to use the Handler, but you are into another thread, you can use runonuithread to run the handler in UI thread. This will save you from Exceptions thrown asking to call Looper.Prepare()

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //Do something after 1 second
            }
        }, 1000);
    }
});

Looks quite messy, but this is one of the way.

Eclipse says: “Workspace in use or cannot be created, chose a different one.” How do I unlock a workspace?

I had this error after I restarted the system (after a long time. Normally I just make it sleep). Found out that once I mounted the drives (by clicking and opening it) where project folder is located, and relaunching eclipse, solved the issue for me.

PS: I'm an ubuntu user.

How can I get all the request headers in Django?

This is another way to do it, very similar to Manoj Govindan's answer above:

import re
regex_http_          = re.compile(r'^HTTP_.+$')
regex_content_type   = re.compile(r'^CONTENT_TYPE$')
regex_content_length = re.compile(r'^CONTENT_LENGTH$')

request_headers = {}
for header in request.META:
    if regex_http_.match(header) or regex_content_type.match(header) or regex_content_length.match(header):
        request_headers[header] = request.META[header]

That will also grab the CONTENT_TYPE and CONTENT_LENGTH request headers, along with the HTTP_ ones. request_headers['some_key] == request.META['some_key'].

Modify accordingly if you need to include/omit certain headers. Django lists a bunch, but not all, of them here: https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.META

Django's algorithm for request headers:

  1. Replace hyphen - with underscore _
  2. Convert to UPPERCASE.
  3. Prepend HTTP_ to all headers in original request, except for CONTENT_TYPE and CONTENT_LENGTH.

The values of each header should be unmodified.

Why does an onclick property set with setAttribute fail to work in IE?

Did you try:

    execBtn.setAttribute("onclick", function() { runCommand() });

Default behavior of "git push" without a branch specified

You can push current branch with command

git push origin HEAD

(took from here)

String.format() to format double in java

There are many way you can do this. Those are given bellow:

Suppose your original number is given bellow: double number = 2354548.235;

Using NumberFormat and Rounding mode

NumberFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);
    DecimalFormat decimalFormatter = (DecimalFormat) nf;
    decimalFormatter.applyPattern("#,###,###.##");
    decimalFormatter.setRoundingMode(RoundingMode.CEILING);

    String fString = decimalFormatter.format(number);
    System.out.println(fString);

Using String formatter

System.out.println(String.format("%1$,.2f", number));

In all cases the output will be: 2354548.24

Note:

During rounding you can add RoundingMode in your formatter. Here are some Rounding mode given bellow:

    decimalFormat.setRoundingMode(RoundingMode.CEILING);
    decimalFormat.setRoundingMode(RoundingMode.FLOOR);
    decimalFormat.setRoundingMode(RoundingMode.HALF_DOWN);
    decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
    decimalFormat.setRoundingMode(RoundingMode.UP);

Here are the imports:

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;

The matching wildcard is strict, but no declaration can be found for element 'context:component-scan

This error can also be caused if the jar file that contains the XSD you require is not included in your deployed class path.

Make sure the dependencies are available in your container.

How to navigate to a section of a page

My Solutions:

$("body").scrollspy({ target: ".target", offset: fix_header_height });

$(".target").click(function() {
 $("body").animate(
  {
   scrollTop: $($(this).attr("href")).offset().top - fix_header_height
  },
  500
 );
 return;
});

iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

The root problem here seems that iOS8 safari won't hide the address bar when scrolling down if the content is equal or less than the viewport.

As you found out already, adding some padding at the bottom gets around this issue:

html {
    /* enough space to scroll up to get fullscreen on iOS8 */
    padding-bottom: 80px;
}
// sort of emulate safari's "bounce back to top" scroll
window.addEventListener('scroll', function(ev) {
    // avoids scrolling when the focused element is e.g. an input
    if (
        !document.activeElement
        || document.activeElement === document.body
    ) {
        document.body.scrollIntoViewIfNeeded(true);
    }
});

The above css should be conditionally applied, for example with UA sniffing adding a gt-ios8 class to <html>.

how to call url of any other website in php

The simplest way would be to use FOpen or one of FOpen's Wrappers.

$page = file_get_contents("http://www.domain.com/filename");

This does require FOpen which some web hosts disable and some web hosts will allow FOpen, but not allow access to external files. You may want to check where you are going to run the script to see if you have access to External FOpen.

jQuery 'each' loop with JSON array

My solutions in one of my own sites, with a table:

$.getJSON("sections/view_numbers_update.php", function(data) {
 $.each(data, function(index, objNumber) {
  $('#tr_' + objNumber.intID).find("td").eq(3).html(objNumber.datLastCalled);
  $('#tr_' + objNumber.intID).find("td").eq(4).html(objNumber.strStatus);
  $('#tr_' + objNumber.intID).find("td").eq(5).html(objNumber.intDuration);
  $('#tr_' + objNumber.intID).find("td").eq(6).html(objNumber.blnWasHuman);
 });
});

sections/view_numbers_update.php Returns something like:

[{"intID":"19","datLastCalled":"Thu, 10 Jan 13 08:52:20 +0000","strStatus":"Completed","intDuration":"0:04 secs","blnWasHuman":"Yes","datModified":1357807940},
{"intID":"22","datLastCalled":"Thu, 10 Jan 13 08:54:43 +0000","strStatus":"Completed","intDuration":"0:00 secs","blnWasHuman":"Yes","datModified":1357808079}]

HTML table:

<table id="table_numbers">
 <tr>
  <th>[...]</th>
  <th>[...]</th>
  <th>[...]</th>
  <th>Last Call</th>
  <th>Status</th>
  <th>Duration</th>
  <th>Human?</th>
  <th>[...]</th>
 </tr>
 <tr id="tr_123456">
  [...]
 </tr>
</table>

This essentially gives every row a unique id preceding with 'tr_' to allow for other numbered element ids, at server script time. The jQuery script then just gets this TR_[id] element, and fills the correct indexed cell with the json return.

The advantage is you could get the complete array from the DB, and either foreach($array as $record) to create the table html, OR (if there is an update request) you can die(json_encode($array)) before displaying the table, all in the same page, but same display code.

Selected value for JSP drop down using JSTL

In HTML, the selected option is represented by the presence of the selected attribute on the <option> element like so:

<option ... selected>...</option>

Or if you're HTML/XHTML strict:

<option ... selected="selected">...</option>

Thus, you just have to let JSP/EL print it conditionally. Provided that you've prepared the selected department as follows:

request.setAttribute("selectedDept", selectedDept);

then this should do:

<select name="department">
    <c:forEach var="item" items="${dept}">
        <option value="${item.key}" ${item.key == selectedDept ? 'selected="selected"' : ''}>${item.value}</option>
    </c:forEach>
</select>

See also:

Can functions be passed as parameters?

You can also pass the function of a struct, like:

    package main
    // define struct
    type Apple struct {}
    
    // return apple's color
    func (Apple) GetColor() string {
         return "Red" 
    }
    
    func main () {
        // instantiate
        myApple := Apple{}
        
        // put the func in a variable
        theFunc := myApple.GetColor
        
        // execute the variable as a function
        color := theFunc()
    
        print(color)
    }

output will be "Red", check on the playground

How to catch all exceptions in c# using try and catch?

Both ways are correct.

If you need to do something with the Exception object in the catch block then you should use

try {
    // code....
}
catch (Exception ex){}

and then use ex in the catch block.

Anyway, it is not always a good practice to catch the Exception class, it is a better practice to catch a more specific exception - an exception which you expect.

How to set selected value on select using selectpicker plugin from bootstrap

The value is correctly selected, but you didn't see it because the plugin hide the real select and show a button with an unordered list, so, if you want that the user see the selected value on the select you can do something like this:

//Get the text using the value of select
var text = $("select[name=selValue] option[value='1']").text();
//We need to show the text inside the span that the plugin show
$('.bootstrap-select .filter-option').text(text);
//Check the selected attribute for the real select
$('select[name=selValue]').val(1);

Edit:

Like @blushrt points out, a better solution is:

$('select[name=selValue]').val(1);
$('.selectpicker').selectpicker('refresh')

Edit 2:

To select multiple values, pass the values as an array.

How do I return multiple values from a function?

I vote for the dictionary.

I find that if I make a function that returns anything more than 2-3 variables I'll fold them up in a dictionary. Otherwise I tend to forget the order and content of what I'm returning.

Also, introducing a 'special' structure makes your code more difficult to follow. (Someone else will have to search through the code to find out what it is)

If your concerned about type look up, use descriptive dictionary keys, for example, 'x-values list'.

def g(x):
  y0 = x + 1
  y1 = x * 3
  y2 = y0 ** y3
  return {'y0':y0, 'y1':y1 ,'y2':y2 }

Update Tkinter Label from variable

The window is only displayed once the mainloop is entered. So you won't see any changes you make in your while True block preceding the line root.mainloop().


GUI interfaces work by reacting to events while in the mainloop. Here's an example where the StringVar is also connected to an Entry widget. When you change the text in the Entry widget it automatically changes in the Label.

from tkinter import *

root = Tk()
var = StringVar()
var.set('hello')

l = Label(root, textvariable = var)
l.pack()

t = Entry(root, textvariable = var)
t.pack()

root.mainloop() # the window is now displayed

I like the following reference: tkinter 8.5 reference: a GUI for Python


Here is a working example of what you were trying to do:

from tkinter import *
from time import sleep

root = Tk()
var = StringVar()
var.set('hello')

l = Label(root, textvariable = var)
l.pack()

for i in range(6):
    sleep(1) # Need this to slow the changes down
    var.set('goodbye' if i%2 else 'hello')
    root.update_idletasks()

root.update Enter event loop until all pending events have been processed by Tcl.

What is considered a good response time for a dynamic, personalized web application?

There's a great deal of research on this. Here's a quick summary.

Response Times: The 3 Important Limits

by Jakob Nielsen on January 1, 1993

Summary: There are 3 main time limits (which are determined by human perceptual abilities) to keep in mind when optimizing web and application performance.

Excerpt from Chapter 5 in my book Usability Engineering, from 1993:

The basic advice regarding response times has been about the same for thirty years [Miller 1968; Card et al. 1991]:

  • 0.1 second is about the limit for having the user feel that the system is reacting instantaneously, meaning that no special feedback is necessary except to display the result.
  • 1.0 second is about the limit for the user's flow of thought to stay uninterrupted, even though the user will notice the delay. Normally, no special feedback is necessary during delays of more than 0.1 but less than 1.0 second, but the user does lose the feeling of operating directly on the data.
  • 10 seconds is about the limit for keeping the user's attention focused on the dialogue. For longer delays, users will want to perform other tasks while waiting for the computer to finish, so they should be given feedback indicating when the computer expects to be done. Feedback during the delay is especially important if the response time is likely to be highly variable, since users will then not know what to expect.

How to pass a view's onClick event to its parent on Android?

This answer is similar to Alexander Ukhov's answer, except that it uses touch events rather than click events. Those event allow the parent to display the proper pressed states (e.g., ripple effect). This answer is also in Kotlin instead of Java.

view.setOnTouchListener { view, motionEvent ->
    (view.parent as View).onTouchEvent(motionEvent)
}

`node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX

are you running the example from the node_modules folder?

They are not supposed to be ran from there.

Create the following file on your project instead:

post-data.js

var Curl = require( 'node-libcurl' ).Curl,
   querystring = require( 'querystring' );

var curl = new Curl(),
  url  = 'http://posttestserver.com/post.php',
data = { //Data to send, inputName : value
    'input-arr[0]' : 'input-arr-val0',
    'input-arr[1]' : 'input-arr-val1',
    'input-arr[2]' : 'input-arr-val2',
    'input-name' : 'input-val'
};

//You need to build the query string, 
// node has this helper function, but it's limited for real use cases (no support for 
array values for example)
data = querystring.stringify( data );

 curl.setOpt( Curl.option.URL, url );
 curl.setOpt( Curl.option.POSTFIELDS, data );
 curl.setOpt( Curl.option.HTTPHEADER, ['User-Agent: node-libcurl/1.0'] );
 curl.setOpt( Curl.option.VERBOSE, true );

 console.log( querystring.stringify( data ) );

 curl.perform();

 curl.on( 'end', function( statusCode, body ) {

console.log( body );

this.close();
});

curl.on( 'error', curl.close.bind( curl ) );

Run with node post-data.js

ref:https://github.com/JCMais/node-libcurl/issues/98

Set order of columns in pandas dataframe

Construct it with a list instead of a dictionary

frame = pd.DataFrame([
        [1, .1, 'a'],
        [2, .2, 'e'],
        [3,  1, 'i'],
        [4,  4, 'o']
    ], columns=['one thing', 'second thing', 'other thing'])

frame

   one thing  second thing other thing
0          1           0.1           a
1          2           0.2           e
2          3           1.0           i
3          4           4.0           o

How to filter empty or NULL names in a QuerySet?

Name.objects.filter(alias__gt='',alias__isnull=False)

How to use jQuery with Angular?

Why is everyone making it a rocket science? For anyone else who needs to do some basic stuff on static elements, for example, body tag, just do this:

  1. In index.html add script tag with the path to your jquery lib, doesn't matter where (this way you can also use IE conditional tags to load lower version of jquery for IE9 and less).
  2. In your export component block have a function that calls your code: $("body").addClass("done"); Normaly this causes declaration error, so just after all imports in this .ts file, add declare var $:any; and you are good to go!

How to push objects in AngularJS between ngRepeat arrays

change your method to:

$scope.toggleChecked = function (index) {
    $scope.checked.push($scope.items[index]);
    $scope.items.splice(index, 1);
};

Working Demo

How to get all options in a drop-down list by Selenium WebDriver using C#?

To get all options in a drop-down list by Selenium WebDriver C#:

SelectElement TimeZoneSelect = new SelectElement(driver.FindElement(By.Name("time_zone")));
IList<IWebElement> ElementCount = TimeZoneSelect.Options;
int ItemSize = ElementCount.Count;

for (int i = 0; i < ItemSize; i++)
{
    String ItemValue = ElementCount.ElementAt(i).Text;
    Console.WriteLine(ItemValue);
}

Sorting a list with stream.sorted() in Java

Java 8 provides different utility api methods to help us sort the streams better.

If your list is a list of Integers(or Double, Long, String etc.,) then you can simply sort the list with default comparators provided by java.

List<Integer> integerList = Arrays.asList(1, 4, 3, 4, 5);

Creating comparator on fly:

integerList.stream().sorted((i1, i2) -> i1.compareTo(i2)).forEach(System.out::println);

With default comparator provided by java 8 when no argument passed to sorted():

integerList.stream().sorted().forEach(System.out::println); //Natural order

If you want to sort the same list in reverse order:

 integerList.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println); // Reverse Order

If your list is a list of user defined objects, then:

List<Person> personList = Arrays.asList(new Person(1000, "First", 25, 30000),
        new Person(2000, "Second", 30, 45000),
        new Person(3000, "Third", 35, 25000));

Creating comparator on fly:

personList.stream().sorted((p1, p2) -> ((Long)p1.getPersonId()).compareTo(p2.getPersonId()))
        .forEach(person -> System.out.println(person.getName()));

Using Comparator.comparingLong() method(We have comparingDouble(), comparingInt() methods too):

personList.stream().sorted(Comparator.comparingLong(Person::getPersonId)).forEach(person -> System.out.println(person.getName()));

Using Comparator.comparing() method(Generic method which compares based on the getter method provided):

personList.stream().sorted(Comparator.comparing(Person::getPersonId)).forEach(person -> System.out.println(person.getName()));

We can do chaining too using thenComparing() method:

personList.stream().sorted(Comparator.comparing(Person::getPersonId).thenComparing(Person::getAge)).forEach(person -> System.out.println(person.getName())); //Sorting by person id and then by age.

Person class

public class Person {
    private long personId;
    private String name;
    private int age;
    private double salary;

    public long getPersonId() {
        return personId;
    }

    public void setPersonId(long personId) {
        this.personId = personId;
    }

    public Person(long personId, String name, int age, double salary) {
        this.personId = personId;
        this.name = name;
        this.age = age;

        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
}

How to add text to an existing div with jquery

You need to define the button text and have valid HTML for the button. I would also suggest using .on for the click handler of the button

_x000D_
_x000D_
$(function () {_x000D_
  $('#Add').on('click', function () {_x000D_
    $('<p>Text</p>').appendTo('#Content');_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="Content">_x000D_
    <button id="Add">Add Text</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Also I would make sure the jquery is at the bottom of the page just before the closing </body> tag. Doing so will make it so you do not have to have the whole thing wrapped in $(function but I would still do that. Having your javascript load at the end of the page makes it so the rest of the page loads incase there is a slow down in your javascript somewhere.

Creating instance list of different objects

If you can't be more specific than Object with your instances, then use:

List<Object> employees = new ArrayList<Object>();

Otherwise be as specific as you can:

List<? extends SpecificType> employees = new ArrayList<? extends SpecificType>();

How do you initialise a dynamic array in C++?

you have to initialize it "by hand" :

char* c = new char[length];
for(int i = 0;i<length;i++)
    c[i]='\0';

onclick on a image to navigate to another page using Javascript

You can define a a click function and then set the onclick attribute for the element.

function imageClick(url) {
    window.location = url;
}

<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" onclick="imageClick('../images/bottle.html')" />

This approach lets you get rid of the surrounding <a> element. If you want to keep it, then define the onclick attribute on <a> instead of on <img>.

How to negate specific word in regex?

I came across this forum thread while trying to identify a regex for the following English statement:

Given an input string, match everything unless this input string is exactly 'bar'; for example I want to match 'barrier' and 'disbar' as well as 'foo'.

Here's the regex I came up with

^(bar.+|(?!bar).*)$

My English translation of the regex is "match the string if it starts with 'bar' and it has at least one other character, or if the string does not start with 'bar'.

Slidedown and slideup layout with animation

I had a similar requirement in the app I am working on. And, I found a third-party library which does a slide-up, slide-down and slide-right in Android.

Refer to the link for more details: https://github.com/mancj/SlideUp-Android

To set up the library(copied from the ReadMe portion of its Github page on request):

Get SlideUp library

Add the JitPack repository to your build file. Add it in your root build.gradle at the end of repositories:

allprojects {
  repositories {
    ...
    maven { url 'https://jitpack.io' }
    maven { url "https://maven.google.com" } // or google() in AS 3.0
  }
}

Add the dependency (in the Module gradle)

dependencies {
    compile 'com.github.mancj:SlideUp-Android:2.2.1'
    compile 'ru.ztrap:RxSlideUp2:2.x.x' //optional, for reactive listeners based on RxJava-2
    compile 'ru.ztrap:RxSlideUp:1.x.x' //optional, for reactive listeners based on RxJava
}

To add the SlideUp into your project, follow these three simple steps:

Step 1:

create any type of layout

<LinearLayout
  android:id="@+id/slideView"
  android:layout_width="match_parent"
  android:layout_height="match_parent"/>

Step 2:

Find that view in your activity/fragment

View slideView = findViewById(R.id.slideView);

Step 3:

Create a SlideUp object and pass in your view

slideUp = new SlideUpBuilder(slideView)
                .withStartState(SlideUp.State.HIDDEN)
                .withStartGravity(Gravity.BOTTOM)

                //.withSlideFromOtherView(anotherView)
                //.withGesturesEnabled()
                //.withHideSoftInputWhenDisplayed()
                //.withInterpolator()
                //.withAutoSlideDuration()
                //.withLoggingEnabled()
                //.withTouchableAreaPx()
                //.withTouchableAreaDp()
                //.withListeners()
                //.withSavedState()
                .build();

You may also refer to the sample project on the link. I found it quite useful.

Docker error response from daemon: "Conflict ... already in use by container"

No issues with the latest kartoza/qgis-desktop

I ran

docker pull kartoza/qgis-desktop

followed by

docker run -it --rm --name "qgis-desktop-2-4" -v ${HOME}:/home/${USER} -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY=unix$DISPLAY kartoza/qgis-desktop:latest

I did try multiple times without the conflict error - you do have to exit the app beforehand. Also, please note the parameters do differ slightly.

How to change font size in a textbox in html

To actually do it in HTML with inline CSS (not with an external CSS style sheet)

<input type="text" style="font-size: 44pt">

A lot of people would consider putting the style right into the html like this to be poor form. However, I frequently make extreeemly simple web pages for my own use that don't even have a <html> or <body> tag, and such is appropriate there.

size of struct in C

The compiler may add padding for alignment requirements. Note that this applies not only to padding between the fields of a struct, but also may apply to the end of the struct (so that arrays of the structure type will have each element properly aligned).

For example:

struct foo_t {
    int x;
    char c;
};

Even though the c field doesn't need padding, the struct will generally have a sizeof(struct foo_t) == 8 (on a 32-bit system - rather a system with a 32-bit int type) because there will need to be 3 bytes of padding after the c field.

Note that the padding might not be required by the system (like x86 or Cortex M3) but compilers might still add it for performance reasons.

Create a Path from String in Java7

Even when the question is regarding Java 7, I think it adds value to know that from Java 11 onward, there is a static method in Path class that allows to do this straight away:

With all the path in one String:

Path.of("/tmp/foo");

With the path broken down in several Strings:

Path.of("/tmp","foo");

sqlite copy data from one table to another

If you're copying data like that, that probably means your datamodel isn't fully normalized, right? Is it possible to make one list of countries and do a JOIN more?

Instead of a JOIN you could also use virtual tables so you don't have to change the queries in your system.

Automatically open Chrome developer tools when new tab/new window is opened

With the Developer Tools window visible, click the menu icon (the three vertical dots in the top right corner) and click Settings.

Setting

Under Dev Tools, check the Auto-open DevTools for popups option

setting details

How to trigger a build only if changes happen on particular set of files

The Git plugin has an option (excluded region) to use regexes to determine whether to skip building based on whether files in the commit match the excluded region regex.

Unfortunately, the stock Git plugin does not have a "included region" feature at this time (1.15). However, someone posted patches on GitHub that work on Jenkins and Hudson that implement the feature you want.

It is a little work to build, but it works as advertised and has been extremely useful since one of my Git trees has multiple independent projects.

https://github.com/jenkinsci/git-plugin/pull/49

Update: The Git plugin (1.16) now has the 'included' region feature.

MySQL CREATE FUNCTION Syntax

MySQL create function syntax:

DELIMITER //

CREATE FUNCTION GETFULLNAME(fname CHAR(250),lname CHAR(250))
    RETURNS CHAR(250)
    BEGIN
        DECLARE fullname CHAR(250);
        SET fullname=CONCAT(fname,' ',lname);
        RETURN fullname;
    END //

DELIMITER ;

Use This Function In Your Query

SELECT a.*,GETFULLNAME(a.fname,a.lname) FROM namedbtbl as a


SELECT GETFULLNAME("Biswarup","Adhikari") as myname;

Watch this Video how to create mysql function and how to use in your query

Create Mysql Function Video Tutorial

How to format a number as percentage in R?

Check out the scales package. It used to be a part of ggplot2, I think.

library('scales')
percent((1:10) / 100)
#  [1] "1%"  "2%"  "3%"  "4%"  "5%"  "6%"  "7%"  "8%"  "9%"  "10%"

The built-in logic for detecting the precision should work well enough for most cases.

percent((1:10) / 1000)
#  [1] "0.1%" "0.2%" "0.3%" "0.4%" "0.5%" "0.6%" "0.7%" "0.8%" "0.9%" "1.0%"
percent((1:10) / 100000)
#  [1] "0.001%" "0.002%" "0.003%" "0.004%" "0.005%" "0.006%" "0.007%" "0.008%"
#  [9] "0.009%" "0.010%"
percent(sqrt(seq(0, 1, by=0.1)))
#  [1] "0%"   "32%"  "45%"  "55%"  "63%"  "71%"  "77%"  "84%"  "89%"  "95%" 
# [11] "100%"
percent(seq(0, 0.1, by=0.01) ** 2)
#  [1] "0.00%" "0.01%" "0.04%" "0.09%" "0.16%" "0.25%" "0.36%" "0.49%" "0.64%"
# [10] "0.81%" "1.00%"

How to create a user in Django?

If you creat user normally, you will not be able to login as password creation method may b different You can use default signup form for that

from django.contrib.auth.forms import UserCreationForm

You can extend that also

from django.contrib.auth.forms import UserCreationForm

class UserForm(UserCreationForm):
    mobile = forms.CharField(max_length=15, min_length=10)
    email = forms.EmailField(required=True)
    class Meta:
        model = User
        fields = ['username', 'password', 'first_name', 'last_name', 'email', 'mobile' ]

Then in view use this class

class UserCreate(CreateView):
    form_class = UserForm
    template_name = 'registration/signup.html'
    success_url = reverse_lazy('list')

    def form_valid(self, form):
        user = form.save()

Application Loader stuck at "Authenticating with the iTunes store" when uploading an iOS app

Using Xcode 12.3 Distribute App and xcodebuild both got stuck today at this point.

I finally was able to solve this. Peeking around my system I found 3 versions of iTMSTransporter. Printing the version of each using ./iTMSTransporter -version gives the following results:

  • /Applications/Transporter.app/Contents/itms/bin/ has version 2.0.0

  • /Applications/Xcode.app/Contents/SharedFrameworks/ContentDeliveryServices.framework/Versions/A/itms/bin/ has version 2.1.0

  • /usr/local/itms/bin/ has version version 1.9.3

So it looks that old version in /usr/local/itms was used by Xcode. After deleting /usr/local/itms I was able to upload my binary within Xcode 12.2 and using the xcodebuild command line tool.

tkinter: Open a new window with a button prompt

Here's the nearly shortest possible solution to your question. The solution works in python 3.x. For python 2.x change the import to Tkinter rather than tkinter (the difference being the capitalization):

import tkinter as tk
#import Tkinter as tk  # for python 2
    
def create_window():
    window = tk.Toplevel(root)

root = tk.Tk()
b = tk.Button(root, text="Create new window", command=create_window)
b.pack()

root.mainloop()

This is definitely not what I recommend as an example of good coding style, but it illustrates the basic concepts: a button with a command, and a function that creates a window.

Can I run HTML files directly from GitHub, instead of just viewing their source?

To piggyback on @niutech's answer, you can make a very simple bookmark snippet.
Using Chrome, though it works similarly with other browsers

  1. Right click your bookmark bar
  2. Click Add File
  3. Name it something like Github HTML
  4. For the URL type javascript:top.location="http://htmlpreview.github.com/?"+document.URL
  5. When you're on a github file view page (not raw.github.com) click the bookmark link and you're golden.

jQuery - Check if DOM element already exists

This should work for all elements regardless of when they are generated.

if($('some_element').length == 0) {
}

write your code in the ajax callback functions and it should work fine.

How to include view/partial specific styling in AngularJS

@sz3, funny enough today I had to do exactly what you were trying to achieve: 'load a specific CSS file only when a user access' a specific page. So I used the solution above.

But I am here to answer your last question: 'where exactly should I put the code. Any ideas?'

You were right including the code into the resolve, but you need to change a bit the format.

Take a look at the code below:

.when('/home', {
  title:'Home - ' + siteName,
  bodyClass: 'home',
  templateUrl: function(params) {
    return 'views/home.html';
  },
  controler: 'homeCtrl',
  resolve: {
    style : function(){
      /* check if already exists first - note ID used on link element*/
      /* could also track within scope object*/
      if( !angular.element('link#mobile').length){
        angular.element('head').append('<link id="home" href="home.css" rel="stylesheet">');
      }
    }
  }
})

I've just tested and it's working fine, it injects the html and it loads my 'home.css' only when I hit the '/home' route.

Full explanation can be found here, but basically resolve: should get an object in the format

{
  'key' : string or function()
} 

You can name the 'key' anything you like - in my case I called 'style'.

Then for the value you have two options:

  • If it's a string, then it is an alias for a service.

  • If it's function, then it is injected and the return value is treated as the dependency.

The main point here is that the code inside the function is going to be executed before before the controller is instantiated and the $routeChangeSuccess event is fired.

Hope that helps.

What is this: [Ljava.lang.Object;?

[Ljava.lang.Object; is the name for Object[].class, the java.lang.Class representing the class of array of Object.

The naming scheme is documented in Class.getName():

If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by the Java Language Specification (§13.1).

If this class object represents a primitive type or void, then the name returned is the Java language keyword corresponding to the primitive type or void.

If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more '[' characters representing the depth of the array nesting. The encoding of element type names is as follows:

Element Type        Encoding
boolean             Z
byte                B
char                C
double              D
float               F
int                 I
long                J
short               S 
class or interface  Lclassname;

Yours is the last on that list. Here are some examples:

// xxxxx varies
System.out.println(new int[0][0][7]); // [[[I@xxxxx
System.out.println(new String[4][2]); // [[Ljava.lang.String;@xxxxx
System.out.println(new boolean[256]); // [Z@xxxxx

The reason why the toString() method on arrays returns String in this format is because arrays do not @Override the method inherited from Object, which is specified as follows:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Note: you can not rely on the toString() of any arbitrary object to follow the above specification, since they can (and usually do) @Override it to return something else. The more reliable way of inspecting the type of an arbitrary object is to invoke getClass() on it (a final method inherited from Object) and then reflecting on the returned Class object. Ideally, though, the API should've been designed such that reflection is not necessary (see Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection).


On a more "useful" toString for arrays

java.util.Arrays provides toString overloads for primitive arrays and Object[]. There is also deepToString that you may want to use for nested arrays.

Here are some examples:

int[] nums = { 1, 2, 3 };

System.out.println(nums);
// [I@xxxxx

System.out.println(Arrays.toString(nums));
// [1, 2, 3]

int[][] table = {
        { 1, },
        { 2, 3, },
        { 4, 5, 6, },
};

System.out.println(Arrays.toString(table));
// [[I@xxxxx, [I@yyyyy, [I@zzzzz]

System.out.println(Arrays.deepToString(table));
// [[1], [2, 3], [4, 5, 6]]

There are also Arrays.equals and Arrays.deepEquals that perform array equality comparison by their elements, among many other array-related utility methods.

Related questions

Wordpress keeps redirecting to install-php after migration

I had the same problem and I fixed it by changing the database user privileges to full read & write.

How do I add records to a DataGridView in VB.Net?

If you want to add the row to the end of the grid use the Add() method of the Rows collection...

DataGridView1.Rows.Add(New String(){Value1, Value2, Value3})

If you want to insert the row at a partiular position use the Insert() method of the Rows collection (as GWLlosa also said)...

DataGridView1.Rows.Insert(rowPosition, New String(){value1, value2, value3})

I know you mentioned you weren't doing databinding, but if you defined a strongly-typed dataset with a single datatable in your project, you could use that and get some nice strongly typed methods to do this stuff rather than rely on the grid methods...

DataSet1.DataTable.AddRow(1, "John Doe", true)

jQuery click events not working in iOS

You should bind the tap event, the click does not exist on mobile safari or in the UIWbview. You can also use this polyfill ,to avoid the 300ms delay when a link is touched.

Get full path without filename from path that includes filename

Path.GetDirectoryName() returns the directory name, so for what you want (with the trailing reverse solidus character) you could call Path.GetDirectoryName(filePath) + Path.DirectorySeparatorChar.

How to increase the vertical split window size in Vim

Another tip from my side:

In order to set the window's width to let's say exactly 80 columns, use

80 CTRL+W |

In order to set it to maximum width, just omit the preceding number:

CTRL+W |

SQL sum with condition

Try this instead:

SUM(CASE WHEN ValueDate > @startMonthDate THEN cash ELSE 0 END)

Explanation

Your CASE expression has incorrect syntax. It seems you are confusing the simple CASE expression syntax with the searched CASE expression syntax. See the documentation for CASE:

The CASE expression has two formats:

  • The simple CASE expression compares an expression to a set of simple expressions to determine the result.
  • The searched CASE expression evaluates a set of Boolean expressions to determine the result.

You want the searched CASE expression syntax:

CASE
     WHEN Boolean_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END

As a side note, if performance is an issue you may find that this expression runs more quickly if you rewrite using a JOIN and GROUP BY instead of using a dependent subquery.

Where can I download an offline installer of Cygwin?

Not a direct answer to your question, but you can get the most commonly used utilities from http://www.mingw.org/ without having to jump through the hoops with that horrible Cygwin installer.

Here is a slightly more informative link http://sourceforge.net/apps/mediawiki/cobcurses/index.php?title=Install-MSYS.

How to disable a input in angular2

Demo

make is_edit of type boolean.

<input [disabled]=is_edit id="name" type="text">

export class App {
  name:string;
  is_edit: boolean; 
  constructor() {
    this.name = 'Angular2'
    this.is_edit = true;
  }
}

What is the maximum size of a web browser's cookie's key?

Not completely entirely a direct answer to the original question, but relevant for the curious quickly trying to visually understand their cookie information storage planning without implementing a complex limiter algorithm, this string is 4096 ASCII character bytes:

"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmn"

Windows equivalent of OS X Keychain?

A free and open source password manager that keeps all of your passwords safe in one place is "KeePass" and alternative to Windows Credential Manager.

SELECT data from another schema in oracle

In addition to grants, you can try creating synonyms. It will avoid the need for specifying the table owner schema every time.

From the connecting schema:

CREATE SYNONYM pi_int FOR pct.pi_int;

Then you can query pi_int as:

SELECT * FROM pi_int;

Android "elevation" not showing a shadow

set background color to the layout or view

Python how to plot graph sine wave

import matplotlib.pyplot as plt # For ploting
import numpy as np # to work with numerical data efficiently

fs = 100 # sample rate 
f = 2 # the frequency of the signal

x = np.arange(fs) # the points on the x axis for plotting
# compute the value (amplitude) of the sin wave at the for each sample
y = np.sin(2*np.pi*f * (x/fs)) 

#this instruction can only be used with IPython Notbook. 
% matplotlib inline
# showing the exact location of the smaples
plt.stem(x,y, 'r', )
plt.plot(x,y)

enter image description here

Call async/await functions in parallel

In my case, I have several tasks I want to execute in parallel, but I need to do something different with the result of those tasks.

function wait(ms, data) {
    console.log('Starting task:', data, ms);
    return new Promise(resolve => setTimeout(resolve, ms, data));
}

var tasks = [
    async () => {
        var result = await wait(1000, 'moose');
        // do something with result
        console.log(result);
    },
    async () => {
        var result = await wait(500, 'taco');
        // do something with result
        console.log(result);
    },
    async () => {
        var result = await wait(5000, 'burp');
        // do something with result
        console.log(result);
    }
]

await Promise.all(tasks.map(p => p()));
console.log('done');

And the output:

Starting task: moose 1000
Starting task: taco 500
Starting task: burp 5000
taco
moose
burp
done

Remove pandas rows with duplicate indices

If anyone like me likes chainable data manipulation using the pandas dot notation (like piping), then the following may be useful:

df3 = df3.query('~index.duplicated()')

This enables chaining statements like this:

df3.assign(C=2).query('~index.duplicated()').mean()

Youtube autoplay not working on mobile devices with embedded HTML5 player

The code below was tested on iPhone, iPad (iOS13), Safari (Catalina). It was able to autoplay the YouTube video on all devices. Make sure the video is muted and the playsinline parameter is on. Those are the magic parameters that make it work.

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=1.0, user-scalable=yes">
    </head>
  <body>
<!-- 1. The <iframe> (video player) will replace this <div> tag. -->
<div id="player"></div>

<script>
  // 2. This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');

  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      width: '100%',
      videoId: 'osz5tVY97dQ',
      playerVars: { 'autoplay': 1, 'playsinline': 1 },
      events: {
        'onReady': onPlayerReady
      }
    });
  }

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
     event.target.mute();
    event.target.playVideo();
  }
</script>
  </body>
</html>

No connection could be made because the target machine actively refused it 127.0.0.1

If you have config file transforms then ensure you have the correct config selected within your publish profile. (Publish > Settings > Configuration)

How do I get the number of elements in a list?

While this may not be useful due to the fact that it'd make a lot more sense as being "out of the box" functionality, a fairly simple hack would be to build a class with a length property:

class slist(list):
    @property
    def length(self):
        return len(self)

You can use it like so:

>>> l = slist(range(10))
>>> l.length
10
>>> print l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Essentially, it's exactly identical to a list object, with the added benefit of having an OOP-friendly length property.

As always, your mileage may vary.

Can I run CUDA on Intel's integrated graphics processor?

Portland group have a commercial product called CUDA x86, it is hybrid compiler which creates CUDA C/ C++ code which can either run on GPU or use SIMD on CPU, this is done fully automated without any intervention for the developer. Hope this helps.

Link: http://www.pgroup.com/products/pgiworkstation.htm

Adding system header search path to Xcode

To use quotes just for completeness.

"/Users/my/work/a project with space"/**

If not recursive, remove the /**

Unordered List (<ul>) default indent

Typical default display properties for ul

ul {
    display: block;
    list-style-type: disc;
    margin-before: 1em;
    margin-after: 1em;
    margin-start: 0;
    margin-end: 0;
    padding-start: 40px;
}

C# how to change data in DataTable?

dt.Rows[1].ItemArray gives you a copy of item arrays. When you modify it, you're not modifying the original.

You can simply do this:

dt.Rows[1][3] = "Value";

ItemArray property is used when you want to modify all row values.

ex.:

dt.Rows[1].ItemArray = newItemArray;

How to create a file on Android Internal Storage?

Write a file

When saving a file to internal storage, you can acquire the appropriate directory as a File by calling one of two methods:

getFilesDir()

      Returns a File representing an internal directory for your app.

getCacheDir()

     Returns a File representing an internal directory for your 
     app's temporary cache files.
     Be sure to delete each file once it is no longer needed and implement a reasonable 
     size limit for the amount of memory you use at any given time, such as 1MB.

Caution: If the system runs low on storage, it may delete your cache files without warning.

Laravel Carbon subtract days from current date

From Laravel 5.6 you can use whereDate:

$users = Users::where('status_id', 'active')
       ->whereDate( 'created_at', '>', now()->subDays(30))
       ->get();

You also have whereMonth / whereDay / whereYear / whereTime

jQuery select option elements by value

Here's the simplest solution with a clear selector:

function select_option(i) {
  return $('span#span_id select option[value="' + i + '"]').html();
}

Maven Modules + Building a Single Specific Module

You say you "really just want B", but this is false. You want B, but you also want an updated A if there have been any changes to it ("active development").

So, sometimes you want to work with A, B, and C. For this case you have aggregator project P. For the case where you want to work with A and B (but do not want C), you should create aggregator project Q.

Edit 2016: The above information was perhaps relevant in 2009. As of 2016, I highly recommend ignoring this in most cases, and simply using the -am or -pl command-line flags as described in the accepted answer. If you're using a version of maven from before v2.1, change that first :)

Return a value if no rows are found in Microsoft tSQL

DECLARE @col int; 
select @col = id  FROM site WHERE status = 1; 
select coalesce(@col,0);

C# equivalent to Java's charAt()?

you can use LINQ

string abc = "abc";
char getresult = abc.Where((item, index) => index == 2).Single();

how to count the total number of lines in a text file using python

I am not new to stackoverflow, just never had an account and usually came here for answers. I can't comment or vote up an answer yet. BUT wanted to say that the code from Michael Bacon above works really well. I am new to Python but not to programming. I have been reading Python Crash Course and there are a few things I wanted to do to break up the reading cover to cover approach. One utility that has uses from an ETL or even data quality perspective would be to capture the row count of a file independently from any ETL. The file has X number of rows, you import into SQL or Hadoop and you end up with X number of rows. You can validate at the lowest level the row count of a raw data file.

I have been playing with his code and doing some testing and this code is very efficient so far. I have created several different CSV files, various sizes, and row counts. You can see my code below and my comments provide the times and details. The code Michael Bacon above provided runs about 6 times faster than the normal Python method of just looping the lines.

Hope this helps someone.


 import time
from itertools import (takewhile,repeat)

def readfilesimple(myfile):

    # watch me whip
    linecounter = 0
    with open(myfile,'r') as file_object:
        # watch me nae nae
         for lines in file_object:
            linecounter += 1

    return linecounter

def readfileadvanced(myfile):

    # watch me whip
    f = open(myfile, 'rb')
    # watch me nae nae
    bufgen = takewhile(lambda x: x, (f.raw.read(1024 * 1024) for _ in repeat(None)))
    return sum(buf.count(b'\n') for buf in bufgen if buf)
    #return linecounter


# ************************************
# Main
# ************************************

#start the clock

start_time = time.time()

# 6.7 seconds to read a 475MB file that has 24 million rows and 3 columns
#mycount = readfilesimple("c:/junk/book1.csv")

# 0.67 seconds to read a 475MB file that has 24 million rows and 3 columns
#mycount = readfileadvanced("c:/junk/book1.csv")

# 25.9 seconds to read a 3.9Gb file that has 3.25 million rows and 104 columns
#mycount = readfilesimple("c:/junk/WideCsvExample/ReallyWideReallyBig1.csv")

# 5.7 seconds to read a 3.9Gb file that has 3.25 million rows and 104 columns
#mycount = readfileadvanced("c:/junk/WideCsvExample/ReallyWideReallyBig1.csv")


# 292.92 seconds to read a 43Gb file that has 35.7 million rows and 104 columns
mycount = readfilesimple("c:/junk/WideCsvExample/ReallyWideReallyBig.csv")

# 57 seconds to read a 43Gb file that has 35.7 million rows and 104 columns
#mycount = readfileadvanced("c:/junk/WideCsvExample/ReallyWideReallyBig.csv")


#stop the clock
elapsed_time = time.time() - start_time


print("\nCode Execution: " + str(elapsed_time) + " seconds\n")
print("File contains: " + str(mycount) + " lines of text.")

IN-clause in HQL or Java Persistence Query Language

query.setParameterList("name", new String[] { "Ron", "Som", "Roxi"}); fixed my issue

What do the makefile symbols $@ and $< mean?

The $@ and $< are called automatic variables. The variable $@ represents the name of the target and $< represents the first prerequisite required to create the output file.
For example:

hello.o: hello.c hello.h
         gcc -c $< -o $@

Here, hello.o is the output file. This is what $@ expands to. The first dependency is hello.c. That's what $< expands to.

The -c flag generates the .o file; see man gcc for a more detailed explanation. The -o specifies the output file to create.

For further details, you can read this article about Linux Makefiles.

Also, you can check the GNU make manuals. It will make it easier to make Makefiles and to debug them.

If you run this command, it will output the makefile database:

make -p 

log4j logging hierarchy order

Use the force, read the source (excerpt from the Priority and Level class compiled, TRACE level was introduced in version 1.2.12):

public final static int OFF_INT = Integer.MAX_VALUE;
public final static int FATAL_INT = 50000;
public final static int ERROR_INT = 40000;
public final static int WARN_INT  = 30000;
public final static int INFO_INT  = 20000;
public final static int DEBUG_INT = 10000;
public static final int TRACE_INT = 5000; 
public final static int ALL_INT = Integer.MIN_VALUE; 

or the log4j API for the Level class, which makes it quite clear.

When the library decides whether to print a certain statement or not, it computes the effective level of the responsible Logger object (based on configuration) and compares it with the LogEvent's level (depends on which method was used in the code – trace/debug/.../fatal). If LogEvent's level is greater or equal to the Logger's level, the LogEvent is sent to appender(s) – "printed". At the core, it all boils down to an integer comparison and this is where these constants come to action.

First Heroku deploy failed `error code=H10`

For me, I had things unnecessarily split into separate folders. I'm running plotly dash and I had my Procfile, and Pipfile (and lock) together, but separate from the other features of my app (run.py and app.py, the actual content of the pages being used was in a subfolder). So joining much of that together repaired my H10 error

How to add a RequiredFieldValidator to DropDownList control?

InitialValue="0" : initial validation will fire when 0th index item is selected in ddl.

<asp:RequiredFieldValidator InitialValue="0" Display="Dynamic" CssClass="error" runat="server" ID="your_id" ValidationGroup="validationgroup" ControlToValidate="your_dropdownlist_id" />

Webdriver Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms

I got the same error; I've used selenium-java version 2.25.0 and Firefox vresion 18.0.2; I've changed the version of selenium-java to 2.30.0 and now works.

Converting byte array to string in javascript

Didn't find any solution that would work with UTF-8 characters. String.fromCharCode is good until you meet 2 byte character.

For example Hüser will come as [0x44,0x61,0x6e,0x69,0x65,0x6c,0x61,0x20,0x48,0xc3,0xbc,0x73,0x65,0x72]

But if you go through it with String.fromCharCode you will have Hüser as each byte will be converted to a char separately.

Solution

Currently I'm using following solution:

function pad(n) { return (n.length < 2 ? '0' + n : n); }
function decodeUtf8(data) {
  return decodeURIComponent(
    data.map(byte => ('%' + pad(byte.toString(16)))).join('')
  );
}

Where is NuGet.Config file located in Visual Studio project?

Visual Studio reads NuGet.Config files from the solution root. Try moving it there instead of placing it in the same folder as the project.

You can also place the file at %appdata%\NuGet\NuGet.Config and it will be used everywhere.

https://docs.microsoft.com/en-us/nuget/schema/nuget-config-file

How to change values in a tuple?

i did this:

list = [1,2,3,4,5]
tuple = (list)

and to change, just do

list[0]=6

and u can change a tuple :D

here is it copied exactly from IDLE

>>> list=[1,2,3,4,5,6,7,8,9]

>>> tuple=(list)

>>> print(tuple)

[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> list[0]=6

>>> print(tuple)

[6, 2, 3, 4, 5, 6, 7, 8, 9]

How to get a substring of text?

If you want a string, then the other answers are fine, but if what you're looking for is the first few letters as characters you can access them as a list:

your_text.chars.take(30)

How to reload apache configuration for a site without restarting apache?

Updated for Apache 2.4, for non-systemd (e.g., CentOS 6.x, Amazon Linux AMI) and for systemd (e.g., CentOS 7.x):

There are two ways of having the apache process reload the configuration, depending on what you want done with its current threads, either advise to exit when idle, or killing them directly.

Note that Apache recommends using apachectl -k as the command, and for systemd, the command is replaced by httpd -k

apachectl -k graceful or httpd -k graceful

Apache will advise its threads to exit when idle, and then apache reloads the configuration (it doesn't exit itself), this means statistics are not reset.

apachectl -k restart or httpd -k restart

This is similar to stop, in that the process kills off its threads, but then the process reloads the configuration file, rather than killing itself.

Source: https://httpd.apache.org/docs/2.4/stopping.html

Angular 2 http post params and body

And it works, thanks @trichetriche. The problem was in my RequestOptions, apparently, you can not pass params or body to the RequestOptions while using the post. Removing one of them gives me an error, removing both and it works. Still no final solution to my problem, but I now have something to work with. Final working code.

public post(cmd: string, data: string): Observable<any> {

    const options = new RequestOptions({
      headers: this.getAuthorizedHeaders(),
      responseType: ResponseContentType.Json,
      withCredentials: false
    });

    console.log('Options: ' + JSON.stringify(options));

    return this.http.post(this.BASE_URL, JSON.stringify({
      cmd: cmd,
      data: data}), options)
      .map(this.handleData)
      .catch(this.handleError);
  }

Declare a const array

I believe you can only make it readonly.

How to send a simple email from a Windows batch file?

I've used Blat ( http://www.blat.net/ ) for many years. It's a simple command line utility that can send email from command line. It's free and opensource.

You can use command like "Blat myfile.txt -to [email protected] -server smtp.domain.com -port 6000"

Here is some other software you can try to send email from command line (I've never used them):
http://caspian.dotconf.net/menu/Software/SendEmail/
http://www.petri.co.il/sendmail.htm
http://www.petri.co.il/software/mailsend105.zip
http://retired.beyondlogic.org/solutions/cmdlinemail/cmdlinemail.htm

Here ( http://www.petri.co.il/send_mail_from_script.htm ) you can find other various way of sending email from a VBS script, plus link to some of the mentioned software

The following VBScript code is taken from that page

Set objEmail = CreateObject("CDO.Message")
objEmail.From = "[email protected]"
objEmail.To = "[email protected]"
objEmail.Subject = "Server is down!"
objEmail.Textbody = "Server100 is no longer accessible over the network."
objEmail.Send

Save the file as something.vbs

Set Msg = CreateObject("CDO.Message")

With Msg

 .To = "[email protected]"
 .From = "[email protected]"
 .Subject = "Hello"
 .TextBody = "Just wanted to say hi."
 .Send

End With

Save the file as something2.vbs

I think these VBS scripts use the windows default mail server, if present. I've not tested these scripts...

Build a simple HTTP server in C

Open a TCP socket on port 80, start listening for new connections, implement this. Depending on your purposes, you can ignore almost everything. At the easiest, you can send the same response for every request, which just involves writing text to the socket.

Is it good practice to make the constructor throw an exception?

It is bad practice to throw Exception, as that requires anyone who calls your constructor to catch Exception which is a bad practice.

It is a good idea to have a constructor (or any method) throw an exception, generally speaking IllegalArgumentException, which is unchecked, and thus the compiler doesn't force you to catch it.

You should throw checked exceptions (things that extend from Exception, but not RuntimeException) if you want the caller to catch it.

What is the JUnit XML format specification that Hudson supports?

Basic Structure Here is an example of a JUnit output file, showing a skip and failed result, as well as a single passed result.

<?xml version="1.0" encoding="UTF-8"?>
<testsuites>
   <testsuite name="JUnitXmlReporter" errors="0" tests="0" failures="0" time="0" timestamp="2013-05-24T10:23:58" />
   <testsuite name="JUnitXmlReporter.constructor" errors="0" skipped="1" tests="3" failures="1" time="0.006" timestamp="2013-05-24T10:23:58">
      <properties>
         <property name="java.vendor" value="Sun Microsystems Inc." />
         <property name="compiler.debug" value="on" />
         <property name="project.jdk.classpath" value="jdk.classpath.1.6" />
      </properties>
      <testcase classname="JUnitXmlReporter.constructor" name="should default path to an empty string" time="0.006">
         <failure message="test failure">Assertion failed</failure>
      </testcase>
      <testcase classname="JUnitXmlReporter.constructor" name="should default consolidate to true" time="0">
         <skipped />
      </testcase>
      <testcase classname="JUnitXmlReporter.constructor" name="should default useDotNotation to true" time="0" />
   </testsuite>
</testsuites>

Below is the documented structure of a typical JUnit XML report. Notice that a report can contain 1 or more test suite. Each test suite has a set of properties (recording environment information). Each test suite also contains 1 or more test case and each test case will either contain a skipped, failure or error node if the test did not pass. If the test case has passed, then it will not contain any nodes. For more details of which attributes are valid for each node please consult the following section "Schema".

<testsuites>        => the aggregated result of all junit testfiles
  <testsuite>       => the output from a single TestSuite
    <properties>    => the defined properties at test execution
      <property>    => name/value pair for a single property
      ...
    </properties>
    <error></error> => optional information, in place of a test case - normally if the tests in the suite could not be found etc.
    <testcase>      => the results from executing a test method
      <system-out>  => data written to System.out during the test run
      <system-err>  => data written to System.err during the test run
      <skipped/>    => test was skipped
      <failure>     => test failed
      <error>       => test encountered an error
    </testcase>
    ...
  </testsuite>
  ...
</testsuites>

Unable to load script from assets index.android.bundle on windows

Chipping in an obvious suggestion that worked for me. Delete the app, restart the server and deploy again from your tooling to device.

Use of min and max functions in C++

I always use the min and max macros for ints. I'm not sure why anyone would use fmin or fmax for integer values.

The big gotcha with min and max is that they're not functions, even if they look like them. If you do something like:

min (10, BigExpensiveFunctionCall())

That function call may get called twice depending on the implementation of the macro. As such, its best practice in my org to never call min or max with things that aren't a literal or variable.

getResourceAsStream() is always returning null

I had the same problem when I changed from Websphere 8.5 to WebSphere Liberty.

I utilized FileInputStream instead of getResourceAsStream(), because for some reason WebSphere Liberty can't locate the file in the WEB-INF folder.

The script was :

FileInputStream fis = new FileInputStream(getServletContext().getRealPath("/") 
                        + "\WEBINF\properties\myProperties.properties")

Note: I used this script only for development.

Windows command to get service status?

my intention was to create a script which switches services ON and OFF (in 1 script)

net start NameOfSercive 2>nul
if errorlevel 2 goto AlreadyRunning
if errorlevel 1 goto Error

...

Helped a lot!! TYVM z666

but when e.g. service is disabled(also errorlevel =2?)it goes to "AlreadyRuning"and never comes to

if errorlevel 1 goto Error  ?!!

i wanted an output for that case ...

 :AlreadyRunning
 net stop NameOfSercive
 if errorlevel 1 goto Error


 :Error
 Echo ERROR!!1!
 Pause

my 2 Cents, hope this helps

Strangest language feature

In Lisp you can copy a list, and you can copy a vector, and you can copy a struct, and you can copy a CLOS object...

... but you cannot copy an array or a hash table.

How to get a pixel's x,y coordinate color from an image?

With : i << 2

const data = context.getImageData(x, y, width, height).data;
const pixels = [];

for (let i = 0, dx = 0; dx < data.length; i++, dx = i << 2) {
    if (data[dx+3] <= 8)
        console.log("transparent x= " + i);
}

jQuery to retrieve and set selected option value of html select element

The way you have it is correct at the moment. Either the id of the select is not what you say or you have some issues in the dom.

Check the Id of the element and also check your markup validates at here at W3c.

Without a valid dom jQuery cannot work correctly with the selectors.

If the id's are correct and your dom validates then the following applies:

To Read Select Option Value

$('#selectId').val();

To Set Select Option Value

$('#selectId').val('newValue');

To Read Selected Text

$('#selectId>option:selected').text();

count number of rows in a data frame in R based on group

Using the example data set that Ananda dummied up, here's an example using aggregate(), which is part of core R. aggregate() just needs something to count as function of the different values of MONTH-YEAR. In this case, I used VALUE as the thing to count:

aggregate(cbind(count = VALUE) ~ MONTH.YEAR, 
          data = mydf, 
          FUN = function(x){NROW(x)})

which gives you..

  MONTH.YEAR count
1  FEB. 2012     2
2  JAN. 2012     2
3  MAR. 2012     1

Add Legend to Seaborn point plot

I would suggest not to use seaborn pointplot for plotting. This makes things unnecessarily complicated.
Instead use matplotlib plot_date. This allows to set labels to the plots and have them automatically put into a legend with ax.legend().

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np

date = pd.date_range("2017-03", freq="M", periods=15)
count = np.random.rand(15,4)
df1 = pd.DataFrame({"date":date, "count" : count[:,0]})
df2 = pd.DataFrame({"date":date, "count" : count[:,1]+0.7})
df3 = pd.DataFrame({"date":date, "count" : count[:,2]+2})

f, ax = plt.subplots(1, 1)
x_col='date'
y_col = 'count'

ax.plot_date(df1.date, df1["count"], color="blue", label="A", linestyle="-")
ax.plot_date(df2.date, df2["count"], color="red", label="B", linestyle="-")
ax.plot_date(df3.date, df3["count"], color="green", label="C", linestyle="-")

ax.legend()

plt.gcf().autofmt_xdate()
plt.show()

enter image description here


In case one is still interested in obtaining the legend for pointplots, here a way to go:

sns.pointplot(ax=ax,x=x_col,y=y_col,data=df1,color='blue')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df2,color='green')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df3,color='red')

ax.legend(handles=ax.lines[::len(df1)+1], labels=["A","B","C"])

ax.set_xticklabels([t.get_text().split("T")[0] for t in ax.get_xticklabels()])
plt.gcf().autofmt_xdate()

plt.show()

"code ." Not working in Command Line for Visual Studio Code on OSX/Mac

On my MAC I got it working:

add to .bash_profile

code() {
   open -a Visual\ Studio\ Code.app $1
}

save and in terminal 'source .bash_profile'

Then in terminal code index.html (or whatever) will open that file in VS Code.

MySQL's now() +1 day

better use quoted `data` and `date`. AFAIR these may be reserved words my version is:

INSERT INTO `table` ( `data` , `date` ) VALUES('".$date."',NOW()+INTERVAL 1 DAY);

How can I make robocopy silent in the command line except for progress?

robocopy also tends to print empty lines even if it does not do anything. I'm filtering empty lines away using command like this:

robocopy /NDL /NJH /NJS /NP /NS /NC %fromDir% %toDir% %filenames% | findstr /r /v "^$"

How can we programmatically detect which iOS version is device running on?

To get more specific version number information with major and minor versions separated:

NSString* versionString = [UIDevice currentDevice].systemVersion;
NSArray* vN = [versionString componentsSeparatedByString:@"."];

The array vN will contain the major and minor versions as strings, but if you want to do comparisons, version numbers should be stored as numbers (ints). You can add this code to store them in the C-array* versionNumbers:

int versionNumbers[vN.count];
for (int i = 0; i < sizeof(versionNumbers)/sizeof(versionNumbers[0]); i++)
    versionNumbers[i] = [[vN objectAtIndex:i] integerValue];

* C-arrays used here for more concise syntax.

Bootstrap full responsive navbar with logo or brand name text

I checked and it worked for me.

<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1" style="margin-top:100px;"><!--style with margin-top according to your need-->
        <ul class="nav navbar-nav navbar-right">
            <li><a href="#">About</a></li>
            <li><a href="#">Services</a></li>
            <li><a href="#">Contact</a></li>
        </ul>
    </div>

When does a process get SIGABRT (signal 6)?

The GNU libc will print out information to /dev/tty regarding some fatal conditions before it calls abort() (which then triggers SIGABRT), but if you are running your program as a service or otherwise not in a real terminal window, these message can get lost, because there is no tty to display the messages.

See my post on redirecting libc to write to stderr instead of /dev/tty:

Catching libc error messages, redirecting from /dev/tty

Appending an element to the end of a list in Scala

List(1,2,3) :+ 4

Results in List[Int] = List(1, 2, 3, 4)

Note that this operation has a complexity of O(n). If you need this operation frequently, or for long lists, consider using another data type (e.g. a ListBuffer).

What is the purpose of mvnw and mvnw.cmd files?

The Maven Wrapper is an excellent choice for projects that need a specific version of Maven (or for users that don't want to install Maven at all). Instead of installing many versions of it in the operating system, we can just use the project-specific wrapper script.

mvnw: it's an executable Unix shell script used in place of a fully installed Maven

mvnw.cmd: it's for Windows environment


Use Cases

The wrapper should work with different operating systems such as:

  • Linux
  • OSX
  • Windows
  • Solaris

After that, we can run our goals like this for the Unix system:

./mvnw clean install

And the following command for Batch:

./mvnw.cmd clean install

If we don't have the specified Maven in the wrapper properties, it'll be downloaded and installed in the folder $USER_HOME/.m2/wrapper/dists of the system.


Maven Wrapper plugin

Maven Wrapper plugin to make auto installation in a simple Spring Boot project.

First, we need to go in the main folder of the project and run this command:

mvn -N io.takari:maven:wrapper

We can also specify the version of Maven:

mvn -N io.takari:maven:wrapper -Dmaven=3.5.2

The option -N means –non-recursive so that the wrapper will only be applied to the main project of the current directory, not in any submodules.


Source 1 (further reading): https://www.baeldung.com/maven-wrapper

A TypeScript GUID class?

There is an implementation in my TypeScript utilities based on JavaScript GUID generators.

Here is the code:

_x000D_
_x000D_
class Guid {_x000D_
  static newGuid() {_x000D_
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {_x000D_
      var r = Math.random() * 16 | 0,_x000D_
        v = c == 'x' ? r : (r & 0x3 | 0x8);_x000D_
      return v.toString(16);_x000D_
    });_x000D_
  }_x000D_
}_x000D_
_x000D_
// Example of a bunch of GUIDs_x000D_
for (var i = 0; i < 100; i++) {_x000D_
  var id = Guid.newGuid();_x000D_
  console.log(id);_x000D_
}
_x000D_
_x000D_
_x000D_

Please note the following:

C# GUIDs are guaranteed to be unique. This solution is very likely to be unique. There is a huge gap between "very likely" and "guaranteed" and you don't want to fall through this gap.

JavaScript-generated GUIDs are great to use as a temporary key that you use while waiting for a server to respond, but I wouldn't necessarily trust them as the primary key in a database. If you are going to rely on a JavaScript-generated GUID, I would be tempted to check a register each time a GUID is created to ensure you haven't got a duplicate (an issue that has come up in the Chrome browser in some cases).

ArrayList vs List<> in C#

ArrayList is the collections of different types data whereas List<> is the collection of similar type of its own depedencties.

javascript getting my textbox to display a variable

Even if this is already answered (1 year ago) you could also let the fields be calculated automatically.

The HTML

    <tr>
        <td><input type="text" value="" ></td>
        <td><input type="text" class="class_name" placeholder="bla bla"/></td>
    </tr>
    <tr>
        <td><input type="text" value="" ></td>
        <td><input type="text" class="class_name" placeholder="bla bla."/></td>
    </tr>

The script

$(document).ready(function(){
                $(".class_name").each(function(){
                    $(this).keyup(function(){
                        calculateSum()
                        ;})
                    ;})
                ;}
                );
            function calculateSum(){
                var sum=0;
                $(".class_name").each(function(){
                    if(!isNaN(this.value) && this.value.length!=0){
                        sum+=parseFloat(this.value);
                    }
                    else if(isNaN(this.value)) {
                        alert("Maybe an alert if they type , instead of .");
                    }
                }
                );
                $("#sum").html(sum.toFixed(2));
                } 

What svn command would list all the files modified on a branch?

-u option will display including object files if they are added during compilation.

So, to overcome that additionally you may use like this.

svn status -u | grep -v '\?' 

Getting the count of unique values in a column in bash

Perl

This code computes the occurrences of all columns, and prints a sorted report for each of them:

# columnvalues.pl
while (<>) {
    @Fields = split /\s+/;
    for $i ( 0 .. $#Fields ) {
        $result[$i]{$Fields[$i]}++
    };
}
for $j ( 0 .. $#result ) {
    print "column $j:\n";
    @values = keys %{$result[$j]};
    @sorted = sort { $result[$j]{$b} <=> $result[$j]{$a}  ||  $a cmp $b } @values;
    for $k ( @sorted ) {
        print " $k $result[$j]{$k}\n"
    }
}

Save the text as columnvalues.pl
Run it as: perl columnvalues.pl files*

Explanation

In the top-level while loop:
* Loop over each line of the combined input files
* Split the line into the @Fields array
* For every column, increment the result array-of-hashes data structure

In the top-level for loop:
* Loop over the result array
* Print the column number
* Get the values used in that column
* Sort the values by the number of occurrences
* Secondary sort based on the value (for example b vs g vs m vs z)
* Iterate through the result hash, using the sorted list
* Print the value and number of each occurrence

Results based on the sample input files provided by @Dennis

column 0:
 a 3
 z 3
 t 1
 v 1
 w 1
column 1:
 d 3
 r 2
 b 1
 g 1
 m 1
 z 1
column 2:
 c 4
 a 3
 e 2

.csv input

If your input files are .csv, change /\s+/ to /,/

Obfuscation

In an ugly contest, Perl is particularly well equipped.
This one-liner does the same:

perl -lane 'for $i (0..$#F){$g[$i]{$F[$i]}++};END{for $j (0..$#g){print "$j:";for $k (sort{$g[$j]{$b}<=>$g[$j]{$a}||$a cmp $b} keys %{$g[$j]}){print " $k $g[$j]{$k}"}}}' files*

C++ compile error: has initializer but incomplete type

` Please include either of these:

`#include<sstream>`

using std::istringstream; 

implements Closeable or implements AutoCloseable

It seems to me that you are not very familiar with interfaces. In the code you have posted, you don't need to implement AutoCloseable.

You only have to (or should) implement Closeable or AutoCloseable if you are about to implement your own PrintWriter, which handles files or any other resources which needs to be closed.

In your implementation, it is enough to call pw.close(). You should do this in a finally block:

PrintWriter pw = null;
try {
   File file = new File("C:\\test.txt");
   pw = new PrintWriter(file);
} catch (IOException e) {
   System.out.println("bad things happen");
} finally {
   if (pw != null) {
      try {
         pw.close();
      } catch (IOException e) {
      }
   }
}

The code above is Java 6 related. In Java 7 this can be done more elegantly (see this answer).

Getting the name of the currently executing method

Util.java:

public static String getCurrentClassAndMethodNames() {
    final StackTraceElement e = Thread.currentThread().getStackTrace()[2];
    final String s = e.getClassName();
    return s.substring(s.lastIndexOf('.') + 1, s.length()) + "." + e.getMethodName();
}

SomeClass.java:

public class SomeClass {
    public static void main(String[] args) {
        System.out.println(Util.getCurrentClassAndMethodNames()); // output: SomeClass.main
    }
}

Twitter bootstrap collapse: change display of toggle button

You do like this. the function return the old text.

$('button').click(function(){ 
        $(this).text(function(i,old){
            return old=='Read More' ?  'Read Less' : 'Read More';
        });
    });

Android Studio 3.0 Execution failed for task: unable to merge dex

Same thing happened to me, figured out that I was in the middle of updating to AS 3.0.1 and after I did the update, cleaned and rebuilt the app, everything was fixed.

Binary search (bisection) in Python

I needed binary search in python and generic for Django models. In Django models, one model can have foreign key to another model and I wanted to perform some search on the retrieved models objects. I wrote following function you can use this.

def binary_search(values, key, lo=0, hi=None, length=None, cmp=None):
    """
    This is a binary search function which search for given key in values.
    This is very generic since values and key can be of different type.
    If they are of different type then caller must specify `cmp` function to
    perform a comparison between key and values' item.
    :param values:  List of items in which key has to be search
    :param key: search key
    :param lo: start index to begin search
    :param hi: end index where search will be performed
    :param length: length of values
    :param cmp: a comparator function which can be used to compare key and values
    :return: -1 if key is not found else index
    """
    assert type(values[0]) == type(key) or cmp, "can't be compared"
    assert not (hi and length), "`hi`, `length` both can't be specified at the same time"

    lo = lo
    if not lo:
        lo = 0
    if hi:
        hi = hi
    elif length:
        hi = length - 1
    else:
        hi = len(values) - 1

    while lo <= hi:
        mid = lo + (hi - lo) // 2
        if not cmp:
            if values[mid] == key:
                return mid
            if values[mid] < key:
                lo = mid + 1
            else:
                hi = mid - 1
        else:
            val = cmp(values[mid], key)
            # 0 -> a == b
            # > 0 -> a > b
            # < 0 -> a < b
            if val == 0:
                return mid
            if val < 0:
                lo = mid + 1
            else:
                hi = mid - 1
    return -1

Intellisense and code suggestion not working in Visual Studio 2012 Ultimate RC

I had been facing this problems since 2 weeks, finally figured it out using a Sysinternal tool called Process monitor (ProcMon.exe). The problem has to do with the automatic updates settings. I applied the below solution and got it working

Solution: Tools -> Options -> Environment -> Extensions and Updates -> (uncheck) Automatically check for updates->OK

How does numpy.newaxis work and when to use it?

Simply put, numpy.newaxis is used to increase the dimension of the existing array by one more dimension, when used once. Thus,

  • 1D array will become 2D array

  • 2D array will become 3D array

  • 3D array will become 4D array

  • 4D array will become 5D array

and so on..

Here is a visual illustration which depicts promotion of 1D array to 2D arrays.

newaxis canva visualization


Scenario-1: np.newaxis might come in handy when you want to explicitly convert a 1D array to either a row vector or a column vector, as depicted in the above picture.

Example:

# 1D array
In [7]: arr = np.arange(4)
In [8]: arr.shape
Out[8]: (4,)

# make it as row vector by inserting an axis along first dimension
In [9]: row_vec = arr[np.newaxis, :]     # arr[None, :]
In [10]: row_vec.shape
Out[10]: (1, 4)

# make it as column vector by inserting an axis along second dimension
In [11]: col_vec = arr[:, np.newaxis]     # arr[:, None]
In [12]: col_vec.shape
Out[12]: (4, 1)

Scenario-2: When we want to make use of numpy broadcasting as part of some operation, for instance while doing addition of some arrays.

Example:

Let's say you want to add the following two arrays:

 x1 = np.array([1, 2, 3, 4, 5])
 x2 = np.array([5, 4, 3])

If you try to add these just like that, NumPy will raise the following ValueError :

ValueError: operands could not be broadcast together with shapes (5,) (3,)

In this situation, you can use np.newaxis to increase the dimension of one of the arrays so that NumPy can broadcast.

In [2]: x1_new = x1[:, np.newaxis]    # x1[:, None]
# now, the shape of x1_new is (5, 1)
# array([[1],
#        [2],
#        [3],
#        [4],
#        [5]])

Now, add:

In [3]: x1_new + x2
Out[3]:
array([[ 6,  5,  4],
       [ 7,  6,  5],
       [ 8,  7,  6],
       [ 9,  8,  7],
       [10,  9,  8]])

Alternatively, you can also add new axis to the array x2:

In [6]: x2_new = x2[:, np.newaxis]    # x2[:, None]
In [7]: x2_new     # shape is (3, 1)
Out[7]: 
array([[5],
       [4],
       [3]])

Now, add:

In [8]: x1 + x2_new
Out[8]: 
array([[ 6,  7,  8,  9, 10],
       [ 5,  6,  7,  8,  9],
       [ 4,  5,  6,  7,  8]])

Note: Observe that we get the same result in both cases (but one being the transpose of the other).


Scenario-3: This is similar to scenario-1. But, you can use np.newaxis more than once to promote the array to higher dimensions. Such an operation is sometimes needed for higher order arrays (i.e. Tensors).

Example:

In [124]: arr = np.arange(5*5).reshape(5,5)

In [125]: arr.shape
Out[125]: (5, 5)

# promoting 2D array to a 5D array
In [126]: arr_5D = arr[np.newaxis, ..., np.newaxis, np.newaxis]    # arr[None, ..., None, None]

In [127]: arr_5D.shape
Out[127]: (1, 5, 5, 1, 1)

As an alternative, you can use numpy.expand_dims that has an intuitive axis kwarg.

# adding new axes at 1st, 4th, and last dimension of the resulting array
In [131]: newaxes = (0, 3, -1)
In [132]: arr_5D = np.expand_dims(arr, axis=newaxes)
In [133]: arr_5D.shape
Out[133]: (1, 5, 5, 1, 1)

More background on np.newaxis vs np.reshape

newaxis is also called as a pseudo-index that allows the temporary addition of an axis into a multiarray.

np.newaxis uses the slicing operator to recreate the array while numpy.reshape reshapes the array to the desired layout (assuming that the dimensions match; And this is must for a reshape to happen).

Example

In [13]: A = np.ones((3,4,5,6))
In [14]: B = np.ones((4,6))
In [15]: (A + B[:, np.newaxis, :]).shape     # B[:, None, :]
Out[15]: (3, 4, 5, 6)

In the above example, we inserted a temporary axis between the first and second axes of B (to use broadcasting). A missing axis is filled-in here using np.newaxis to make the broadcasting operation work.


General Tip: You can also use None in place of np.newaxis; These are in fact the same objects.

In [13]: np.newaxis is None
Out[13]: True

P.S. Also see this great answer: newaxis vs reshape to add dimensions

What does "atomic" mean in programming?

It's something that "appears to the rest of the system to occur instantaneously", and falls under categorisation of Linearizability in computing processes. To quote that linked article further:

Atomicity is a guarantee of isolation from concurrent processes. Additionally, atomic operations commonly have a succeed-or-fail definition — they either successfully change the state of the system, or have no apparent effect.

So, for instance, in the context of a database system, one can have 'atomic commits', meaning that you can push a changeset of updates to a relational database and those changes will either all be submitted, or none of them at all in the event of failure, in this way data does not become corrupt, and consequential of locks and/or queues, the next operation will be a different write or a read, but only after the fact. In the context of variables and threading this is much the same, applied to memory.

Your quote highlights that this need not be expected behaviour in all instances.

C# Form.Close vs Form.Dispose

Using usingis a pretty good way:

using (MyForm foo = new MyForm())
{
    if (foo.ShowDialog() == DialogResult.OK)
    {
        // your code
    }
}

Check if current date is between two dates Oracle SQL

TSQL: Dates- need to look for gaps in dates between Two Date

select
distinct
e1.enddate,
e3.startdate,
DATEDIFF(DAY,e1.enddate,e3.startdate)-1 as [Datediff]
from #temp e1 
   join #temp e3 on e1.enddate < e3.startdate          
       /* Finds the next start Time */
and e3.startdate = (select min(startdate) from #temp e5
where e5.startdate > e1.enddate)
and not exists (select *  /* Eliminates e1 rows if it is overlapped */
from #temp e5 
where e5.startdate < e1.enddate and e5.enddate > e1.enddate);

Python: count repeated elements in the list

This works for Python 2.6.6

a = ["a", "b", "a"]
result = dict((i, a.count(i)) for i in a)
print result

prints

{'a': 2, 'b': 1}

Changing Locale within the app itself

I couldn't used android:anyDensity="true" because objects in my game would be positioned completely different... seems this also does the trick:

// creating locale
Locale locale2 = new Locale(loc); 
Locale.setDefault(locale2);
Configuration config2 = new Configuration();
config2.locale = locale2;

// updating locale
mContext.getResources().updateConfiguration(config2, null);

How to use relative paths without including the context root name?

This could be done simpler:

<base href="${pageContext.request.contextPath}/"/>

All URL will be formed without unnecessary domain:port but with application context.

Check if a string has white space

Your regex won't match anything, as it is. You definitely need to remove the quotes -- the "/" characters are sufficient.

/^\s+$/ is checking whether the string is ALL whitespace:

  • ^ matches the start of the string.
  • \s+ means at least 1, possibly more, spaces.
  • $ matches the end of the string.

Try replacing the regex with /\s/ (and no quotes)

Convert string in base64 to image and save on filesystem in Python

Try this solution,

image file --> binary encoded string

binary encoded string --> image file

import base64

"""
1st step - convert image into binary
"""
with open("original_image.png", "rb") as original_file:
    encoded_string = base64.b64encode(original_file.read())

print(encoded_string)
# xmzWowsfJbpGwCe0DTveqwvos7Mf0lcVNe/Q+G1hO/p+UNPd/stUse8AhP/3fDixf8HI3No67nvhlYAAAAASUVORK5CYII='

print(type(encoded_string))
# <class 'bytes'>

"""
2nd step - create new image using the encoded string
"""
with open("new_image.png", "wb") as new_file:
    new_file.write(base64.decodebytes(encoded_string))

References:

How to use MySQL dump from a remote machine

This is how you would restore a backup after you successfully backup your .sql file

mysql -u [username] [databasename]

And choose your sql file with this command:

source MY-BACKED-UP-DATABASE-FILE.sql

Laravel 5 Eloquent where and or in Clauses

Also, if you have a variable,

CabRes::where('m_Id', 46)
      ->where('t_Id', 2)
      ->where(function($q) use ($variable){
          $q->where('Cab', 2)
            ->orWhere('Cab', $variable);
      })
      ->get();

Merging 2 branches together in GIT

merge is used to bring two (or more) branches together.

a little example:

# on branch A:
# create new branch B
$ git checkout -b B
# hack hack
$ git commit -am "commit on branch B"

# create new branch C from A
$ git checkout -b C A
# hack hack
$ git commit -am "commit on branch C"

# go back to branch A
$ git checkout A
# hack hack
$ git commit -am "commit on branch A"

so now there are three separate branches (namely A B and C) with different heads

to get the changes from B and C back to A, checkout A (already done in this example) and then use the merge command:

# create an octopus merge
$ git merge B C

your history will then look something like this:

…-o-o-x-------A
      |\     /|
      | B---/ |
       \     /
        C---/

if you want to merge across repository/computer borders, have a look at git pull command, e.g. from the pc with branch A (this example will create two new commits):

# pull branch B
$ git pull ssh://host/… B
# pull branch C
$ git pull ssh://host/… C

How to fix syntax error, unexpected T_IF error in php?

PHP parser errors take some getting used to; if it complains about an unexpected 'something' at line X, look at line X-1 first. In this case it will not tell you that you forgot a semi-colon at the end of the previous line , instead it will complain about the if that comes next.

You'll get used to it :)

How to calculate DATE Difference in PostgreSQL?

This is how I usually do it. A simple number of days perspective of B minus A.

DATE_PART('day', MAX(joindate) - MIN(joindate)) as date_diff

Display a loading bar before the entire page is loaded

I've recently made a page loader in vanilla .js for a project, just wanted to share it as all the other answers are jQuery based. It's a plug and play, one-liner.

It automatically creates a <div> tag prepended to the <body>, with a <svg> loader. If you want to customize the color you just have to update the t variable at the beginning of the script.

var t="#106CF6",u=document.querySelector("*"),s=document.createElement("style"),a=document.createElement("aside"),m="http://www.w3.org/2000/svg",g=document.createElementNS(m,"svg"),c=document.createElementNS(m,"circle");document.head.appendChild(s),(s.innerHTML="#sailor {background:"+t+";color:"+t+";display:flex;align-items:center;justify-content:center;position:fixed;top:0;height:100vh;width:100vw;z-index:2147483647}@keyframes swell{to{transform:rotate(360deg)}}#sailor svg{animation:.3s swell infinite linear}"),a.setAttribute("id","sailor"),document.body.prepend(a),g.setAttribute("height","50"),g.setAttribute("filter","brightness(175%)"),g.setAttribute("viewBox","0 0 100 100"),a.prepend(g),c.setAttribute("cx","50"),c.setAttribute("cy","50"),c.setAttribute("r","35"),c.setAttribute("fill","none"),c.setAttribute("stroke","currentColor"),c.setAttribute("stroke-dasharray","165 57"),c.setAttribute("stroke-width","10"),g.prepend(c),(u.style.pointerEvents="none"),(u.style.userSelect="none"),(u.style.cursor="wait"),window.addEventListener("load",function(){setTimeout(function(){(u.style.pointerEvents=""),(u.style.userSelect=""),(u.style.cursor="");a.remove()},100)})

You can see the full project and documentation on the GitHub

How to enable multidexing with the new Android Multidex support library

build.gradle

multiDexEnabled true
implementation 'androidx.multidex:multidex:2.0.1'

AndroidManifest.xml

<application
    android:name="androidx.multidex.MultiDexApplication"

ERROR 2013 (HY000): Lost connection to MySQL server at 'reading authorization packet', system error: 0

Another possibility can be connection reset from the TCP wrappers (/etc/hosts.deny and /etc/hosts.allow). Just check what is coming in from the telnet to port 3306 - if it is nothing, then there is something is in the middle preventing communication from happening.

How to use "Share image using" sharing Intent to share images in android?

All the Above solution doesnot work for me in Android Api 26 & 27 (Oreo), was gettting Error: exposed beyond app through ClipData.Item.getUri. The solution that fits in my situation was

  1. get path uri using FileProvider.getUriForFile(Context,packagename,File) as
void shareImage() {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(this,getPackageName(),deleteFilePath));
        startActivity(Intent.createChooser(intent,"Share with..."));
    }
  1. Define a <provider> in your Manifest.xml as
<provider
     android:name="android.support.v4.content.FileProvider"
     android:authorities="com.example.stickerapplication"
      android:exported="false"
      android:grantUriPermissions="true">
      <meta-data
          android:name="android.support.FILE_PROVIDER_PATHS"
          android:resource="@xml/file_paths">
       </meta-data>
</provider>
  1. And the last step is to define resource file for your directorys
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="." />
</paths>
*Note this solution is for `external storage` `uri`

Jackson serialization: ignore empty values (or null)

You can also set the global option:

objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

Input type for HTML form for integer

No, it is not about the data type of input. It specifies the type of control to create:

type = text|password|checkbox|radio|submit|reset|file|hidden|image|button [CI] This attribute specifies the type of control to create. The default value for this attribute is "text".

Update built-in vim on Mac OS X

I just installed vim by:

brew install vim

now the new vim is accessed by vim and the old vim (built-in vim) by vi

How to debug JavaScript / jQuery event bindings with Firebug or similar tools?

Using DevTools in the latest Chrome (v29) I find these two tips very helpful for debugging events:

  1. Listing jQuery events of the last selected DOM element

    • Inspect an element on the page
    • type the following in the console:

      $._data($0, "events") //assuming jQuery 1.7+

    • It will list all jQuery event objects associated with it, expand the interested event, right-click on the function of the "handler" property and choose "Show function definition". It will open the file containing the specified function.

  2. Utilizing the monitorEvents() command

'cl' is not recognized as an internal or external command,

For me, this was related to the scenario described by Smi, with the difference being that vcvarsall.bat itself was failing due to an invalid path.

This was cause by line-breaks within the path, which meant vcvarsall.bat couldn't find the common tools directory for some reason.

What are XAND and XOR

XOR is short for exclusive or. It is a logical, binary operator that requires that one of the two operands be true but not both.

So these statements are true:

TRUE XOR FALSE
FALSE XOR TRUE

And these statements are false:

FALSE XOR FALSE
TRUE XOR TRUE

There really isn't such a thing as an"exclusive and" (or XAND) since in theory it would have the same exact requirements as XOR. There also isn't an XNOT since NOT is a unary operator that negates its single operand (basically it just flips a boolean value to its opposite) and as such it cannot support any notion of exclusivity.

MySQL error 1449: The user specified as a definer does not exist

// update all or particular procedures to your wanted, use existing user (my case -root)

1) UPDATE mysql.proc p SET definer = 'root@%' WHERE 1=1 LIMIT 1000; (limit clause is for the reason that various mysql versions complains when is updated not restricted with limit or no where condition is used)

2) FLUSH PRIVILEGES; // or restart the server