Programs & Examples On #Hierarchical query

Regular Expression to find a string included between two characters while EXCLUDING the delimiters

If you need extract the text without the brackets, you can use bash awk

echo " [hola mundo] " | awk -F'[][]' '{print $2}'

result:

hola mundo

How to trim a string to N chars in Javascript?

    let trimString = function (string, length) {
      return string.length > length ? 
             string.substring(0, length) + '...' :
             string;
    };

Use Case,

let string = 'How to trim a string to N chars in Javascript';

trimString(string, 20);

//How to trim a string...

Compare 2 JSON objects

Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).

You need to do a deep equals.

From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.

Object.extend(Object, {
   deepEquals: function(o1, o2) {
     var k1 = Object.keys(o1).sort();
     var k2 = Object.keys(o2).sort();
     if (k1.length != k2.length) return false;
     return k1.zip(k2, function(keyPair) {
       if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
         return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
       } else {
         return o1[keyPair[0]] == o2[keyPair[1]];
       }
     }).all();
   }
});

Usage:

var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);

if (Object.deepEquals(anObj, anotherObj))
   ...

PHP: date function to get month of the current date

See http://php.net/date

date('m') or date('n') or date('F') ...

Update

m Numeric representation of a month, with leading zeros 01 through 12

n Numeric representation of a month, without leading zeros 1 through 12

F Alphabetic representation of a month January through December

....see the docs link for even more options.

How to save a data frame as CSV to a user selected location using tcltk

You need not to use even the package "tcltk". You can simply do as shown below:

write.csv(x, file = "c:\\myname\\yourfile.csv", row.names = FALSE)

Give your path inspite of "c:\myname\yourfile.csv".

What is `git push origin master`? Help with git's refs, heads and remotes

Or as a single command:

git push -u origin master:my_test

Pushes the commits from your local master branch to a (possibly new) remote branch my_test and sets up master to track origin/my_test.

How do you push a tag to a remote repository using Git?

To push a single tag:

git push origin <tag_name>

And the following command should push all tags (not recommended):

git push --tags

Python - Using regex to find multiple matches and print them out

Do not use regular expressions to parse HTML.

But if you ever need to find all regexp matches in a string, use the findall function.

import re
line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</form> more text?'
matches = re.findall('<form>(.*?)</form>', line, re.DOTALL)
print(matches)

# Output: ['Form 1', 'Form 2']

What does Visual Studio mean by normalize inconsistent line endings?

It means that, for example, some of your lines of text with a <Carriage Return><Linefeed> (the Windows standard), and some end with just a <Linefeed> (the Unix standard).

If you click 'yes' these the end-of-lines in your source file will be converted to have all the same format.

This won't make any difference to the compiler (because end-of-lines count as mere whitespace), but it might make some difference to other tools (e.g. the 'diff' on your version control system).

ReferenceError: event is not defined error in Firefox

It is because you forgot to pass in event into the click function:

$('.menuOption').on('click', function (e) { // <-- the "e" for event

    e.preventDefault(); // now it'll work

    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();
});

On a side note, e is more commonly used as opposed to the word event since Event is a global variable in most browsers.

CSS vertical alignment of inline/inline-block elements

For fine tuning the position of an inline-block item, use top and left:

  position: relative;
  top: 5px;
  left: 5px;

Thanks CSS-Tricks!

What does the "$" sign mean in jQuery or JavaScript?

The $ symbol simply invokes the jQuery library's selector functionality. So $("#Text") returns the jQuery object for the Text div which can then be modified.

Upgrade version of Pandas

Simple Solution, just type the below:

conda update pandas 

Type this in your preferred shell (on Windows, use Anaconda Prompt as administrator).

Is "delete this" allowed in C++?

One of the reasons that C++ was designed was to make it easy to reuse code. In general, C++ should be written so that it works whether the class is instantiated on the heap, in an array, or on the stack. "Delete this" is a very bad coding practice because it will only work if a single instance is defined on the heap; and there had better not be another delete statement, which is typically used by most developers to clean up the heap. Doing this also assumes that no maintenance programmer in the future will cure a falsely perceived memory leak by adding a delete statement.

Even if you know in advance that your current plan is to only allocate a single instance on the heap, what if some happy-go-lucky developer comes along in the future and decides to create an instance on the stack? Or, what if he cuts and pastes certain portions of the class to a new class that he intends to use on the stack? When the code reaches "delete this" it will go off and delete it, but then when the object goes out of scope, it will call the destructor. The destructor will then try to delete it again and then you are hosed. In the past, doing something like this would screw up not only the program but the operating system and the computer would need to be rebooted. In any case, this is highly NOT recommended and should almost always be avoided. I would have to be desperate, seriously plastered, or really hate the company I worked for to write code that did this.

Is there an easy way to return a string repeated X number of times?

You can repeat your string (in case it's not a single char) and concat the result, like this:

String.Concat(Enumerable.Repeat("---", 5))

Construct pandas DataFrame from list of tuples of (row,col,values)

I submit that it is better to leave your data stacked as it is:

df = pandas.DataFrame(data, columns=['R_Number', 'C_Number', 'Avg', 'Std'])

# Possibly also this if these can always be the indexes:
# df = df.set_index(['R_Number', 'C_Number'])

Then it's a bit more intuitive to say

df.set_index(['R_Number', 'C_Number']).Avg.unstack(level=1)

This way it is implicit that you're seeking to reshape the averages, or the standard deviations. Whereas, just using pivot, it's purely based on column convention as to what semantic entity it is that you are reshaping.

Is there a way to force npm to generate package-lock.json?

By default, package-lock.json is updated whenever you run npm install. However, this can be disabled globally by setting package-lock=false in ~/.npmrc.

When the global package-lock=false setting is active, you can still force a project’s package-lock.json file to be updated by running:

npm install --package-lock

This command is the only surefire way of forcing a package-lock.json update.

What's the simplest way of detecting keyboard input in a script from the terminal?

import turtle

wn = turtle.Screen()
turtle = turtle.Turtle()

def printLetter():
    print("a")

turtle.listen()
turtle.onkey(printLetter, "a")

Remove directory from remote repository after adding them to .gitignore

The answer from Blundell should work, but for some bizarre reason it didn't do with me. I had to pipe first the filenames outputted by the first command into a file and then loop through that file and delete that file one by one.

git ls-files -i --exclude-from=.gitignore > to_remove.txt
while read line; do `git rm -r --cached "$line"`; done < to_remove.txt
rm to_remove.txt
git commit -m 'Removed all files that are in the .gitignore' 
git push origin master

Newline in JLabel

Surround the string with <html></html> and break the lines with <br/>.

JLabel l = new JLabel("<html>Hello World!<br/>blahblahblah</html>", SwingConstants.CENTER);

What issues should be considered when overriding equals and hashCode in Java?

One gotcha I have found is where two objects contain references to each other (one example being a parent/child relationship with a convenience method on the parent to get all children).
These sorts of things are fairly common when doing Hibernate mappings for example.

If you include both ends of the relationship in your hashCode or equals tests it's possible to get into a recursive loop which ends in a StackOverflowException.
The simplest solution is to not include the getChildren collection in the methods.

How do I open a Visual Studio project in design view?

Click on the form in the Solution Explorer

How to print multiple variable lines in Java

You can create Class Person with fields firstName and lastName and define method toString(). Here I created a util method which returns String presentation of a Person object.

This is a sample

Main

public class Main {

    public static void main(String[] args) {
        Person person = generatePerson();
        String personStr = personToString(person);
        System.out.println(personStr);
    }

    private static Person generatePerson() {
        String firstName = "firstName";//generateFirstName();
        String lastName = "lastName";//generateLastName;
        return new Person(firstName, lastName);
    }

    /*
     You can even put this method into a separate util class.
    */
    private static String personToString(Person person) {
        return person.getFirstName() + "\n" + person.getLastName();
    }
}

Person

public class Person {

    private String firstName;
    private String lastName;

    //getters, setters, constructors.
}

I prefer a separate util method to toString(), because toString() is used for debug. https://stackoverflow.com/a/3615741/4587961

I had experience writing programs with many outputs: HTML UI, excel or txt file, console. They may need different object presentation, so I created a util class which builds a String depending on the output.

How to add images to README.md on GitHub?

There are 2 simple way you can do this ,

1) use HTML img tag ,

2) ![](the path where your image is saved/image-name.png)

the path would you can copy from the URL in the browser while you have opened that image. there might be an issue occur of spacing so make sure if there is any space b/w two words of path or in image name add-> %20. just like browser do.

Both of them will work , if you want to understand more you can check my github -> https://github.com/adityarawat29

What is the difference between the float and integer data type when the size is the same?

Floats are used to store a wider range of number than can be fit in an integer. These include decimal numbers and scientific notation style numbers that can be bigger values than can fit in 32 bits. Here's the deep dive into them: http://en.wikipedia.org/wiki/Floating_point

Java: recommended solution for deep cloning/copying an instance

I'd suggest to override Object.clone(), call super.clone() first and than call ref = ref.clone() on all references that you want to have deep copied. It's more or less Do it yourself approach but needs a bit less coding.

Change Spinner dropdown icon

Add theme to spinner

<Spinner style="@style/SpinnerTheme"
      android:layout_width="match_parent"
      android:layout_height="match_parent"/>

Add spinnerTheme to styles.xml

<style name="SpinnerTheme" parent="android:Widget.Spinner">
    <item name="android:background">@drawable/spinner_background</item>
</style>

Add New -> "Vector Asset" to drawable with e.g. "ic_keyboard_arrow_down_24dp"

Add spinner_background.xml to drawable

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <layer-list>
            <item android:drawable="@drawable/ic_keyboard_arrow_down_24dp" android:gravity="center_vertical|right" android:right="5dp"/>
        </layer-list>
    </item>
</selector>

How to create a .NET DateTime from ISO 8601 format

using System.Globalization;

DateTime d;
DateTime.TryParseExact(
    "2010-08-20T15:00:00",
    "s",
    CultureInfo.InvariantCulture,
    DateTimeStyles.AssumeUniversal, out d);

Undefined index error PHP

This is happening because your PHP code is getting executed before the form gets posted.

To avoid this wrap your PHP code in following if statement and it will handle the rest no need to set if statements for each variables

       if(isset($_POST) && array_key_exists('name_of_your_submit_input',$_POST))
        {
             //process PHP Code
        }
        else
        {
             //do nothing
         }

Git commit date

You can use the git show command.

To get the last commit date from git repository in a long(Unix epoch timestamp):

  • Command: git show -s --format=%ct
  • Result: 1605103148

Note: You can visit the git-show documentation to get a more detailed description of the options.

How to clean up R memory (without the need to restart my PC)?

I've found it helpful to go into my "tmp" folder and delete all hanging rsession files. This usually frees any memory that seems to be "stuck".

No Network Security Config specified, using platform default - Android Log

I had also the same problem. Please add this line in application tag in manifest. I hope it will also help you.

android:usesCleartextTraffic="true"

Bootstrap datepicker disabling past dates without current date

The following worked for me

$('.input-group.date').datepicker({
     format: 'dd/mm/yyyy',
     startDate: new Date()
});

C# - How to convert string to char?

var theString = "TEST";
char[] myChar = theString.ToCharArray();

I tested this in the C# interactive window of Visual Studio 2019 and got:

char[4] { 'T', 'E', 'S', 'T' }

Example of waitpid() in use?

Syntax of waitpid():

pid_t waitpid(pid_t pid, int *status, int options);

The value of pid can be:

  • < -1: Wait for any child process whose process group ID is equal to the absolute value of pid.
  • -1: Wait for any child process.
  • 0: Wait for any child process whose process group ID is equal to that of the calling process.
  • > 0: Wait for the child whose process ID is equal to the value of pid.

The value of options is an OR of zero or more of the following constants:

  • WNOHANG: Return immediately if no child has exited.
  • WUNTRACED: Also return if a child has stopped. Status for traced children which have stopped is provided even if this option is not specified.
  • WCONTINUED: Also return if a stopped child has been resumed by delivery of SIGCONT.

For more help, use man waitpid.

Java String encoding (UTF-8)

How is this different from the following?

This line of code here:

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));

constructs a new String object (i.e. a copy of oldString), while this line of code:

String newString = oldString;

declares a new variable of type java.lang.String and initializes it to refer to the same String object as the variable oldString.

Is there any scenario in which the two lines will have different outputs?

Absolutely:

String newString = oldString;
boolean isSameInstance = newString == oldString; // isSameInstance == true

vs.

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
 // isSameInstance == false (in most cases)    
boolean isSameInstance = newString == oldString;

a_horse_with_no_name (see comment) is right of course. The equivalent of

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));

is

String newString = new String(oldString);

minus the subtle difference wrt the encoding that Peter Lawrey explains in his answer.

How to initialize struct?

You use an implicit operator that converts the string value to a struct value:

public struct MyStruct {
  public string s;
  public int length;

  public static implicit operator MyStruct(string value) {
    return new MyStruct() { s = value, length = value.Length };
  }

}

Example:

MyStruct myStruct = "Lol";
Console.WriteLine(myStruct.s);
Console.WriteLine(myStruct.length);

Output:

Lol
3

Invalid Host Header when ngrok tries to connect to React dev server

If you use webpack devServer the simplest way is to set disableHostCheck, check webpack doc like this

devServer: {
    contentBase: path.join(__dirname, './dist'),
    compress: true,
    host: 'localhost',
    // host: '0.0.0.0',
    port: 8080,
    disableHostCheck: true //for ngrok
},

Getting the parameters of a running JVM

You can use jps like

jps -lvm

prints something like

4050 com.intellij.idea.Main -Xms128m -Xmx512m -XX:MaxPermSize=250m -ea -Xbootclasspath/a:../lib/boot.jar -Djb.restart.code=88
4667 sun.tools.jps.Jps -lvm -Dapplication.home=/opt/java/jdk1.6.0_22 -Xms8m

