Programs & Examples On #Classcastexception

The Java exception thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.

android.app.Application cannot be cast to android.app.Activity

In my case, when I'm in an activity that extends from AppCompatActivity, it did not work(Activity) getApplicationContext (), I just putthis in its place.

explicit casting from super class to subclass

In order to avoid this kind of ClassCastException, if you have:

class A
class B extends A

You can define a constructor in B that takes an object of A. This way we can do the "cast" e.g.:

public B(A a) {
    super(a.arg1, a.arg2); //arg1 and arg2 must be, at least, protected in class A
    // If B class has more attributes, then you would initilize them here
}

ClassCastException, casting Integer to Double

Integer x=10;
Double y = x.doubleValue();

Explanation of "ClassCastException" in Java

Straight from the API Specifications for the ClassCastException:

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.

So, for example, when one tries to cast an Integer to a String, String is not an subclass of Integer, so a ClassCastException will be thrown.

Object i = Integer.valueOf(42);
String s = (String)i;            // ClassCastException thrown here.

Test method is inconclusive: Test wasn't run. Error?

Very strange behavior.

Just moved a new appsetting entry recently added to the bottom of the app.config solved my issue.

<appSettings>
    <add key="xxxxxx" value="xxxxx" />
</appSettings>

Hope this helps someone

How to create a link to a directory

you should use :

ln -s /home/jake/doc/test/2000/something xxx

How to use an output parameter in Java?

Wrap the value passed in different classes that might be helpful doing the trick, check below for more real example:

  class Ref<T>{

    T s;

    public void set(T value){
        s =  value;
    }

    public T get(){
        return s;
    }

    public Ref(T value) {
        s = value;
    }
}


class Out<T>{

    T s;

    public void set(T value){
        s =  value;
    }
    public T get(){
        return s;
    }

    public Out() {
    }
}

public static void doAndChangeRefs (Ref<String> str, Ref<Integer> i, Out<String> str2){
    //refs passed .. set value
    str.set("def");
    i.set(10);

    //out param passed as null .. instantiate and set 
    str2 = new Out<String>();
    str2.set("hello world");
}
public static void main(String args[]) {
        Ref<Integer>  iRef = new Ref<Integer>(11);
        Out<String> strOut = null; 
        doAndChangeRefs(new Ref<String>("test"), iRef, strOut);
        System.out.println(iRef.get());
        System.out.println(strOut.get());

    }

Best way to serialize/unserialize objects in JavaScript?

I had a similar problem and since I couldn't find a sufficient solution, I also created a serialization library for javascript: https://github.com/wavesoft/jbb (as a matter of fact it's a bit more, since it's mainly intended for bundling resources)

It is close to Binary-JSON but it adds a couple of additional features, such as metadata for the objects being encoded and some extra optimizations like data de-duplication, cross-referencing to other bundles and structure-level compression.

However there is a catch: In order to keep the bundle size small there are no type information in the bundle. Such information are provided in a separate "profile" that describes your objects for encoding and decoding. For optimization reasons this information is given in a form of script.

But you can make your life easier using the gulp-jbb-profile (https://github.com/wavesoft/gulp-jbb-profile) utility for generating the encodeing/decoding scripts from simple YAML object specifications like this:

# The 'Person' object has the 'age' and 'isOld'
# properties
Person:
  properties:
    - age
    - isOld

For example you can have a look on the jbb-profile-three profile. When you have your profile ready, you can use JBB like this:

var JBBEncoder = require('jbb/encode');
var MyEncodeProfile = require('profile/profile-encode');

// Create a new bundle
var bundle = new JBBEncoder( 'path/to/bundle.jbb' );

// Add one or more profile(s) in order for JBB
// to understand your custom objects
bundle.addProfile(MyEncodeProfile);

// Encode your object(s) - They can be any valid
// javascript object, or objects described in
// the profiles you added previously.

var p1 = new Person(77);
bundle.encode( p1, 'person' );

var people = [
        new Person(45),
        new Person(77),
        ...
    ];
bundle.encode( people, 'people' );

// Close the bundle when you are done
bundle.close();

And you can read it back like this:

var JBBDecoder = require('jbb/decode');
var MyDecodeProfile = require('profile/profile-decode');

// Instantiate a new binary decoder
var binaryLoader = new JBBDecoder( 'path/to/bundle' );

// Add your decoding profile
binaryLoader.addProfile( MyDecodeProfile );

// Add one or more bundles to load
binaryLoader.add( 'bundle.jbb' );

// Load and callback when ready
binaryLoader.load(function( error, database ) {

    // Your objects are in the database
    // and ready to use!
    var people = database['people'];

});

Apache SSL Configuration Error (SSL Connection Error)

A common cause I wanted to suggest for this situation:

Sometimes a customer is running Skype, which is using port 443 without their realizing it. When they go to start Tomcat or Apache, it appears to start but cannot bind with port 443. This is the exact message that the user would receive in the browser. The fix is to stop what was running on port 443 and re-start the webserver so it can bind with port 443.

The customer can re-start Skype after starting the webserver, and Skype will detect that port 443 is in use and choose a different port to use.

Do while loop in SQL Server 2008

You can also use an exit variable if you want your code to be a bit more readable:

DECLARE @Flag int = 0
DECLARE @Done bit = 0

WHILE @Done = 0 BEGIN
    SET @Flag = @Flag + 1
    PRINT @Flag
    IF @Flag >= 5 SET @Done = 1
END

This would probably be more relevant when you have a more complicated loop and are trying to keep track of the logic. As stated loops are expensive so try and use other methods if you can.

adb is not recognized as internal or external command on windows

You have two ways:

First go to the particular path of Android SDK:

1) Open your command prompt and traverse to the platform-tools directory through it such as

$ cd Frameworks\Android-Sdk\platform-tools

2) Run your adb commands now such as to know that your adb is working properly :

$ adb devices OR adb logcat OR simply adb

Second way is :

1) Right click on your My Computer.

2) Open Environment variables.

3) Add new variable to your System PATH variable(Add if not exist otherwise no need to add new variable if already exist).

4) Add path of platform-tools directory to as value of this variable such as C:\Program Files\android-sdk\platform-tools.

5) Restart your computer once.

6) Now run the above adb commands such adb devices or other adb commands from anywhere in command prompt.

Also on you can fire a command on terminal setx PATH "%PATH%;C:\Program Files\android-sdk\platform-tools"

Is there a portable way to get the current username in Python?

These might work. I don't know how they behave when running as a service. They aren't portable, but that's what os.name and ifstatements are for.

win32api.GetUserName()

win32api.GetUserNameEx(...) 

See: http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html

Sockets: Discover port availability using Java

I have Tried something Like this and it worked really fine with me

            Socket Skt;
            String host = "localhost";
            int i = 8983; // port no.

                 try {
                    System.out.println("Looking for "+ i);
                    Skt = new Socket(host, i);
                    System.out.println("There is a Server on port "
                    + i + " of " + host);
                 }
                 catch (UnknownHostException e) {
                    System.out.println("Exception occured"+ e);

                 }
                 catch (IOException e) {
                     System.out.println("port is not used");

                 }

Can't concatenate 2 arrays in PHP

Both will have a key of 0, and that method of combining the arrays will collapse duplicates. Try using array_merge() instead.

$arr1 = array('foo'); // Same as array(0 => 'foo')
$arr2 = array('bar'); // Same as array(0 => 'bar')

// Will contain array('foo', 'bar');
$combined = array_merge($arr1, $arr2);

If the elements in your array used different keys, the + operator would be more appropriate.

$arr1 = array('one' => 'foo');
$arr2 = array('two' => 'bar');

// Will contain array('one' => 'foo', 'two' => 'bar');
$combined = $arr1 + $arr2;

Edit: Added a code snippet to clarify

Passing argument to alias in bash

To simplify leed25d's answer, use a combination of an alias and a function. For example:

function __GetIt {
    cp ./path/to/stuff/$* .
}

alias GetIt='__GetIt'

Oracle SQL, concatenate multiple columns + add text

Try this:

SELECT 'I like ' || type_column_name || ' cake with ' || 
icing_column_name || ' and a ' fruit_column_name || '.' 
AS Cake_Column FROM your_table_name;

It should concatenate all that data as a single column entry named "Cake_Column".

Hive cast string to date dd-MM-yyyy

AFAIK you must reformat your String in ISO format to be able to cast it as a Date:

cast(concat(substr(STR_DMY,7,4), '-',
            substr(STR_DMY,1,2), '-',
            substr(STR_DMY,4,2)
           )
     as date
     ) as DT

To display a Date as a String with specific format, then it's the other way around, unless you have Hive 1.2+ and can use date_format()

=> did you check the documentation by the way?

How to see local history changes in Visual Studio Code?

I built an extension called Checkpoints, an alternative to Local History. Checkpoints has support for viewing history for all files (that has checkpoints) in the tree view, not just the currently active file. There are some other minor differences aswell, but overall they are pretty similar.

Indenting code in Sublime text 2?

No one seems to love mac re-indentation, So here How I do it:

[
   { "keys": ["command+shift+i"], "command": "reindent"}
]

In Preferences > Key Binding - User

One more extra tip: add

{ "keys": ["command+0"], "command": "focus_side_bar" }

to have sidebar file tree view navigation using keyboard.

Note: Add , at the end of each {}, if you have more than one {} set of objects

MySQL Sum() multiple columns

SELECT student, SUM(mark1+mark2+mark3+....+markn) AS Total FROM your_table

How to do multiple conditions for single If statement

As Hogan notes above, use an AND instead of &. See this tutorial for more info.

Comparing two input values in a form validation with AngularJS

One way to achieve this is with a custom directive. Here's an example using a custom directive (ng-match in this case):

<p>Email:<input type="email" name="email1" ng-model="emailReg">
Repeat Email:<input type="email" name="email2" ng-model="emailReg2" ng-match="emailReg"></p>

<span data-ng-show="myForm.emailReg2.$error.match">Emails have to match!</span>

NOTE: It's not generally recommended to use ng- as a prefix for a custom directive because it may conflict with an official AngularJS directive.

Update

It's also possible to get this functionality without using a custom directive:

HTML

<button ng-click="add()></button>
<span ng-show="IsMatch">Emails have to match!</span>

Controller

$scope.add = function() {
  if ($scope.emailReg != $scope.emailReg2) {
    $scope.IsMatch=true;
    return false;
  }
  $scope.IsMatch=false;
}

git remote add with other SSH port

Rather than using the ssh:// protocol prefix, you can continue using the conventional URL form for accessing git over SSH, with one small change. As a reminder, the conventional URL is:

git@host:path/to/repo.git

To specify an alternative port, put brackets around the user@host part, including the port:

[git@host:port]:path/to/repo.git

But if the port change is merely temporary, you can tell git to use a different SSH command instead of changing your repository’s remote URL:

export GIT_SSH_COMMAND='ssh -p port'
git clone git@host:path/to/repo.git # for instance

Convert JsonNode into POJO

If you're using org.codehaus.jackson, this has been possible since 1.6. You can convert a JsonNode to a POJO with ObjectMapper#readValue: http://jackson.codehaus.org/1.9.4/javadoc/org/codehaus/jackson/map/ObjectMapper.html#readValue(org.codehaus.jackson.JsonNode, java.lang.Class)


    ObjectMapper mapper = new ObjectMapper();
    JsonParser jsonParser = mapper.getJsonFactory().createJsonParser("{\"foo\":\"bar\"}");
    JsonNode tree = jsonParser.readValueAsTree();
    // Do stuff to the tree
    mapper.readValue(tree, Foo.class);

Metadata file '.dll' could not be found

As user @burzhuy points out, it can be important to look at the Outputwindow, and not just the Error List window.

In my case I was working on making modifications to the Roslyn compiler. Its build projects run an extra check to see if the public fields are consistent with what has been defined as the compiler's public interface, otherwise it produces an RS0016 or RS0017 error. I had added a couple of public fields, and fixed the RS0016 error by hovering the mouse over the error and selecting "Add to public API".

Later I changed my mind and moved the public fields to a different class. For some reason this produced the "Metadata file could not be found error", and the more I fiddled with it the more errors I got.

You need to to find the correct PublicAPI.Unshipped.txtfile (in my case it was in E:\Roslyn\32414\src\Compilers\Core\Portable) and edit it manually to remove the lines that are no longer relevant.

How to import an existing directory into Eclipse?

The thing that works best for me when that happens is :

  1. Create a new eclipse project(JAVA)

  2. Take your source file (contents of the src folder!!!) and drag from finder and drop into the src folder in eclipse IDE

  3. Make sure you add your external jars and stuff and tada you're done!!

Convert Base64 string to an image file?

$datetime = date("Y-m-d h:i:s");
$timestamp = strtotime($datetime);
$image = $_POST['image'];
$imgdata = base64_decode($image);
$f = finfo_open();
$mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);
$temp=explode('/',$mime_type);
$path = "uploads/$timestamp.$temp[1]";
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded->>> $timestamp.$temp[1]";

This will be enough for image processing. Special thanks to Mr. Dev Karan Sharma

Unable to find valid certification path to requested target - error even after cert imported

You need to configuring JSSE System Properties, specifically point to client certificate store.

Via command line:

java -Djavax.net.ssl.trustStore=truststores/client.ts com.progress.Client

or via Java code:

import java.util.Properties;
    ...
    Properties systemProps = System.getProperties();
    systemProps.put("javax.net.ssl.keyStorePassword","passwordForKeystore");
    systemProps.put("javax.net.ssl.keyStore","pathToKeystore.ks");
    systemProps.put("javax.net.ssl.trustStore", "pathToTruststore.ts");
    systemProps.put("javax.net.ssl.trustStorePassword","passwordForTrustStore");
    System.setProperties(systemProps);
    ...

For more refer to details on RedHat site.

Sequence contains no matching element

Use FirstOrDefault. First will never return null - if it can't find a matching element it throws the exception you're seeing.

_dsACL.Documents.FirstOrDefault(o => o.ID == id);

How to solve munmap_chunk(): invalid pointer error in C++

The hint is, the output file is created even if you get this error. The automatic deconstruction of vector starts after your code executed. Elements in the vector are deconstructed as well. This is most probably where the error occurs. The way you access the vector is through vector::operator[] with an index read from stream. Try vector::at() instead of vector::operator[]. This won't solve your problem, but will show which assignment to the vector causes error.

An array of List in c#

// The letter "t" is usually letter "i"//

    for(t=0;t<x[t];t++)
    {

         printf(" %2d          || %7d \n ",t,x[t]);
    }

Return JSON with error status code MVC

The neatest solution I've found is to create your own JsonResult that extends the original implementation and allows you to specify a HttpStatusCode:

public class JsonHttpStatusResult : JsonResult
{
    private readonly HttpStatusCode _httpStatus;

    public JsonHttpStatusResult(object data, HttpStatusCode httpStatus)
    {
        Data = data;
        _httpStatus = httpStatus;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        context.RequestContext.HttpContext.Response.StatusCode = (int)_httpStatus;
        base.ExecuteResult(context);
    }
}

You can then use this in your controller action like so:

if(thereWereErrors)
{
    var errorModel = new { error = "There was an error" };
    return new JsonHttpStatusResult(errorModel, HttpStatusCode.InternalServerError);
}

How to remove class from all elements jquery

You need to select the li tags contained within the .edgetoedge class. .edgetoedge only matches the one ul tag:

$(".edgetoedge li").removeClass("highlight");

Android OnClickListener - identify a button

use setTag();

like this:

@Override    
public void onClick(View v) {     
    int tag = (Integer) v.getTag();     
    switch (tag) {     
    case 1:     
        System.out.println("button1 click");     
        break;     
    case 2:     
        System.out.println("button2 click");     
       break;   
    }     
}     

Copy Data from a table in one Database to another separate database

SELECT ... INTO creates a new table. You'll need to use INSERT. Also, you have the database and owner names reversed.

INSERT INTO DB1.dbo.TempTable
SELECT * FROM DB2.dbo.TempTable

Why do I need to override the equals and hashCode methods in Java?

1) The common mistake is shown in the example below.

public class Car {

    private String color;

    public Car(String color) {
        this.color = color;
    }

    public boolean equals(Object obj) {
        if(obj==null) return false;
        if (!(obj instanceof Car))
            return false;   
        if (obj == this)
            return true;
        return this.color.equals(((Car) obj).color);
    }

    public static void main(String[] args) {
        Car a1 = new Car("green");
        Car a2 = new Car("red");

        //hashMap stores Car type and its quantity
        HashMap<Car, Integer> m = new HashMap<Car, Integer>();
        m.put(a1, 10);
        m.put(a2, 20);
        System.out.println(m.get(new Car("green")));
    }
}

the green Car is not found

2. Problem caused by hashCode()

The problem is caused by the un-overridden method hashCode(). The contract between equals() and hashCode() is:

  1. If two objects are equal, then they must have the same hash code.
  2. If two objects have the same hash code, they may or may not be equal.

    public int hashCode(){  
      return this.color.hashCode(); 
    }
    

Subtract 1 day with PHP

Answear taken from Php manual strtotime function comments :

echo date( "Y-m-d", strtotime( "2009-01-31 -1 day"));

Or

$date = "2009-01-31";
echo date( "Y-m-d", strtotime( $date . "-1 day"));

Difference between objectForKey and valueForKey?

Here's a great reason to use objectForKey: wherever possible instead of valueForKey: - valueForKey: with an unknown key will throw NSUnknownKeyException saying "this class is not key value coding-compliant for the key ".

Mythical man month 10 lines per developer day - how close on large projects?

One suspects this perennial bit of manager-candy was coined when everything was a sys app written in C because if nothing else the magic number would vary by orders of magnitude depending on the language, scale and nature of the application. And then you have to discount comments and attributes. And ultimately who cares about the number of lines of code written? Are you supposed to be finished when you've reach 10K lines? 100K? So arbitrary.

It's useless.

Is there a way to get rid of accents and convert a whole string to regular letters?

As of 2011 you can use Apache Commons StringUtils.stripAccents(input) (since 3.0):

    String input = StringUtils.stripAccents("Thïs iš â funky Štring");
    System.out.println(input);
    // Prints "This is a funky String"

Note:

The accepted answer (Erick Robertson's) doesn't work for Ø or L. Apache Commons 3.5 doesn't work for Ø either, but it does work for L. After reading the Wikipedia article for Ø, I'm not sure it should be replaced with "O": it's a separate letter in Norwegian and Danish, alphabetized after "z". It's a good example of the limitations of the "strip accents" approach.

Can you write virtual functions / methods in Java?

Can you write virtual functions in Java?

Yes. In fact, all instance methods in Java are virtual by default. Only certain methods are not virtual:

  • Class methods (because typically each instance holds information like a pointer to a vtable about its specific methods, but no instance is available here).
  • Private instance methods (because no other class can access the method, the calling instance has always the type of the defining class itself and is therefore unambiguously known at compile time).

Here are some examples:

"Normal" virtual functions

The following example is from an old version of the wikipedia page mentioned in another answer.

import java.util.*;

public class Animal 
{
   public void eat() 
   { 
      System.out.println("I eat like a generic Animal."); 
   }

   public static void main(String[] args) 
   {
      List<Animal> animals = new LinkedList<Animal>();

      animals.add(new Animal());
      animals.add(new Fish());
      animals.add(new Goldfish());
      animals.add(new OtherAnimal());

      for (Animal currentAnimal : animals) 
      {
         currentAnimal.eat();
      }
   }
}

class Fish extends Animal 
{
   @Override
   public void eat() 
   { 
      System.out.println("I eat like a fish!"); 
   }
}

class Goldfish extends Fish 
{
   @Override
   public void eat() 
   { 
      System.out.println("I eat like a goldfish!"); 
   }
}

class OtherAnimal extends Animal {}

Output:

I eat like a generic Animal.
I eat like a fish!
I eat like a goldfish!
I eat like a generic Animal.

Example with virtual functions with interfaces

Java interface methods are all virtual. They must be virtual because they rely on the implementing classes to provide the method implementations. The code to execute will only be selected at run time.

For example:

interface Bicycle {         //the function applyBrakes() is virtual because
    void applyBrakes();     //functions in interfaces are designed to be 
}                           //overridden.

class ACMEBicycle implements Bicycle {
    public void applyBrakes(){               //Here we implement applyBrakes()
       System.out.println("Brakes applied"); //function
    }
}

Example with virtual functions with abstract classes.

Similar to interfaces Abstract classes must contain virtual methods because they rely on the extending classes' implementation. For Example:

abstract class Dog {                   
    final void bark() {               //bark() is not virtual because it is 
        System.out.println("woof");   //final and if you tried to override it
    }                                 //you would get a compile time error.

    abstract void jump();             //jump() is a "pure" virtual function 
}                                     
class MyDog extends Dog{
    void jump(){
        System.out.println("boing");    //here jump() is being overridden
    }                                  
}
public class Runner {
    public static void main(String[] args) {
        Dog dog = new MyDog();       // Create a MyDog and assign to plain Dog variable
        dog.jump();                  // calling the virtual function.
                                     // MyDog.jump() will be executed 
                                     // although the variable is just a plain Dog.
    }
}

Javascript Regex: How to put a variable inside a regular expression?

You can always give regular expression as string, i.e. "ReGeX" + testVar + "ReGeX". You'll possibly have to escape some characters inside your string (e.g., double quote), but for most cases it's equivalent.

You can also use RegExp constructor to pass flags in (see the docs).

CSS: Position text in the middle of the page

Here's a method using display:flex:

_x000D_
_x000D_
.container {_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  display: flex;_x000D_
  position: fixed;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div>centered text!</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

View on Codepen
Check Browser Compatability

Convert number of minutes into hours & minutes using PHP

$m = 250;

$extraIntH = intval($m/60);

$extraIntHs = ($m/60);             // float value   

$whole = floor($extraIntHs);      //  return int value 1

$fraction = $extraIntHs - $whole; // Total - int = . decimal value

$extraIntHss =  ($fraction*60); 

$TotalHoursAndMinutesString  =  $extraIntH."h ".$extraIntHss."m";

How to decrypt a password from SQL server?

You shouldn't really be de-encrypting passwords.

You should be encrypting the password entered into your application and comparing against the encrypted password from the database.

Edit - and if this is because the password has been forgotten, then setup a mechanism to create a new password.

C# Set collection?

I know this is an old thread, but I was running into the same problem and found HashSet to be very unreliable because given the same seed, GetHashCode() returned different codes. So, I thought, why not just use a List and hide the add method like this

public class UniqueList<T> : List<T>
{
    public new void Add(T obj)
    {
        if(!Contains(obj))
        {
            base.Add(obj);
        }
    }
}

Because List uses the Equals method solely to determine equality, you can define the Equals method on your T type to make sure you get the desired results.

close fxml window by code, javafx

I found a nice solution which does not need an event to be triggered:

@FXML
private Button cancelButton;

close(new Event(cancelButton, stage, null));

@FXML
private void close(Event event) {
    ((Node)(event.getSource())).getScene().getWindow().hide();                      
}

Position Absolute + Scrolling

So gaiour is right, but if you're looking for a full height item that doesn't scroll with the content, but is actually the height of the container, here's the fix. Have a parent with a height that causes overflow, a content container that has a 100% height and overflow: scroll, and a sibling then can be positioned according to the parent size, not the scroll element size. Here is the fiddle: http://jsfiddle.net/M5cTN/196/

and the relevant code:

html:

<div class="container">
  <div class="inner">
    Lorem ipsum ...
  </div>
  <div class="full-height"></div>
</div>

css:

.container{
  height: 256px;
  position: relative;
}
.inner{
  height: 100%;
  overflow: scroll;
}
.full-height{
  position: absolute;
  left: 0;
  width: 20%;
  top: 0;
  height: 100%;
}

How to force addition instead of concatenation in javascript

The following statement appends the value to the element with the id of response

$('#response').append(total);

This makes it look like you are concatenating the strings, but you aren't, you're actually appending them to the element

change that to

$('#response').text(total);

You need to change the drop event so that it replaces the value of the element with the total, you also need to keep track of what the total is, I suggest something like the following

$(function() {
    var data = [];
    var total = 0;

    $( "#draggable1" ).draggable();
    $( "#draggable2" ).draggable();
    $( "#draggable3" ).draggable();

    $("#droppable_box").droppable({
        drop: function(event, ui) {
        var currentId = $(ui.draggable).attr('id');
        data.push($(ui.draggable).attr('id'));

        if(currentId == "draggable1"){
            var myInt1 = parseFloat($('#MealplanCalsPerServing1').val());
        }
        if(currentId == "draggable2"){
            var myInt2 = parseFloat($('#MealplanCalsPerServing2').val());
        }
        if(currentId == "draggable3"){
            var myInt3 = parseFloat($('#MealplanCalsPerServing3').val());
        }
        if ( typeof myInt1 === 'undefined' || !myInt1 ) {
            myInt1 = parseInt(0);
        }
        if ( typeof myInt2 === 'undefined' || !myInt2){
            myInt2 = parseInt(0);
        }
        if ( typeof myInt3 === 'undefined' || !myInt3){
        myInt3 = parseInt(0);
        }
        total += parseFloat(myInt1 + myInt2 + myInt3);
        $('#response').text(total);
        }
    });

    $('#myId').click(function(event) {
        $.post("process.php", ({ id: data }), function(return_data, status) {
            alert(data);
            //alert(total);
        });
    });
});

I moved the var total = 0; statement out of the drop event and changed the assignment statment from this

total = parseFloat(myInt1 + myInt2 + myInt3);

to this

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

Here is a working example http://jsfiddle.net/axrwkr/RCzGn/

How to check whether an object is a date?

Couldn't you just use

function getFormatedDate(date) {
    if (date.isValid()) {
       var month = date.GetMonth();
    }
}

Opacity CSS not working in IE8

CSS

I used to use the following from CSS-Tricks:

.transparent_class {
  /* IE 8 */
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";

  /* IE 5-7 */
  filter: alpha(opacity=50);

  /* Netscape */
  -moz-opacity: 0.5;

  /* Safari 1.x */
  -khtml-opacity: 0.5;

  /* Good browsers */
  opacity: 0.5;
}

Compass

However, a better solution is to use the Opacity Compass mixin, all you need to do is to @include opacity(0.1); and it will take care of any cross-browser issues for you. You can find an example here.

Convert PEM traditional private key to PKCS8 private key

To convert the private key from PKCS#1 to PKCS#8 with openssl:

# openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in pkcs1.key -out pkcs8.key

That will work as long as you have the PKCS#1 key in PEM (text format) as described in the question.

Setting mime type for excel document

I am using EPPlus to generate .xlsx (OpenXML format based) excel file. For sending this excel file as attachment in email I use the following MIME type and it works fine with EPPlus generated file and opens properly in ms-outlook mail client preview.

string mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
System.Net.Mime.ContentType contentType = null;
if (mimeType?.Length > 0)
{
    contentType = new System.Net.Mime.ContentType(mimeType);
}

Remove ':hover' CSS behavior from element

I also had this problem, my solution was to have an element above the element i dont want a hover effect on:

_x000D_
_x000D_
.no-hover {_x000D_
  position: relative;_x000D_
  opacity: 0.65 !important;_x000D_
  display: inline-block;_x000D_
}_x000D_
_x000D_
.no-hover::before {_x000D_
  content: '';_x000D_
  background-color: transparent;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  z-index: 60;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<button class="btn btn-primary">hover</button>_x000D_
<span class="no-hover">_x000D_
  <button class="btn btn-primary ">no hover</button>_x000D_
</span>
_x000D_
_x000D_
_x000D_

Why does git perform fast-forward merges by default?

Fast-forward merging makes sense for short-lived branches, but in a more complex history, non-fast-forward merging may make the history easier to understand, and make it easier to revert a group of commits.

Warning: Non-fast-forwarding has potential side effects as well. Please review https://sandofsky.com/blog/git-workflow.html, avoid the 'no-ff' with its "checkpoint commits" that break bisect or blame, and carefully consider whether it should be your default approach for master.

alt text
(From nvie.com, Vincent Driessen, post "A successful Git branching model")

Incorporating a finished feature on develop

Finished features may be merged into the develop branch to add them to the upcoming release:

$ git checkout develop
Switched to branch 'develop'
$ git merge --no-ff myfeature
Updating ea1b82a..05e9557
(Summary of changes)
$ git branch -d myfeature
Deleted branch myfeature (was 05e9557).
$ git push origin develop

The --no-ff flag causes the merge to always create a new commit object, even if the merge could be performed with a fast-forward. This avoids losing information about the historical existence of a feature branch and groups together all commits that together added the feature.

Jakub Narebski also mentions the config merge.ff:

By default, Git does not create an extra merge commit when merging a commit that is a descendant of the current commit. Instead, the tip of the current branch is fast-forwarded.
When set to false, this variable tells Git to create an extra merge commit in such a case (equivalent to giving the --no-ff option from the command line).
When set to 'only', only such fast-forward merges are allowed (equivalent to giving the --ff-only option from the command line).


The fast-forward is the default because:

  • short-lived branches are very easy to create and use in Git
  • short-lived branches often isolate many commits that can be reorganized freely within that branch
  • those commits are actually part of the main branch: once reorganized, the main branch is fast-forwarded to include them.

But if you anticipate an iterative workflow on one topic/feature branch (i.e., I merge, then I go back to this feature branch and add some more commits), then it is useful to include only the merge in the main branch, rather than all the intermediate commits of the feature branch.

In this case, you can end up setting this kind of config file:

[branch "master"]
# This is the list of cmdline options that should be added to git-merge 
# when I merge commits into the master branch.

# The option --no-commit instructs git not to commit the merge
# by default. This allows me to do some final adjustment to the commit log
# message before it gets commited. I often use this to add extra info to
# the merge message or rewrite my local branch names in the commit message
# to branch names that are more understandable to the casual reader of the git log.

# Option --no-ff instructs git to always record a merge commit, even if
# the branch being merged into can be fast-forwarded. This is often the
# case when you create a short-lived topic branch which tracks master, do
# some changes on the topic branch and then merge the changes into the
# master which remained unchanged while you were doing your work on the
# topic branch. In this case the master branch can be fast-forwarded (that
# is the tip of the master branch can be updated to point to the tip of
# the topic branch) and this is what git does by default. With --no-ff
# option set, git creates a real merge commit which records the fact that
# another branch was merged. I find this easier to understand and read in
# the log.

mergeoptions = --no-commit --no-ff

The OP adds in the comments:

I see some sense in fast-forward for [short-lived] branches, but making it the default action means that git assumes you... often have [short-lived] branches. Reasonable?

Jefromi answers:

I think the lifetime of branches varies greatly from user to user. Among experienced users, though, there's probably a tendency to have far more short-lived branches.

To me, a short-lived branch is one that I create in order to make a certain operation easier (rebasing, likely, or quick patching and testing), and then immediately delete once I'm done.
That means it likely should be absorbed into the topic branch it forked from, and the topic branch will be merged as one branch. No one needs to know what I did internally in order to create the series of commits implementing that given feature.

More generally, I add:

it really depends on your development workflow:

  • if it is linear, one branch makes sense.
  • If you need to isolate features and work on them for a long period of time and repeatedly merge them, several branches make sense.

See "When should you branch?"

Actually, when you consider the Mercurial branch model, it is at its core one branch per repository (even though you can create anonymous heads, bookmarks and even named branches)
See "Git and Mercurial - Compare and Contrast".

Mercurial, by default, uses anonymous lightweight codelines, which in its terminology are called "heads".
Git uses lightweight named branches, with injective mapping to map names of branches in remote repository to names of remote-tracking branches.
Git "forces" you to name branches (well, with the exception of a single unnamed branch, which is a situation called a "detached HEAD"), but I think this works better with branch-heavy workflows such as topic branch workflow, meaning multiple branches in a single repository paradigm.

get current date and time in groovy?

Date has the time part, so we only need to extract it from Date

I personally prefer the default format parameter of the Date when date and time needs to be separated instead of using the extra SimpleDateFormat

Date date = new Date()
String datePart = date.format("dd/MM/yyyy")
String timePart = date.format("HH:mm:ss")

println "datePart : " + datePart + "\ttimePart : " + timePart

Current date and time as string

#include <chrono>
#include <iostream>

int main()
{
    std::time_t ct = std::time(0);
    char* cc = ctime(&ct);

    std::cout << cc << std::endl;
    return 0;
}

see if two files have the same content in python

Yes, I think hashing the file would be the best way if you have to compare several files and store hashes for later comparison. As hash can clash, a byte-by-byte comparison may be done depending on the use case.

Generally byte-by-byte comparison would be sufficient and efficient, which filecmp module already does + other things too.

See http://docs.python.org/library/filecmp.html e.g.

>>> import filecmp
>>> filecmp.cmp('file1.txt', 'file1.txt')
True
>>> filecmp.cmp('file1.txt', 'file2.txt')
False

Speed consideration: Usually if only two files have to be compared, hashing them and comparing them would be slower instead of simple byte-by-byte comparison if done efficiently. e.g. code below tries to time hash vs byte-by-byte

Disclaimer: this is not the best way of timing or comparing two algo. and there is need for improvements but it does give rough idea. If you think it should be improved do tell me I will change it.

import random
import string
import hashlib
import time

def getRandText(N):
    return  "".join([random.choice(string.printable) for i in xrange(N)])

N=1000000
randText1 = getRandText(N)
randText2 = getRandText(N)

def cmpHash(text1, text2):
    hash1 = hashlib.md5()
    hash1.update(text1)
    hash1 = hash1.hexdigest()

    hash2 = hashlib.md5()
    hash2.update(text2)
    hash2 = hash2.hexdigest()

    return  hash1 == hash2

def cmpByteByByte(text1, text2):
    return text1 == text2

for cmpFunc in (cmpHash, cmpByteByByte):
    st = time.time()
    for i in range(10):
        cmpFunc(randText1, randText2)
    print cmpFunc.func_name,time.time()-st

and the output is

cmpHash 0.234999895096
cmpByteByByte 0.0

Trying to SSH into an Amazon Ec2 instance - permission error

Just change the permission of pem file to 0600 allowing only for the allowed user and it will work like charm.

sudo chmod 0600 myfile.pem

And then try to ssh it will work perfectly.

ssh -i myfile.pem <<ssh_user>>@<<server>>

Creating a Zoom Effect on an image on hover using CSS?

_x000D_
_x000D_
    .img-wrap:hover img {_x000D_
        transform: scale(0.8);_x000D_
    }_x000D_
    .img-wrap img {_x000D_
        display: block;_x000D_
        transition: all 0.3s ease 0s;_x000D_
        width: 100%;_x000D_
    }
_x000D_
    <div class="img-wrap">_x000D_
    <img src="http://www.sampleimages/images.jpg"/> // Your image_x000D_
    </div>
_x000D_
_x000D_
_x000D_

This code is only for zoom-out effect.Set the div "img-wrap" according to your styles and insert the above style results zoom-out effect.For zoom-in effect you must increase the scale value(eg: for zoom-in,use transform: scale(1.3);

Is it possible to change the content HTML5 alert messages?

Yes:

<input required title="Enter something OR ELSE." /> 

The title attribute will be used to notify the user of a problem.

Resource leak: 'in' is never closed

Because you don't close your Scanner

in.close();

How to dump a dict to a json file?

Also wanted to add this (Python 3.7)

import json

with open("dict_to_json_textfile.txt", 'w') as fout:
    json_dumps_str = json.dumps(a_dictionary, indent=4)
    print(json_dumps_str, file=fout)

BOOLEAN or TINYINT confusion

Just a note for php developers (I lack the necessary stackoverflow points to post this as a comment) ... the automagic (and silent) conversion to TINYINT means that php retrieves a value from a "BOOLEAN" column as a "0" or "1", not the expected (by me) true/false.

A developer who is looking at the SQL used to create a table and sees something like: "some_boolean BOOLEAN NOT NULL DEFAULT FALSE," might reasonably expect to see true/false results when a row containing that column is retrieved. Instead (at least in my version of PHP), the result will be "0" or "1" (yes, a string "0" or string "1", not an int 0/1, thank you php).

It's a nit, but enough to cause unit tests to fail.

Java double.MAX_VALUE?

this states that Account.deposit(Double.MAX_VALUE); it is setting deposit value to MAX value of Double dataType.to procced for running tests.

Alert after page load

There are three ways.
The first is to put the script tag on the bottom of the page:

<body>
<!--Body content-->
<script type="text/javascript">
alert('<%: TempData["Resultat"]%>');
</script>
</body>

The second way is to create an onload event:

<head>
<script type="text/javascript">
window.onload = function(){//window.addEventListener('load',function(){...}); (for Netscape) and window.attachEvent('onload',function(){...}); (for IE and Opera) also work
    alert('<%: TempData["Resultat"]%>');
}
</script>
</head>

It will execute a function when the window loads.
Finally, the third way is to create a readystatechange event and check the current document.readystate:

<head>
<script type="text/javascript">
document.onreadystatechange = function(){//window.addEventListener('readystatechange',function(){...}); (for Netscape) and window.attachEvent('onreadystatechange',function(){...}); (for IE and Opera) also work
    if(document.readyState=='loaded' || document.readyState=='complete')
        alert('<%: TempData["Resultat"]%>');
}
</script>
</head>

AttributeError: 'dict' object has no attribute 'predictors'

The dict.items iterates over the key-value pairs of a dictionary. Therefore for key, value in dictionary.items() will loop over each pair. This is documented information and you can check it out in the official web page, or even easier, open a python console and type help(dict.items). And now, just as an example:

>>> d = {'hello': 34, 'world': 2999}
>>> for key, value in d.items():
...   print key, value
...
world 2999
hello 34

The AttributeError is an exception thrown when an object does not have the attribute you tried to access. The class dict does not have any predictors attribute (now you know where to check it :) ), and therefore it complains when you try to access it. As easy as that.

Pass user defined environment variable to tomcat

You can use setenv.bat or .sh to pass the environment variables to the Tomcat.

Create CATALINA_BASE/bin/setenv.bat or .sh file and put the following line in it, and then start the Tomcat.

On Windows:

set APP_MASTER_PASSWORD=foo

On Unix like systems:

export APP_MASTER_PASSWORD=foo

how to get the last character of a string?

An elegant and short alternative, is the String.prototype.slice method.

Just by:

str.slice(-1);

A negative start index slices the string from length+index, to length, being index -1, the last character is extracted:

"abc".slice(-1); // "c";

Programmatically find the number of cores on a machine

OpenMP is supported on many platforms (including Visual Studio 2005) and it offers a

int omp_get_num_procs();

function that returns the number of processors/cores available at the time of call.

How do I select a MySQL database through CLI?

Hope this helps.

use [YOUR_DB_NAME];

glob exclude pattern

If the position of the character isn't important, that is for example to exclude manifests files (wherever it is found _) with glob and re - regular expression operations, you can use:

import glob
import re
for file in glob.glob('*.txt'):
    if re.match(r'.*\_.*', file):
        continue
    else:
        print(file)

Or with in a more elegant way - list comprehension

filtered = [f for f in glob.glob('*.txt') if not re.match(r'.*\_.*', f)]

for mach in filtered:
    print(mach)

Execute a large SQL script (with GO commands)

I had the same problem in java and I solved it with a bit of logic and regex. I believe the same logic can be applied.First I read from the slq file into memory. Then I apply the following logic. It's pretty much what has been said before however I believe that using regex word bound is safer than expecting a new line char.

String pattern = "\\bGO\\b|\\bgo\\b";

String[] splitedSql = sql.split(pattern);
for (String chunk : splitedSql) {
  getJdbcTemplate().update(chunk);
}

This basically splits the sql string into an array of sql strings. The regex is basically to detect full 'go' words either lower case or upper case. Then you execute the different querys sequentially.

Change color of Button when Mouse is over

Try this- In this example Original color is green and mouseover color will be DarkGoldenrod

<Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Bottom" Width="50" Height="50" HorizontalContentAlignment="Left" BorderBrush="{x:Null}" Foreground="{x:Null}" Margin="50,0,0,0">
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Background" Value="Green"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border Background="{TemplateBinding Background}">
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Background" Value="DarkGoldenrod"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

R: "Unary operator error" from multiline ggplot2 command

This is a well-known nuisance when posting multiline commands in R. (You can get different behavior when you source() a script to when you copy-and-paste the lines, both with multiline and comments)

Rule: always put the dangling '+' at the end of a line so R knows the command is unfinished:

ggplot(...) + geom_whatever1(...) +
  geom_whatever2(...) +
  stat_whatever3(...) +
  geom_title(...) + scale_y_log10(...)

Don't put the dangling '+' at the start of the line, since that tickles the error:

Error in "+ geom_whatever2(...) invalid argument to unary operator"

And obviously don't put dangling '+' at both end and start since that's a syntax error.

So, learn a habit of being consistent: always put '+' at end-of-line.

cf. answer to "Split code over multiple lines in an R script"

Use different Python version with virtualenv

Suppose you currently have python 2.7 installed in your virtualenv. But want to make use of python3.2, You would have to update this with:

$ virtualenv --python=/usr/bin/python3.2 name_of_your_virtualenv

Then activate your virtualenv by:

$ source activate name_of_your_virtualenv

and then do: python --version in shell to check whether your version is now updated.

Returning a value from thread?

class Program
{
    static void Main(string[] args)
    {
        string returnValue = null;
       new Thread(
          () =>
          {
              returnValue =test() ; 
          }).Start();
        Console.WriteLine(returnValue);
        Console.ReadKey();
    }

    public static string test()
    {
        return "Returning From Thread called method";
    }
}

Python: Figure out local timezone

You may be happy with pendulum

>>> pendulum.datetime(2015, 2, 5, tz='local').timezone.name
'Israel'

Pendulum has a well designed API for manipulating dates. Everything is TZ-aware.

Moving up one directory in Python

Use the os module:

import os
os.chdir('..')

should work

Connecting to Microsoft SQL server using Python

An alternative approach would be installing Microsoft ODBC Driver 13, then replace SQLOLEDB with ODBC Driver 13 for SQL Server

Regards.

Serialize and Deserialize Json and Json Array in Unity

Unity <= 2019

Narottam Goyal had a good idea of wrapping the array in a json object, and then deserializing into a struct. The following uses Generics to solve this for arrays of all type, as opposed to making a new class everytime.

[System.Serializable]
private struct JsonArrayWrapper<T> {
    public T wrap_result;
}

public static T ParseJsonArray<T>(string json) {
    var temp = JsonUtility.FromJson<JsonArrayWrapper<T>>("{\" wrap_result\":" + json + "}");
    return temp.wrap_result;
}

It can be used in the following way:

string[] options = ParseJsonArray<string[]>(someArrayOfStringsJson);

Unity 2020

In Unity 2020 there is an official newtonsoft package which is a far better json library.

Datatable vs Dataset

There are some optimizations you can use when filling a DataTable, such as calling BeginLoadData(), inserting the data, then calling EndLoadData(). This turns off some internal behavior within the DataTable, such as index maintenance, etc. See this article for further details.

replace String with another in java

     String s1 = "HelloSuresh";
     String m = s1.replace("Hello","");
     System.out.println(m);

Error Code: 1406. Data too long for column - MySQL

This happened to me recently. I was fully migrate to MySQL 5.7, and everything is in default configuration.

All previously answers are already clear and I just want to add something.

This 1406 error could happen in your function / procedure too and not only to your table's column length.

In my case, I've trigger which call procedure with IN parameter varchar(16) but received 32 length value.

I hope this help someone with similar problem.

Array initialization syntax when not in a declaration

For those of you, who doesn't like this monstrous new AClass[] { ... } syntax, here's some sugar:

public AClass[] c(AClass... arr) { return arr; }

Use this little function as you like:

AClass[] array;
...
array = c(object1, object2);

How can I exit from a javascript function?

I had the same problem in Google App Scripts, and solved it like the rest said, but with a little more..

function refreshGrid(entity) {
var store = window.localStorage;
var partitionKey;
if (condition) {
  return Browser.msgBox("something");
  }
}

This way you not only exit the function, but show a message saying why it stopped. Hope it helps.

How to use Google fonts in React.js?

Google fonts in React.js?

Open your stylesheet i.e, app.css, style.css (what name you have), it doesn't matter, just open stylesheet and paste this code

@import url('https://fonts.googleapis.com/css?family=Josefin+Sans');

and don't forget to change URL of your font that you want, else working fine

and use this as :

body {
  font-family: 'Josefin Sans', cursive;
}

How can I use the python HTMLParser library to extract data from a specific div tag?

class LinksParser(HTMLParser.HTMLParser):
  def __init__(self):
    HTMLParser.HTMLParser.__init__(self)
    self.recording = 0
    self.data = []

  def handle_starttag(self, tag, attributes):
    if tag != 'div':
      return
    if self.recording:
      self.recording += 1
      return
    for name, value in attributes:
      if name == 'id' and value == 'remository':
        break
    else:
      return
    self.recording = 1

  def handle_endtag(self, tag):
    if tag == 'div' and self.recording:
      self.recording -= 1

  def handle_data(self, data):
    if self.recording:
      self.data.append(data)

self.recording counts the number of nested div tags starting from a "triggering" one. When we're in the sub-tree rooted in a triggering tag, we accumulate the data in self.data.

The data at the end of the parse are left in self.data (a list of strings, possibly empty if no triggering tag was met). Your code from outside the class can access the list directly from the instance at the end of the parse, or you can add appropriate accessor methods for the purpose, depending on what exactly is your goal.

The class could be easily made a bit more general by using, in lieu of the constant literal strings seen in the code above, 'div', 'id', and 'remository', instance attributes self.tag, self.attname and self.attvalue, set by __init__ from arguments passed to it -- I avoided that cheap generalization step in the code above to avoid obscuring the core points (keep track of a count of nested tags and accumulate data into a list when the recording state is active).

ActiveRecord OR query

in Rails 3, it should be

Model.where("column = ? or other_column = ?", value, other_value)

This also includes raw sql but I dont think there is a way in ActiveRecord to do OR operation. Your question is not a noob question.

Logout button php

Instead of a button, put a link and navigate it to another page

<a href="logout.php">Logout</a>

Then in logout.php page, use

session_start();
session_destroy();
header('Location: login.php');
exit;

Changing date format in R

This is really easy using package lubridate. All you have to do is tell R what format your date is already in. It then converts it into the standard format

nzd$date <- dmy(nzd$date)

that's it.

How to make ConstraintLayout work with percentage values?

Try this code. You can change the height and width percentages with app:layout_constraintHeight_percent and app:layout_constraintWidth_percent.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#FF00FF"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHeight_percent=".6"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintWidth_percent=".4"></LinearLayout>

</android.support.constraint.ConstraintLayout>

Gradle:

dependencies {
...
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
}

enter image description here

How to change the size of the font of a JLabel to take the maximum size

Not the most pretty code, but the following will pick an appropriate font size for a JLabel called label such that the text inside will fit the interior as much as possible without overflowing the label:

Font labelFont = label.getFont();
String labelText = label.getText();

int stringWidth = label.getFontMetrics(labelFont).stringWidth(labelText);
int componentWidth = label.getWidth();

// Find out how much the font can grow in width.
double widthRatio = (double)componentWidth / (double)stringWidth;

int newFontSize = (int)(labelFont.getSize() * widthRatio);
int componentHeight = label.getHeight();

// Pick a new font size so it will not be larger than the height of label.
int fontSizeToUse = Math.min(newFontSize, componentHeight);

// Set the label's font size to the newly determined size.
label.setFont(new Font(labelFont.getName(), Font.PLAIN, fontSizeToUse));

Basically, the code looks at how much space the text in the JLabel takes up by using the FontMetrics object, and then uses that information to determine the largest font size that can be used without overflowing the text from the JLabel.

The above code can be inserted into perhaps the paint method of the JFrame which holds the JLabel, or some method which will be invoked when the font size needs to be changed.

The following is an screenshot of the above code in action:

alt text
(source: coobird.net)

Erase whole array Python

Note that list and array are different classes. You can do:

del mylist[:]

This will actually modify your existing list. David's answer creates a new list and assigns it to the same variable. Which you want depends on the situation (e.g. does any other variable have a reference to the same list?).

Try:

a = [1,2]
b = a
a = []

and

a = [1,2]
b = a
del a[:]

Print a and b each time to see the difference.

How to set a JVM TimeZone Properly

Setting environment variable TZ should also works

ex: export TZ=Asia/Shanghai

How to prevent scientific notation in R?

Try format function:

> xx = 100000000000
> xx
[1] 1e+11
> format(xx, scientific=F)
[1] "100000000000"

How do I compare 2 rows from the same table (SQL Server)?

Some people find the following alternative syntax easier to see what is going on:

select t1.value,t2.value
from MyTable t1
    inner join MyTable t2 on
        t1.id = t2.id
where t1.id = @id

Reset git proxy to default configuration

On my Linux machine :

git config --system --get https.proxy (returns nothing)
git config --global --get https.proxy (returns nothing)

git config --system --get http.proxy (returns nothing)
git config --global --get http.proxy (returns nothing)

I found out my https_proxy and http_proxy are set, so I just unset them.

unset https_proxy
unset http_proxy

On my Windows machine :

set https_proxy=""
set http_proxy=""

Optionally use setx to set environment variables permanently on Windows and set system environment using "/m"

setx https_proxy=""
setx http_proxy=""

"webxml attribute is required" error in Maven

As per the documentation, it says : Whether or not to fail the build if the web.xml file is missing. Set to false if you want you WAR built without a web.xml file. This may be useful if you are building an overlay that has no web.xml file. Default value is: true. User property is: failOnMissingWebXml.

<plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.1.1</version>
    <extensions>false</extensions>
    <configuration>
        <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
</plugin>

Hope it makes more clear

sass --watch with automatic minify?

If you are using JetBrains editors like IntelliJ IDEA, PhpStorm, WebStorm etc. Use the following settings in Settings > File Watchers. enter image description here

  1. Convert style.scss to style.css set the arguments

    --no-cache --update $FileName$:$FileNameWithoutExtension$.css
    

    and output paths to refresh

    $FileNameWithoutExtension$.css
    
  2. Convert style.scss to compressed style.min.css set the arguments

    --no-cache --update $FileName$:$FileNameWithoutExtension$.min.css --style compressed
    

    and output paths to refresh

    $FileNameWithoutExtension$.min.css
    

No serializer found for class org.hibernate.proxy.pojo.javassist.Javassist?

You could use the add-on module for Jackson which handles Hibernate lazy-loading.

More info on https://github.com/FasterXML/jackson-datatype-hibernate wich support hibernate 3 and 4 separately.

How to clear cache of Eclipse Indigo

It's very simple. Right click inside the internal browser and click "refresh".

How to reload/refresh jQuery dataTable?

With version 1.10.0 of DataTables, it is built-in and easy:

var table = $('#example').DataTable();
table.ajax.reload();

or just

$('#example').DataTable().ajax.reload();

http://datatables.net/reference/api/ajax.reload()

Dependent DLL is not getting copied to the build output folder in Visual Studio

If you right Click the referenced assembly, you will see a property called Copy Local. If Copy Local is set to true, then the assembly should be included in the bin. However, there seams to be a problem with Visual studio, that sometimes it does not include the referenced dll in the bin folder... this is the workaround that worked for me:

enter image description here

Set an empty DateTime variable

If you set the date to

DateTime dNewDate = new DateTime();

The value is set to {1/1/0001 12:00:00 AM}

Two dimensional array in python

There aren't multidimensional arrays as such in Python, what you have is a list containing other lists.

>>> arr = [[]]
>>> len(arr)
1

What you have done is declare a list containing a single list. So arr[0] contains a list but arr[1] is not defined.

You can define a list containing two lists as follows:

arr = [[],[]]

Or to define a longer list you could use:

>>> arr = [[] for _ in range(5)]
>>> arr
[[], [], [], [], []]

What you shouldn't do is this:

arr = [[]] * 3

As this puts the same list in all three places in the container list:

>>> arr[0].append('test')
>>> arr
[['test'], ['test'], ['test']]

How should I tackle --secure-file-priv in MySQL?

I'm working on MySQL5.7.11 on Debian, the command that worked for me to see the directory is:

mysql> SELECT @@global.secure_file_priv;

How do I disable a Pylint warning?

You can also use the following command:

pylint --disable=C0321  test.py

My Pylint version is 0.25.1.

PHP Error: Cannot use object of type stdClass as array (array and object issues)

The example you copied from is using data in the form of an array holding arrays, you are using data in the form of an array holding objects. Objects and arrays are not the same, and because of this they use different syntaxes for accessing data.

If you don't know the variable names, just do a var_dump($blog); within the loop to see them.

The simplest method - access $blog as an object directly:

Try (assuming those variables are correct):

<?php 
    foreach ($blogs as $blog) {
        $id         = $blog->id;
        $title      = $blog->title;
        $content    = $blog->content;
?>

<h1> <?php echo $title; ?></h1>
<h1> <?php echo $content; ?> </h1>

<?php } ?>

The alternative method - access $blog as an array:

Alternatively, you may be able to turn $blog into an array with get_object_vars (documentation):

<?php
    foreach($blogs as &$blog) {
        $blog     = get_object_vars($blog);
        $id       = $blog['id'];
        $title    = $blog['title'];
        $content  = $blog['content'];
?>

<h1> <?php echo $title; ?></h1>
<h1> <?php echo $content; ?> </h1>

<?php } ?> 

It's worth mentioning that this isn't necessarily going to work with nested objects so its viability entirely depends on the structure of your $blog object.

Better than either of the above - Inline PHP Syntax

Having said all that, if you want to use PHP in the most readable way, neither of the above are right. When using PHP intermixed with HTML, it's considered best practice by many to use PHP's alternative syntax, this would reduce your whole code from nine to four lines:

<?php foreach($blogs as $blog): ?>
    <h1><?php echo $blog->title; ?></h1>
    <p><?php echo $blog->content; ?></p>
<?php endforeach; ?>

Hope this helped.

Can a unit test project load the target application's app.config file?

I use NUnit and in my project directory I have a copy of my App.Config that I change some configuration (example I redirect to a test database...). You need to have it in the same directory of the tested project and you will be fine.

python pip on Windows - command 'cl.exe' failed

I was facing the same problem with visual studio 2017.

you can find cl.exe in C:\Program Files(x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\bin\Hostx86\x86.

just set the environment variable as the able address and run the command in anaconda, it worked for me.

Creating multiple objects with different names in a loop to store in an array list

You can use this code...

public class Main {

    public static void main(String args[]) {
        String[] names = {"First", "Second", "Third"};//You Can Add More Names
        double[] amount = {20.0, 30.0, 40.0};//You Can Add More Amount
        List<Customer> customers = new ArrayList<Customer>();
        int i = 0;
        while (i < names.length) {
            customers.add(new Customer(names[i], amount[i]));
            i++;
        }
    }
}

How to show progress bar while loading, using ajax

try this it may help you

 $.ajax({
  type:"post",
            url:"clientnetworkpricelist/yourfile.php",
        data:"title="+clientid,
  beforeSend: function(  ) {
    // load your loading fiel here
  }
})
  .done(function( data ) {
    //hide your loading file here
  });

Load properties file in JAR?

For the record, this is documented in How do I add resources to my JAR? (illustrated for unit tests but the same applies for a "regular" resource):

To add resources to the classpath for your unit tests, you follow the same pattern as you do for adding resources to the JAR except the directory you place resources in is ${basedir}/src/test/resources. At this point you would have a project directory structure that would look like the following:

my-app
|-- pom.xml
`-- src
    |-- main
    |   |-- java
    |   |   `-- com
    |   |       `-- mycompany
    |   |           `-- app
    |   |               `-- App.java
    |   `-- resources
    |       `-- META-INF
    |           |-- application.properties
    `-- test
        |-- java
        |   `-- com
        |       `-- mycompany
        |           `-- app
        |               `-- AppTest.java
        `-- resources
            `-- test.properties

In a unit test you could use a simple snippet of code like the following to access the resource required for testing:

...

// Retrieve resource
InputStream is = getClass().getResourceAsStream("/test.properties" );

// Do something with the resource

...

Copy a file in a sane, safe and efficient way

With C++17 the standard way to copy a file will be including the <filesystem> header and using:

bool copy_file( const std::filesystem::path& from,
                const std::filesystem::path& to);

bool copy_file( const std::filesystem::path& from,
                const std::filesystem::path& to,
                std::filesystem::copy_options options);

The first form is equivalent to the second one with copy_options::none used as options (see also copy_file).

The filesystem library was originally developed as boost.filesystem and finally merged to ISO C++ as of C++17.

Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type

A more hacky way is to add eg., in boot.tsx the line

import './path/declare_modules.d.ts';

with

declare module 'react-materialize';
declare module 'react-router';
declare module 'flux';

in declare_modules.d.ts

It works but other solutions are better IMO.

Deserialize a json string to an object in python

If you want to save lines of code and leave the most flexible solution, we can deserialize the json string to a dynamic object:

p = lambda:None
p.__dict__ = json.loads('{"action": "print", "method": "onData", "data": "Madan Mohan"}')


>>>> p.action
output: u'print'

>>>> p.method
output: u'onData'

What is the difference between parseInt(string) and Number(string) in JavaScript?

The first one takes two parameters:

parseInt(string, radix)

The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.

If the radix parameter is omitted, JavaScript assumes the following:

  • If the string begins with "0x", the
    radix is 16 (hexadecimal)
  • If the string begins with "0", the radix is 8 (octal). This feature
    is deprecated
  • If the string begins with any other value, the radix is 10 (decimal)

The other function you mentioned takes only one parameter:

Number(object)

The Number() function converts the object argument to a number that represents the object's value.

If the value cannot be converted to a legal number, NaN is returned.

regular expression for Indian mobile numbers

You may use this

/^(?:(?:\+|0{0,2})91(\s*|[\-])?|[0]?)?([6789]\d{2}([ -]?)\d{3}([ -]?)\d{4})$/

Valid Entries:

6856438922
7856128945
8945562713
9998564723
+91-9883443344
09883443344
919883443344
0919883443344
+919883443344
+91-9883443344
0091-9883443344
+91 9883443344
+91-785-612-8945
+91 999 856 4723

Invalid Entries:

WAQU9876567892
ABCD9876541212
0226-895623124
0924645236
0222-895612
098-8956124
022-2413184

Validate it at https://regex101.com/

How to access environment variable values?

For django see (https://github.com/joke2k/django-environ)

$ pip install django-environ

import environ
env = environ.Env(
# set casting, default value
DEBUG=(bool, False)
)
# reading .env file
environ.Env.read_env()

# False if not in os.environ
DEBUG = env('DEBUG')

# Raises django's ImproperlyConfigured exception if SECRET_KEY not in os.environ
SECRET_KEY = env('SECRET_KEY')

Does a finally block always get executed in Java?

Finally is always run that's the whole point, just because it appears in the code after the return doesn't mean that that's how it's implemented. The Java runtime has the responsibility to run this code when exiting the try block.

For example if you have the following:

int foo() { 
    try {
        return 42;
    }
    finally {
        System.out.println("done");
    }
}

The runtime will generate something like this:

int foo() {
    int ret = 42;
    System.out.println("done");
    return 42;
}

If an uncaught exception is thrown the finally block will run and the exception will continue propagating.

How to fetch data from local JSON file on react native?

Use this

import data from './customData.json';

The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication

To diagnose this problem, run the service under the Visual Studio debugger. Use the menu: Debug|Exceptions and indicate that you want to break when an Exception is thrown.

The original exception thrown will have a much better error message than "..it is in the Faulted state."

For example I was getting this exception from ServiceHost.Open(), but when I caught the original exception at the time it was thrown, the error message was:

Service 'MyServiceName' has zero application (non-infrastructure) endpoints. This might be because no configuration file was found for your application, or because no service element matching the service name could be found in the configuration file, or because no endpoints were defined in the service element.

Fixing the spelling error in App.config solved the problem.

Can I set up HTML/Email Templates with ASP.NET?

What would be ideal what be to use a .ASPX page as a template somehow, then just tell my code to serve that page, and use the HTML returned for the email.

You could easily just construct a WebRequest to hit an ASPX page and get the resultant HTML. With a little more work, you can probably get it done without the WebRequest. A PageParser and a Response.Filter would allow you to run the page and capture the output...though there may be some more elegant ways.

Package php5 have no installation candidate (Ubuntu 16.04)

If you just want to install PHP no matter what version it is, try PHP7

sudo apt-get install php7.0 php7.0-mcrypt

Laravel PDOException SQLSTATE[HY000] [1049] Unknown database 'forge'

first clear your cache using this command

php artisan cache:clear

Then restart the server using this command

php artisan serve

How to get absolute value from double - c-language

Use fabs instead of abs to find absolute value of double (or float) data types. Include the <math.h> header for fabs function.

double d1 = fabs(-3.8951);

How to delete SQLite database from Android programmatically

I have used the following for "formatting" the database on device after I have changed the structure of the database in assets. I simply uncomment the line in MainActivity when I wanted that the database is read from the assets again. This will reset the device database values and structure to mach with the preoccupied database in assets folder.

    //database initialization. Uncomment to clear the database
    //deleteDatabase("questions.db");

Next, I will implement a button that will run the deleteDatabase so that the user can reset its progress in the game.

Web-scraping JavaScript page with Python

You'll want to use urllib, requests, beautifulSoup and selenium web driver in your script for different parts of the page, (to name a few).
Sometimes you'll get what you need with just one of these modules.
Sometimes you'll need two, three, or all of these modules.
Sometimes you'll need to switch off the js on your browser.
Sometimes you'll need header info in your script.
No websites can be scraped the same way and no website can be scraped in the same way forever without having to modify your crawler, usually after a few months. But they can all be scraped! Where there's a will there's a way for sure.
If you need scraped data continuously into the future just scrape everything you need and store it in .dat files with pickle.
Just keep searching how to try what with these modules and copying and pasting your errors into the Google.

Android Studio SDK location

This is the sdk path Android Studio installed for me: "C:\Users\<username>\appdata\local\android\sdk"

I'm running windows 8.1.

You can find the path going into Android Studio -> Configure -> SDK Manager -> On the top left it should say SDK Path.

I don't think it's necessary to install the sdk separately, as the default option for Android Studio is to install the latest sdk too.

Declaring array of objects

Use array.push() to add an item to the end of the array.

var sample = new Array();
sample.push(new Object());

To do this n times use a for loop.

var n = 100;
var sample = new Array();
for (var i = 0; i < n; i++)
    sample.push(new Object());

Note that you can also substitute new Array() with [] and new Object() with {} so it becomes:

var n = 100;
var sample = [];
for (var i = 0; i < n; i++)
    sample.push({});

Capture the screen shot using .NET

It's certainly possible to grab a screenshot using the .NET Framework. The simplest way is to create a new Bitmap object and draw into that using the Graphics.CopyFromScreen method.

Sample code:

using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width, 
                                            Screen.PrimaryScreen.Bounds.Height))
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
{
    g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
                     Screen.PrimaryScreen.Bounds.Y,
                     0, 0,
                     bmpScreenCapture.Size,
                     CopyPixelOperation.SourceCopy);
}

Caveat: This method doesn't work properly for layered windows. Hans Passant's answer here explains the more complicated method required to get those in your screen shots.

Syncing Android Studio project with Gradle files

EDIT

Starting with Android Studio 3.1, you should go to:

File -> Sync Project with Gradle Files


OLD

Clicking the button 'Sync Project With Gradle Files' should do the trick:

Tools -> Android -> Sync Project with Gradle Files

If that fails, try running 'Rebuild project':

Build -> Rebuild Project

HTML/CSS: Making two floating divs the same height

I needed to do something similar, here is my implementation. To recap the purpose, it is to have 2 elements take up the width of a given parent container, and the height to only be as high as it needs to be. Essentially height equaling max height of largest amount of content, but the other container being flush.

html

<div id="ven">
<section>some content</section>
<section>some content</section>
</div>

css

#ven {
height: 100%;
}
#ven section {
width: 50%;
float: left;
height: 100%;
}