Getting Integer value from a String using javascript/jquery

Is this logically possible??.. I guess the approach that you must take is this way :

Str1 ="test123.00"
Str2 ="yes50.00"

This will be impossible to tackle unless you have delimiter in between test and 123.00

eg: Str1 = "test-123.00" 

Then you can split this way

Str2 = Str1.split("-"); 

This will return you an array of words split with "-"

Then you can do parseFloat(Str2[1]) to get the floating value i.e 123.00

minimize app to system tray

Handle the form’s Resize event. In this handler, you override the basic functionality of the Resize event to make the form minimize to the system tray and not to the taskbar. This can be done by doing the following in your form’s Resize event handler: Check whether the form’s WindowState property is set to FormWindowState.Minimized. If yes, hide your form, enable the NotifyIcon object, and show the balloon tip that shows some information. Once the WindowState becomes FormWindowState.Normal, disable the NotifyIcon object by setting its Visible property to false. Now, you want the window to reappear when you double click on the NotifyIcon object in the taskbar. For this, handle the NotifyIcon’s MouseDoubleClick event. Here, you show the form using the Show() method.

private void frmMain_Resize(object sender, EventArgs e)
{
    if (FormWindowState.Minimized == this.WindowState)
    {
       mynotifyicon.Visible = true;
       mynotifyicon.ShowBalloonTip(500);
       this.Hide();
    }

    else if (FormWindowState.Normal == this.WindowState)
    {
       mynotifyicon.Visible = false;
    }
}

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.

Static nested class in Java, why?

static nested class is just like any other outer class, as it doesn't have access to outer class members.

Just for packaging convenience we can club static nested classes into one outer class for readability purpose. Other than this there is no other use case of static nested class.

Example for such kind of usage, you can find in Android R.java (resources) file. Res folder of android contains layouts (containing screen designs), drawable folder (containing images used for project), values folder (which contains string constants), etc..

Sine all the folders are part of Res folder, android tool generates a R.java (resources) file which internally contains lot of static nested classes for each of their inner folders.

Here is the look and feel of R.java file generated in android: Here they are using only for packaging convenience.

/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */

package com.techpalle.b17_testthird;

public final class R {
    public static final class drawable {
        public static final int ic_launcher=0x7f020000;
    }
    public static final class layout {
        public static final int activity_main=0x7f030000;
    }
    public static final class menu {
        public static final int main=0x7f070000;
    }
    public static final class string {
        public static final int action_settings=0x7f050001;
        public static final int app_name=0x7f050000;
        public static final int hello_world=0x7f050002;
    }
}

Use superscripts in R axis labels