How to zero pad a sequence of integers in bash so that all have the same width?

Use awk like this:

awk -v start=1 -v end=10 'BEGIN{for (i=start; i<=end; i++) printf("%05d\n", i)}'

OUTPUT:

00001
00002
00003
00004
00005
00006
00007
00008
00009
00010

Update:

As pure bash alternative you can do this to get same output:

for i in {1..10}
do
   printf "%05d\n" $i
done

This way you can avoid using an external program seq which is NOT available on all the flavors of *nix.

Merge, update, and pull Git branches without using checkouts

git worktree add [-f] [--detach] [--checkout] [--lock] [-b <new-branch>] <path> [<commit-ish>]

You can try git worktree to have two branches open side by side, this sounds like it might be what you want but very different than some of the other answers I've seen here.

In this way you can have two separate branches tracking in the same git repo so you only have to fetch once to get updates in both work trees (rather than having to git clone twice and git pull on each)

Worktree will create a new working directory for your code where you can have a different branch checked out simultaneously instead of swapping branches in place.

When you want to remove it you can clean up with

git worktree remove [-f] <worktree>

Disable a link in Bootstrap

You cant set links to "disabled" just system elements like input, textfield etc.

But you can disable links with jQuery/JavaScript

$('.disabled').click(function(e){
    e.preventDefault();
});

Just wrap the above code in whatever event you want to disable the links.

Remove legend ggplot 2.2

from r cookbook, where bp is your ggplot:

Remove legend for a particular aesthetic (fill):

bp + guides(fill=FALSE)

It can also be done when specifying the scale:

bp + scale_fill_discrete(guide=FALSE)

This removes all legends:

bp + theme(legend.position="none")

How can I get the current screen orientation?

In case anyone would like to obtain meaningful orientation description (like that passed to onConfigurationChanged(..) with those reverseLandscape, sensorLandscape and so on), simply use getRequestedOrientation()

Force DOM redraw/refresh on Chrome/Mac

This works for me. Kudos go here.

jQuery.fn.redraw = function() {
    return this.hide(0, function() {
        $(this).show();
    });
};

$(el).redraw();

Custom li list-style with font-awesome icon

I did two things inspired by @OscarJovanny comment, with some hacks.

Step 1:

  • Download icons file as svg from Here, as I only need only this icon from font awesome

Step 2:

<style>
ul {
    list-style-type: none;
    margin-left: 10px;
}

ul li {
    margin-bottom: 12px;
    margin-left: -10px;
    display: flex;
    align-items: center;
}

ul li::before {
    color: transparent;
    font-size: 1px;
    content: " ";
    margin-left: -1.3em;
    margin-right: 15px;
    padding: 10px;
    background-color: orange;
    -webkit-mask-image: url("./assets/img/check-circle-solid.svg");
    -webkit-mask-size: cover;
}
</style>