It works the same way for axes: parse(text='70^o*N') will raise the o as a superscript (the *N is to make sure the N doesn't get raised too).

labelsX=parse(text=paste(abs(seq(-100, -50, 10)), "^o ", "*W", sep=""))
labelsY=parse(text=paste(seq(50,100,10), "^o ", "*N", sep=""))
plot(-100:-50, 50:100, type="n", xlab="", ylab="", axes=FALSE)
axis(1, seq(-100, -50, 10), labels=labelsX)
axis(2, seq(50, 100, 10), labels=labelsY)
box()

How do I get the computer name in .NET

2 more helpful methods: System.Environment.GetEnvironmentVariable("ComputerName" )

System.Environment.GetEnvironmentVariable("ClientName" ) to get the name of the user's PC if they're connected via Citrix XenApp or Terminal Services (aka RDS, RDP, Remote Desktop)

How to create an Array with AngularJS's ng-model

It works fine for me: http://jsfiddle.net/qwertynl/htb9h/

My javascript:

var app = angular.module("myApp", [])
app.controller("MyCtrl", ['$scope', function($scope) {
    $scope.telephone = []; // << remember to set this
}]);

Android Percentage Layout Height

With introduction of ContraintLayout, it's possible to implement with Guidelines:

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.eugene.test1.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#AAA"
        android:text="TextView"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/guideline" />

    <android.support.constraint.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.5" />

</android.support.constraint.ConstraintLayout>

Result View

You can read more in this article Building interfaces with ConstraintLayout.

Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings

Here's some future-proof code for browsers that may lack escape/unescape(). Note that IE 9 and older don't support atob/btoa(), so you'd need to use custom base64 functions for them.

// Polyfill for escape/unescape
if( !window.unescape ){
    window.unescape = function( s ){
        return s.replace( /%([0-9A-F]{2})/g, function( m, p ) {
            return String.fromCharCode( '0x' + p );
        } );
    };
}
if( !window.escape ){
    window.escape = function( s ){
        var chr, hex, i = 0, l = s.length, out = '';
        for( ; i < l; i ++ ){
            chr = s.charAt( i );
            if( chr.search( /[A-Za-z0-9\@\*\_\+\-\.\/]/ ) > -1 ){
                out += chr; continue; }
            hex = s.charCodeAt( i ).toString( 16 );
            out += '%' + ( hex.length % 2 != 0 ? '0' : '' ) + hex;
        }
        return out;
    };
}

// Base64 encoding of UTF-8 strings
var utf8ToB64 = function( s ){
    return btoa( unescape( encodeURIComponent( s ) ) );
};
var b64ToUtf8 = function( s ){
    return decodeURIComponent( escape( atob( s ) ) );
};

A more comprehensive example for UTF-8 encoding and decoding can be found here: http://jsfiddle.net/47zwb41o/

calculating execution time in c++

OVERVIEW

I have written a simple semantic hack for this using @AshutoshMehraresponse. You code looks really readable this way!

MACRO

#include <time.h>

#ifndef SYSOUT_F
#define SYSOUT_F(f, ...)      _RPT1( 0, f, __VA_ARGS__ ) // For Visual studio
#endif

#ifndef speedtest__             
#define speedtest__(data)   for (long blockTime = NULL; (blockTime == NULL ? (blockTime = clock()) != NULL : false); SYSOUT_F(data "%.9fs", (double) (clock() - blockTime) / CLOCKS_PER_SEC))
#endif

USAGE

speedtest__("Block Speed: ")
{
    // The code goes here
}

OUTPUT

Block Speed: 0.127000000s

Angular bootstrap datepicker date format does not format ng-model value

All proposed solutions didn't work for me but the closest one was from @Rishii.

I'm using AngularJS 1.4.4 and UI Bootstrap 0.13.3.

.directive('jsr310Compatible', ['dateFilter', 'dateParser', function(dateFilter, dateParser) {
  return {
    restrict: 'EAC',
    require: 'ngModel',
    priority: 1,
    link: function(scope, element, attrs, ngModel) {
      var dateFormat = 'yyyy-MM-dd';

      ngModel.$parsers.push(function(viewValue) {
        return dateFilter(viewValue, dateFormat);
      });

      ngModel.$validators.date = function (modelValue, viewValue) {
        var value = modelValue || viewValue;

        if (!attrs.ngRequired && !value) {
          return true;
        }

        if (angular.isNumber(value)) {
          value = new Date(value);
        }

        if (!value) {
          return true;
        }
        else if (angular.isDate(value) && !isNaN(value)) {
          return true;
        }
        else if (angular.isString(value)) {
          var date = dateParser.parse(value, dateFormat);
          return !isNaN(date);
        }
        else {
          return false;
        }
      };
    }
  };
}])

How to call python script on excel vba?

You can also try ExcelPython which allows you to manipulate Python object and call code from VBA.

What is null in Java?

There are two major categories of types in Java: primitive and reference. Variables declared of a primitive type store values; variables declared of a reference type store references.

String x = null;

In this case, the initialization statement declares a variables “x”. “x” stores String reference. It is null here. First of all, null is not a valid object instance, so there is no memory allocated for it. It is simply a value that indicates that the object reference is not currently referring to an object.

Set keyboard caret position in html textbox

I found an easy way to fix this issue, tested in IE and Chrome:

function setCaret(elemId, caret)
 {
   var elem = document.getElementById(elemId);
   elem.setSelectionRange(caret, caret);
 }

Pass text box id and caret position to this function.

creating a table in ionic

This is the way i use it. It's very simple and work very well.. Ionic html:

  <ion-content>
 

  <ion-grid class="ion-text-center">

    <ion-row class="ion-margin">
      <ion-col>
        <ion-title>
          <ion-text color="default">
            Your title remove if don't want use
          </ion-text>
        </ion-title>
      </ion-col>
    </ion-row>

    <ion-row class="header-row">
      <ion-col>
        <ion-text>Data</ion-text>
      </ion-col>

      <ion-col>
        <ion-text>Cliente</ion-text>
      </ion-col>

      <ion-col>
        <ion-text>Pagamento</ion-text>
      </ion-col>
    </ion-row>


    <ion-row>
      <ion-col>
        <ion-text>
            19/10/2020
        </ion-text>
      </ion-col>

        <ion-col>
          <ion-text>
            Nome
          </ion-text>
        </ion-col>
  
        <ion-col>
          <ion-text>
            R$ 200
          </ion-text>
        </ion-col>
    </ion-row>

  </ion-grid>
</ion-content>

CSS:

.header-row {
  background: #7163AA;
  color: #fff;
  font-size: 18px;
}

ion-col {
  border: 1px solid #ECEEEF;
}

Result of the code

Convert data.frame column to a vector?

There's now an easy way to do this using dplyr.

dplyr::pull(aframe, a2)

iPhone/iPad browser simulator?

I have been using Mobilizer, which is an awesome free app

Currently it has default simulation for Iphone4, Iphone5, Samsung Galaxt S3, Nokia Lumia, Palm Pre, Blackberry Storm and HTC Evo. Simple straightforward and effective.

How to start anonymous thread class

You're already creating an instance of the Thread class - you're just not doing anything with it. You could call start() without even using a local variable:

new Thread()
{
    public void run() {
        System.out.println("blah");
    }
}.start();

... but personally I'd normally assign it to a local variable, do anything else you want (e.g. setting the name etc) and then start it:

Thread t = new Thread() {
    public void run() {
        System.out.println("blah");
    }
};
t.start();

Regex to match only letters

Pattern pattern = Pattern.compile("^[a-zA-Z]+$");

if (pattern.matcher("a").find()) {

   ...do something ......
}

Authentication issues with WWW-Authenticate: Negotiate

Putting this information here for future readers' benefit.

  • 401 (Unauthorized) response header -> Request authentication header

  • Here are several WWW-Authenticate response headers. (The full list is at IANA: HTTP Authentication Schemes.)

    • WWW-Authenticate: Basic-> Authorization: Basic + token - Use for basic authentication
    • WWW-Authenticate: NTLM-> Authorization: NTLM + token (2 challenges)
    • WWW-Authenticate: Negotiate -> Authorization: Negotiate + token - used for Kerberos authentication
      • By the way: IANA has this angry remark about Negotiate: This authentication scheme violates both HTTP semantics (being connection-oriented) and syntax (use of syntax incompatible with the WWW-Authenticate and Authorization header field syntax).

You can set the Authorization: Basic header only when you also have the WWW-Authenticate: Basic header on your 401 challenge.

But since you have WWW-Authenticate: Negotiate this should be the case for Kerberos based authentication.

Vertically align an image inside a div with responsive height

Make another div and add both 'dummy' and 'img-container' inside the div

Do HTML and CSS like follows

_x000D_
_x000D_
html , body {height:100%;}_x000D_
.responsive-container { height:100%; display:table; text-align:center; width:100%;}_x000D_
.inner-container {display:table-cell; vertical-align:middle;}
_x000D_
<div class="responsive-container">_x000D_
    <div class="inner-container">_x000D_
  <div class="dummy">Sample</div>_x000D_
  <div class="img-container">_x000D_
   Image tag_x000D_
  </div>_x000D_
 </div> _x000D_
</div>
_x000D_
_x000D_
_x000D_

Instead of 100% for the 'responsive-container' you can give the height that you want.,

How to extract this specific substring in SQL Server?

An alternative to the answer provided by @Marc

SELECT SUBSTRING(LEFT(YOUR_FIELD, CHARINDEX('[', YOUR_FIELD) - 1), CHARINDEX(';', YOUR_FIELD) + 1, 100)
FROM YOUR_TABLE
WHERE CHARINDEX('[', YOUR_FIELD) > 0 AND
    CHARINDEX(';', YOUR_FIELD) > 0;

This makes sure the delimiters exist, and solves an issue with the currently accepted answer where doing the LEFT last is working with the position of the last delimiter in the original string, rather than the revised substring.

Request format is unrecognized for URL unexpectedly ending in

Despite 90% of all the information I found (while trying to find a solution to this error) telling me to add the HttpGet and HttpPost to the configuration, that did not work for me... and didn't make sense to me anyway.

My application is running on lots of servers (30+) and I've never had to add this configuration for any of them. Either the version of the application running under .NET 2.0 or .NET 4.0.

The solution for me was to re-register ASP.NET against IIS.

I used the following command line to achieve this...

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i

"psql: could not connect to server: Connection refused" Error when connecting to remote database

I have struggled with this when trying to remotely connect to a new PostgreSQL installation on my Raspberry Pi. Here's the full breakdown of what I did to resolve this issue:

First, open the PostgreSQL configuration file and make sure that the service is going to listen outside of localhost.

sudo [editor] /etc/postgresql/[version]/main/postgresql.conf

I used nano, but you can use the editor of your choice, and while I have version 9.1 installed, that directory will be for whichever version you have installed.

Search down to the section titled 'Connections and Authentication'. The first setting should be 'listen_addresses', and might look like this:

#listen_addresses = 'localhost'     # what IP address(es) to listen on;

The comments to the right give good instructions on how to change this field, and using the suggested '*' for all will work well.

Please note that this field is commented out with #. Per the comments, it will default to 'localhost', so just changing the value to '*' isn't enough, you also need to uncomment the setting by removing the leading #.

It should now look like this:

listen_addresses = '*'         # what IP address(es) to listen on;

You can also check the next setting, 'port', to make sure that you're connecting correctly. 5432 is the default, and is the port that psql will try to connect to if you don't specify one.

Save and close the file, then open the Client Authentication config file, which is in the same directory:

sudo [editor] /etc/postgresql/[version]/main/pg_hba.conf

I recommend reading the file if you want to restrict access, but for basic open connections you'll jump to the bottom of the file and add a line like this:

host all all all md5

You can press tab instead of space to line the fields up with the existing columns if you like.

Personally, I instead added a row that looked like this:

host [database_name] pi 192.168.1.0/24 md5

This restricts the connection to just the one user and just the one database on the local area network subnet.

Once you've saved changes to the file you will need to restart the service to implement the changes.

sudo service postgresql restart

Now you can check to make sure that the service is openly listening on the correct port by using the following command:

sudo netstat -ltpn

If you don't run it as elevated (using sudo) it doesn't tell you the names of the processes listening on those ports.

One of the processes should be Postgres, and the Local Address should be open (0.0.0.0) and not restricted to local traffic only (127.0.0.1). If it isn't open, then you'll need to double check your config files and restart the service. You can again confirm that the service is listening on the correct port (default is 5432, but your configuration could be different).

Finally you'll be able to successfully connect from a remote computer using the command:

psql -h [server ip address] -p [port number, optional if 5432] -U [postgres user name] [database name]

How to find foreign key dependencies in SQL Server?

One that I really like to use is called SQL Dependency Tracker by Red Gate Software. You can put in any database object(s) such as tables, stored procedures, etc. and it will then automatically draw the relationship lines between all the other objects that rely on your selected item(s).

Gives a very good graphical representation of the dependencies in your schema.

Ifelse statement in R with multiple conditions

Very simple use of any

df <- <your structure>

df$Den <- apply(df,1,function(i) {ifelse(any(is.na(i)) | any(i != 1), 0, 1)})

Setting default values for columns in JPA

In my case, I modified hibernate-core source code, well, to introduce a new annotation @DefaultValue:

commit 34199cba96b6b1dc42d0d19c066bd4d119b553d5
Author: Lenik <xjl at 99jsj.com>
Date:   Wed Dec 21 13:28:33 2011 +0800

    Add default-value ddl support with annotation @DefaultValue.

diff --git a/hibernate-core/src/main/java/org/hibernate/annotations/DefaultValue.java b/hibernate-core/src/main/java/org/hibernate/annotations/DefaultValue.java
new file mode 100644
index 0000000..b3e605e
--- /dev/null
+++ b/hibernate-core/src/main/java/org/hibernate/annotations/DefaultValue.java
@@ -0,0 +1,35 @@
+package org.hibernate.annotations;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import java.lang.annotation.Retention;
+
+/**
+ * Specify a default value for the column.
+ *
+ * This is used to generate the auto DDL.
+ *
+ * WARNING: This is not part of JPA 2.0 specification.
+ *
+ * @author ???
+ */
[email protected]({ FIELD, METHOD })
+@Retention(RUNTIME)
+public @interface DefaultValue {
+
+    /**
+     * The default value sql fragment.
+     *
+     * For string values, you need to quote the value like 'foo'.
+     *
+     * Because different database implementation may use different 
+     * quoting format, so this is not portable. But for simple values
+     * like number and strings, this is generally enough for use.
+     */
+    String value();
+
+}
diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3Column.java b/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3Column.java
index b289b1e..ac57f1a 100644
--- a/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3Column.java
+++ b/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3Column.java
@@ -29,6 +29,7 @@ import org.hibernate.AnnotationException;
 import org.hibernate.AssertionFailure;
 import org.hibernate.annotations.ColumnTransformer;
 import org.hibernate.annotations.ColumnTransformers;
+import org.hibernate.annotations.DefaultValue;
 import org.hibernate.annotations.common.reflection.XProperty;
 import org.hibernate.cfg.annotations.Nullability;
 import org.hibernate.mapping.Column;
@@ -65,6 +66,7 @@ public class Ejb3Column {
    private String propertyName;
    private boolean unique;
    private boolean nullable = true;
+   private String defaultValue;
    private String formulaString;
    private Formula formula;
    private Table table;
@@ -175,7 +177,15 @@ public class Ejb3Column {
        return mappingColumn.isNullable();
    }

-   public Ejb3Column() {
+   public String getDefaultValue() {
+        return defaultValue;
+    }
+
+    public void setDefaultValue(String defaultValue) {
+        this.defaultValue = defaultValue;
+    }
+
+    public Ejb3Column() {
    }

    public void bind() {
@@ -186,7 +196,7 @@ public class Ejb3Column {
        }
        else {
            initMappingColumn(
-                   logicalColumnName, propertyName, length, precision, scale, nullable, sqlType, unique, true
+                   logicalColumnName, propertyName, length, precision, scale, nullable, sqlType, unique, defaultValue, true
            );
            log.debug( "Binding column: " + toString());
        }
@@ -201,6 +211,7 @@ public class Ejb3Column {
            boolean nullable,
            String sqlType,
            boolean unique,
+           String defaultValue,
            boolean applyNamingStrategy) {
        if ( StringHelper.isNotEmpty( formulaString ) ) {
            this.formula = new Formula();
@@ -217,6 +228,7 @@ public class Ejb3Column {
            this.mappingColumn.setNullable( nullable );
            this.mappingColumn.setSqlType( sqlType );
            this.mappingColumn.setUnique( unique );
+           this.mappingColumn.setDefaultValue(defaultValue);

            if(writeExpression != null && !writeExpression.matches("[^?]*\\?[^?]*")) {
                throw new AnnotationException(
@@ -454,6 +466,11 @@ public class Ejb3Column {
                    else {
                        column.setLogicalColumnName( columnName );
                    }
+                   DefaultValue _defaultValue = inferredData.getProperty().getAnnotation(DefaultValue.class);
+                   if (_defaultValue != null) {
+                       String defaultValue = _defaultValue.value();
+                       column.setDefaultValue(defaultValue);
+                   }

                    column.setPropertyName(
                            BinderHelper.getRelativePath( propertyHolder, inferredData.getPropertyName() )
diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3JoinColumn.java b/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3JoinColumn.java
index e57636a..3d871f7 100644
--- a/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3JoinColumn.java
+++ b/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3JoinColumn.java
@@ -423,6 +424,7 @@ public class Ejb3JoinColumn extends Ejb3Column {
                getMappingColumn() != null ? getMappingColumn().isNullable() : false,
                referencedColumn.getSqlType(),
                getMappingColumn() != null ? getMappingColumn().isUnique() : false,
+               null, // default-value
                false
        );
        linkWithValue( value );
@@ -502,6 +504,7 @@ public class Ejb3JoinColumn extends Ejb3Column {
                getMappingColumn().isNullable(),
                column.getSqlType(),
                getMappingColumn().isUnique(),
+               null, // default-value
                false //We do copy no strategy here
        );
        linkWithValue( value );

Well, this is a hibernate-only solution.

Remove insignificant trailing zeros from a number?

If you use toFixed(n) where n > 0, a more simple and stable (no more float operations) solution can be:

(+n).toFixed(2).replace(/(\.0+|0+)$/, '')


// 0 => 0
// 0.1234 => 0.12
// 0.1001 => 0.1

// 1 => 1
// 1.1234 => 1.12
// 1.1001 => 1.1

// 100 => 100
// 100.1234 => 100.12
// 100.1001 => 100.1

PS: if you use toFixed(0), then no replace is needed.

How to make an inline element appear on new line, or block element not occupy the whole line?

I think floats may work best for you here, if you dont want the element to occupy the whole line, float it left should work.

.feature_wrapper span {
    float: left;
    clear: left;
    display:inline
}

EDIT: now browsers have better support you can make use of the do inline-block.

.feature_wrapper span {
    display:inline-block;
    *display:inline; *zoom:1;
}

Depending on the text-align this will appear as through its inline while also acting like a block element.

The preferred way of creating a new element with jQuery

The first option gives you more flexibilty:

var $div = $("<div>", {id: "foo", "class": "a"});
$div.click(function(){ /* ... */ });
$("#box").append($div);

And of course .html('*') overrides the content while .append('*') doesn't, but I guess, this wasn't your question.

Another good practice is prefixing your jQuery variables with $:
Is there any specific reason behind using $ with variable in jQuery

Placing quotes around the "class" property name will make it more compatible with less flexible browsers.

Socket File "/var/pgsql_socket/.s.PGSQL.5432" Missing In Mountain Lion (OS X Server)

Try paste in console this:

$ mkdir /var/pgsql_socket/ 

$ ln -s /private/tmp/.s.PGSQL.5432 /var/pgsql_socket/

Long Press in JavaScript?

For cross platform developers (Note All answers given so far will not work on iOS):

Mouseup/down seemed to work okay on android - but not all devices ie (samsung tab4). Did not work at all on iOS.

Further research its seems that this is due to the element having selection and the native magnification interupts the listener.

This event listener enables a thumbnail image to be opened in a bootstrap modal, if the user holds the image for 500ms.

It uses a responsive image class therefore showing a larger version of the image. This piece of code has been fully tested upon (iPad/Tab4/TabA/Galaxy4):

var pressTimer;  
$(".thumbnail").on('touchend', function (e) {
   clearTimeout(pressTimer);
}).on('touchstart', function (e) {
   var target = $(e.currentTarget);
   var imagePath = target.find('img').attr('src');
   var title = target.find('.myCaption:visible').first().text();
   $('#dds-modal-title').text(title);
   $('#dds-modal-img').attr('src', imagePath);
   // Set timeout
   pressTimer = window.setTimeout(function () {
      $('#dds-modal').modal('show');
   }, 500)
});

C# - Print dictionary

My goto is

Console.WriteLine( Serialize(dictionary.ToList() ) );

Make sure you include the package using static System.Text.Json.JsonSerializer;

javascript filter array multiple conditions

Another take for those of you that enjoy succinct code.

NOTE: The FILTER method can take an additional this argument, then using an E6 arrow function we can reuse the correct this to get a nice one-liner.

_x000D_
_x000D_
var users = [{name: 'John',email: '[email protected]',age: 25,address: 'USA'},_x000D_
             {name: 'Tom',email: '[email protected]',age: 35,address: 'England'},_x000D_
             {name: 'Mark',email: '[email protected]',age: 28,address: 'England'}];_x000D_
_x000D_
var query = {address: "England", name: "Mark"};_x000D_
_x000D_
var result = users.filter(search, query);_x000D_
_x000D_
function search(user){_x000D_
  return Object.keys(this).every((key) => user[key] === this[key]);_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
// |----------------------- Code for displaying results -----------------|_x000D_
var element = document.getElementById('result');_x000D_
_x000D_
function createMarkUp(data){_x000D_
  Object.keys(query).forEach(function(key){_x000D_
    var p = document.createElement('p');_x000D_
    p.appendChild(document.createTextNode(_x000D_
    key.toUpperCase() + ': ' + result[0][key]));_x000D_
    element.appendChild(p);_x000D_
  });_x000D_
}_x000D_
_x000D_
createMarkUp(result);
_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

How do I clear this setInterval inside a function?

the_int=window.clearInterval(the_int);

TypeError("'bool' object is not iterable",) when trying to return a Boolean

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

PivotTable to show values, not sum of values

Another easier way to do it is to upload your file to google sheets, then add a pivot, for the columns and rows select the same as you would with Excel, however, for values select Calculated Field and then in the formula type in =

In my case the column header is URL

Git: How to find a deleted file in the project commit history?

Could not edit the accepted response so adding it as an answer here,

to restore the file in git, use the following (note the '^' sign just after the SHA)

git checkout <SHA>^ -- /path/to/file

Will the IE9 WebBrowser Control Support all of IE9's features, including SVG?

Yes, WebBrowser control uses whatever version of IE you have installed. This means of course that if you run your application on a machine with IE 8 then the IE 9 features you depend on will not be available.

Is there a command to list all Unix group names?

If you want all groups known to the system, I would recommend using getent group instead of parsing /etc/group:

getent group

The reason is that on networked systems, groups may not only read from /etc/group file, but also obtained through LDAP or Yellow Pages (the list of known groups comes from the local group file plus groups received via LDAP or YP in these cases).

If you want just the group names you can use:

getent group | cut -d: -f1

Convert bytes to a string

I made a function to clean a list

def cleanLists(self, lista):
    lista = [x.strip() for x in lista]
    lista = [x.replace('\n', '') for x in lista]
    lista = [x.replace('\b', '') for x in lista]
    lista = [x.encode('utf8') for x in lista]
    lista = [x.decode('utf8') for x in lista]

    return lista

JavaScript: client-side vs. server-side validation

JavaScript can be modified at runtime.

I suggest a pattern of creating a validation structure on the server, and sharing this with the client.

You'll need separate validation logic on both ends, ex:

"required" attributes on inputs client-side

field.length > 0 server-side.

But using the same validation specification will eliminate some redundancy (and mistakes) of mirroring validation on both ends.

Cannot open include file: 'unistd.h': No such file or directory

If you're using ZLib in your project, then you need to find :

#if 1

in zconf.h and replace(uncomment) it with :

#if HAVE_UNISTD_H /* ...the rest of the line

If it isn't ZLib I guess you should find some alternative way to do this. GL.

Hide text within HTML?

you can use css property to hide style="display:none;"

<div style="display:none;">CREDITS_HERE</div>

Create a unique number with javascript time

In 2020, you can use the in-browser Crypto API to generate cryptographically strong random values.

function getRandomNumbers() {
  const typedArray = new Uint8Array(10);
  const randomValues = window.crypto.getRandomValues(typedArray);
  return randomValues.join('');
}

console.log(getRandomNumbers());
// 1857488137147725264738

both Uint8Array and Crypto.getRandomValues are supported on all major browsers, including IE11

golang why don't we have a set datastructure

Like Vatine wrote: Since go lacks generics it would have to be part of the language and not the standard library. For that you would then have to pollute the language with keywords set, union, intersection, difference, subset...

The other reason is, that it's not clear at all what the "right" implementation of a set is:

  1. There is a functional approach:

    func IsInEvenNumbers(n int) bool {
        if n % 2 == 0 {
            return true
        }
       return false
    }
    

This is a set of all even ints. It has a very efficient lookup and union, intersect, difference and subset can easily be done by functional composition.

  1. Or you do a has-like approach like Dali showed.

A map does not have that problem, since you store something associated with the value.

How do I view events fired on an element in Chrome DevTools?

  • Hit F12 to open Dev Tools
  • Click the Sources tab
  • On right-hand side, scroll down to "Event Listener Breakpoints", and expand tree
  • Click on the events you want to listen for.
  • Interact with the target element, if they fire you will get a break point in the debugger

Similarly, you can right click on the target element -> select "inspect element" Scroll down on the right side of the dev frame, at the bottom is 'event listeners'. Expand the tree to see what events are attached to the element. Not sure if this works for events that are handled through bubbling (I'm guessing not)

MongoDB: update every document on one field

I have been using MongoDB .NET driver for a little over a month now. If I were to do it using .NET driver, I would use Update method on the collection object. First, I will construct a query that will get me all the documents I am interested in and do an Update on the fields I want to change. Update in Mongo only affects the first document and to update all documents resulting from the query one needs to use 'Multi' update flag. Sample code follows...

var collection = db.GetCollection("Foo");
var query = Query.GTE("No", 1); // need to construct in such a way that it will give all 20K //docs.
var update = Update.Set("timestamp", datetime.UtcNow);
collection.Update(query, update, UpdateFlags.Multi);

CSS: fixed to bottom and centered

There are 2 potential issues that I see:

1 - IE has had trouble with position:fixed in the past. If you are using IE7+ with a valid doctype or a non-IE browser this isn't part of the problem

2 - You need to specify a width for the footer if you want the footer object to be centered. Otherwise it defaults to the full width of the page and the auto margin for the left and right get set to 0. If you want the footer bar to take up the width (like the StackOverflow notice bar) and center the text, then you need to add "text-align: center" to your definition.

How to get the number of characters in a std::string?

It depends on what string type you're talking about. There are many types of strings:

  1. const char* - a C-style multibyte string
  2. const wchar_t* - a C-style wide string
  3. std::string - a "standard" multibyte string
  4. std::wstring - a "standard" wide string

For 3 and 4, you can use .size() or .length() methods.

For 1, you can use strlen(), but you must ensure that the string variable is not NULL (=== 0)

For 2, you can use wcslen(), but you must ensure that the string variable is not NULL (=== 0)

There are other string types in non-standard C++ libraries, such as MFC's CString, ATL's CComBSTR, ACE's ACE_CString, and so on, with methods such as .GetLength(), and so on. I can't remember the specifics of them all right off the top of my head.

The STLSoft libraries have abstracted this all out with what they call string access shims, which can be used to get the string length (and other aspects) from any type. So for all of the above (including the non-standard library ones) using the same function stlsoft::c_str_len(). This article describes how it all works, as it's not all entirely obvious or easy.

Debugging JavaScript in IE7

The hard truth is: the only good debugger for IE is Visual Studio.

If you don't have money for the real deal, download free Visual Web Developer 2008 Express EditionVisual Web Developer 2010 Express Edition. While the former allows you to attach debugger to already running IE, the latter doesn't (at least previous versions I used didn't allow that). If this is still the case, the trick is to create a simple project with one empty web page, "run" it (it starts the browser), now navigate to whatever page you want to debug, and start debugging.

Microsoft gives away full Visual Studio on different events, usually with license restrictions, but they allow tinkering at home. Check their schedule and the list of freebies.

Another hint: try to debug your web application with other browsers first. I had a great success with Opera. Somehow Opera's emulation of IE and its bugs was pretty close, but the debugger is much better.

How to reload the datatable(jquery) data?

I'm posting this just in case someone need it..

Just create a button:

<button type="button" href="javascript:void(0);" onclick="mytable.fnDraw();">Refresh</button>

but don't forget to add this when calling the datatable:

mytable = $("#mytable").dataTable();

How does strcmp() work?

This, from the masters themselves (K&R, 2nd ed., pg. 106):

// strcmp: return < 0 if s < t, 0 if s == t, > 0 if s > t
int strcmp(char *s, char *t) 
{
    int i;

    for (i = 0; s[i] == t[i]; i++)
        if (s[i] == '\0')
            return 0;
    return s[i] - t[i];
}

curl error 18 - transfer closed with outstanding read data remaining

I had this problem working with pycurl and I solved it using

c.setopt(pycurl.HTTP_VERSION, pycurl.CURL_HTTP_VERSION_1_0) 

like Eric Caron says.

How can I get a specific number child using CSS?

For IE 7 & 8 (and other browsers without CSS3 support not including IE6) you can use the following to get the 2nd and 3rd children:

2nd Child:

td:first-child + td

3rd Child:

td:first-child + td + td

Then simply add another + td for each additional child you wish to select.

If you want to support IE6 that can be done too! You simply need to use a little javascript (jQuery in this example):

$(function() {
    $('td:first-child').addClass("firstChild");
    $(".table-class tr").each(function() {
        $(this).find('td:eq(1)').addClass("secondChild");
        $(this).find('td:eq(2)').addClass("thirdChild");
    });
});

Then in your css you simply use those class selectors to make whatever changes you like:

table td.firstChild { /*stuff here*/ }
table td.secondChild { /*stuff to apply to second td in each row*/ }

moment.js - UTC gives wrong date

Both Date and moment will parse the input string in the local time zone of the browser by default. However Date is sometimes inconsistent with this regard. If the string is specifically YYYY-MM-DD, using hyphens, or if it is YYYY-MM-DD HH:mm:ss, it will interpret it as local time. Unlike Date, moment will always be consistent about how it parses.

The correct way to parse an input moment as UTC in the format you provided would be like this:

moment.utc('07-18-2013', 'MM-DD-YYYY')

Refer to this documentation.

If you want to then format it differently for output, you would do this:

moment.utc('07-18-2013', 'MM-DD-YYYY').format('YYYY-MM-DD')

You do not need to call toString explicitly.

Note that it is very important to provide the input format. Without it, a date like 01-04-2013 might get processed as either Jan 4th or Apr 1st, depending on the culture settings of the browser.

Firefox 'Cross-Origin Request Blocked' despite headers

I came across this question having found requests in Firefox were being blocked with the message:

Reason: CORS request did not succeed

After pulling my hair out I found out that a newly installed Firefox extension, Privacy Badger, was blocking the requests.

If you come to this question after scratching your head, try checking to see what extensions you have installed to see if any of them are blocking requests.

See Reason: CORS request did not succeed on MDN for details.

An unhandled exception was generated during the execution of the current web request

You have more than one form tags with runat="server" on your template, most probably you have one in your master page, remove one on your aspx page, it is not needed if already have form in master page file which is surrounding your content place holders.

Try to remove that tag:

<form id="formID" runat="server">

and of course closing tag:

</form>

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

In terminal execute in root project folder:

./gradlew clean

It helped me.

How can I get the nth character of a string?

char* str = "HELLO";
char c = str[1];

Keep in mind that arrays and strings in C begin indexing at 0 rather than 1, so "H" is str[0], "E" is str[1], the first "L" is str[2] and so on.

java collections - keyset() vs entrySet() in map

An Iterator moves forward only, if it read it once, it's done. Your

m.get(itr2.next());

is reading the next value of itr2.next();, that is why you are missing a few (actually not a few, every other) keys.

Python, how to read bytes from file and save it?

In my examples I use the 'b' flag ('wb', 'rb') when opening the files because you said you wanted to read bytes. The 'b' flag tells Python not to interpret end-of-line characters which can differ between operating systems. If you are reading text, then omit the 'b' and use 'w' and 'r' respectively.

This reads the entire file in one chunk using the "simplest" Python code. The problem with this approach is that you could run out memory when reading a large file:

ifile = open(input_filename,'rb')
ofile = open(output_filename, 'wb')
ofile.write(ifile.read())
ofile.close()
ifile.close()

This example is refined to read 1MB chunks to ensure it works for files of any size without running out of memory:

ifile = open(input_filename,'rb')
ofile = open(output_filename, 'wb')
data = ifile.read(1024*1024)
while data:
    ofile.write(data)
    data = ifile.read(1024*1024)
ofile.close()
ifile.close()

This example is the same as above but leverages using with to create a context. The advantage of this approach is that the file is automatically closed when exiting the context:

with open(input_filename,'rb') as ifile:
    with open(output_filename, 'wb') as ofile:
        data = ifile.read(1024*1024)
        while data:
            ofile.write(data)
            data = ifile.read(1024*1024)

See the following:

Disable Drag and Drop on HTML elements?

This is a fiddle I always use with my Web applications:

$('body').on('dragstart drop', function(e){
    e.preventDefault();
    return false;
});

It will prevent anything on your app being dragged and dropped. Depending on tour needs, you can replace body selector with any container that childrens should not be dragged.

JavaScript: How to get parent element by selector?

Finds the closest parent (or the element itself) that matches the given selector. Also included is a selector to stop searching, in case you know a common ancestor that you should stop searching at.

function closest(el, selector, stopSelector) {
  var retval = null;
  while (el) {
    if (el.matches(selector)) {
      retval = el;
      break
    } else if (stopSelector && el.matches(stopSelector)) {
      break
    }
    el = el.parentElement;
  }
  return retval;
}

Is it worth using Python's re.compile?

Legibility/cognitive load preference

To me, the main gain is that I only need to remember, and read, one form of the complicated regex API syntax - the <compiled_pattern>.method(xxx) form rather than that and the re.func(<pattern>, xxx) form.

The re.compile(<pattern>) is a bit of extra boilerplate, true.

But where regex are concerned, that extra compile step is unlikely to be a big cause of cognitive load. And in fact, on complicated patterns, you might even gain clarity from separating the declaration from whatever regex method you then invoke on it.

I tend to first tune complicated patterns in a website like Regex101, or even in a separate minimal test script, then bring them into my code, so separating the declaration from its use fits my workflow as well.

Why does the 'int' object is not callable error occur when using the sum() function?

This means that somewhere else in your code, you have something like:

sum = 0

Which shadows the builtin sum (which is callable) with an int (which isn't).

How is the java memory pool divided?

Heap memory

The heap memory is the runtime data area from which the Java VM allocates memory for all class instances and arrays. The heap may be of a fixed or variable size. The garbage collector is an automatic memory management system that reclaims heap memory for objects.

  • Eden Space: The pool from which memory is initially allocated for most objects.

  • Survivor Space: The pool containing objects that have survived the garbage collection of the Eden space.

  • Tenured Generation or Old Gen: The pool containing objects that have existed for some time in the survivor space.

Non-heap memory

Non-heap memory includes a method area shared among all threads and memory required for the internal processing or optimization for the Java VM. It stores per-class structures such as a runtime constant pool, field and method data, and the code for methods and constructors. The method area is logically part of the heap but, depending on the implementation, a Java VM may not garbage collect or compact it. Like the heap memory, the method area may be of a fixed or variable size. The memory for the method area does not need to be contiguous.

  • Permanent Generation: The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas.

  • Code Cache: The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.

Here's some documentation on how to use Jconsole.

How to list all dates between two dates

I made a calendar using:

http://social.technet.microsoft.com/wiki/contents/articles/22776.t-sql-calendar-table.aspx

then a Store procedure passing two dates and thats all:

USE DB_NAME;
GO

CREATE PROCEDURE [dbo].[USP_LISTAR_RANGO_FECHAS]
@FEC_INICIO date,
@FEC_FIN date
AS
Select Date from CALENDARIO where Date BETWEEN @FEC_INICIO AND @FEC_FIN;

How to display a jpg file in Python?

from PIL import Image

image = Image.open('File.jpg')
image.show()

Git Diff with Beyond Compare

Run these commands for Beyond Compare 3(if the BCompare.exe path is different in your system, please replace it according to yours):

git config --global diff.tool bc3
git config --global difftool.bc3.cmd "\"c:/program files (x86)/beyond compare 3/BCompare.exe\" \"$LOCAL\" \"$REMOTE\""
git config --global difftool.prompt false

Then use git difftool

How can I echo a newline in a batch file?

You can also do like this,

(for %i in (a b "c d") do @echo %~i)

The output will be,

a
b
c d

Note that when this is put in a batch file, '%' shall be doubled.

(for %%i in (a b "c d") do @echo %%~i)

Does MySQL foreign_key_checks affect the entire database?

Actually, there are two foreign_key_checks variables: a global variable and a local (per session) variable. Upon connection, the session variable is initialized to the value of the global variable.
The command SET foreign_key_checks modifies the session variable.
To modify the global variable, use SET GLOBAL foreign_key_checks or SET @@global.foreign_key_checks.

Consult the following manual sections:
http://dev.mysql.com/doc/refman/5.7/en/using-system-variables.html
http://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html

Detect the Internet connection is offline?

There are 2 answers forthis for two different senarios:-

  1. If you are using JavaScript on a website(i.e; or any front-end part) The simplest way to do it is:

    <h2>The Navigator Object</h2>
    
    <p>The onLine property returns true if the browser is online:</p>
    
    <p id="demo"></p>
    
    <script>
      document.getElementById("demo").innerHTML = "navigator.onLine is " + navigator.onLine;
    </script>
    

  2. But if you're using js on server side(i.e; node etc.), You can determine that the connection is lost by making failed XHR requests.

    The standard approach is to retry the request a few times. If it doesn't go through, alert the user to check the connection, and fail gracefully.

How do I add an integer value with javascript (jquery) to a value that's returning a string?

The integer is being converted into a string rather than vice-versa. You want:

var newValue = parseInt(currentValue) + 1

How do I calculate the MD5 checksum of a file in Python?

In regards to your error and what's missing in your code. m is a name which is not defined for getmd5() function.

No offence, I know you are a beginner, but your code is all over the place. Let's look at your issues one by one :)

First, you are not using hashlib.md5.hexdigest() method correctly. Please refer explanation on hashlib functions in Python Doc Library. The correct way to return MD5 for provided string is to do something like this:

>>> import hashlib
>>> hashlib.md5("filename.exe").hexdigest()
'2a53375ff139d9837e93a38a279d63e5'

However, you have a bigger problem here. You are calculating MD5 on a file name string, where in reality MD5 is calculated based on file contents. You will need to basically read file contents and pipe it though MD5. My next example is not very efficient, but something like this:

>>> import hashlib
>>> hashlib.md5(open('filename.exe','rb').read()).hexdigest()
'd41d8cd98f00b204e9800998ecf8427e'

As you can clearly see second MD5 hash is totally different from the first one. The reason for that is that we are pushing contents of the file through, not just file name.

A simple solution could be something like that:

# Import hashlib library (md5 method is part of it)
import hashlib

# File to check
file_name = 'filename.exe'

# Correct original md5 goes here
original_md5 = '5d41402abc4b2a76b9719d911017c592'  

# Open,close, read file and calculate MD5 on its contents 
with open(file_name) as file_to_check:
    # read contents of the file
    data = file_to_check.read()    
    # pipe contents of the file through
    md5_returned = hashlib.md5(data).hexdigest()

# Finally compare original MD5 with freshly calculated
if original_md5 == md5_returned:
    print "MD5 verified."
else:
    print "MD5 verification failed!."

Please look at the post Python: Generating a MD5 checksum of a file. It explains in detail a couple of ways how it can be achieved efficiently.

Best of luck.

How do you transfer or export SQL Server 2005 data to Excel

Create the excel data source and insert the values,

insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=D:\testing.xls;', 
'SELECT * FROM [SheetName$]') select * from SQLServerTable

More informations are available here http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926

Accessing the index in 'for' loops?

You can do it with this code:

ints = [8, 23, 45, 12, 78]
index = 0

for value in (ints):
    index +=1
    print index, value

Use this code if you need to reset the index value at the end of the loop:

ints = [8, 23, 45, 12, 78]
index = 0

for value in (ints):
    index +=1
    print index, value
    if index >= len(ints)-1:
        index = 0

Difference between array_push() and $array[] =

both are the same, but array_push makes a loop in it's parameter which is an array and perform $array[]=$element

When is the init() function run?

Here is another example - https://play.golang.org/p/9P-LmSkUMKY

package main

import (
    "fmt"
)

func callOut() int {
    fmt.Println("Outside is beinge executed")
    return 1
}

var test = callOut()

func init() {
    fmt.Println("Init3 is being executed")
}

func init() {
    fmt.Println("Init is being executed")
}

func init() {
    fmt.Println("Init2 is being executed")
}

func main() {
    fmt.Println("Do your thing !")
}

Output of the above program

$ go run init/init.go
Outside is being executed
Init3 is being executed
Init is being executed
Init2 is being executed
Do your thing !

Check if a value exists in pandas dataframe index

Multi index works a little different from single index. Here are some methods for multi-indexed dataframe.

df = pd.DataFrame({'col1': ['a', 'b','c', 'd'], 'col2': ['X','X','Y', 'Y'], 'col3': [1, 2, 3, 4]}, columns=['col1', 'col2', 'col3'])
df = df.set_index(['col1', 'col2'])

in df.index works for the first level only when checking single index value.

'a' in df.index     # True
'X' in df.index     # False

Check df.index.levels for other levels.

'a' in df.index.levels[0] # True
'X' in df.index.levels[1] # True

Check in df.index for an index combination tuple.

('a', 'X') in df.index  # True
('a', 'Y') in df.index  # False

How do you Change a Package's Log Level using Log4j?

set the system property log4j.debug=true. Then you can determine where your configuration is running amuck.

Simple state machine example in C#?

Let's start with this simple state diagram:

simple state machine diagram

We have:

  • 4 states (Inactive, Active, Paused, and Exited)
  • 5 types of state transitions (Begin Command, End Command, Pause Command, Resume Command, Exit Command).

You can convert this to C# in a handful of ways, such as performing a switch statement on the current state and command, or looking up transitions in a transition table. For this simple state machine, I prefer a transition table, which is very easy to represent using a Dictionary:

using System;
using System.Collections.Generic;

namespace Juliet
{
    public enum ProcessState
    {
        Inactive,
        Active,
        Paused,
        Terminated
    }

    public enum Command
    {
        Begin,
        End,
        Pause,
        Resume,
        Exit
    }

    public class Process
    {
        class StateTransition
        {
            readonly ProcessState CurrentState;
            readonly Command Command;

            public StateTransition(ProcessState currentState, Command command)
            {
                CurrentState = currentState;
                Command = command;
            }

            public override int GetHashCode()
            {
                return 17 + 31 * CurrentState.GetHashCode() + 31 * Command.GetHashCode();
            }

            public override bool Equals(object obj)
            {
                StateTransition other = obj as StateTransition;
                return other != null && this.CurrentState == other.CurrentState && this.Command == other.Command;
            }
        }

        Dictionary<StateTransition, ProcessState> transitions;
        public ProcessState CurrentState { get; private set; }

        public Process()
        {
            CurrentState = ProcessState.Inactive;
            transitions = new Dictionary<StateTransition, ProcessState>
            {
                { new StateTransition(ProcessState.Inactive, Command.Exit), ProcessState.Terminated },
                { new StateTransition(ProcessState.Inactive, Command.Begin), ProcessState.Active },
                { new StateTransition(ProcessState.Active, Command.End), ProcessState.Inactive },
                { new StateTransition(ProcessState.Active, Command.Pause), ProcessState.Paused },
                { new StateTransition(ProcessState.Paused, Command.End), ProcessState.Inactive },
                { new StateTransition(ProcessState.Paused, Command.Resume), ProcessState.Active }
            };
        }

        public ProcessState GetNext(Command command)
        {
            StateTransition transition = new StateTransition(CurrentState, command);
            ProcessState nextState;
            if (!transitions.TryGetValue(transition, out nextState))
                throw new Exception("Invalid transition: " + CurrentState + " -> " + command);
            return nextState;
        }

        public ProcessState MoveNext(Command command)
        {
            CurrentState = GetNext(command);
            return CurrentState;
        }
    }


    public class Program
    {
        static void Main(string[] args)
        {
            Process p = new Process();
            Console.WriteLine("Current State = " + p.CurrentState);
            Console.WriteLine("Command.Begin: Current State = " + p.MoveNext(Command.Begin));
            Console.WriteLine("Command.Pause: Current State = " + p.MoveNext(Command.Pause));
            Console.WriteLine("Command.End: Current State = " + p.MoveNext(Command.End));
            Console.WriteLine("Command.Exit: Current State = " + p.MoveNext(Command.Exit));
            Console.ReadLine();
        }
    }
}

As a matter of personal preference, I like to design my state machines with a GetNext function to return the next state deterministically, and a MoveNext function to mutate the state machine.

Understanding Apache's access log

I also don't under stand what the "-" means after the 200 140 section of the log

That value corresponds to the referer as described by Joachim. If you see a dash though, that means that there was no referer value to begin with (eg. the user went straight to a specific destination, like if he/she typed a URL in their browser)

How to compute precision, recall, accuracy and f1-score for the multiclass case with scikit learn?

I think there is a lot of confusion about which weights are used for what. I am not sure I know precisely what bothers you so I am going to cover different topics, bear with me ;).

Class weights

The weights from the class_weight parameter are used to train the classifier. They are not used in the calculation of any of the metrics you are using: with different class weights, the numbers will be different simply because the classifier is different.

Basically in every scikit-learn classifier, the class weights are used to tell your model how important a class is. That means that during the training, the classifier will make extra efforts to classify properly the classes with high weights.
How they do that is algorithm-specific. If you want details about how it works for SVC and the doc does not make sense to you, feel free to mention it.

The metrics

Once you have a classifier, you want to know how well it is performing. Here you can use the metrics you mentioned: accuracy, recall_score, f1_score...

Usually when the class distribution is unbalanced, accuracy is considered a poor choice as it gives high scores to models which just predict the most frequent class.

I will not detail all these metrics but note that, with the exception of accuracy, they are naturally applied at the class level: as you can see in this print of a classification report they are defined for each class. They rely on concepts such as true positives or false negative that require defining which class is the positive one.

             precision    recall  f1-score   support

          0       0.65      1.00      0.79        17
          1       0.57      0.75      0.65        16
          2       0.33      0.06      0.10        17
avg / total       0.52      0.60      0.51        50

The warning

F1 score:/usr/local/lib/python2.7/site-packages/sklearn/metrics/classification.py:676: DeprecationWarning: The 
default `weighted` averaging is deprecated, and from version 0.18, 
use of precision, recall or F-score with multiclass or multilabel data  
or pos_label=None will result in an exception. Please set an explicit 
value for `average`, one of (None, 'micro', 'macro', 'weighted', 
'samples'). In cross validation use, for instance, 
scoring="f1_weighted" instead of scoring="f1".

You get this warning because you are using the f1-score, recall and precision without defining how they should be computed! The question could be rephrased: from the above classification report, how do you output one global number for the f1-score? You could:

  1. Take the average of the f1-score for each class: that's the avg / total result above. It's also called macro averaging.
  2. Compute the f1-score using the global count of true positives / false negatives, etc. (you sum the number of true positives / false negatives for each class). Aka micro averaging.
  3. Compute a weighted average of the f1-score. Using 'weighted' in scikit-learn will weigh the f1-score by the support of the class: the more elements a class has, the more important the f1-score for this class in the computation.

These are 3 of the options in scikit-learn, the warning is there to say you have to pick one. So you have to specify an average argument for the score method.

Which one you choose is up to how you want to measure the performance of the classifier: for instance macro-averaging does not take class imbalance into account and the f1-score of class 1 will be just as important as the f1-score of class 5. If you use weighted averaging however you'll get more importance for the class 5.

The whole argument specification in these metrics is not super-clear in scikit-learn right now, it will get better in version 0.18 according to the docs. They are removing some non-obvious standard behavior and they are issuing warnings so that developers notice it.

Computing scores

Last thing I want to mention (feel free to skip it if you're aware of it) is that scores are only meaningful if they are computed on data that the classifier has never seen. This is extremely important as any score you get on data that was used in fitting the classifier is completely irrelevant.

Here's a way to do it using StratifiedShuffleSplit, which gives you a random splits of your data (after shuffling) that preserve the label distribution.

from sklearn.datasets import make_classification
from sklearn.cross_validation import StratifiedShuffleSplit
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, classification_report, confusion_matrix

# We use a utility to generate artificial classification data.
X, y = make_classification(n_samples=100, n_informative=10, n_classes=3)
sss = StratifiedShuffleSplit(y, n_iter=1, test_size=0.5, random_state=0)
for train_idx, test_idx in sss:
    X_train, X_test, y_train, y_test = X[train_idx], X[test_idx], y[train_idx], y[test_idx]
    svc.fit(X_train, y_train)
    y_pred = svc.predict(X_test)
    print(f1_score(y_test, y_pred, average="macro"))
    print(precision_score(y_test, y_pred, average="macro"))
    print(recall_score(y_test, y_pred, average="macro"))    

Hope this helps.

is not JSON serializable

class CountryListView(ListView):
     model = Country

    def render_to_response(self, context, **response_kwargs):

         return HttpResponse(json.dumps(list(self.get_queryset().values_list('code', flat=True))),mimetype="application/json") 

fixed the problem

also mimetype is important.

XML string to XML document

Try this code:

var myXmlDocument = new XmlDocument();
myXmlDocument.LoadXml(theString);

What is the difference between background, backgroundTint, backgroundTintMode attributes in android layout xml?

android:backgroundTintMode

Blending mode used to apply the background tint.

android:backgroundTint

Tint to apply to the background. Must be a color value, in the form of #rgb, #argb, #rrggbb, or #aarrggbb.

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

jquery: get id from class selector

Use "attr" method in jquery.

$('.test').click(function(){
    var id = $(this).attr('id');
});

how to get request path with express req object

If you want to really get only "path" without querystring, you can use url library to parse and get only path part of url.

var url = require('url');

//auth required or redirect
app.use('/account', function(req, res, next) {
    var path = url.parse(req.url).pathname;
    if ( !req.session.user ) {
      res.redirect('/login?ref='+path);
    } else {
      next();
    }
});

Centering the image in Bootstrap

.img-responsive {
     margin: 0 auto;
 }

you can write like above code in your document so no need to add one another class in image tag.

Leaflet - How to find existing markers, and delete markers?

Have you tried layerGroup yet?

Docs here https://leafletjs.com/reference-1.2.0.html#layergroup

Just create a layer, add all marker to this layer, then you can find and destroy marker easily.

var markers = L.layerGroup()
const marker = L.marker([], {})
markers.addLayer(marker)

How to convert/parse from String to char in java?

The simplest way to convert a String to a char is using charAt():

String stringAns="hello";
char charAns=stringAns.charAt(0);//Gives You 'h'
char charAns=stringAns.charAt(1);//Gives You 'e'
char charAns=stringAns.charAt(2);//Gives You 'l'
char charAns=stringAns.charAt(3);//Gives You 'l'
char charAns=stringAns.charAt(4);//Gives You 'o'
char charAns=stringAns.charAt(5);//Gives You:: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5

Here is a full script:

import java.util.Scanner;

class demo {
    String accNo,name,fatherName,motherName;
    int age;
    static double rate=0.25;
    static double balance=1000;
    Scanner scanString=new Scanner(System.in);
    Scanner scanNum=new Scanner(System.in);

    void input()
    {
        System.out.print("Account Number:");
        accNo=scanString.nextLine();
        System.out.print("Name:");
        name=scanString.nextLine();
        System.out.print("Father's Name:");
        fatherName=scanString.nextLine();
        System.out.print("Mother's Name:");
        motherName=scanString.nextLine();
        System.out.print("Age:");
        age=scanNum.nextInt();
        System.out.println();
    }

    void withdraw() {
        System.out.print("How Much:");
        double withdraw=scanNum.nextDouble();
        balance=balance-withdraw;
        if(balance<1000)
        {
            System.out.println("Invalid Data Entry\n Balance below Rs 1000 not allowed");
            System.exit(0);
        }       
    }

    void deposit() {
        System.out.print("How Much:");
        double deposit=scanNum.nextDouble();
        balance=balance+deposit;
    }

    void display() {
        System.out.println("Your  Balnce:Rs "+balance);
    }

    void oneYear() {
        System.out.println("After one year:");
        balance+=balance*rate*0.01;
    }

    public static void main(String args[]) {
        demo d1=new demo();
        d1.input();
        d1.display();
        while(true) {//Withdraw/Deposit
            System.out.println("Withdraw/Deposit Press W/D:");
            String reply1= ((d1.scanString.nextLine()).toLowerCase()).trim();
            char reply=reply1.charAt(0);
            if(reply=='w') {
                d1.withdraw();
            }
            else if(reply=='d') {
                d1.deposit();
            }
            else {
                System.out.println("Invalid Entry");
            }
            //More Manipulation 
            System.out.println("Want More Manipulations: Y/N:");
            String manipulation1= ((d1.scanString.nextLine()).toLowerCase()).trim();

            char manipulation=manipulation1.charAt(0);
            System.out.println(manipulation);

            if(manipulation=='y') { }
            else if(manipulation=='n') {
                break;
            }
            else {
                System.out.println("Invalid Entry");
                break;
            }
        }   

        d1.oneYear();
        d1.display();   
    }
}

SQL Not Like Statement not working

If WPP.COMMENT contains NULL, the condition will not match.

This query:

SELECT  1
WHERE   NULL NOT LIKE '%test%'

will return nothing.

On a NULL column, both LIKE and NOT LIKE against any search string will return NULL.

Could you please post relevant values of a row which in your opinion should be returned but it isn't?

How to animate GIFs in HTML document?

Agreed with Yuri Tkachenko's answer.

I wanna point this out.

It's a pretty specific scenario. BUT it happens.

When you copy a gif before its loaded fully in some site like google images. it just gives the preview image address of that gif. Which is clearly not a gif.

So, make sure it ends with .gif extension

How to implement WiX installer upgrade?

Below worked for me.

<Product Id="*" Name="XXXInstaller" Language="1033" Version="1.0.0.0" 
    Manufacturer="XXXX" UpgradeCode="YOUR_GUID_HERE">
<Package InstallerVersion="xxx" Compressed="yes"/>
<Upgrade Id="YOUR_GUID_HERE">
    <UpgradeVersion Property="REMOVINGTHEOLDVERSION" Minimum="1.0.0.0" 
        RemoveFeatures="ALL" />
</Upgrade>
<InstallExecuteSequence>
    <RemoveExistingProducts After="InstallInitialize" />
</InstallExecuteSequence>

Please make sure that the UpgradeCode in Product is matching to Id in Upgrade.

How to set Android camera orientation properly?

From other member and my problem:

Camera Rotation issue depend on different Devices and certain Version.

Version 1.6: to fix the Rotation Issue, and it is good for most of devices

if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
        {   
            p.set("orientation", "portrait");
            p.set("rotation",90);
        }
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
        {                               
            p.set("orientation", "landscape");          
            p.set("rotation", 90);
        }

Version 2.1: depend on kind of devices, for example, Cannt fix the issue with XPeria X10, but it is good for X8, and Mini

Camera.Parameters parameters = camera.getParameters();
parameters.set("orientation", "portrait");
camera.setParameters(parameters);

Version 2.2: not for all devices

camera.setDisplayOrientation(90);

http://code.google.com/p/android/issues/detail?id=1193#c42

How to make external HTTP requests with Node.js

NodeJS supports http.request as a standard module: http://nodejs.org/docs/v0.4.11/api/http.html#http.request

var http = require('http');

var options = {
  host: 'example.com',
  port: 80,
  path: '/foo.html'
};

http.get(options, function(resp){
  resp.on('data', function(chunk){
    //do something with chunk
  });
}).on("error", function(e){
  console.log("Got error: " + e.message);
});

How to use count and group by at the same select statement

I know this is an old post, in SQL Server:

select  isnull(town,'TOTAL') Town, count(*) cnt
from    user
group by town WITH ROLLUP

Town         cnt
Copenhagen   58
NewYork      58
Athens       58
TOTAL        174

Why is the default value of the string type null instead of an empty string?

Why the designers of C# chose to use null as the default value of strings?

Because strings are reference types, reference types are default value is null. Variables of reference types store references to the actual data.

Let's use default keyword for this case;

string str = default(string); 

str is a string, so it is a reference type, so default value is null.

int str = (default)(int);

str is an int, so it is a value type, so default value is zero.

How to get the type of a variable in MATLAB?

Use the class function

>> b = 2
b =
     2
>> a = 'Hi'
a =
Hi
>> class(b)
ans =
double
>> class(a)
ans =
char

Why is it string.join(list) instead of list.join(string)?

Think of it as the natural orthogonal operation to split.

I understand why it is applicable to anything iterable and so can't easily be implemented just on list.

For readability, I'd like to see it in the language but I don't think that is actually feasible - if iterability were an interface then it could be added to the interface but it is just a convention and so there's no central way to add it to the set of things which are iterable.

How to redirect to an external URL in Angular2?

I think you need à target="_blank", so then you can use window.open :

gotoGoogle() : void {
     window.open("https://www.google.com", "_blank");
}

Cannot push to Git repository on Bitbucket

I found the solution that worked best for me was breaking up the push into smaller chunks.

and removing the large screenshot image files (10mb+) from the commits

Security wasnt an issue in the end more about limits of bin files

How do I configure git to ignore some files locally?

Both --assume-unchanged and --skip-worktree are NOT A CORRECT WAY to ignore files locally... Kindly check this answer and the notes in the documentation of git update-index. Files that for any reason keep changing frequently (and/or change from a clone to another) and their changes should not be committed, then these files SHOULD NOT be tracked in the first place.

However, the are two proper ways to ignore files locally (both work with untracked files). Either to put files names in .git/info/exclude file which is the local alternative of .gitignore but specific to the current clone. Or to use a global .gitignore (which should be properly used only for common auxiliary files e.g. pyz, pycache, etc) and the file will be ignored in any git repo in your machine.

To make the above as kind of automated (adding to exclude or global .gitignore), you can use the following commands (add to your bash-profile):

  • Per clone local exclude (Note that you should be in the root of the repository when calling the command because of using the relative path), change ##FILE-NAME## to .git/info/exclude
  • Global .gitignore, first make global .gitignore here then change ##FILE-NAME## to ~/.gitignore

Linux

alias git-ignore='echo $1 >> ##FILE-NAME##'
alias git-show-ignored='cat ##FILE-NAME##'
git-unignore(){
  GITFILETOUNIGNORE=${1//\//\\\/}
  sed -i "/$GITFILETOUNIGNORE/d" ##FILE-NAME##
  unset GITFILETOUNIGNORE
}

MacOS (you need the .bak for sed inplace modifications (i.e. you are forced to add a file extension to inplace sed. i.e. make a backup before replacing something), therefore to delete the .bak file I added rm filename.bak)

alias git-ignore='echo $1 >> ##FILE-NAME##'
alias git-show-ignored='cat ##FILE-NAME##'
git-unignore(){
  GITFILETOUNIGNORE=${1//\//\\\/}
  sed -i.bak "/$GITFILETOUNIGNORE/d" ##FILE-NAME##
  rm ##FILE-NAME##.bak
  unset GITFILETOUNIGNORE
}

Then you can do:

git-ignore example_file.txt
git-unignore example_file.txt

The infamous java.sql.SQLException: No suitable driver found

As well as adding the MySQL JDBC connector ensure the context.xml (if not unpacked in the Tomcat webapps folder) with your DB connection definitions are included within Tomcats conf directory.

sqlite database default time value 'now'

This alternative example stores the local time as Integer to save the 20 bytes. The work is done in the field default, Update-trigger, and View. strftime must use '%s' (single-quotes) because "%s" (double-quotes) threw a 'Not Constant' error on me.

Create Table Demo (
   idDemo    Integer    Not Null Primary Key AutoIncrement
  ,DemoValue Text       Not Null Unique
  ,DatTimIns Integer(4) Not Null Default (strftime('%s', DateTime('Now', 'localtime'))) -- get Now/UTC, convert to local, convert to string/Unix Time, store as Integer(4)
  ,DatTimUpd Integer(4)     Null
);

Create Trigger trgDemoUpd After Update On Demo Begin
  Update Demo Set
    DatTimUpd  =                          strftime('%s', DateTime('Now', 'localtime'))  -- same as DatTimIns
  Where idDemo = new.idDemo;
End;

Create View If Not Exists vewDemo As Select -- convert Unix-Times to DateTimes so not every single query needs to do so
   idDemo
  ,DemoValue
  ,DateTime(DatTimIns, 'unixepoch') As DatTimIns -- convert Integer(4) (treating it as Unix-Time)
  ,DateTime(DatTimUpd, 'unixepoch') As DatTimUpd --   to YYYY-MM-DD HH:MM:SS
From Demo;

Insert Into Demo (DemoValue) Values ('One');                      -- activate the field Default
-- WAIT a few seconds --    
Insert Into Demo (DemoValue) Values ('Two');                      -- same thing but with
Insert Into Demo (DemoValue) Values ('Thr');                      --   later time values

Update Demo Set DemoValue = DemoValue || ' Upd' Where idDemo = 1; -- activate the Update-trigger

Select * From    Demo;                                            -- display raw audit values
idDemo  DemoValue  DatTimIns   DatTimUpd
------  ---------  ----------  ----------
1       One Upd    1560024902  1560024944
2       Two        1560024944
3       Thr        1560024944

Select * From vewDemo;                                            -- display automatic audit values
idDemo  DemoValue  DatTimIns            DatTimUpd
------  ---------  -------------------  -------------------
1       One Upd    2019-06-08 20:15:02  2019-06-08 20:15:44
2       Two        2019-06-08 20:15:44
3       Thr        2019-06-08 20:15:44

How to convert UTF8 string to byte array?

The TextEncoder and TextDecoder Encoding API will let you both encode and decode UTF-8 easily (using typed arrays):

const encoded = new TextEncoder().encode("Ge?a s?? ??sµe");
const decoded = new TextDecoder().decode(encoded);

console.log(encoded, decoded);

Browser support isn't too bad, and there's a polyfill that should work in IE11 and older versions of Edge.


Older versions of TextEncoder supported other different encodings as a string constructor parameter argument, but since Firefox 48 and Chrome 53 this is no-longer supported and TextEncoder and TextDecoder support only UTF-8.

So this will no-longer work in modern web-browsers used since 2016:

new TextDecoder("shift-jis").decode(new Uint8Array(textbuffer))

Cell Style Alignment on a range

Don't use "Style:

worksheet.Cells[y,x].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;

How to install mechanize for Python 2.7?

pip install mechanize

mechanize supports only python 2.

For python3 refer https://stackoverflow.com/a/31774959/4773973 for alternatives.

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

You state in the comments that the returned JSON is this:

{ 
  "dstOffset" : 3600, 
  "rawOffset" : 36000, 
  "status" : "OK", 
  "timeZoneId" : "Australia/Hobart", 
  "timeZoneName" : "Australian Eastern Daylight Time" 
}

You're telling Gson that you have an array of Post objects:

List<Post> postsList = Arrays.asList(gson.fromJson(reader,
                    Post[].class));

You don't. The JSON represents exactly one Post object, and Gson is telling you that.

Change your code to be:

Post post = gson.fromJson(reader, Post.class);

What bitrate is used for each of the youtube video qualities (360p - 1080p), in regards to flowplayer?

Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:

                   240p       360p        480p        720p        1080p
Resolution      426 x 240   640 x 360   854x480     1280x720    1920x1080
Video Bitrates                   
Maximum         700 Kbps    1000 Kbps   2000 Kbps   4000 Kbps   6000 Kbps
Recommended     400 Kbps    750 Kbps    1000 Kbps   2500 Kbps   4500 Kbps
Minimum         300 Kbps    400 Kbps    500 Kbps    1500 Kbps   3000 Kbps

It would appear as though this is the case, although the numbers dont sync up to the google table above:

// the bitrates, video width and file names for this clip
      bitrates: [
        { url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
        { url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
        { url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
      ],

How do I jump out of a foreach loop in C#?

how about:

return(sList.Contains("ok"));

That should do the trick if all you want to do is check for an "ok" and return the answer ...

How to print Unicode character in C++?

In Linux, I can just do:

std::cout << "?";

I just copy-pasted characters from here and it didn't fail for at least the random sample that I tried on.

How do I get the web page contents from a WebView?

Have you considered fetching the HTML separately, and then loading it into a webview?

String fetchContent(WebView view, String url) throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet get = new HttpGet(url);
    HttpResponse response = httpClient.execute(get);
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    HttpEntity entity = response.getEntity();
    String html = EntityUtils.toString(entity); // assume html for simplicity
    view.loadDataWithBaseURL(url, html, "text/html", "utf-8", url); // todo: get mime, charset from entity
    if (statusCode != 200) {
        // handle fail
    }
    return html;
}

add scroll bar to table body

you can wrap the content of the <tbody> in a scrollable <div> :

html

....
<tbody>
  <tr>
    <td colspan="2">
      <div class="scrollit">
        <table>
          <tr>
            <td>January</td>
            <td>$100</td>
          </tr>
          <tr>
            <td>February</td>
            <td>$80</td>
          </tr>
          <tr>
            <td>January</td>
            <td>$100</td>
          </tr>
          <tr>
            <td>February</td>
            <td>$80</td>
          </tr>
          ...

css

.scrollit {
    overflow:scroll;
    height:100px;
}

see my jsfiddle, forked from yours: http://jsfiddle.net/VTNax/2/

Laravel 5 Eloquent where and or in Clauses

When we use multiple and (where) condition with last (where + or where) the where condition fails most of the time. for that we can use the nested where function with parameters passing in that.

$feedsql = DB::table('feeds as t1')
                   ->leftjoin('groups as t2', 't1.groups_id', '=', 't2.id')
                    ->where('t2.status', 1)
                    ->whereRaw("t1.published_on <= NOW()") 
                    >whereIn('t1.groupid', $group_ids)
                   ->where(function($q)use ($userid) {
                            $q->where('t2.contact_users_id', $userid)
                            ->orWhere('t1.users_id', $userid);
                     })
                  ->orderBy('t1.published_on', 'desc')->get();

The above query validate all where condition then finally checks where t2.status=1 and (where t2.contact_users_id='$userid' or where t1.users_id='$userid')

How do I find out my root MySQL password?

sudo mysql -u root
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'YOUR_PASSWORD_HERE';
FLUSH PRIVILEGES;

mysql -u root -p # and it works

Where does VBA Debug.Print log to?

Debug.Print outputs to the "Immediate" window.

Debug.Print outputs to the Immediate window

Also, you can simply type ? and then a statement directly into the immediate window (and then press Enter) and have the output appear right below, like this:

simply type ? and then a statement directly into the immediate window

This can be very handy to quickly output the property of an object...

? myWidget.name

...to set the property of an object...

myWidget.name = "thingy"

...or to even execute a function or line of code, while in debugging mode:

Sheet1.MyFunction()

Installing MySQL-python

In python3 with virtualenv on a Ubuntu Bionic machine the following commands worked for me:

sudo apt install build-essential python-dev libmysqlclient-dev
sudo apt-get install libssl-dev
pip install mysqlclient

Can you do greater than comparison on a date in a Rails 3 search?

If you aren't a fan of passing in a string, I prefer how @sesperanto has done it, except to make it even more concise, you could drop Float::INFINITY in the date range and instead simply use created_at: p[:date]..

Note.where(
    user_id: current_user.id,
    notetype: p[:note_type],
    created_at: p[:date]..
).order(:date, :created_at)

Take note that this will change the query to be >= instead of >. If that's a concern, you could always add a unit of time to the date by running something like p[:date] + 1.day..

startForeground fail after upgrade to Android 8.1

Here is my solution

private static final int NOTIFICATION_ID = 200;
private static final String CHANNEL_ID = "myChannel";
private static final String CHANNEL_NAME = "myChannelName";

private void startForeground() {

    final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            getApplicationContext(), CHANNEL_ID);

    Notification notification;



        notification = mBuilder.setTicker(getString(R.string.app_name)).setWhen(0)
                .setOngoing(true)
                .setContentTitle(getString(R.string.app_name))
                .setContentText("Send SMS gateway is running background")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setShowWhen(true)
                .build();

        NotificationManager notificationManager = (NotificationManager) getApplication().getSystemService(Context.NOTIFICATION_SERVICE);

        //All notifications should go through NotificationChannel on Android 26 & above
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                    CHANNEL_NAME,
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);

        }
        notificationManager.notify(NOTIFICATION_ID, notification);

    }

Hope it will help :)

How do I find the absolute position of an element using jQuery?

.offset() will return the offset position of an element as a simple object, eg:

var position = $(element).offset(); // position = { left: 42, top: 567 }

You can use this return value to position other elements at the same spot:

$(anotherElement).css(position)

AngularJS - Trigger when radio button is selected

For dynamic values!

<div class="col-md-4" ng-repeat="(k, v) in tiposAcesso">
    <label class="control-label">
        <input type="radio" name="tipoAcesso" ng-model="userLogin.tipoAcesso" value="{{k}}" ng-change="changeTipoAcesso(k)" />              
        <span ng-bind="v"></span>
    </label>
</div>

in controller

$scope.changeTipoAcesso = function(value) {
    console.log(value);
};

Full-screen responsive background image

For the full-screen responsive background image cover

<div class="full-screen">

</div>

CSS

.full-screen{
    background-image: url("img_girl.jpg");
    height: 100%; 
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
}

D3 Appending Text to a SVG Rectangle

Have you tried the SVG text element?

.append("text").text(function(d, i) { return d[whichevernode];})

rect element doesn't permit text element inside of it. It only allows descriptive elements (<desc>, <metadata>, <title>) and animation elements (<animate>, <animatecolor>, <animatemotion>, <animatetransform>, <mpath>, <set>)

Append the text element as a sibling and work on positioning.

UPDATE

Using g grouping, how about something like this? fiddle

You can certainly move the logic to a CSS class you can append to, remove from the group (this.parentNode)

Building a fat jar using maven

An alternative is to use the maven shade plugin to build an uber-jar.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version> Your Version Here </version>
    <configuration>
            <!-- put your configurations here -->
    </configuration>
    <executions>
            <execution>
                    <phase>package</phase>
                    <goals>
                            <goal>shade</goal>
                    </goals>
            </execution>
    </executions>
</plugin>

How to pass a querystring or route parameter to AWS Lambda from Amazon API Gateway

I have used this mapping template to provide Body, Headers, Method, Path, and URL Query String Parameters to the Lambda event. I wrote a blog post explaining the template in more detail: http://kennbrodhagen.net/2015/12/06/how-to-create-a-request-object-for-your-lambda-event-from-api-gateway/

Here is the Mapping Template you can use:

{
  "method": "$context.httpMethod",
  "body" : $input.json('$'),
  "headers": {
    #foreach($param in $input.params().header.keySet())
    "$param": "$util.escapeJavaScript($input.params().header.get($param))" #if($foreach.hasNext),#end

    #end
  },
  "queryParams": {
    #foreach($param in $input.params().querystring.keySet())
    "$param": "$util.escapeJavaScript($input.params().querystring.get($param))" #if($foreach.hasNext),#end

    #end
  },
  "pathParams": {
    #foreach($param in $input.params().path.keySet())
    "$param": "$util.escapeJavaScript($input.params().path.get($param))" #if($foreach.hasNext),#end

    #end
  }  
}

How to prevent 'query timeout expired'? (SQLNCLI11 error '80040e31')

Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.

I had a opened record set of the post that was created by:

Set RecSet = Conn.Execute()

This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...

RecSet.Close
Set RecSet = Nothing

...everything worked just fine.

So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.

Java ArrayList clear() function

If you in any doubt, have a look at JDK source code

ArrayList.clear() source code:

public void clear() {
    modCount++;

    // Let gc do its work
    for (int i = 0; i < size; i++)
        elementData[i] = null;

    size = 0;
}

You will see that size is set to 0 so you start from 0 position.

Please note that when adding elements to ArrayList, the backend array is extended (i.e. array data is copied to bigger array if needed) in order to be able to add new items. When performing ArrayList.clear() you only remove references to array elements and sets size to 0, however, capacity stays as it was.

How to specify a min but no max decimal using the range data annotation attribute?

It seems there's no choice but to put in the max value manually. I was hoping there was some type of overload where you didn't need to specify one.

[Range(typeof(decimal), "0", "79228162514264337593543950335")]
public decimal Price { get; set; }

Iterate two Lists or Arrays with one ForEach statement in C#

If you don't want to wait for .NET 4.0, you could implement your own Zip method. The following works with .NET 2.0. You can adjust the implementation depending on how you want to handle the case where the two enumerations (or lists) have different lengths; this one continues to the end of the longer enumeration, returning the default values for missing items from the shorter enumeration.

static IEnumerable<KeyValuePair<T, U>> Zip<T, U>(IEnumerable<T> first, IEnumerable<U> second)
{
    IEnumerator<T> firstEnumerator = first.GetEnumerator();
    IEnumerator<U> secondEnumerator = second.GetEnumerator();

    while (firstEnumerator.MoveNext())
    {
        if (secondEnumerator.MoveNext())
        {
            yield return new KeyValuePair<T, U>(firstEnumerator.Current, secondEnumerator.Current);
        }
        else
        {
            yield return new KeyValuePair<T, U>(firstEnumerator.Current, default(U));
        }
    }
    while (secondEnumerator.MoveNext())
    {
        yield return new KeyValuePair<T, U>(default(T), secondEnumerator.Current);
    }
}

static void Test()
{
    IList<string> names = new string[] { "one", "two", "three" };
    IList<int> ids = new int[] { 1, 2, 3, 4 };

    foreach (KeyValuePair<string, int> keyValuePair in ParallelEnumerate(names, ids))
    {
        Console.WriteLine(keyValuePair.Key ?? "<null>" + " - " + keyValuePair.Value.ToString());
    }
}

combining results of two select statements

You can use a Union.

This will return the results of the queries in separate rows.

First you must make sure that both queries return identical columns.

Then you can do :

SELECT tableA.Id, tableA.Name, [tableB].Username AS Owner, [tableB].ImageUrl, [tableB].CompanyImageUrl, COUNT(tableD.UserId) AS Number
FROM tableD 
RIGHT OUTER JOIN [tableB] 
INNER JOIN tableA ON [tableB].Id = tableA.Owner ON tableD.tableAId = tableA.Id 
GROUP BY tableA.Name, [tableB].Username, [tableB].ImageUrl, [tableB].CompanyImageUrl

UNION

SELECT tableA.Id, tableA.Name,  '' AS Owner, '' AS ImageUrl, '' AS CompanyImageUrl, COUNT([tableC].Id) AS Number
FROM 
[tableC] 
RIGHT OUTER JOIN tableA ON [tableC].tableAId = tableA.Id GROUP BY tableA.Id, tableA.Name

As has been mentioned, both queries return quite different data. You would probably only want to do this if both queries return data that could be considered similar.

SO

You can use a Join

If there is some data that is shared between the two queries. This will put the results of both queries into a single row joined by the id, which is probably more what you want to be doing here...

You could do :

SELECT tableA.Id, tableA.Name, [tableB].Username AS Owner, [tableB].ImageUrl, [tableB].CompanyImageUrl, COUNT(tableD.UserId) AS NumberOfUsers, query2.NumberOfPlans
FROM tableD 
RIGHT OUTER JOIN [tableB] 
INNER JOIN tableA ON [tableB].Id = tableA.Owner ON tableD.tableAId = tableA.Id 


INNER JOIN 
  (SELECT tableA.Id, COUNT([tableC].Id) AS NumberOfPlans 
   FROM [tableC] 
   RIGHT OUTER JOIN tableA ON [tableC].tableAId = tableA.Id 
   GROUP BY tableA.Id, tableA.Name) AS query2 
ON query2.Id = tableA.Id

GROUP BY tableA.Name, [tableB].Username, [tableB].ImageUrl, [tableB].CompanyImageUrl

How to run docker-compose up -d at system start up?

Use restart: always in your docker compose file.

Docker-compose up -d will launch container from images again. Use docker-compose start to start the stopped containers, it never launches new containers from images.

nginx:   
    restart: always   
    image: nginx   
    ports:
      - "80:80"
      - "443:443"   links:
      - other_container:other_container

Also you can write the code up in the docker file so that it gets created first, if it has the dependency of other containers.

Convert String to equivalent Enum value

Assuming you use Java 5 enums (which is not so certain since you mention old Enumeration class), you can use the valueOf method of java.lang.Enum subclass:

MyEnum e = MyEnum.valueOf("ONE_OF_CONSTANTS");

Subtract two variables in Bash

For simple integer arithmetic, you can also use the builtin let command.

 ONE=1
 TWO=2
 let "THREE = $ONE + $TWO"
 echo $THREE
    3

For more info on let, look here.

Change drive in git bash for windows

In order to navigate to a different drive/directory you can do it in convenient way (instead of typing cd /e/Study/Codes), just type in cd[Space], and drag-and-drop your directory Codes with your mouse to git bash, hit [Enter].

How to send redirect to JSP page in Servlet

Please use the below code and let me know

try{

            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con = DriverManager.getConnection(c, "root", "MyNewPass");
            System.out.println("connection done");


            PreparedStatement ps=con.prepareStatement(q);
            System.out.println(q);
            rs=ps.executeQuery();
            System.out.println("done2");
            while (rs.next()) {
               System.out.println(rs.getString(1));
               System.out.println(rs.getString(2));

            }

         response.sendRedirect("myfolder/welcome.jsp"); // wherever you wanna redirect this page.

        }
            catch (Exception e) {
                // TODO: handle exception
                System.out.println("Failed");
            }

myfolder/welcome.jsp is the relative path of your jsp page. So, change it as per your jsp page path.

Twitter Bootstrap button click to toggle expand/collapse text section above button

html:

<h4 data-toggle-selector="#me">toggle</h4>
<div id="me">content here</div>

js:

$(function () {
    $('[data-toggle-selector]').on('click',function () {
        $($(this).data('toggle-selector')).toggle(300);
    })
})

Convert Map to JSON using Jackson

If you're using jackson, better to convert directly to ObjectNode.

//not including SerializationFeatures for brevity
static final ObjectMapper mapper = new ObjectMapper();

//pass it your payload
public static ObjectNode convObjToONode(Object o) {
    StringWriter stringify = new StringWriter();
    ObjectNode objToONode = null;

    try {
        mapper.writeValue(stringify, o);
        objToONode = (ObjectNode) mapper.readTree(stringify.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println(objToONode);
    return objToONode;
}

Merging Cells in Excel using C#

This solves the issue in the appropriate way

// Merge a row
            ws.Cell("B2").Value = "Merged Row(1) of Range (B2:D3)";
            ws.Range("B2:D3").Row(1).Merge();

Launch Bootstrap Modal on page load

I recently needed to launch a Bootstrap 5 modal without jQuery and not with a button click (eg, on page load) using Django messages. This is how I did it:

Template/HTML

<div class="modal" id="notification">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Notification!</h5>
        <button type="button" class="btn-close"
                data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        {% for m in messages %}
          {{ m }}
        {% endfor %}
      </div>
      <div class="modal-footer justify-content-between">
        <a class="float-none btn btn-secondary" href="{% url 'some_view' %}"
           type="button">
          Link/Button A
        </a>
        <button type="button" class="btn btn-primary"
                data-bs-dismiss="modal">
          Link/Button B
        </button>
      </div>
    </div>
  </div>
</div>

JS in a file or in the template

{% block javascript %}
  {{ block.super }}
  <script>
    var test_modal = new bootstrap.Modal(
      document.getElementById('notification')
    )
    test_modal.show()
  </script>
{% endblock javascript %}

This method will work without the Django template; just use the HTML and put the JS in a file or script elements that loads after the Bootstrap JS before the end of the body element.

How do I import a sql data file into SQL Server?

Try this process -

Open the Query Analyzer

Start --> Programs --> MS SQL Server --> Query Analyzer

Once opened, connect to the database that you are wish running the script on.

Next, open the SQL file using File --> Open option. Select .sql file.

Once it is open, you can execute the file by pressing F5.

How do I make a burn down chart in Excel?

But why would you use excel when you could do it all online and have your boss check your dynamic link.

We are using this new tool since last week. http://www.burndown-charts.com/

What I do is I send my boss the link to my chart and he plays around with the links to see if we will be on time...

http://www.burndown-charts.com/teams/dreamteam/sprints/prototype-x

How do you determine the size of a file in C?

Matt's solution should work, except that it's C++ instead of C, and the initial tell shouldn't be necessary.

unsigned long fsize(char* file)
{
    FILE * f = fopen(file, "r");
    fseek(f, 0, SEEK_END);
    unsigned long len = (unsigned long)ftell(f);
    fclose(f);
    return len;
}

Fixed your brace for you, too. ;)

Update: This isn't really the best solution. It's limited to 4GB files on Windows and it's likely slower than just using a platform-specific call like GetFileSizeEx or stat64.

How to install JDK 11 under Ubuntu?

For anyone running a JDK on Ubuntu and want to upgrade to JDK11, I'd recommend installing via sdkman. SDKMAN is a tool for switching JVMs, removing and upgrading.

SDKMAN is a tool for managing parallel versions of multiple Software Development Kits on most Unix based systems. It provides a convenient Command Line Interface (CLI) and API for installing, switching, removing and listing Candidates.

Install SDKMAN

$ curl -s "https://get.sdkman.io" | bash
$ source "$HOME/.sdkman/bin/sdkman-init.sh"
$ sdk version

Install Java (11.0.3-zulu)

$ sdk install java

Given an RGB value, how do I create a tint (or shade)?

I'm currently experimenting with canvas and pixels... I'm finding this logic works out for me better.

  1. Use this to calculate the grey-ness ( luma ? )
  2. but with both the existing value and the new 'tint' value
  3. calculate the difference ( I found I did not need to multiply )
  4. add to offset the 'tint' value

    var grey =  (r + g + b) / 3;    
    var grey2 = (new_r + new_g + new_b) / 3;
    
    var dr =  grey - grey2 * 1;    
    var dg =  grey - grey2 * 1    
    var db =  grey - grey2 * 1;  
    
    tint_r = new_r + dr;    
    tint_g = new_g + dg;   
    tint_b = new_b _ db;
    

or something like that...

Check if list<t> contains any of another list

Here is a sample to find if there are match elements in another list

List<int> nums1 = new List<int> { 2, 4, 6, 8, 10 };
List<int> nums2 = new List<int> { 1, 3, 6, 9, 12};

if (nums1.Any(x => nums2.Any(y => y == x)))
{
    Console.WriteLine("There are equal elements");
}
else
{
    Console.WriteLine("No Match Found!");
}

How to retrieve the first word of the output of a command in bash?

I wondered how several of the top answers measured up in terms of speed. I tested the following:

1 @mattbh's

echo "..." | awk '{print $1;}'

2 @ghostdog74's

string="..."; set -- $string; echo $1

3 @boontawee-home's

echo "..." | { read -a array ; echo ${array[0]} ; }

and 4 @boontawee-home's

echo "..." | { read first _ ; echo $first ; }

I measured them with Python's timeit in a Bash script in a Zsh terminal on macOS, using a test string with 215 5-letter words. Did each measurement five times (the results were all for 100 loops, best of 3), and averaged the results:

method       time
--------------------------------
1. awk       9.2ms
2. set       11.6ms (1.26 * "1")
3. read -a   11.7ms (1.27 * "1")
4. read      13.6ms (1.48 * "1")

Nice job, voters The votes (as of this writing) match the solutions' speed!

How to sanity check a date in Java

Above methods of date parsing are nice , i just added new check in existing methods that double check the converted date with original date using formater, so it works for almost each case as i verified. e.g. 02/29/2013 is invalid date. Given function parse the date according to current acceptable date formats. It returns true if date is not parsed successfully.

 public final boolean validateDateFormat(final String date) {
        String[] formatStrings = {"MM/dd/yyyy"};
        boolean isInvalidFormat = false;
        Date dateObj;
        for (String formatString : formatStrings) {
            try {
                SimpleDateFormat sdf = (SimpleDateFormat) DateFormat.getDateInstance();
                sdf.applyPattern(formatString);
                sdf.setLenient(false);
                dateObj = sdf.parse(date);
                System.out.println(dateObj);
                if (date.equals(sdf.format(dateObj))) {
                    isInvalidFormat = false;
                    break;
                }
            } catch (ParseException e) {
                isInvalidFormat = true;
            }
        }
        return isInvalidFormat;
    }

How do I deal with corrupted Git object files?

In general, fixing corrupt objects can be pretty difficult. However, in this case, we're confident that the problem is an aborted transfer, meaning that the object is in a remote repository, so we should be able to safely remove our copy and let git get it from the remote, correctly this time.

The temporary object file, with zero size, can obviously just be removed. It's not going to do us any good. The corrupt object which refers to it, d4a0e75..., is our real problem. It can be found in .git/objects/d4/a0e75.... As I said above, it's going to be safe to remove, but just in case, back it up first.

At this point, a fresh git pull should succeed.

...assuming it was going to succeed in the first place. In this case, it appears that some local modifications prevented the attempted merge, so a stash, pull, stash pop was in order. This could happen with any merge, though, and didn't have anything to do with the corrupted object. (Unless there was some index cleanup necessary, and the stash did that in the process... but I don't believe so.)

How does Python return multiple values from a function?

Here It is actually returning tuple.

If you execute this code in Python 3:

def get():
    a = 3
    b = 5
    return a,b
number = get()
print(type(number))
print(number)

Output :

<class 'tuple'>
(3, 5)

But if you change the code line return [a,b] instead of return a,b and execute :

def get():
    a = 3
    b = 5
    return [a,b]
number = get()
print(type(number))
print(number)

Output :

<class 'list'>
[3, 5]

It is only returning single object which contains multiple values.

There is another alternative to return statement for returning multiple values, use yield( to check in details see this What does the "yield" keyword do in Python?)

Sample Example :

def get():
    for i in range(5):
        yield i
number = get()
print(type(number))
print(number)
for i in number:
    print(i)

Output :

<class 'generator'>
<generator object get at 0x7fbe5a1698b8>
0
1
2
3
4

How to use ESLint with Jest

some of the answers assume you have 'eslint-plugin-jest' installed, however without needing to do that, you can simply do this in your .eslintrc file, add:

  "globals": {
    "jest": true,
  }

How do I get the coordinate position after using jQuery drag and drop?

I would start with something like this. Then update that to use the position plugin and that should get you where you want to be.

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

Your Event.hbm.xml says:

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

In plain english, this means that the column Attendee.attendeeId is the foreign key for the association attendees and points to the primary key of Event.

When you add those Attendees to the event, hibernate updates the foreign key to express the changed association. Since that same column is also the primary key of Attendee, this violates the primary key constraint.

Since an Attendee's identity and event participation are independent, you should use separate columns for the primary and foreign key.

Edit: The selects might be because you don't appear to have a version property configured, making it impossible for hibernate to know whether the attendees already exists in the database (they might have been loaded in a previous session), so hibernate emits selects to check. As for the update statements, it was probably easier to implement that way. If you want to get rid of these separate updates, I recommend mapping the association from both ends, and declare the Event-end as inverse.

How to create a Custom Dialog box in android?

I found this as the easiest way for showing custom dialog.

You have layout your_layout.xml

public void showCustomDialog(final Context context) {
    Dialog dialog = new Dialog(context);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    view = inflater.inflate(R.layout.your_layout, null, false);
    findByIds(view);  /*HERE YOU CAN FIND YOU IDS AND SET TEXTS OR BUTTONS*/
    ((Activity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    dialog.setContentView(view);
    final Window window = dialog.getWindow();
    window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
    window.setBackgroundDrawableResource(R.color.colorTransparent);
    window.setGravity(Gravity.CENTER);
    dialog.show();
}

80-characters / right margin line in Sublime Text 3

Yes, it is possible both in Sublime Text 2 and 3 (which you should really upgrade to if you haven't already). Select View ? Ruler ? 80 (there are several other options there as well). If you like to actually wrap your text at 80 columns, select View ? Word Wrap Column ? 80. Make sure that View ? Word Wrap is selected.

To make your selections permanent (the default for all opened files or views), open Preferences ? Settings—User and use any of the following rules:

{
    // set vertical rulers in specified columns.
    // Use "rulers": [80] for just one ruler
    // default value is []
    "rulers": [80, 100, 120],

    // turn on word wrap for source and text
    // default value is "auto", which means off for source and on for text
    "word_wrap": true,

    // set word wrapping at this column
    // default value is 0, meaning wrapping occurs at window width
    "wrap_width": 80
}

These settings can also be used in a .sublime-project file to set defaults on a per-project basis, or in a syntax-specific .sublime-settings file if you only want them to apply to files written in a certain language (Python.sublime-settings vs. JavaScript.sublime-settings, for example). Access these settings files by opening a file with the desired syntax, then selecting Preferences ? Settings—More ? Syntax Specific—User.

As always, if you have multiple entries in your settings file, separate them with commas , except for after the last one. The entire content should be enclosed in curly braces { }. Basically, make sure it's valid JSON.

If you'd like a key combo to automatically set the ruler at 80 for a particular view/file, or you are interested in learning how to set the value without using the mouse, please see my answer here.

Finally, as mentioned in another answer, you really should be using a monospace font in order for your code to line up correctly. Other types of fonts have variable-width letters, which means one 80-character line may not appear to be the same length as another 80-character line with different content, and your indentations will look all messed up. Sublime has monospace fonts set by default, but you can of course choose any one you want. Personally, I really like Liberation Mono. It has glyphs to support many different languages and Unicode characters, looks good at a variety of different sizes, and (most importantly for a programming font) clearly differentiates between 0 and O (digit zero and capital letter oh) and 1 and l (digit one and lowercase letter ell), which not all monospace fonts do, unfortunately. Version 2.0 and later of the font are licensed under the open-source SIL Open Font License 1.1 (here is the FAQ).

How to use Git Revert

git revert makes a new commit

git revert simply creates a new commit that is the opposite of an existing commit.

It leaves the files in the same state as if the commit that has been reverted never existed. For example, consider the following simple example:

$ cd /tmp/example
$ git init
Initialized empty Git repository in /tmp/example/.git/
$ echo "Initial text" > README.md
$ git add README.md
$ git commit -m "initial commit"
[master (root-commit) 3f7522e] initial commit
 1 file changed, 1 insertion(+)
 create mode 100644 README.md
$ echo "bad update" > README.md 
$ git commit -am "bad update"
[master a1b9870] bad update
 1 file changed, 1 insertion(+), 1 deletion(-)

In this example the commit history has two commits and the last one is a mistake. Using git revert:

$ git revert HEAD
[master 1db4eeb] Revert "bad update"
 1 file changed, 1 insertion(+), 1 deletion(-)

There will be 3 commits in the log:

$ git log --oneline
1db4eeb Revert "bad update"
a1b9870 bad update
3f7522e initial commit

So there is a consistent history of what has happened, yet the files are as if the bad update never occured:

cat README.md 
Initial text

It doesn't matter where in the history the commit to be reverted is (in the above example, the last commit is reverted - any commit can be reverted).

Closing questions

do you have to do something else after?

A git revert is just another commit, so e.g. push to the remote so that other users can pull/fetch/merge the changes and you're done.

Do you have to commit the changes revert made or does revert directly commit to the repo?

git revert is a commit - there are no extra steps assuming reverting a single commit is what you wanted to do.

Obviously you'll need to push again and probably announce to the team.

Indeed - if the remote is in an unstable state - communicating to the rest of the team that they need to pull to get the fix (the reverting commit) would be the right thing to do :).