Results

enter image description here

How to use 'find' to search for files created on a specific date?

@Max: is right about the creation time.

However, if you want to calculate the elapsed days argument for one of the -atime, -ctime, -mtime parameters, you can use the following expression

ELAPSED_DAYS=$(( ( $(date +%s) - $(date -d '2008-09-24' +%s) ) / 60 / 60 / 24 - 1 ))

Replace "2008-09-24" with whatever date you want and ELAPSED_DAYS will be set to the number of days between then and today. (Update: subtract one from the result to align with find's date rounding.)

So, to find any file modified on September 24th, 2008, the command would be:

find . -type f -mtime $(( ( $(date +%s) - $(date -d '2008-09-24' +%s) ) / 60 / 60 / 24 - 1 ))

This will work if your version of find doesn't support the -newerXY predicates mentioned in @Arve:'s answer.

std::string to char*

No body ever mentioned sprintf?

std::string s;
char * c;
sprintf(c, "%s", s.c_str());

Python: import module from another directory at the same level in project hierarchy

From Python 2.5 onwards, you can use

from ..Modules import LDAPManager

The leading period takes you "up" a level in your heirarchy.

See the Python docs on intra-package references for imports.

Why is jquery's .ajax() method not sending my session cookie?

After trying out the other solutions and still not getting it to work, I found out what the problem was in my case. I changed contentType from "application/json" to "text/plain".

$.ajax(fullUrl, {
    type: "GET",
    contentType: "text/plain",
    xhrFields: {
         withCredentials: true
    },
    crossDomain: true
});

How to bind 'touchstart' and 'click' events but not respond to both?

Usually this works as well:

$('#buttonId').on('touchstart click', function(e){
    e.stopPropagation(); e.preventDefault();
    //your code here

});

How to find out "The most popular repositories" on Github?

Ranking by stars or forks is not working. Each promoted or created by a famous company repository is popular at the beginning. Also it is possible to have a number of them which are in trend right now (publications, marketing, events). It doesn't mean that those repositories are useful/popular.

The gitmostwanted.com project (repo at github) analyses GH Archive data in order to highlight the most interesting repositories and exclude others. Just compare the results with mentioned resources.

Setting the default ssh key location

man ssh gives me this options would could be useful.

-i identity_file Selects a file from which the identity (private key) for RSA or DSA authentication is read. The default is ~/.ssh/identity for protocol version 1, and ~/.ssh/id_rsa and ~/.ssh/id_dsa for pro- tocol version 2. Identity files may also be specified on a per- host basis in the configuration file. It is possible to have multiple -i options (and multiple identities specified in config- uration files).

So you could create an alias in your bash config with something like

alias ssh="ssh -i /path/to/private_key"

I haven't looked into a ssh configuration file, but like the -i option this too could be aliased

-F configfile Specifies an alternative per-user configuration file. If a configuration file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored. The default for the per-user configuration file is ~/.ssh/config.

How to populate a dropdownlist with json data in jquery?

//javascript
//teams.Table does not exist

function OnSuccessJSON(data, status) {
    var teams = eval('(' + data.d + ')');
    var listItems = "";
    for (var i = 0; i < teams.length; i++) {
      listItems += "<option value='" + teams[i][0]+ "'>" + teams[i][1] + "</option>";
    }
    $("#<%=ddlTeams.ClientID%>").html(listItems);
} 

What is the use of "using namespace std"?

When you make a call to using namespace <some_namespace>; all symbols in that namespace will become visible without adding the namespace prefix. A symbol may be for instance a function, class or a variable.

E.g. if you add using namespace std; you can write just cout instead of std::cout when calling the operator cout defined in the namespace std.

This is somewhat dangerous because namespaces are meant to be used to avoid name collisions and by writing using namespace you spare some code, but loose this advantage. A better alternative is to use just specific symbols thus making them visible without the namespace prefix. Eg:

#include <iostream>
using std::cout;

int main() {
  cout << "Hello world!";
  return 0;
}

Android Studio - Failed to notify project evaluation listener error

org.gradle.configureondemand=false

add this code into your gradle.properties file, It will work well but you may receive other errors.

Javascript change font color

Try like this:

var clr = 'green';
var html = '<font color="' + clr + '">' + onlineff + ' </font>';

This being said, you should avoid using the <font> tag. It is now deprecated. Use CSS to change the style (color) of a given element in your markup.

How can I update npm on Windows?

The previous answers will work installing a new version of Node.js (probably the best option), but if you have a dependency on a specific Node.js version then the following will work: "npm install npm -g". Verify by running npm -v before and after the command.

Enter image description here

How do you display JavaScript datetime in 12 hour AM/PM format?

_x000D_
_x000D_
function formatTime( d = new Date(), ampm = true ) 
{
    var hour = d.getHours();
    
    if ( ampm )
    {
        var a = ( hour >= 12 ) ? 'PM' : 'AM';
        hour = hour % 12;
        hour = hour ? hour : 12; // the hour '0' should be '12'  
    }

    var hour    = checkDigit(hour);  
    var minute  = checkDigit(d.getMinutes());
    var second  = checkDigit(d.getSeconds());
  
    // https://stackoverflow.com/questions/1408289/how-can-i-do-string-interpolation-in-javascript
    return ( ampm ) ? `${hour}:${minute}:${second} ${a}` : `${hour}:${minute}:${second}`;
}

function checkDigit(t)
{
  return ( t < 10 ) ? `0${t}` : t;
}

document.querySelector("#time1").innerHTML = formatTime();
document.querySelector("#time2").innerHTML = formatTime( new Date(), false );
_x000D_
<p>ampm true:   <span id="time1"></span> (default)</p>
<p>ampm false:  <span id="time2"></span></p>
_x000D_
_x000D_
_x000D_

How do I create delegates in Objective-C?

An Objective-C delegate is an object that has been assigned to the delegate property another object. To create one, you define a class that implements the delegate methods you're interested in, and mark that class as implementing the delegate protocol.

For example, suppose you have a UIWebView. If you'd like to implement its delegate's webViewDidStartLoad: method, you could create a class like this:

@interface MyClass<UIWebViewDelegate>
// ...
@end

@implementation MyClass
- (void)webViewDidStartLoad:(UIWebView *)webView { 
    // ... 
}
@end

Then you could create an instance of MyClass and assign it as the web view's delegate:

MyClass *instanceOfMyClass = [[MyClass alloc] init];
myWebView.delegate = instanceOfMyClass;

On the UIWebView side, it probably has code similar to this to see if the delegate responds to the webViewDidStartLoad: message using respondsToSelector: and send it if appropriate.

if([self.delegate respondsToSelector:@selector(webViewDidStartLoad:)]) {
    [self.delegate webViewDidStartLoad:self];
}

The delegate property itself is typically declared weak (in ARC) or assign (pre-ARC) to avoid retain loops, since the delegate of an object often holds a strong reference to that object. (For example, a view controller is often the delegate of a view it contains.)

Making Delegates for Your Classes

To define your own delegates, you'll have to declare their methods somewhere, as discussed in the Apple Docs on protocols. You usually declare a formal protocol. The declaration, paraphrased from UIWebView.h, would look like this:

@protocol UIWebViewDelegate <NSObject>
@optional
- (void)webViewDidStartLoad:(UIWebView *)webView;
// ... other methods here
@end

This is analogous to an interface or abstract base class, as it creates a special type for your delegate, UIWebViewDelegate in this case. Delegate implementors would have to adopt this protocol:

@interface MyClass <UIWebViewDelegate>
// ...
@end

And then implement the methods in the protocol. For methods declared in the protocol as @optional (like most delegate methods), you need to check with -respondsToSelector: before calling a particular method on it.

Naming

Delegate methods are typically named starting with the delegating class name, and take the delegating object as the first parameter. They also often use a will-, should-, or did- form. So, webViewDidStartLoad: (first parameter is the web view) rather than loadStarted (taking no parameters) for example.

Speed Optimizations

Instead of checking whether a delegate responds to a selector every time we want to message it, you can cache that information when delegates are set. One very clean way to do this is to use a bitfield, as follows:

@protocol SomethingDelegate <NSObject>
@optional
- (void)something:(id)something didFinishLoadingItem:(id)item;
- (void)something:(id)something didFailWithError:(NSError *)error;
@end

@interface Something : NSObject
@property (nonatomic, weak) id <SomethingDelegate> delegate;
@end

@implementation Something {
  struct {
    unsigned int didFinishLoadingItem:1;
    unsigned int didFailWithError:1;
  } delegateRespondsTo;
}
@synthesize delegate;

- (void)setDelegate:(id <SomethingDelegate>)aDelegate {
  if (delegate != aDelegate) {
    delegate = aDelegate;

    delegateRespondsTo.didFinishLoadingItem = [delegate respondsToSelector:@selector(something:didFinishLoadingItem:)];
    delegateRespondsTo.didFailWithError = [delegate respondsToSelector:@selector(something:didFailWithError:)];
  }
}
@end

Then, in the body, we can check that our delegate handles messages by accessing our delegateRespondsTo struct, rather than by sending -respondsToSelector: over and over again.

Informal Delegates

Before protocols existed, it was common to use a category on NSObject to declare the methods a delegate could implement. For example, CALayer still does this:

@interface NSObject(CALayerDelegate)
- (void)displayLayer:(CALayer *)layer;
// ... other methods here
@end

This tells the compiler that any object might implement displayLayer:.

You would then use the same -respondsToSelector: approach as described above to call this method. Delegates implement this method and assign the delegate property, and that's it (there's no declaring you conform to a protocol). This method is common in Apple's libraries, but new code should use the more modern protocol approach above, since this approach pollutes NSObject (which makes autocomplete less useful) and makes it hard for the compiler to warn you about typos and similar errors.

DatabaseError: current transaction is aborted, commands ignored until end of transaction block?

I have met this issue , the error comes out since the error transactions hasn't been ended rightly, I found the postgresql_transactions of Transaction Control command here

Transaction Control

The following commands are used to control transactions

BEGIN TRANSACTION - To start a transaction.

COMMIT - To save the changes, alternatively you can use END TRANSACTION command.

ROLLBACK - To rollback the changes.

so i use the END TRANSACTION to end the error TRANSACTION, code like this:

    for key_of_attribute, command in sql_command.items():
        cursor = connection.cursor()
        g_logger.info("execute command :%s" % (command))
        try:
            cursor.execute(command)
            rows = cursor.fetchall()
            g_logger.info("the command:%s result is :%s" % (command, rows))
            result_list[key_of_attribute] = rows
            g_logger.info("result_list is :%s" % (result_list))
        except Exception as e:
            cursor.execute('END TRANSACTION;')
            g_logger.info("error command :%s and error is :%s" % (command, e))
    return result_list

Could not load file or assembly '***.dll' or one of its dependencies

Had the same issue and got it resolved by making sure projects in the solution have the same configuration and platform (in my case it was Debug x64). Somehow the VIsual Studio was missing x64 for part of the projects and I edited the .sln file manually (copied the configurations and platforms from correctly built projects to the projects that were missing the settings I needed). This is what it looks like for one of the projects:

{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Debug|x64.ActiveCfg = Debug|x64
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Debug|x64.Build.0 = Debug|x64
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Release|Any CPU.Build.0 = Release|Any CPU
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Release|x64.ActiveCfg = Release|x64
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Release|x64.Build.0 = Release|x64

But then the same error occurred for a project that had a Java file (*.jar) in the dependencies. I had to edit Environment Variables manually to create a record with this value

C:\Program Files\Java\jre1.8.0_171\bin\server

for Java's path, and put it on top of the Path items.

This fixed the issue until I updated Java on my machine. I had to edit the version number in Environment Variables to match the updated folder name.

C:\Program Files\Java\jre1.8.0_181\bin\server

How get data from material-ui TextField, DropDownMenu components?

Here all solutions are based on Class Component, but i guess most of the people who learned React recently (like me), at this time using functional Component. So here is the solution based on functional component.

Using useRef hooks of ReactJs and inputRef property of TextField.

    import React, { useRef, Component } from 'react'
    import { TextField, Button } from '@material-ui/core'
    import SendIcon from '@material-ui/icons/Send'

    export default function MultilineTextFields() {
    const valueRef = useRef('') //creating a refernce for TextField Component

    const sendValue = () => {
        return console.log(valueRef.current.value) //on clicking button accesing current value of TextField and outputing it to console 
    }

    return (
        <form noValidate autoComplete='off'>
        <div>
            <TextField
            id='outlined-textarea'
            label='Content'
            placeholder='Write your thoughts'
            multiline
            variant='outlined'
            rows={20}
            inputRef={valueRef}   //connecting inputRef property of TextField to the valueRef
            />
            <Button
            variant='contained'
            color='primary'
            size='small'
            endIcon={<SendIcon />}
            onClick={sendValue}
            >
            Send
            </Button>
        </div>
        </form>
    )
    }

How do I create a ListView with rounded corners in Android?

Although that did work, it took out the entire background colour as well. I was looking for a way to do just the border and just replace that XML layout code with this one and I was good to go!

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke android:width="4dp" android:color="#FF00FF00" />
    <padding android:left="7dp" android:top="7dp"
            android:right="7dp" android:bottom="7dp" />
    <corners android:radius="4dp" />
</shape> 

There are No resources that can be added or removed from the server

Right click on the project, select properties and then select "Targeted Runtimes". Check if Tomcat is selected here.

Targeted Runtimes

SQL: How to properly check if a record exists

You can use:

SELECT COUNT(1) FROM MyTable WHERE ... 

or

WHERE [NOT] EXISTS 
( SELECT 1 FROM MyTable WHERE ... )

This will be more efficient than SELECT * since you're simply selecting the value 1 for each row, rather than all the fields.

There's also a subtle difference between COUNT(*) and COUNT(column name):

  • COUNT(*) will count all rows, including nulls
  • COUNT(column name) will only count non null occurrences of column name

Gradle build without tests

gradle build -x test --parallel

If your machine has multiple cores. However, it is not recommended to use parallel clean.

What is the difference between URI, URL and URN?

URL -- Uniform Resource Locator

Contains information about how to fetch a resource from its location. For example:

  • http://example.com/mypage.html
  • ftp://example.com/download.zip
  • mailto:[email protected]
  • file:///home/user/file.txt
  • http://example.com/resource?foo=bar#fragment
  • /other/link.html (A relative URL, only useful in the context of another URL)

URLs always start with a protocol (http) and usually contain information such as the network host name (example.com) and often a document path (/foo/mypage.html). URLs may have query parameters and fragment identifiers.

URN -- Uniform Resource Name

Identifies a resource by name. It always starts with the prefix urn: For example:

  • urn:isbn:0451450523 to identify a book by its ISBN number.
  • urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66 a globally unique identifier
  • urn:publishing:book - An XML namespace that identifies the document as a type of book.

URNs can identify ideas and concepts. They are not restricted to identifying documents. When a URN does represent a document, it can be translated into a URL by a "resolver". The document can then be downloaded from the URL.

URI -- Uniform Resource Identifier

URIs encompasses both URLs, URNs, and other ways to indicate a resource.

An example of a URI that is neither a URL nor a URN would be a data URI such as data:,Hello%20World. It is not a URL or URN because the URI contains the data. It neither names it, nor tells you how to locate it over the network.

There are also uniform resource citations (URCs) that point to meta data about a document rather than to the document itself. An example of a URC would be an indicator for viewing the source code of a web page: view-source:http://example.com/. A URC is another type of URI that is neither URL nor URN.

Frequently Asked Questions

I've heard that I shouldn't say URL anymore, why?

The w3 spec for HTML says that the href of an anchor tag can contain a URI, not just a URL. You should be able to put in a URN such as <a href="urn:isbn:0451450523">. Your browser would then resolve that URN to a URL and download the book for you.

Do any browsers actually know how to fetch documents by URN?

Not that I know of, but modern web browser do implement the data URI scheme.

Can a URI be both a URL and a URN?

Good question. I've seen lots of places on the web that state this is true. I haven't been able to find any examples of something that is both a URL and a URN. I don't see how it is possible because a URN starts with urn: which is not a valid network protocol.

Does the difference between URL and URI have anything to do with whether it is relative or absolute?

No. Both relative and absolute URLs are URLs (and URIs.)

Does the difference between URL and URI have anything to do with whether it has query parameters?

No. Both URLs with and without query parameters are URLs (and URIs.)

Does the difference between URL and URI have anything to do with whether it has a fragment identifier?

No. Both URLs with and without fragment identifiers are URLs (and URIs.)

Is a tel: URI a URL or a URN?

For example tel:1-800-555-5555. It doesn't start with urn: and it has a protocol for reaching a resource over a network. It must be a URL.

But doesn't the w3C now say that URLs and URIs are the same thing?

Yes. The W3C realized that there is a ton of confusion about this. They issued a URI clarification document that says that it is now OK to use URL and URI interchangeably. It is no longer useful to strictly segment URIs into different types such as URL, URN, and URC.

WCF change endpoint address at runtime

app.config

<client>
    <endpoint address="" binding="basicHttpBinding" 
    bindingConfiguration="LisansSoap" 
    contract="Lisans.LisansSoap" 
    name="LisansSoap" />
</client>

program

 Lisans.LisansSoapClient test = new LisansSoapClient("LisansSoap",
                         "http://webservis.uzmanevi.com/Lisans/Lisans.asmx");

 MessageBox.Show(test.LisansKontrol("","",""));

What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?

The first, curly braces. Otherwise, you run into consistency issues with keys that have odd characters in them, like =.

# Works fine.
a = {
    'a': 'value',
    'b=c': 'value',
}

# Eeep! Breaks if trying to be consistent.
b = dict( 
    a='value',
    b=c='value',
)

Get first day of week in PHP?

You can use Carbon library as well

$dateString = '02-21-2015'; // example in format MM-dd-yyyy
$date = Carbon::createFromFormat('m-d-Y', $dateString);
$date->hour(0)->minute(0)->second(0)->startOfWeek();
$dateString = $date->Format('m-d-Y'); // and you have got a string value "02-16-2015"

Capture iOS Simulator video for App Preview

For Xcode 8.2 or later

You can take videos and screenshots of Simulator using the xcrun simctl, a command-line utility to control the Simulator

  1. Run your app on the simulator

  2. Open a terminal

  3. Run the command

    • To take a screenshot

      xcrun simctl io booted screenshot <filename>.<file extension>

      For example:

      xcrun simctl io booted screenshot myScreenshot.png

    • To take a video

      xcrun simctl io booted recordVideo <filename>.<file extension>

      For example:

      xcrun simctl io booted recordVideo appVideo.mov

  4. Press ctrl + C to stop recording the video.

The default location for the created file is the current directory.

Xcode 11.2 and later gives extra options.

From Xcode 11.2 Beta Release Notes

simctl video recording now produces smaller video files, supports HEIC compression, and takes advantage of hardware encoding support where available. In addition, the ability to record video on iOS 13, tvOS 13, and watchOS 6 devices has been restored.

You could use additional flags:

xcrun simctl io --help
Set up a device IO operation.
Usage: simctl io <device> <operation> <arguments>

...

    recordVideo [--codec=<codec>] [--display=<display>] [--mask=<policy>] [--force] <file or url>
        Records the display to a QuickTime movie at the specified file or url.
        --codec      Specifies the codec type: "h264" or "hevc". Default is "hevc".

        --display    iOS: supports "internal" or "external". Default is "internal".
                     tvOS: supports only "external"
                     watchOS: supports only "internal"

        --mask       For non-rectangular displays, handle the mask by policy:
                     ignored: The mask is ignored and the unmasked framebuffer is saved.
                     alpha: Not supported, but retained for compatibility; the mask is rendered black.
                     black: The mask is rendered black.

        --force      Force the output file to be written to, even if the file already exists.

    screenshot [--type=<type>] [--display=<display>] [--mask=<policy>] <file or url>
        Saves a screenshot as a PNG to the specified file or url(use "-" for stdout).
        --type       Can be "png", "tiff", "bmp", "gif", "jpeg". Default is png.

        --display    iOS: supports "internal" or "external". Default is "internal".
                     tvOS: supports only "external"
                     watchOS: supports only "internal"

                     You may also specify a port by UUID
        --mask       For non-rectangular displays, handle the mask by policy:
                     ignored: The mask is ignored and the unmasked framebuffer is saved.
                     alpha: The mask is used as premultiplied alpha.
                     black: The mask is rendered black.

Now you can take a screenshot in jpeg, with mask (for non-rectangular displays) and some other flags:

xcrun simctl io booted screenshot --type=jpeg --mask=black screenshot.jpeg

CSS for grabbing cursors (drag & drop)

I think move would probably be the closest standard cursor value for what you're doing:

move
Indicates something is to be moved.

How to capture a list of specific type with mockito

Based on @tenshi's and @pkalinow's comments (also kudos to @rogerdpack), the following is a simple solution for creating a list argument captor that also disables the "uses unchecked or unsafe operations" warning:

@SuppressWarnings("unchecked")
final ArgumentCaptor<List<SomeType>> someTypeListArgumentCaptor =
    ArgumentCaptor.forClass(List.class);

Full example here and corresponding passing CI build and test run here.

Our team has been using this for some time in our unit tests and this looks like the most straightforward solution for us.

This compilation unit is not on the build path of a Java project

Another alternative to Loganathan Mohanraj's solution (which effectively does the same, but from the GUI):

  1. Right-Click on your project
  2. Go to "Properties"
  3. Choose "Project Natures"
  4. Click on "Add"
  5. Choose "Java"
  6. Click "Apply and Close"

How to compare only date in moment.js

Meanwhile you can use the isSameOrAfter method:

moment('2010-10-20').isSameOrAfter('2010-10-20', 'day');

Docs: https://momentjs.com/docs/#/query/is-same-or-after/

Check if one date is between two dates

Instead of comparing the dates directly, compare the getTime() value of the date. The getTime() function returns the number of milliseconds since Jan 1, 1970 as an integer-- should be trivial to determine if one integer falls between two other integers.

Something like

if((check.getTime() <= to.getTime() && check.getTime() >= from.getTime()))      alert("date contained");

Could not load type from assembly error

I was getting this error and nothing I found on StackOverflow or elsewhere solved it, but bmoeskau's answer to this question pointed me in the right direction for the fix, which hasn't been mentioned yet as an answer. My answer isn't strictly related to the original question, but I'm posting it here under the assumption that someone having this problem will find there way here through searching Google or something similar (like myself one month from now when this bites me again, arg!).

My assembly is in the GAC, so there is theoretically only one version of the assembly available. Except IIS is helpfully caching the old version and giving me this error. I had just changed, rebuilt and reinstalled the assembly in the GAC. One possible solution is to use Task Manager to kill w3wp.exe. This forces IIS to reread the assembly from the GAC: problem solved.

Downloading all maven dependencies to a directory NOT in repository?

I finally figured out a how to use Maven. From within Eclipse, create a new Maven project.

Download Maven, extract the archive, add the /bin folder to path.

Validate install from command-line by running mvn -v (will print version and java install path)

Change to the project root folder (where pom.xml is located) and run:

mvn dependency:copy-dependencies

All jar-files are downloaded to /target/dependency.

To set another output directory:

mvn dependency:copy-dependencies -DoutputDirectory="c:\temp"

Now it's possible to re-use this Maven-project for all dependency downloads by altering the pom.xml

Add jars to java project by build path -> configure build path -> libraries -> add JARs..

Android: ListView elements with multiple clickable buttons

I Know it's late but this may help, this is an example how I write custom adapter class for different click actions

 public class CustomAdapter extends BaseAdapter {

    TextView title;
  Button button1,button2;

    public long getItemId(int position) {
        return position;
    }

    public int getCount() {
        return mAlBasicItemsnav.size();  // size of your list array
    }

    public Object getItem(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = getLayoutInflater().inflate(R.layout.listnavsub_layout, null, false); // use sublayout which you want to inflate in your each list item
        }

        title = (TextView) convertView.findViewById(R.id.textViewnav); // see you have to find id by using convertView.findViewById 
        title.setText(mAlBasicItemsnav.get(position));
      button1=(Button) convertView.findViewById(R.id.button1);
      button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //your click action 

           // if you have different click action at different positions then
            if(position==0)
              {
                       //click action of 1st list item on button click
        }
           if(position==1)
              {
                       //click action of 2st list item on button click
        }
    });

 // similarly for button 2

   button2=(Button) convertView.findViewById(R.id.button2);
      button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //your click action 

    });



        return convertView;
    }
}

How are SSL certificate server names resolved/Can I add alternative names using keytool?

How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)

From RFC 2818 (Section 3.1):

If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.

[...]

In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.

Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).

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

EDIT:

You can request a SAN in OpenSSL by changing openssl.cnf (it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF environment variable).

Set the following options (find the appropriate sections within brackets first):

[req]
req_extensions = v3_req

[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com

There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html

Get all dates between two dates in SQL Server

This is the method that I would use.

DECLARE 
    @DateFrom DATETIME = GETDATE(),
    @DateTo DATETIME = DATEADD(HOUR, -1, GETDATE() + 2); -- Add 2 days and minus one hour


-- Dates spaced a day apart 

WITH MyDates (MyDate)
AS (
    SELECT @DateFrom
    UNION ALL
    SELECT DATEADD(DAY, 1, MyDate)
    FROM MyDates
    WHERE MyDate < @DateTo
   )

SELECT 
    MyDates.MyDate
    , CONVERT(DATE, MyDates.MyDate) AS [MyDate in DATE format]
FROM 
    MyDates;

Here is a similar example, but this time the dates are spaced one hour apart to further aid understanding of how the query works:

-- Alternative example with dates spaced an hour apart

WITH MyDates (MyDate)
AS (SELECT @DateFrom
    UNION ALL
    SELECT DATEADD(HOUR, 1, MyDate)
    FROM MyDates
    WHERE MyDate < @DateTo
   )

SELECT 
    MyDates.MyDate
FROM 
    MyDates;

As you can see, the query is fast, accurate and versatile.

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

It seems the button you are invoking is not in the layout you are using in setContentView(R.layout.your_layout) Check it.

Call js-function using JQuery timer

setInterval is the function you want. That repeats every x miliseconds.

window.setInterval(function() {
    alert('test');
}, 10000);

SQL not a single-group group function

Maybe you find this simpler

select * from (
    select ssn, sum(time) from downloads
    group by ssn
    order by sum(time) desc
) where rownum <= 10 --top 10 downloaders

Regards
K

How to Git stash pop specific stash in 1.8.3?

You need to escape the braces:

git stash pop stash@\{1\}

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

Enable Multidex through build.gradle of your app module

multiDexEnabled true

Same as below -

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

Then follow below steps -

  1. From the Build menu -> press the Clean Project button.
  2. When task completed, press the Rebuild Project button from the Build menu.
  3. From menu File -> Invalidate cashes / Restart

compile is now deprecated so it's better to use implementation or api

recursively use scp but excluding some folders

This one works fine for me as the directories structure is not important for me.

scp -r USER@HOSTNAME:~/bench1/?cpu/p_?/image/ .

Assuming /bench1 is in the home directory of the current user. Also, change USER and HOSTNAME to the real values.

Does HTML5 <video> playback support the .avi format?

Short answer: No. Use WebM or Ogg instead.

This article covers just about everything you need to know about the <video> element, including which browsers support which container formats and codecs.

What is the naming convention in Python for variable and function names?

I personally use Java's naming conventions when developing in other programming languages as it is consistent and easy to follow. That way I am not continuously struggling over what conventions to use which shouldn't be the hardest part of my project!

Where is SQL Profiler in my SQL Server 2008?

Management Studio->Tools->SQL Server Profiler.

If it is not installed see this link

Swift error : signal SIGABRT how to solve it

If you run into this in Xcode 10 you will have to clean before build. Or, switch to the legacy build system. File -> Workspace Settings... -> Build System: Legacy Build System.

Defined Edges With CSS3 Filter Blur

You can stop the image from overlapping it's edges by clipping the image and applying a wrapper element which sets the blur effect to 0 pixels. This is how it looks like:

HTML

<div id="wrapper">
  <div id="image"></div>
</div>

CSS

#wrapper {
  width: 1024px;
  height: 768px;

  border: 1px solid black;

  // 'blur(0px)' will prevent the wrapped image
  // from overlapping the border
  -webkit-filter: blur(0px);
  -moz-filter: blur(0px);
  -ms-filter: blur(0px);
  filter: blur(0px);
}

#wrapper #image {
  width: 1024px;
  height: 768px;

  background-image: url("../images/cats.jpg");
  background-size: cover;

  -webkit-filter: blur(10px);
  -moz-filter: blur(10px);
  -ms-filter: blur(10px);
  filter: blur(10px);

  // Position 'absolute' is needed for clipping
  position: absolute;
  clip: rect(0px, 1024px, 768px, 0px);
}

How do I convert NSMutableArray to NSArray?

i was search for the answer in swift 3 and this question was showed as first result in search and i get inspired the answer from it so here is the swift 3 code

let array: [String] = nsMutableArrayObject.copy() as! [String]

Python Pandas merge only certain columns

You want to use TWO brackets, so if you are doing a VLOOKUP sort of action:

df = pd.merge(df,df2[['Key_Column','Target_Column']],on='Key_Column', how='left')

This will give you everything in the original df + add that one corresponding column in df2 that you want to join.

Sending files using POST with HttpURLConnection

based on Mihai's solution, if anyone has the problem of saving images on the server like what happened on my server. change the Bitmap to bytebuffer part to :

ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG,100,bos);
        byte[] pixels = bos.toByteArray();

Initialization of an ArrayList in one line

It would be simpler if you were to just declare it as a List - does it have to be an ArrayList?

List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");

Or if you have only one element:

List<String> places = Collections.singletonList("Buenos Aires");

This would mean that places is immutable (trying to change it will cause an UnsupportedOperationException exception to be thrown).

To make a mutable list that is a concrete ArrayList you can create an ArrayList from the immutable list:

ArrayList<String> places = new ArrayList<>(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));

How to pass model attributes from one Spring MVC controller to another controller?

I used @ControllerAdvice , please check is available in Spring 3.X; I am using it in Spring 4.0.

@ControllerAdvice 
public class CommonController extends ControllerBase{
@Autowired
MyService myServiceInstance;

    @ModelAttribute("userList")
    public List<User> getUsersList()
    {
       //some code
       return ...
    }
}

How can I declare and use Boolean variables in a shell script?

In many programming languages, the Boolean type is, or is implemented as, a subtype of integer, where true behaves like 1 and false behaves like 0:

Mathematically, Boolean algebra resembles integer arithmetic modulo 2. Therefore, if a language doesn't provide native Boolean type, the most natural and efficient solution is to use integers. This works with almost any language. For example, in Bash you can do:

# val=1; ((val)) && echo "true" || echo "false"
true
# val=0; ((val)) && echo "true" || echo "false"
false

man bash:

((expression))

The expression is evaluated according to the rules described below under ARITHMETIC EVALUATION. If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1. This is exactly equivalent to let "expression".

New to MongoDB Can not run command mongo

You just need to create directory in C:. as C:\data\db\

Now just start mongoDB:

C:\Users\gi.gupta>"c:\Program Files\MongoDB\Server\3.2\bin\mongod.exe"
2016-05-03T10:49:30.412+0530 I CONTROL  [main] Hotfix KB2731284 or later update is not installed, will zero-out data files
2016-05-03T10:49:30.414+0530 I CONTROL  [initandlisten] MongoDB starting : pid=7904 port=27017 dbpath=C:\data\db\ 64-bit host=GLTPM-W036
2016-05-03T10:49:30.414+0530 I CONTROL  [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2
2016-05-03T10:49:30.414+0530 I CONTROL  [initandlisten] db version v3.2.6
2016-05-03T10:49:30.414+0530 I CONTROL  [initandlisten] git version: 05552b562c7a0b3143a729aaa0838e558dc49b25
2016-05-03T10:49:30.414+0530 I CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.0.1p-fips 9 Jul 2015
2016-05-03T10:49:30.414+0530 I CONTROL  [initandlisten] allocator: tcmalloc
2016-05-03T10:49:30.414+0530 I CONTROL  [initandlisten] modules: none
2016-05-03T10:49:30.414+0530 I CONTROL  [initandlisten] build environment:
2016-05-03T10:49:30.414+0530 I CONTROL  [initandlisten]     distmod: 2008plus-ssl
2016-05-03T10:49:30.414+0530 I CONTROL  [initandlisten]     distarch: x86_64
2016-05-03T10:49:30.414+0530 I CONTROL  [initandlisten]     target_arch: x86_64
2016-05-03T10:49:30.414+0530 I CONTROL  [initandlisten] options: {}
2016-05-03T10:49:30.427+0530 I -        [initandlisten] Detected data files in C:\data\db\ created by the 'wiredTiger' storage engine, so setting the active storage engine to
2016-05-03T10:49:30.429+0530 I STORAGE  [initandlisten] wiredtiger_open config: create,cache_size=1G,session_max=20000,eviction=(threads_max=4),config_base=false,statistics=(f
chive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000),checkpoint=(wait=60,log_size=2GB),statistics_log=(wait=0),
2016-05-03T10:49:30.998+0530 I NETWORK  [HostnameCanonicalizationWorker] Starting hostname canonicalization worker
2016-05-03T10:49:30.998+0530 I FTDC     [initandlisten] Initializing full-time diagnostic data capture with directory 'C:/data/db/diagnostic.data'
2016-05-03T10:49:31.000+0530 I NETWORK  [initandlisten] waiting for connections on port 27017
2016-05-03T10:49:40.766+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:57504 #1 (1 connection now open)

It will then run as service in background.

How do I do base64 encoding on iOS?

Since this seems to be the number one google hit on base64 encoding and iphone, I felt like sharing my experience with the code snippet above.

It works, but it is extremely slow. A benchmark on a random image (0.4 mb) took 37 seconds on native iphone. The main reason is probably all the OOP magic - single char NSStrings etc, which are only autoreleased after the encoding is done.

Another suggestion posted here (ab)uses the openssl library, which feels like overkill as well.

The code below takes 70 ms - that's a 500 times speedup. This only does base64 encoding (decoding will follow as soon as I encounter it)

+ (NSString *) base64StringFromData: (NSData *)data length: (int)length {
int lentext = [data length]; 
if (lentext < 1) return @"";

char *outbuf = malloc(lentext*4/3+4); // add 4 to be sure

if ( !outbuf ) return nil;

const unsigned char *raw = [data bytes];

int inp = 0;
int outp = 0;
int do_now = lentext - (lentext%3);

for ( outp = 0, inp = 0; inp < do_now; inp += 3 )
{
    outbuf[outp++] = base64EncodingTable[(raw[inp] & 0xFC) >> 2];
    outbuf[outp++] = base64EncodingTable[((raw[inp] & 0x03) << 4) | ((raw[inp+1] & 0xF0) >> 4)];
    outbuf[outp++] = base64EncodingTable[((raw[inp+1] & 0x0F) << 2) | ((raw[inp+2] & 0xC0) >> 6)];
    outbuf[outp++] = base64EncodingTable[raw[inp+2] & 0x3F];
}

if ( do_now < lentext )
{
    char tmpbuf[2] = {0,0};
    int left = lentext%3;
    for ( int i=0; i < left; i++ )
    {
        tmpbuf[i] = raw[do_now+i];
    }
    raw = tmpbuf;
    outbuf[outp++] = base64EncodingTable[(raw[inp] & 0xFC) >> 2];
    outbuf[outp++] = base64EncodingTable[((raw[inp] & 0x03) << 4) | ((raw[inp+1] & 0xF0) >> 4)];
    if ( left == 2 ) outbuf[outp++] = base64EncodingTable[((raw[inp+1] & 0x0F) << 2) | ((raw[inp+2] & 0xC0) >> 6)];
}

NSString *ret = [[[NSString alloc] initWithBytes:outbuf length:outp encoding:NSASCIIStringEncoding] autorelease];
free(outbuf);

return ret;
}

I left out the line-cutting since I didn't need it, but it's trivial to add.

For those who are interested in optimizing: the goal is to minimize what happens in the main loop. Therefore all logic to deal with the last 3 bytes is treated outside the loop.

Also, try to work on data in-place, without additional copying to/from buffers. And reduce any arithmetic to the bare minimum.

Observe that the bits that are put together to look up an entry in the table, would not overlap when they were to be orred together without shifting. A major improvement could therefore be to use 4 separate 256 byte lookup tables and eliminate the shifts, like this:

outbuf[outp++] = base64EncodingTable1[(raw[inp] & 0xFC)];
outbuf[outp++] = base64EncodingTable2[(raw[inp] & 0x03) | (raw[inp+1] & 0xF0)];
outbuf[outp++] = base64EncodingTable3[(raw[inp+1] & 0x0F) | (raw[inp+2] & 0xC0)];
outbuf[outp++] = base64EncodingTable4[raw[inp+2] & 0x3F];

Of course you could take it a whole lot further, but that's beyond the scope here.

Connect to mysql in a docker container from the host

mysql -u root -P 4406 -h localhost --protocol=tcp -p

Remember to change the user, port and host so that it matches your configurations. The -p flag is required if your database user is configured with a password

Python: 'break' outside loop

break breaks out of a loop, not an if statement, as others have pointed out. The motivation for this isn't too hard to see; think about code like

for item in some_iterable:
    ...
    if break_condition():
        break 

The break would be pretty useless if it terminated the if block rather than terminated the loop -- terminating a loop conditionally is the exact thing break is used for.

Generating Random Number In Each Row In Oracle Query

Something like?

select t.*, round(dbms_random.value() * 8) + 1 from foo t;

Edit: David has pointed out this gives uneven distribution for 1 and 9.

As he points out, the following gives a better distribution:

select t.*, floor(dbms_random.value(1, 10)) from foo t;

htaccess <Directory> deny from all

You can also use RedirectMatch directive to deny access to a folder.

To deny access to a folder, you can use the following RedirectMatch in htaccess :

 RedirectMatch 403 ^/folder/?$

This will forbid an external access to /folder/ eg : http://example.com/folder/ will return a 403 forbidden error.

To deny access to everything inside the folder, You can use this :

RedirectMatch 403 ^/folder/.*$

This will block access to the entire folder eg : http://example.com/folder/anyURI will return a 403 error response to client.

'App not Installed' Error on Android

Check with the Android version.

If you are installing non-market apps, and incompatible version you will get this error.

Ex: Application targetted to 2.3.4 Your device is 2.2 Then you will get this error.

Forward declaring an enum in C++

If you really don't want your enum to appear in your header file AND ensure that it is only used by private methods, then one solution can be to go with the pimpl principle.

It's a technique that ensure to hide the class internals in the headers by just declaring:

class A 
{
public:
    ...
private:
    void* pImpl;
};

Then in your implementation file (cpp), you declare a class that will be the representation of the internals.

class AImpl
{
public:
    AImpl(A* pThis): m_pThis(pThis) {}

    ... all private methods here ...
private:
    A* m_pThis;
};

You must dynamically create the implementation in the class constructor and delete it in the destructor and when implementing public method, you must use:

((AImpl*)pImpl)->PrivateMethod();

There are pros for using pimpl, one is that it decouple your class header from its implementation, no need to recompile other classes when changing one class implementation. Another is that is speeds up your compilation time because your headers are so simple.

But it's a pain to use, so you should really ask yourself if just declaring your enum as private in the header is that much a trouble.