Programs & Examples On #Geotools

GeoTools is an open source Java library that provides tools for geospatial data (http://geotools.org). Questions about programming using GeoTools are on topic here, while questions on geographic issues (while using GeoTools) should be asked on http://gis.stackexchange.com.

VBA: Selecting range by variables

I recorded a macro with 'Relative References' and this is what I got :

Range("F10").Select
ActiveCell.Offset(0, 3).Range("A1:D11").Select

Heres what I thought : If the range selection is in quotes, VBA really wants a STRING and interprets the cells out of it so tried the following:

Dim MyRange as String
MyRange = "A1:D11"
Range(MyRange).Select

And it worked :) ie.. just create a string using your variables, make sure to dimension it as a STRING variables and Excel will read right off of it ;)

Following tested and found working :

Sub Macro04()

Dim Copyrange As String

Startrow = 1
Lastrow = 11
Let Copyrange = "A" & Startrow & ":" & "D" & Lastrow
Range(Copyrange).Select
End Sub

Convert from java.util.date to JodaTime

http://joda-time.sourceforge.net/quickstart.html

Each datetime class provides a variety of constructors. These include the Object constructor. This allows you to construct, for example, DateTime from the following objects:

* Date - a JDK instant
* Calendar - a JDK calendar
* String - in ISO8601 format
* Long - in milliseconds
* any Joda-Time datetime class

Setting graph figure size

A different approach.
On the figure() call specify properties or modify the figure handle properties after h = figure().

This creates a full screen figure based on normalized units.
figure('units','normalized','outerposition',[0 0 1 1])

The units property can be adjusted to inches, centimeters, pixels, etc.

See figure documentation.

CardView Corner Radius

An easy way to achieve this would be:

1.Make a custom background resource (like a rectangle shape) with rounded corners.

2.set this custom background using the command -

cardView = view.findViewById(R.id.card_view2);
cardView.setBackgroundResource(R.drawable.card_view_bg);

this worked for me.

The XML layout I made with top left and bottom right radius.

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/white" />
<corners android:topLeftRadius="18dp" android:bottomRightRadius="18dp" />
</shape>

In your case, you need to change only topLeftRadius as well as topRightRadius.

If you have a layout that overlaps with the corners of the card view and has a different color maybe, then you might need a different background resource file for the layout and in the xml set this background resource to your layout.

I tried and tested the above method. Hope this helps you.

How do I use the ternary operator ( ? : ) in PHP as a shorthand for "if / else"?

The ternary operator is just a shorthand for and if/else block. Your working code does not have an else condition, so is not suitable for this.

The following example will work:

echo empty($address['street2']) ? 'empty' : 'not empty';

Asp.NET Web API - 405 - HTTP verb used to access this page is not allowed - how to set handler mappings

In our case, the problem was with federated signon between a .Net site and ADFS. When redirecting to the ADFS endpoint the wctx parameter needed all three parameters for the WSFederationAuthenticationModule.CreateSignInRequest method: rm, id, and ru

Thanks to Guillaume Raymond for the tip to check the URL parameters!

How to merge many PDF files into a single one?

You can also use Ghostscript to merge different PDFs. You can even use it to merge a mix of PDFs, PostScript (PS) and EPS into one single output PDF file:

gs \
  -o merged.pdf \
  -sDEVICE=pdfwrite \
  -dPDFSETTINGS=/prepress \
   input_1.pdf \
   input_2.pdf \
   input_3.eps \
   input_4.ps \
   input_5.pdf

However, I agree with other answers: for your use case of merging PDF file types only, pdftk may be the best (and certainly fastest) option.

Update:
If processing time is not the main concern, but if the main concern is file size (or a fine-grained control over certain features of the output file), then the Ghostscript way certainly offers more power to you. To highlight a few of the differences:

  • Ghostscript can 'consolidate' the fonts of the input files which leads to a smaller file size of the output. It also can re-sample images, or scale all pages to a different size, or achieve a controlled color conversion from RGB to CMYK (or vice versa) should you need this (but that will require more CLI options than outlined in above command).
  • pdftk will just concatenate each file, and will not convert any colors. If each of your 16 input PDFs contains 5 subsetted fonts, the resulting output will contain 80 subsetted fonts. The resulting PDF's size is (nearly exactly) the sum of the input file bytes.

Best Practice: Software Versioning

There is also the date versioning scheme, eg: YYYY.MM , YY.MM , YYYYMMDD

It is quite informative because a first look gives an impression about the release date. But i prefer the x.y.z scheme, because i always want to know a product's exact point in its life cycle (Major.minor.release)

How can I hide/show a div when a button is clicked?

 $('#btn').click(function() {
     $('#wizard').toggle(); 
 });

if you want to begin with the div hidden, you should add style="display:none;", like this:

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

How to automatically import data from uploaded CSV or XLS file into Google Sheets

You can get Google Drive to automatically convert csv files to Google Sheets by appending

?convert=true

to the end of the api url you are calling.

EDIT: Here is the documentation on available parameters: https://developers.google.com/drive/v2/reference/files/insert

Also, while searching for the above link, I found this question has already been answered here:

Upload CSV to Google Drive Spreadsheet using Drive v2 API

What is the difference between utf8mb4 and utf8 charsets in MySQL?

MySQL added this utf8mb4 code after 5.5.3, Mb4 is the most bytes 4 meaning, specifically designed to be compatible with four-byte Unicode. Fortunately, UTF8MB4 is a superset of UTF8, except that there is no need to convert the encoding to UTF8MB4. Of course, in order to save space, the general use of UTF8 is enough.

The original UTF-8 format uses one to six bytes and can encode 31 characters maximum. The latest UTF-8 specification uses only one to four bytes and can encode up to 21 bits, just to represent all 17 Unicode planes. UTF8 is a character set in Mysql that supports only a maximum of three bytes of UTF-8 characters, which is the basic multi-text plane in Unicode.

To save 4-byte-long UTF-8 characters in Mysql, you need to use the UTF8MB4 character set, but only 5.5. After 3 versions are supported (View version: Select version ();). I think that in order to get better compatibility, you should always use UTF8MB4 instead of UTF8. For char type data, UTF8MB4 consumes more space and, according to Mysql's official recommendation, uses VARCHAR instead of char.

In MariaDB utf8mb4 as the default CHARSET when it not set explicitly in the server config, hence COLLATE utf8mb4_unicode_ci is used.

Refer MariaDB CHARSET & COLLATE Click

CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

How can I create objects while adding them into a vector?

Question 1:

   vectorOfGamers.push_back(Player)

This is problematic because you cannot directly push a class name into a vector. You can either push an object of class into the vector or push reference or pointer to class type into the vector. For example:

vectorOfGamers.push_back(Player(name, id)) 
  //^^assuming name and id are parameters to the vector, call Player constructor
  //^^In other words, push `instance`  of Player class into vector

Question 2:

These 3 classes derives from Gamer. Can I create vector to hold objects of Dealer, Bot and Player at the same time? How do I do that?

Yes you can. You can create a vector of pointers that points to the base class Gamer. A good choice is to use a vector of smart_pointer, therefore, you do not need to manage pointer memory by yourself. Since the other three classes are derived from Gamer, based on polymorphism, you can assign derived class objects to base class pointers. You may find more information from this post: std::vector of objects / pointers / smart pointers to pass objects (buss error: 10)?

Select Tag Helper in ASP.NET Core MVC

I created an Interface and a <options> tag helper for this. So I didn't have to convert the IEnumerable<T> items into IEnumerable<SelectListItem> every time I have to populate the <select> control.

And I think it works beautifully...

The usage is something like:

<select asp-for="EmployeeId">
    <option value="">Please select...</option>
    <options asp-items="@Model.EmployeesList" />
</select>

And to make it work with the tag helper you have to implement that interface in your class:

public class Employee : IIntegerListItem
{
   public int Id { get; set; }
   public string FullName { get; set; }

   public int Value { return Id; }
   public string Text{ return FullName ; }
}

These are the needed codes:

The interface:

public interface IIntegerListItem
{
    int Value { get; }
    string Text { get; }
}

The <options> tag helper:

[HtmlTargetElement("options", Attributes = "asp-items")]
public class OptionsTagHelper : TagHelper
{
    public OptionsTagHelper(IHtmlGenerator generator)
    {
        Generator = generator;
    }

    [HtmlAttributeNotBound]
    public IHtmlGenerator Generator { get; set; }

    [HtmlAttributeName("asp-items")]
    public object Items { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.SuppressOutput();
        // Is this <options /> element a child of a <select/> element the SelectTagHelper targeted?
        object formDataEntry;
        context.Items.TryGetValue(typeof(SelectTagHelper), out formDataEntry);

        var selectedValues = formDataEntry as ICollection<string>;
        var encodedValues = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
        if (selectedValues != null && selectedValues.Count != 0)
        {
            foreach (var selectedValue in selectedValues)
            {
                encodedValues.Add(Generator.Encode(selectedValue));
            }
        }

        IEnumerable<SelectListItem> items = null;
        if (Items != null)
        {
            if (Items is IEnumerable)
            {
                var enumerable = Items as IEnumerable;
                if (Items is IEnumerable<SelectListItem>)
                    items = Items as IEnumerable<SelectListItem>;
                else if (Items is IEnumerable<IIntegerListItem>)
                    items = ((IEnumerable<IIntegerListItem>)Items).Select(x => new SelectListItem() { Selected = false, Value = ((IIntegerListItem)x).Value.ToString(), Text = ((IIntegerListItem)x).Text });
                else
                    throw new InvalidOperationException(string.Format("The {2} was unable to provide metadata about '{1}' expression value '{3}' for <options>.",
                        "<options>",
                        "ForAttributeName",
                        nameof(IModelMetadataProvider),
                        "For.Name"));
            }
            else
            {
                throw new InvalidOperationException("Invalid items for <options>");
            }

            foreach (var item in items)
            {
                bool selected = (selectedValues != null && selectedValues.Contains(item.Value)) || encodedValues.Contains(item.Value);
                var selectedAttr = selected ? "selected='selected'" : "";

                if (item.Value != null)
                    output.Content.AppendHtml($"<option value='{item.Value}' {selectedAttr}>{item.Text}</option>");
                else
                    output.Content.AppendHtml($"<option>{item.Text}</option>");
            }
        }
    }
}

There may be some typo but the aim is clear I think. I had to edit a little bit.

Progress during large file copy (Copy-Item & Write-Progress?)

Not that I'm aware of. I wouldn't recommend using copy-item for this anyway. I don't think it has been designed to be robust like robocopy.exe to support retry which you would want for extremely large file copies over the network.

How to set custom JsonSerializerSettings for Json.NET in ASP.NET Web API?

You can customize the JsonSerializerSettings by using the Formatters.JsonFormatter.SerializerSettings property in the HttpConfiguration object.

For example, you could do that in the Application_Start() method:

protected void Application_Start()
{
    HttpConfiguration config = GlobalConfiguration.Configuration;
    config.Formatters.JsonFormatter.SerializerSettings.Formatting =
        Newtonsoft.Json.Formatting.Indented;
}

How to display all elements in an arraylist?

You are getting an error because your getAll function in the Car class returns a single Car and you want to assign it into an array.

It's really not clear and you may want to post more code. why are you passing a single Car to the function? What is the meaning of calling getAll on a Car.

Convert canvas to PDF

Please see https://github.com/joshua-gould/canvas2pdf. This library creates a PDF representation of your canvas element, unlike the other proposed solutions which embed an image in a PDF document.

//Create a new PDF canvas context.
var ctx = new canvas2pdf.Context(blobStream());

//draw your canvas like you would normally
ctx.fillStyle='yellow';
ctx.fillRect(100,100,100,100);
// more canvas drawing, etc...

//convert your PDF to a Blob and save to file
ctx.stream.on('finish', function () {
    var blob = ctx.stream.toBlob('application/pdf');
    saveAs(blob, 'example.pdf', true);
});
ctx.end();

Angular2 *ngFor in select list, set active based on string from object

Check it out in this demo fiddle, go ahead and change the dropdown or default values in the code.

Setting the passenger.Title with a value that equals to a title.Value should work.

View:

<select [(ngModel)]="passenger.Title">
    <option *ngFor="let title of titleArray" [value]="title.Value">
      {{title.Text}}
    </option>
</select>

TypeScript used:

class Passenger {
  constructor(public Title: string) { };
}
class ValueAndText {
  constructor(public Value: string, public Text: string) { }
}

...
export class AppComponent {
    passenger: Passenger = new Passenger("Lord");

    titleArray: ValueAndText[] = [new ValueAndText("Mister", "Mister-Text"),
                                  new ValueAndText("Lord", "Lord-Text")];

}

How to select Python version in PyCharm?

Quick Answer:

  • File --> Setting
  • In left side in project section --> Project interpreter
  • Select desired Project interpreter
  • Apply + OK

[NOTE]:

Tested on Pycharm 2018 and 2017.


How to increment a pointer address and pointer's value?

First, the ++ operator takes precedence over the * operator, and the () operators take precedence over everything else.

Second, the ++number operator is the same as the number++ operator if you're not assigning them to anything. The difference is number++ returns number and then increments number, and ++number increments first and then returns it.

Third, by increasing the value of a pointer, you're incrementing it by the sizeof its contents, that is you're incrementing it as if you were iterating in an array.

So, to sum it all up:

ptr++;    // Pointer moves to the next int position (as if it was an array)
++ptr;    // Pointer moves to the next int position (as if it was an array)
++*ptr;   // The value of ptr is incremented
++(*ptr); // The value of ptr is incremented
++*(ptr); // The value of ptr is incremented
*ptr++;   // Pointer moves to the next int position (as if it was an array). But returns the old content
(*ptr)++; // The value of ptr is incremented
*(ptr)++; // Pointer moves to the next int position (as if it was an array). But returns the old content
*++ptr;   // Pointer moves to the next int position, and then get's accessed, with your code, segfault
*(++ptr); // Pointer moves to the next int position, and then get's accessed, with your code, segfault

As there are a lot of cases in here, I might have made some mistake, please correct me if I'm wrong.

EDIT:

So I was wrong, the precedence is a little more complicated than what I wrote, view it here: http://en.cppreference.com/w/cpp/language/operator_precedence

Is it possible to modify a registry entry via a .bat/.cmd script?

In addition to reg.exe, I highly recommend that you also check out powershell, its vastly more capable in its registry handling.

Adding default parameter value with type hint in Python

If you're using typing (introduced in Python 3.5) you can use typing.Optional, where Optional[X] is equivalent to Union[X, None]. It is used to signal that the explicit value of None is allowed . From typing.Optional:

def foo(arg: Optional[int] = None) -> None:
    ...

How to integrate Dart into a Rails app

If you run pub build --mode=debug the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug is used.

Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline

How to put a List<class> into a JSONObject and then read that object?

You could use a JSON serializer/deserializer like flexjson to do the conversion for you.

Difference between static, auto, global and local variable in the context of c and c++

Local variables are non existent in the memory after the function termination.
However static variables remain allocated in the memory throughout the life of the program irrespective of whatever function.

Additionally from your question, static variables can be declared locally in class or function scope and globally in namespace or file scope. They are allocated the memory from beginning to end, it's just the initialization which happens sooner or later.

Choosing bootstrap vs material design

As far as I know you can use all mentioned technologies separately or together. It's up to you. I think you look at the problem from the wrong angle. Material Design is just the way particular elements of the page are designed, behave and put together. Material Design provides great UI/UX, but it relies on the graphic layout (HTML/CSS) rather than JS (events, interactions).

On the other hand, AngularJS and Bootstrap are front-end frameworks that can speed up your development by saving you from writing tons of code. For example, you can build web app utilizing AngularJS, but without Material Design. Or You can build simple HTML5 web page with Material Design without AngularJS or Bootstrap. Finally you can build web app that uses AngularJS with Bootstrap and with Material Design. This is the best scenario. All technologies support each other.

  1. Bootstrap = responsive page
  2. AngularJS = MVC
  3. Material Design = great UI/UX

You can check awesome material design components for AngularJS:

https://material.angularjs.org


enter image description here

Demo: https://material.angularjs.org/latest/demo/ enter image description here

Min and max value of input in angular4 application

Most simple approach in Template driven forms for min/max validation with out using reactive forms and building any directive, would be to use pattern attribute of html. This has already been explained and answered here please look https://stackoverflow.com/a/63312336/14069524

AWK to print field $2 first, then field $1

A couple of general tips (besides the DOS line ending issue):

cat is for concatenating files, it's not the only tool that can read files! If a command doesn't read files then use redirection like command < file.

You can set the field separator with the -F option so instead of:

cat foo | awk 'BEGIN{FS="|"} {print $2 " " $1}' 

Try:

awk -F'|' '{print $2" "$1}' foo 

This will output:

com.emailclient.account [email protected]
com.socialsite.auth.accoun [email protected]

To get the desired output you could do a variety of things. I'd probably split() the second field:

awk -F'|' '{split($2,a,".");print a[2]" "$1}' file
emailclient [email protected]
socialsite [email protected]

Finally to get the first character converted to uppercase is a bit of a pain in awk as you don't have a nice built in ucfirst() function:

awk -F'|' '{split($2,a,".");print toupper(substr(a[2],1,1)) substr(a[2],2),$1}' file
Emailclient [email protected]
Socialsite [email protected]

If you want something more concise (although you give up a sub-process) you could do:

awk -F'|' '{split($2,a,".");print a[2]" "$1}' file | sed 's/^./\U&/'
Emailclient [email protected]
Socialsite [email protected]

Define global variable with webpack

There are several way to approach globals:

  1. Put your variables in a module.

Webpack evaluates modules only once, so your instance remains global and carries changes through from module to module. So if you create something like a globals.js and export an object of all your globals then you can import './globals' and read/write to these globals. You can import into one module, make changes to the object from a function and import into another module and read those changes in a function. Also remember the order things happen. Webpack will first take all the imports and load them up in order starting in your entry.js. Then it will execute entry.js. So where you read/write to globals is important. Is it from the root scope of a module or in a function called later?

config.js

export default {
    FOO: 'bar'
}

somefile.js

import CONFIG from './config.js'
console.log(`FOO: ${CONFIG.FOO}`)

Note: If you want the instance to be new each time, then use an ES6 class. Traditionally in JS you would capitalize classes (as opposed to the lowercase for objects) like
import FooBar from './foo-bar' // <-- Usage: myFooBar = new FooBar()

  1. Webpack's ProvidePlugin

Here's how you can do it using Webpack's ProvidePlugin (which makes a module available as a variable in every module and only those modules where you actually use it). This is useful when you don't want to keep typing import Bar from 'foo' again and again. Or you can bring in a package like jQuery or lodash as global here (although you might take a look at Webpack's Externals).

Step 1) Create any module. For example, a global set of utilities would be handy:

utils.js

export function sayHello () {
  console.log('hello')
}

Step 2) Alias the module and add to ProvidePlugin:

webpack.config.js

var webpack = require("webpack");
var path = require("path");

// ...

module.exports = {

  // ...

  resolve: {
    extensions: ['', '.js'],
    alias: {
      'utils': path.resolve(__dirname, './utils')  // <-- When you build or restart dev-server, you'll get an error if the path to your utils.js file is incorrect.
    }
  },

  plugins: [

    // ...

    new webpack.ProvidePlugin({
      'utils': 'utils'
    })
  ]  

}

Now just call utils.sayHello() in any js file and it should work. Make sure you restart your dev-server if you are using that with Webpack.

Note: Don't forget to tell your linter about the global, so it won't complain. For example, see my answer for ESLint here.

  1. Use Webpack's DefinePlugin

If you just want to use const with string values for your globals, then you can add this plugin to your list of Webpack plugins:

new webpack.DefinePlugin({
  PRODUCTION: JSON.stringify(true),
  VERSION: JSON.stringify("5fa3b9"),
  BROWSER_SUPPORTS_HTML5: true,
  TWO: "1+1",
  "typeof window": JSON.stringify("object")
})

Use it like:

console.log("Running App version " + VERSION);
if(!BROWSER_SUPPORTS_HTML5) require("html5shiv");
  1. Use the global window object (or Node's global)

window.foo = 'bar'  // For SPA's, browser environment.
global.foo = 'bar'  // Webpack will automatically convert this to window if your project is targeted for web (default), read more here: https://webpack.js.org/configuration/node/

You'll see this commonly used for polyfills, for example: window.Promise = Bluebird

  1. Use a package like dotenv

(For server side projects) The dotenv package will take a local configuration file (which you could add to your .gitignore if there are any keys/credentials) and adds your configuration variables to Node's process.env object.

// As early as possible in your application, require and configure dotenv.    
require('dotenv').config()

Create a .env file in the root directory of your project. Add environment-specific variables on new lines in the form of NAME=VALUE. For example:

DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3

That's it.

process.env now has the keys and values you defined in your .env file.

var db = require('db')
db.connect({
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASS
})

Notes:

Regarding Webpack's Externals, use it if you want to exclude some modules from being included in your built bundle. Webpack will make the module globally available but won't put it in your bundle. This is handy for big libraries like jQuery (because tree shaking external packages doesn't work in Webpack) where you have these loaded on your page already in separate script tags (perhaps from a CDN).

‘ant’ is not recognized as an internal or external command

I had a similar issue, but the reason that %ANT_HOME% wasn't resolving is that I had added it as a USER variable, not a SYSTEM one. Sorted now, thanks to this post.

How to convert a date String to a Date or Calendar object?

The DateFormat class has a parse method.

See DateFormat for more information.

Go to next item in ForEach-Object

I know this is an old post, but I wanted to add something I learned for the next folks who land here while googling.

In Powershell 5.1, you want to use continue to move onto the next item in your loop. I tested with 6 items in an array, had a foreach loop through, but put an if statement with:

foreach($i in $array){    
    write-host -fore green "hello $i"
    if($i -like "something"){
        write-host -fore red "$i is bad"
        continue
        write-host -fore red "should not see this"
    }
}

Of the 6 items, the 3rd one was something. As expected, it looped through the first 2, then the matching something gave me the red line where $i matched, I saw something is bad and then it went on to the next item in the array without saying should not see this. I tested with return and it exited the loop altogether.

Java: using switch statement with enum under subclass

Java infers automatically the type of the elements in case, so the labels must be unqualified.

int i;
switch(i) {
   case 5: // <- integer is expected
}
MyEnum e;
switch (e) {
   case VALUE_A: // <- an element of the enumeration is expected
}

T-SQL: Opposite to string concatenation - how to split string into multiple records

There are a wide varieties of solutions to this problem documented here, including this little gem:

CREATE FUNCTION dbo.Split (@sep char(1), @s varchar(512))
RETURNS table
AS
RETURN (
    WITH Pieces(pn, start, stop) AS (
      SELECT 1, 1, CHARINDEX(@sep, @s)
      UNION ALL
      SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)
      FROM Pieces
      WHERE stop > 0
    )
    SELECT pn,
      SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s
    FROM Pieces
  )

How to find rows that have a value that contains a lowercase letter

Logically speaking Rohit's solution should have worked, but it didn't. I think SQL Management Studio messed up when trying to optimize this.

But by modifying the string before comparing them I was able to get the right results. This worked for me:

SELECT [ExternalId]
FROM [EquipmentSerialsMaster] where LOWER('0'+[ExternalId]) COLLATE Latin1_General_CS_AS != '0'+[ExternalId]

Html5 Full screen video

No, there is no way to do this yet. I wish they add a future like this in browsers.

EDIT:

Now there is a Full Screen API for the web You can requestFullscreen on an Video or Canvas element to ask user to give you permisions and make it full screen.

Let's consider this element:

<video controls id="myvideo">
  <source src="somevideo.webm"></source>
  <source src="somevideo.mp4"></source>
</video>

We can put that video into fullscreen mode with script like this:

var elem = document.getElementById("myvideo");
if (elem.requestFullscreen) {
  elem.requestFullscreen();
} else if (elem.mozRequestFullScreen) {
  elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
  elem.webkitRequestFullscreen();
} else if (elem.msRequestFullscreen) { 
  elem.msRequestFullscreen();
}

Full documentation

What does <> mean in excel?

It means "not equal to" (as in, the values in cells E37-N37 are not equal to "", or in other words, they are not empty.)

Image convert to Base64

Exactly what you need:) You can choose callback version or Promise version. Note that promises will work in IE only with Promise polyfill lib.You can put this code once on a page, and this function will appear in all your files.

The loadend event is fired when progress has stopped on the loading of a resource (e.g. after "error", "abort", or "load" have been dispatched)

Callback version

        File.prototype.convertToBase64 = function(callback){
                var reader = new FileReader();
                reader.onloadend = function (e) {
                    callback(e.target.result, e.target.error);
                };   
                reader.readAsDataURL(this);
        };

        $("#asd").on('change',function(){
          var selectedFile = this.files[0];
          selectedFile.convertToBase64(function(base64){
               alert(base64);
          }) 
        });

Promise version

    File.prototype.convertToBase64 = function(){
         return new Promise(function(resolve, reject) {
                var reader = new FileReader();
                reader.onloadend = function (e) {
                    resolve({
                      fileName: this.name,
                      result: e.target.result, 
                      error: e.target.error
                    });
                };   
                reader.readAsDataURL(this);
        }.bind(this)); 
    };

    FileList.prototype.convertAllToBase64 = function(regexp){
      // empty regexp if not set
      regexp = regexp || /.*/;
      //making array from FileList
      var filesArray = Array.prototype.slice.call(this);
      var base64PromisesArray = filesArray.
           filter(function(file){
             return (regexp).test(file.name)
           }).map(function(file){
             return file.convertToBase64();
           });
      return Promise.all(base64PromisesArray);
    };

    $("#asd").on('change',function(){
      //for one file
      var selectedFile = this.files[0];
      selectedFile.convertToBase64().
          then(function(obj){
            alert(obj.result);
          });
      });
      //for all files that have file extention png, jpeg, jpg, gif
      this.files.convertAllToBase64(/\.(png|jpeg|jpg|gif)$/i).then(function(objArray){
            objArray.forEach(function(obj, i){
                  console.log("result[" + obj.fileName + "][" + i + "] = " + obj.result);
            });
      });
    })

html

<input type="file" id="asd" multiple/>

Vue js error: Component template should contain exactly one root element

I was confused as I knew VueJS should only contain 1 root element and yet I was still getting this same "template syntax error Component template should contain exactly one root element..." error on an extremely simple component. Turns out I had just mispelled </template> as </tempate> and that was giving me this same error in a few files I copied and pasted. In summary, check your syntax for any mispellings in your component.

What is the "Upgrade-Insecure-Requests" HTTP header?

This explains the whole thing:

The HTTP Content-Security-Policy (CSP) upgrade-insecure-requests directive instructs user agents to treat all of a site's insecure URLs (those served over HTTP) as though they have been replaced with secure URLs (those served over HTTPS). This directive is intended for web sites with large numbers of insecure legacy URLs that need to be rewritten.

The upgrade-insecure-requests directive is evaluated before block-all-mixed-content and if it is set, the latter is effectively a no-op. It is recommended to set one directive or the other, but not both.

The upgrade-insecure-requests directive will not ensure that users visiting your site via links on third-party sites will be upgraded to HTTPS for the top-level navigation and thus does not replace the Strict-Transport-Security (HSTS) header, which should still be set with an appropriate max-age to ensure that users are not subject to SSL stripping attacks.

Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/upgrade-insecure-requests

Android: how to hide ActionBar on certain activities

For selectively hiding Actionbar in activities:

Add the following code to onCreate (preferably on the last line of the function)

Kotlin:

supportActionBar?.hide()

Java:

getSupportActionBar().hide();

How to install/start Postman native v4.10.3 on Ubuntu 16.04 LTS 64-bit?

open terminal and type command

sudo snap install postman

hit enter button if it asks for password enter and proceed it will install postman

If above solution doesn't work for you then you should install snap first to install it

sudo apt update
sudo apt install snapd

when snap is installed successfully then u can use its packages and follow my solution for postman

How to get current location in Android

I'm using this tutorial and it works nicely for my application.

In my activity I put this code:

GPSTracker tracker = new GPSTracker(this);
    if (!tracker.canGetLocation()) {
        tracker.showSettingsAlert();
    } else {
        latitude = tracker.getLatitude();
        longitude = tracker.getLongitude();
    }

also check if your emulator runs with Google API

How to get height of <div> in px dimension

For those looking for a plain JS solution:

let el = document.querySelector("#myElementId");

// including the element's border
let width = el.offsetWidth;
let height = el.offsetHeight;

// not including the element's border:
let width = el.clientWidth;
let height = el.clientHeight;

Check out this article for more details.

change html text from link with jquery

I found this to be the simplest piece of code for getting the job done. As you can see it is super simple.

for original link text

I use:

    $("#sec1").text(Sector1);

where

   Sector1 = 'my new link text';

getCurrentPosition() and watchPosition() are deprecated on insecure origins

Found a likely answer in /jstillwell's posts here: https://github.com/stefanocudini/leaflet-gps/issues/15 basically this feature will not be supported (in Chrome only?) in the future, but only for HTTP sites. HTTPS will still be ok, and there are no plans to create an equivalent replacement for HTTP use.

Javascript: Unicode string to hex

It depends on what encoding you use. If you want to convert utf-8 encoded hex to string, use this:

function fromHex(hex,str){
  try{
    str = decodeURIComponent(hex.replace(/(..)/g,'%$1'))
  }
  catch(e){
    str = hex
    console.log('invalid hex input: ' + hex)
  }
  return str
}

For the other direction use this:

function toHex(str,hex){
  try{
    hex = unescape(encodeURIComponent(str))
    .split('').map(function(v){
      return v.charCodeAt(0).toString(16)
    }).join('')
  }
  catch(e){
    hex = str
    console.log('invalid text input: ' + str)
  }
  return hex
}

How can I set the Secure flag on an ASP.NET Session Cookie?

secure - This attribute tells the browser to only send the cookie if the request is being sent over a secure channel such as HTTPS. This will help protect the cookie from being passed over unencrypted requests. If the application can be accessed over both HTTP and HTTPS, then there is the potential that the cookie can be sent in clear text.

How to delete object from array inside foreach loop?

This should do the trick.....

reset($array);
while (list($elementKey, $element) = each($array)) {
    while (list($key, $value2) = each($element)) {
        if($key == 'id' && $value == 'searched_value') {
            unset($array[$elementKey]);
        }
    }
}

http://localhost/phpMyAdmin/ unable to connect

Your web server isn't running! You need to find the XAMPP control panel and start the web server up.

Of course, you might find other problems after that, but this is the first step.

Matplotlib: ValueError: x and y must have same first dimension

Changing your lists to numpy arrays will do the job!!

import matplotlib.pyplot as plt
from scipy import stats
import numpy as np 

x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,0.77,0.72,0.49,0.55,0.62,0.58,0.88,0.78]) # x is a numpy array now
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,0.478,0.335,0.365,0.424,0.390,0.585,0.511]) # y is a numpy array now
xerr = [0.01]*15
yerr = [0.001]*15

plt.rc('font', family='serif', size=13)
m, b = np.polyfit(x, y, 1)
plt.plot(x,y,'s',color='#0066FF')
plt.plot(x, m*x + b, 'r-') #BREAKS ON THIS LINE
plt.errorbar(x,y,xerr=xerr,yerr=0,linestyle="None",color='black')
plt.xlabel('$\Delta t$ $(s)$',fontsize=20)
plt.ylabel('$\Delta p$ $(hPa)$',fontsize=20)
plt.autoscale(enable=True, axis=u'both', tight=False)
plt.grid(False)
plt.xlim(0.2,1.2)
plt.ylim(0,0.8)
plt.show()

enter image description here

How to check if text fields are empty on form submit using jQuery?

you should try with jquery validate plugin :

$('form').validate({
   rules:{
       email:{
          required:true,
          email:true
       }
   },
   messages:{
       email:{
          required:"Email is required",
          email:"Please type a valid email"
        }
   }
})

How to store an array into mysql?

Storing with json or serialized array is the best solution for now. With some situations (trimming " ' characters) json might be getting trouble but serialize should be great choice.

Note: If you change serialized data manually, you need to be careful about character count.

MVC Razor view nested foreach's model

You could add a Category partial and a Product partial, each would take a smaller part of the main model as it's own model, i.e. Category's model type might be an IEnumerable, you would pass in Model.Theme to it. The Product's partial might be an IEnumerable that you pass Model.Products into (from within the Category partial).

I'm not sure if that would be the right way forward, but would be interested in knowing.

EDIT

Since posting this answer, I've used EditorTemplates and find this the easiest way to handle repeating input groups or items. It handles all your validation message problems and form submission/model binding woes automatically.

How to select the first, second, or third element with a given class name?

In the future (perhaps) you will be able to use :nth-child(an+b of s)

Actually, browser support for the “of” filter is very limited. Only Safari seems to support the syntax.

https://css-tricks.com/almanac/selectors/n/nth-child/

Winforms TableLayoutPanel adding rows programmatically

Create a table layout panel with two columns in your form and name it tlpFields.

Then, simply add new control to table layout panel (in this case I added 5 labels in column-1 and 5 textboxes in column-2).

tlpFields.RowStyles.Clear();  //first you must clear rowStyles

for (int ii = 0; ii < 5; ii++)
{
    Label l1= new Label();
    TextBox t1 = new TextBox();

    l1.Text = "field : ";

    tlpFields.Controls.Add(l1, 0, ii);  // add label in column0
    tlpFields.Controls.Add(t1, 1, ii);  // add textbox in column1

    tlpFields.RowStyles.Add(new RowStyle(SizeType.Absolute,30)); // 30 is the rows space
}

Finally, run the code.

Mockito: Mock private field initialization

Mockito comes with a helper class to save you some reflection boiler plate code:

import org.mockito.internal.util.reflection.Whitebox;

//...

@Mock
private Person mockedPerson;
private Test underTest;

// ...

@Test
public void testMethod() {
    Whitebox.setInternalState(underTest, "person", mockedPerson);
    // ...
}

Update: Unfortunately the mockito team decided to remove the class in Mockito 2. So you are back to writing your own reflection boilerplate code, use another library (e.g. Apache Commons Lang), or simply pilfer the Whitebox class (it is MIT licensed).

Update 2: JUnit 5 comes with its own ReflectionSupport and AnnotationSupport classes that might be useful and save you from pulling in yet another library.

How can I view the shared preferences file using Android Studio?

Shared Preferences File path for Android Emulator in Mac

/Users/"UserName"/Documents/AndroidStudio/DeviceExplorer/"EmulatorName"/data/data/com.app.domain/shared_prefs/

SVN Repository Search

// Edit: Tool was already mentioned in another answer, so give all credits to Kuryaki.

Just found SupoSE which is a java based command line tool which scans a repository to create an index and afterwards is able to answer certain kinds of queries. We're still evaluating the tool but it looks promising. It's worth to mention that it makes a full index of all revisions including source code files and common office formats.

Checkout multiple git repos into same Jenkins workspace

We are using git-repo to manage our multiple GIT repositories. There is also a Jenkins Repo plugin that allows to checkout all or part of the repositories managed by git-repo to the same Jenkins job workspace.

$('body').on('click', '.anything', function(){})

You can try this:

You must follow the following format

    $('element,id,class').on('click', function(){....});

*JQuery code*

    $('body').addClass('.anything').on('click', function(){
      //do some code here i.e
      alert("ok");
    });

Frame Buster Buster ... buster code needed

As of 2015, you should use CSP2's frame-ancestors directive for this. This is implemented via an HTTP response header.

e.g.

Content-Security-Policy: frame-ancestors 'none'

Of course, not many browsers support CSP2 yet so it is wise to include the old X-Frame-Options header:

X-Frame-Options: DENY

I would advise to include both anyway, otherwise your site would continue to be vulnerable to Clickjacking attacks in old browsers, and of course you would get undesirable framing even without malicious intent. Most browsers do update automatically these days, however you still tend to get corporate users being stuck on old versions of Internet Explorer for legacy application compatibility reasons.

Change the Theme in Jupyter Notebook?

For Dark Mode Only: -

I have used Raleway Font for styling

To C:\User\UserName\.jupyter\custom\custom.css file

append the given styles, this is specifically for Dark Mode for jupyter notebook...

This should be your current custom.css file: -

/* This file contains any manual css for this page that needs to override the global styles.
    This is only required when different pages style the same element differently. This is just
    a hack to deal with our current css styles and no new styling should be added in this file.*/

#ipython-main-app {
    position: relative;
}

#jupyter-main-app {
    position: relative;
}

Content to be append starts now

.header-bar {
    display: none;
}

#header-container img {
    display: none;
}

#notebook_name {
    margin-left: 0px !important;
}

#header-container {
    padding-left: 0px !important
}

html,
body {
    overflow: hidden;
    font-family: OpenSans;
}

#header {
    background-color: #212121 !important;
    color: #fff;
    padding-top: 20px;
    padding-bottom: 50px;
}

.navbar-collapse {
    background-color: #212121 !important;
    color: #fff;
    border: none !important
}

#menus {
    border: none !important;
    color: white !important;
}

#menus .dropdown-toggle {
    color: white !important;
}

#filelink {
    color: white !important;
    text-align: centerimportant;
    padding-left: 7px;
    text-decoration: none !important;
}

.navbar-default .navbar-nav>.open>a,
.navbar-default .navbar-nav>.open>a:hover,
.navbar-default .navbar-nav>.open>a:focus {
    background-color: #191919 !important;
    color: #eee !important;
    text-align: left !important;
}

.dropdown-menu,
.dropdown-menu a,
.dropdown-submenu a {
    background-color: #191919;
    color: #fff !important;
}

.dropdown-menu>li>a:hover,
.dropdown-menu>li>a:focus,
.dropdown-submenu>a:after {
    background-color: #212121;
    color: #fff !important;
}

.btn-default {
    color: #fff !important;
    background-color: #212121 !important;
    border: none !important;
}

.dropdown {
    text-align: left !important;
}

.form-control.select-xs {
    background-color: #191919 !important;
    color: #eee !important;
    border: none;
    outline: none;
}

#modal_indicator {
    display: none;
}

#kernel_indicator {
    color: #fff;
}

#notification_trusted,
#notification_notebook {
    background-color: #212121;
    color: #eee !important;
    border: none;
    border-bottom: 1px solid #eee;
}

#logout {
    background-color: #191919;
    color: #eee;
}

#maintoolbar-container {
    padding-top: 0px !important;
}

.notebook_app {
    background-color: #222222;
}

::-webkit-scrollbar {
    display: none;
}

#notebook-container {
    background-color: #212121;
}

div.cell.selected,
div.cell.selected.jupyter-soft-selected {
    border: none !important;
}

.cm-keyword {
    color: orange !important;
}

.input_area {
    background-color: #212121 !important;
    color: white !important;
    border: 1px solid rgba(255, 255, 255, 0.1) !important;
}

.cm-def {
    color: #5bc0de !important;
}

.cm-variable {
    color: yellow !important;
}

.output_subarea.output_text.output_result pre,
.output_subarea.output_text.output_stream.output_stdout pre {
    color: white !important;
}

.CodeMirror-line {
    color: white !important;
}

.cm-operator {
    color: white !important;
}

.cm-number {
    color: lightblue !important;
}

.inner_cell {
    border: 1px thin #eee;
    border-radius: 50px !important;
}

.CodeMirror-lines {
    border-radius: 20px;
}

.prompt.input_prompt {
    color: #5cb85c !important;
}

.prompt.output_prompt {
    color: lightblue;
}

.cm-string {
    color: #6872ac !important;
}

.cm-builtin {
    color: #f0ad4e !important;
}

.run_this_cell {
    color: lightblue !important;
}

.input_area {
    border-radius: 20px;
}

.output_png {
    background-color: white;
}

.CodeMirror-cursor {
    border-left: 1.4px solid white;
}

.box-flex1.output_subarea.raw_input_container {
    color: white;
}

input.raw_input {
    color: black !important;
}

div.output_area pre {
    color: white
}

h1,
h2,
h3,
h4,
h5,
h6 {
    color: white !important;
    font-weight: bolder !important;
}

.CodeMirror-gutter.CodeMirror-linenumber,
.CodeMirror-gutters {
    background-color: #212121 !important;
}


span.filename:hover {
    color: #191919 !important;
    height: auto !important;
}

#site {
    background-color: #191919 !important;
    color: white !important;
}

#tabs li.active a {
    background-color: #212121 !important;
    color: white !important;
}

#tabs li {
    background-color: #191919 !important;
    color: white !important;
    border-top: 1px thin #eee;
}

#notebook_list_header {
    background-color: #212121 !important;
    color: white !important;
}

#running .panel-group .panel {
    background-color: #212121 !important;
    color: white !important;
}

#accordion.panel-heading {
    background-color: #212121 !important;
}

#running .panel-group .panel .panel-heading {
    background-color: #212121;
    color: white
}

.item_name {
    color: white !important;
    cursor: pointer !important;
}

.list_item:hover {
    background-color: #212121 !important;
}

.item_icon.icon-fixed-width {
    color: white !important;
}

#texteditor-backdrop {
    background-color: #191919 !important;
    border-top: 1px solid #eee;
}

.CodeMirror {
    background-color: #212121 !important;
}

#texteditor-backdrop #texteditor-container .CodeMirror-gutter,
#texteditor-backdrop #texteditor-container .CodeMirror-gutters {
    background-color: #212121 !important;
}

.celltoolbar {
    background-color: #212121 !important;
    border: none !important;
}

Dark Mode for Jupyter Notebook

Dark Mode for Jupyter Notebook

Set Content-Type to application/json in jsp file

@Petr Mensik & kensen john

Thanks, I could not used the page directive because I have to set a different content type according to some URL parameter. I will paste my code here since it's something quite common with JSON:

    <%
        String callback = request.getParameter("callback");
        response.setCharacterEncoding("UTF-8");
        if (callback != null) {
            // Equivalent to: <@page contentType="text/javascript" pageEncoding="UTF-8">
            response.setContentType("text/javascript");
        } else {
            // Equivalent to: <@page contentType="application/json" pageEncoding="UTF-8">
            response.setContentType("application/json");
        }

        [...]

        String output = "";

        if (callback != null) {
            output += callback + "(";
        }

        output += jsonObj.toString();

        if (callback != null) {
            output += ");";
        }
    %>
    <%=output %>

When callback is supplied, returns:

    callback({...JSON stuff...});

with content-type "text/javascript"

When callback is NOT supplied, returns:

    {...JSON stuff...}

with content-type "application/json"

Spring default behavior for lazy-init

The default behaviour is false:

By default, ApplicationContext implementations eagerly create and configure all singleton beans as part of the initialization process. Generally, this pre-instantiation is desirable, because errors in the configuration or surrounding environment are discovered immediately, as opposed to hours or even days later. When this behavior is not desirable, you can prevent pre-instantiation of a singleton bean by marking the bean definition as lazy-initialized. A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at startup.

I suggest reading up

Linux/Unix command to determine if process is running?

While pidof and pgrep are great tools for determining what's running, they are both, unfortunately, unavailable on some operating systems. A definite fail safe would be to use the following: ps cax | grep command

The output on Gentoo Linux:

14484 ?        S      0:00 apache2
14667 ?        S      0:00 apache2
19620 ?        Sl     0:00 apache2
21132 ?        Ss     0:04 apache2

The output on OS X:

42582   ??  Z      0:00.00 (smbclient)
46529   ??  Z      0:00.00 (smbclient)
46539   ??  Z      0:00.00 (smbclient)
46547   ??  Z      0:00.00 (smbclient)
46586   ??  Z      0:00.00 (smbclient)
46594   ??  Z      0:00.00 (smbclient)

On both Linux and OS X, grep returns an exit code so it's easy to check if the process was found or not:

#!/bin/bash
ps cax | grep httpd > /dev/null
if [ $? -eq 0 ]; then
  echo "Process is running."
else
  echo "Process is not running."
fi

Furthermore, if you would like the list of PIDs, you could easily grep for those as well:

ps cax | grep httpd | grep -o '^[ ]*[0-9]*'

Whose output is the same on Linux and OS X:

3519 3521 3523 3524

The output of the following is an empty string, making this approach safe for processes that are not running:

echo ps cax | grep aasdfasdf | grep -o '^[ ]*[0-9]*'

This approach is suitable for writing a simple empty string test, then even iterating through the discovered PIDs.

#!/bin/bash
PROCESS=$1
PIDS=`ps cax | grep $PROCESS | grep -o '^[ ]*[0-9]*'`
if [ -z "$PIDS" ]; then
  echo "Process not running." 1>&2
  exit 1
else
  for PID in $PIDS; do
    echo $PID
  done
fi

You can test it by saving it to a file (named "running") with execute permissions (chmod +x running) and executing it with a parameter: ./running "httpd"

#!/bin/bash
ps cax | grep httpd
if [ $? -eq 0 ]; then
  echo "Process is running."
else
  echo "Process is not running."
fi

WARNING!!!

Please keep in mind that you're simply parsing the output of ps ax which means that, as seen in the Linux output, it is not simply matching on processes, but also the arguments passed to that program. I highly recommend being as specific as possible when using this method (e.g. ./running "mysql" will also match 'mysqld' processes). I highly recommend using which to check against a full path where possible.


References:

http://linux.about.com/od/commands/l/blcmdl1_ps.htm

http://linux.about.com/od/commands/l/blcmdl1_grep.htm

Nexus 5 USB driver

I just wanted to bring a small contribution, because I have been able to debug on my Nexus 5 device on Windows 8, without doing all of this.

When I plugged it, there was no yellow exclamation mark within the device manager. So for me, the drivers was OK. But the device was not listed within my eclipse ddms. After a little bit of searching, It was just an option to change in the device settings. By default, the Nexus 5 usb computer connection is in MTP mode (Media Device).

What you have to do is:

  1. Unplug the device from the computer
  2. Go to Settings -> Storage.
  3. In the ActionBar, click the option menu and choose "USB computer connection".
  4. Check "Camera (PTP)" connection.
  5. Plug the device and you should have a popup on the device allowing you to accept the computer's incoming connection, or something like that.
  6. Finally you should see it now in the ddms and voilà.

I hope this will help!

Capture key press without placing an input element on the page?

Code & detects ctrl+z

document.onkeyup = function(e) {
  if(e.ctrlKey && e.keyCode == 90) {
    // ctrl+z pressed
  }
}

what is the most efficient way of counting occurrences in pandas?

When you want to count the frequency of categorical data in a column in pandas dataFrame use: df['Column_Name'].value_counts()

-Source.

Regex - how to match everything except a particular pattern

Match against the pattern and use the host language to invert the boolean result of the match. This will be much more legible and maintainable.

How do I get the App version and build number using Swift?

My answer (as at Aug 2015), given Swift keeps evolving:

let version = NSBundle.mainBundle().infoDictionary!["CFBundleVersion"] as! String

Proper indentation for Python multiline strings

You can use this function trim_indent.

import re


def trim_indent(s: str):
    s = re.sub(r'^\n+', '', s)
    s = re.sub(r'\n+$', '', s)
    spaces = re.findall(r'^ +', s, flags=re.MULTILINE)
    if len(spaces) > 0 and len(re.findall(r'^[^\s]', s, flags=re.MULTILINE)) == 0:
        s = re.sub(r'^%s' % (min(spaces)), '', s, flags=re.MULTILINE)
    return s


print(trim_indent("""


        line one
            line two
                line three
            line two
        line one


"""))

Result:

"""
line one
    line two
        line three
    line two
line one
"""

Convert datetime to Unix timestamp and convert it back in python

For working with UTC timezones:

time_stamp = calendar.timegm(dt.timetuple())

datetime.utcfromtimestamp(time_stamp)

How to calculate percentage with a SQL statement

You have to calculate the total of grades If it is SQL 2005 you can use CTE

    WITH Tot(Total) (
    SELECT COUNT(*) FROM table
    )
    SELECT Grade, COUNT(*) / Total * 100
--, CONVERT(VARCHAR, COUNT(*) / Total * 100) + '%'  -- With percentage sign
--, CONVERT(VARCHAR, ROUND(COUNT(*) / Total * 100, -2)) + '%'  -- With Round
    FROM table
    GROUP BY Grade

ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

Open a terminal and take a look at:

/Applications/Python 3.6/Install Certificates.command

Python 3.6 on MacOS uses an embedded version of OpenSSL, which does not use the system certificate store. More details here.

(To be explicit: MacOS users can probably resolve by opening Finder and double clicking Install Certificates.command)

Richtextbox wpf binding

Guys why bother with all the faff. This works perfectly. No code required

<RichTextBox>
    <FlowDocument>
        <Paragraph>
            <Run Text="{Binding Mytextbinding}"/>
        </Paragraph>
    </FlowDocument>
</RichTextBox>

counting the number of lines in a text file

Your hack of decrementing the count at the end is exactly that -- a hack.

Far better to write your loop correctly in the first place, so it doesn't count the last line twice.

int main() { 
    int number_of_lines = 0;
    std::string line;
    std::ifstream myfile("textexample.txt");

    while (std::getline(myfile, line))
        ++number_of_lines;
    std::cout << "Number of lines in text file: " << number_of_lines;
    return 0;
}

Personally, I think in this case, C-style code is perfectly acceptable:

int main() {
    unsigned int number_of_lines = 0;
    FILE *infile = fopen("textexample.txt", "r");
    int ch;

    while (EOF != (ch=getc(infile)))
        if ('\n' == ch)
            ++number_of_lines;
    printf("%u\n", number_of_lines);
    return 0;
}

Edit: Of course, C++ will also let you do something a bit similar:

int main() {
    std::ifstream myfile("textexample.txt");

    // new lines will be skipped unless we stop it from happening:    
    myfile.unsetf(std::ios_base::skipws);

    // count the newlines with an algorithm specialized for counting:
    unsigned line_count = std::count(
        std::istream_iterator<char>(myfile),
        std::istream_iterator<char>(), 
        '\n');

    std::cout << "Lines: " << line_count << "\n";
    return 0;
}

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

Firstly create app.js file in the directory you want to publish.

var http = require('http');
var fs = require('fs');
var mime = require('mime');
http.createServer(function(req,res){
    if (req.url != '/app.js') {
    var url = __dirname + req.url;
        fs.stat(url,function(err,stat){
            if (err) {
            res.writeHead(404,{'Content-Type':'text/html'});
            res.end('Your requested URI('+req.url+') wasn\'t found on our server');
            } else {
            var type = mime.getType(url);
            var fileSize = stat.size;
            var range = req.headers.range;
                if (range) {
                    var parts = range.replace(/bytes=/, "").split("-");
                var start = parseInt(parts[0], 10);
                    var end = parts[1] ? parseInt(parts[1], 10) : fileSize-1;
                    var chunksize = (end-start)+1;
                    var file = fs.createReadStream(url, {start, end});
                    var head = {
                'Content-Range': `bytes ${start}-${end}/${fileSize}`,
                'Accept-Ranges': 'bytes',
                'Content-Length': chunksize,
                'Content-Type': type
                }
                    res.writeHead(206, head);
                    file.pipe(res);
                    } else {    
                    var head = {
                'Content-Length': fileSize,
                'Content-Type': type
                    }
                res.writeHead(200, head);
                fs.createReadStream(url).pipe(res);
                    }
            }
        });
    } else {
    res.writeHead(403,{'Content-Type':'text/html'});
    res.end('Sorry, access to that file is Forbidden');
    }
}).listen(8080);

Simply run node app.js and your server shall be running on port 8080. Besides video it can stream all kinds of files.

Something better than .NET Reflector?

In my opinion, there are three serious alternatives to keep an eye on, all of which are free:

  • ILSpy: This is from the same people who make the (also free) SharpDevelop IDE. As well as being free, it is also open source. An additional extension they are working on is the ability to debug decompiled code (something which the pro version of Reflector can do), which works surprisingly well.
  • JustDecompile: A standalone decompiler from Telerik (announced today, currently in Beta).
  • dotPeek: A standalone decompiler from JetBrains (available standalone as part of an EAP at the moment).

All of these approach the problem in slightly different ways with differing UIs. I would suggest giving them all a try and seeing which one you prefer.

How do I schedule a task to run at periodic intervals?

timer.scheduleAtFixedRate( new Task(), 1000,3000); 

Getting the name of a variable as a string

>> my_var = 5
>> my_var_name = [ k for k,v in locals().items() if v == my_var][0]
>> my_var_name 
'my_var'

In case you get an error if myvar points to another variable, try this (suggested by @mherzog)-

 >> my_var = 5
>> my_var_name = [ k for k,v in locals().items() if v is my_var][0]
>> my_var_name 
'my_var'

locals() - Return a dictionary containing the current scope's local variables. by iterating through this dictionary we can check the key which has a value equal to the defined variable, just extracting the key will give us the text of variable in string format.

from (after a bit changes) https://www.tutorialspoint.com/How-to-get-a-variable-name-as-a-string-in-Python

How to activate "Share" button in android app?

Add a Button and on click of the Button add this code:

Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); 
sharingIntent.setType("text/plain");
String shareBody = "Here is the share content body";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));

Useful links:

For basic sharing

For customization

Sending Email in Android using JavaMail API without using the default/built-in app

Without user intervention, you can send as follows:

  1. Send email from client apk. Here mail.jar, activation.jar is required to send java email. If these jars are added, it might increase the APK Size.

  2. Alternatively, You can use a web-service at the server side code, which will use the same mail.jar and activation.jar to send email. You can call the web-service via asynctask and send email. Refer same link.

(But, you will need to know the credentials of the mail account)

Reverse HashMap keys and values in Java

private <A, B> Map<B, A> invertMap(Map<A, B> map) {
    Map<B, A> reverseMap = new HashMap<>();
    for (Map.Entry<A, B> entry : map.entrySet()) {
        reverseMap.put(entry.getValue(), entry.getKey());
    }
    return reverseMap;
}

It's important to remember that put replaces the value when called with the same key. So if you map has two keys with the same value only one of them will exist in the inverted map.

How do you implement a class in C?

GTK is built entirely on C and it uses many OOP concepts. I have read through the source code of GTK and it is pretty impressive, and definitely easier to read. The basic concept is that each "class" is simply a struct, and associated static functions. The static functions all accept the "instance" struct as a parameter, do whatever then need, and return results if necessary. For Example, you may have a function "GetPosition(CircleStruct obj)". The function would simply dig through the struct, extract the position numbers, probably build a new PositionStruct object, stick the x and y in the new PositionStruct, and return it. GTK even implements inheritance this way by embedding structs inside structs. pretty clever.

python dictionary sorting in descending order based on values

You can use dictRysan library. I think that will solve your task.

import dictRysan as ry

d = { '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
      '124': { 'key1': 6, 'key2': 56, 'key3': 6 },
      '125': { 'key1': 7, 'key2': 44, 'key3': 9 },
    }

changed_d=ry.nested_2L_value_sort(d,"key3",True)
print(changed_d)

Passing arguments forward to another javascript function

try this

function global_func(...args){
  for(let i of args){
    console.log(i)
  }
}


global_func('task_name', 'action', [{x: 'x'},{x: 'x'}], {x: 'x'}, ['x1','x2'], 1, null, undefined, false, true)




//task_name
//action
//(2) [{...},
//    {...}]
//    {
//        x:"x"
//    }
//(2) [
//        "x1",
//        "x2"
//    ]
//1
//null
//undefined
//false
//true
//func

Insert if not exists Oracle

INSERT INTO schema.myFoo ( primary_key        , value1          , value2         )
                         SELECT 'bar1' AS primary_key ,'baz1' AS value1 ,'bat1' AS value2 FROM DUAL WHERE (SELECT 1 AS value FROM schema.myFoo WHERE LOWER(primary_key) ='bar1' AND ROWNUM=1) is null;

Android Studio - UNEXPECTED TOP-LEVEL EXCEPTION:

In my case TOP LEVEL EXCEPTION was throw because of a special char in project path. Just closed the project, changed "á" to "a" and reopened the project. Works!

Android dex gives a BufferOverflowException when building

I had the same problem after updating to Revision 19. Just do not forget to update ADT, https://dl-ssl.google.com/android/eclipse/. After this, I was able to build project with the latest revision.

How to solve could not create the virtual machine error of Java Virtual Machine Launcher?

Error:

sony@sony-VPCEH25EN:~$ java --version
Picked up JAVA_TOOL_OPTIONS: -javaagent:/usr/share/java/jayatanaag.jar 
Unrecognized option: --version
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

Solution: Remove extra hyphen '-'

sony@sony-VPCEH25EN:~$ java -version
Picked up JAVA_TOOL_OPTIONS: -javaagent:/usr/share/java/jayatanaag.jar 
java version "1.8.0_101"
Java(TM) SE Runtime Environment (build 1.8.0_101-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.101-b13, mixed mode)

Where is the Query Analyzer in SQL Server Management Studio 2008 R2?

To analyze a query you already have entered into the Query editor, you need to choose "Include Actual Execution Plan" (7th toggle button to the right of the "! Execute" button). After executing the query, you need to click on the "Execution Plan" tab in the results pane at the bottom (above the results of the query).

Check if year is leap year in javascript

function leapYear(year)
{
  return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}

SSL error SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

You mention the certificate is self-signed (by you)? Then you have two choices:

  • add the certificate to your trust store (fetching cacert.pem from cURL website won't do anything, since it's self-signed)
  • don't bother verifying the certificate: you trust yourself, don't you?

Here's a list of SSL context options in PHP: https://secure.php.net/manual/en/context.ssl.php

Set allow_self_signed if you import your certificate into your trust store, or set verify_peer to false to skip verification.

The reason why we trust a specific certificate is because we trust its issuer. Since your certificate is self-signed, no client will trust the certificate as the signer (you) is not trusted. If you created your own CA when signing the certificate, you can add the CA to your trust store. If your certificate doesn't contain any CA, then you can't expect anyone to connect to your server.

How to filter rows containing a string pattern from a Pandas dataframe

If you want to set the column you filter on as a new index, you could also consider to use .filter; if you want to keep it as a separate column then str.contains is the way to go.

Let's say you have

df = pd.DataFrame({'vals': [1, 2, 3, 4, 5], 'ids': [u'aball', u'bball', u'cnut', u'fball', 'ballxyz']})

       ids  vals
0    aball     1
1    bball     2
2     cnut     3
3    fball     4
4  ballxyz     5

and your plan is to filter all rows in which ids contains ball AND set ids as new index, you can do

df.set_index('ids').filter(like='ball', axis=0)

which gives

         vals
ids          
aball       1
bball       2
fball       4
ballxyz     5

But filter also allows you to pass a regex, so you could also filter only those rows where the column entry ends with ball. In this case you use

df.set_index('ids').filter(regex='ball$', axis=0)

       vals
ids        
aball     1
bball     2
fball     4

Note that now the entry with ballxyz is not included as it starts with ball and does not end with it.

If you want to get all entries that start with ball you can simple use

df.set_index('ids').filter(regex='^ball', axis=0)

yielding

         vals
ids          
ballxyz     5

The same works with columns; all you then need to change is the axis=0 part. If you filter based on columns, it would be axis=1.

What's the most elegant way to cap a number to a segment?

The way you do it is pretty standard. You can define a utility clamp function:

/**
 * Returns a number whose value is limited to the given range.
 *
 * Example: limit the output of this computation to between 0 and 255
 * (x * 255).clamp(0, 255)
 *
 * @param {Number} min The lower boundary of the output range
 * @param {Number} max The upper boundary of the output range
 * @returns A number in the range [min, max]
 * @type Number
 */
Number.prototype.clamp = function(min, max) {
  return Math.min(Math.max(this, min), max);
};

(Although extending language built-ins is generally frowned upon)

How I can get and use the header file <graphics.h> in my C++ program?

There is a modern port for this Turbo C graphics interface, it's called WinBGIM, which emulates BGI graphics under MinGW/GCC.

I haven't it tried but it looks promising. For example initgraph creates a window, and from this point you can draw into that window using the good old functions, at the end closegraph deletes the window. It also has some more advanced extensions (eg. mouse handling and double buffering).

When I first moved from DOS programming to Windows I didn't have internet, and I begged for something simple like this. But at the end I had to learn how to create windows and how to handle events and use device contexts from the offline help of the Windows SDK.

Text vertical alignment in WPF TextBlock

  <TextBox AcceptsReturn="True" 
           TextWrapping="Wrap"  
           VerticalContentAlignment="Top" >
  </TextBox>

Hibernate dialect for Oracle Database 11g?

Add org.hibernate.dialect.OracleDialect for Oracle11g database. It will resolve this error.

Java code for getting current time

new Date().getTime() is bugged.

    Date date = new Date();
    System.out.println(date);
    System.out.println(date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds());
    long t1 = date.getTime();
    System.out.println((t1 / 1000 / 60 / 60) % 24 + ":" + (t1 / 1000 / 60) % 60 + ":" + (t1 / 1000) % 60);
    long t2 = System.currentTimeMillis();
    System.out.println((t2 / 1000 / 60 / 60) % 24 + ":" + (t2 / 1000 / 60) % 60 + ":" + (t2 / 1000) % 60);

It returns me the wrong time millis. System.currentTimeMillis() too. Since I ask the Date instance to tell me the corresponding time millis it must return the matching ones not others from a different time zone. Funny how deprecated methods are the only ones which return correct values.

Is there a common Java utility to break a list into batches?

import com.google.common.collect.Lists;

List<List<T>> batches = Lists.partition(List<T>,batchSize)

Use Lists.partition(List,batchSize). You need to import Lists from google common package (com.google.common.collect.Lists)

It will return List of List<T> with and the size of every element equal to your batchSize.

SQL Server 2008 - Case / If statements in SELECT Clause

The most obvious solutions are already listed. Depending on where the query is sat (i.e. in application code) you can't always use IF statements and the inline CASE statements can get painful where lots of columns become conditional. Assuming Col1 + Col3 + Col7 are the same type, and likewise Col2, Col4 + Col8 you can do this:

SELECT Col1, Col2 FROM tbl WHERE @Var LIKE 'xyz'
UNION ALL
SELECT Col3, Col4 FROM tbl WHERE @Var LIKE 'zyx'
UNION ALL
SELECT Col7, Col8 FROM tbl WHERE @Var NOT LIKE 'xyz' AND @Var NOT LIKE 'zyx'

As this is a single command there are several performance benefits with regard to plan caching. Also the Query Optimiser will quickly eliminate those statements where @Var doesn't match the appropriate value without touching the storage engine.

Gradle - Could not target platform: 'Java SE 8' using tool chain: 'JDK 7 (1.7)'

Since I had to compile some source with 7 compatibility, because of some legacy system and ran into the same problem. I found out that in the gradle configuration there where two options set to java 8

sourceCompatibility = 1.8
targetCompatibility = 1.8

switching these to 1.7 solved the problem for me, keeping JAVA_HOME pointing to the installed JDK-7

sourceCompatibility = 1.7
targetCompatibility = 1.7

Create a new TextView programmatically then display it below another TextView

You're not assigning any id to the text view, but you're using tv.getId() to pass it to the addRule method as a parameter. Try to set a unique id via tv.setId(int).

You could also use the LinearLayout with vertical orientation, that might be easier actually. I prefer LinearLayout over RelativeLayouts if not necessary otherwise.

Accessing certain pixel RGB value in openCV

A piece of code is easier for people who have such problem. I share my code and you can use it directly. Please note that OpenCV store pixels as BGR.

cv::Mat vImage_; 

if(src_)
{
    cv::Vec3f vec_;

    for(int i = 0; i < vHeight_; i++)
        for(int j = 0; j < vWidth_; j++)
        {
            vec_ = cv::Vec3f((*src_)[0]/255.0, (*src_)[1]/255.0, (*src_)[2]/255.0);//Please note that OpenCV store pixels as BGR.

            vImage_.at<cv::Vec3f>(vHeight_-1-i, j) = vec_;

            ++src_;
        }
}

if(! vImage_.data ) // Check for invalid input
    printf("failed to read image by OpenCV.");
else
{
    cv::namedWindow( windowName_, CV_WINDOW_AUTOSIZE);
    cv::imshow( windowName_, vImage_); // Show the image.
}

How can I turn a DataTable to a CSV?

Here is my solution, based on previous answers by Paul Grimshaw and Anthony VO. I've submitted the code in a C# project on Github.

My main contribution is to eliminate explicitly creating and manipulating a StringBuilder and instead working only with IEnumerable. This avoids the allocation of a big buffer in memory.

public static class Util
{
    public static string EscapeQuotes(this string self) {
        return self?.Replace("\"", "\"\"") ?? "";
    }

    public static string Surround(this string self, string before, string after) {
        return $"{before}{self}{after}";
    }

    public static string Quoted(this string self, string quotes = "\"") {
        return self.Surround(quotes, quotes);
    }

    public static string QuotedCSVFieldIfNecessary(this string self) {
        return (self == null) ? "" : self.Contains('"') ? self.Quoted() : self; 
    }

    public static string ToCsvField(this string self) {
        return self.EscapeQuotes().QuotedCSVFieldIfNecessary();
    }

    public static string ToCsvRow(this IEnumerable<string> self){
        return string.Join(",", self.Select(ToCsvField));
    }

    public static IEnumerable<string> ToCsvRows(this DataTable self) {          
        yield return self.Columns.OfType<object>().Select(c => c.ToString()).ToCsvRow();
        foreach (var dr in self.Rows.OfType<DataRow>())
            yield return dr.ItemArray.Select(item => item.ToString()).ToCsvRow();
    }

    public static void ToCsvFile(this DataTable self, string path) {
        File.WriteAllLines(path, self.ToCsvRows());
    }
}

This approach combines nicely with converting IEnumerable to DataTable as asked here.

How do you represent a JSON array of strings?

String strJson="{\"Employee\":
[{\"id\":\"101\",\"name\":\"Pushkar\",\"salary\":\"5000\"},
{\"id\":\"102\",\"name\":\"Rahul\",\"salary\":\"4000\"},
{\"id\":\"103\",\"name\":\"tanveer\",\"salary\":\"56678\"}]}";

This is an example of a JSON string with Employee as object, then multiple strings and values in an array as a reference to @cregox...

A bit complicated but can explain a lot in a single JSON string.

How can I install a package with go get?

Command go

Download and install packages and dependencies

Usage:

go get [-d] [-f] [-t] [-u] [-v] [-fix] [-insecure] [build flags] [packages]

Get downloads the packages named by the import paths, along with their dependencies. It then installs the named packages, like 'go install'.

The -d flag instructs get to stop after downloading the packages; that is, it instructs get not to install the packages.

The -f flag, valid only when -u is set, forces get -u not to verify that each package has been checked out from the source control repository implied by its import path. This can be useful if the source is a local fork of the original.

The -fix flag instructs get to run the fix tool on the downloaded packages before resolving dependencies or building the code.

The -insecure flag permits fetching from repositories and resolving custom domains using insecure schemes such as HTTP. Use with caution.

The -t flag instructs get to also download the packages required to build the tests for the specified packages.

The -u flag instructs get to use the network to update the named packages and their dependencies. By default, get uses the network to check out missing packages but does not use it to look for updates to existing packages.

The -v flag enables verbose progress and debug output.

Get also accepts build flags to control the installation. See 'go help build'.

When checking out a new package, get creates the target directory GOPATH/src/. If the GOPATH contains multiple entries, get uses the first one. For more details see: 'go help gopath'.

When checking out or updating a package, get looks for a branch or tag that matches the locally installed version of Go. The most important rule is that if the local installation is running version "go1", get searches for a branch or tag named "go1". If no such version exists it retrieves the default branch of the package.

When go get checks out or updates a Git repository, it also updates any git submodules referenced by the repository.

Get never checks out or updates code stored in vendor directories.

For more about specifying packages, see 'go help packages'.

For more about how 'go get' finds source code to download, see 'go help importpath'.

This text describes the behavior of get when using GOPATH to manage source code and dependencies. If instead the go command is running in module-aware mode, the details of get's flags and effects change, as does 'go help get'. See 'go help modules' and 'go help module-get'.

See also: go build, go install, go clean.


For example, showing verbose output,

$ go get -v github.com/capotej/groupcache-db-experiment/...
github.com/capotej/groupcache-db-experiment (download)
github.com/golang/groupcache (download)
github.com/golang/protobuf (download)
github.com/capotej/groupcache-db-experiment/api
github.com/capotej/groupcache-db-experiment/client
github.com/capotej/groupcache-db-experiment/slowdb
github.com/golang/groupcache/consistenthash
github.com/golang/protobuf/proto
github.com/golang/groupcache/lru
github.com/capotej/groupcache-db-experiment/dbserver
github.com/capotej/groupcache-db-experiment/cli
github.com/golang/groupcache/singleflight
github.com/golang/groupcache/groupcachepb
github.com/golang/groupcache
github.com/capotej/groupcache-db-experiment/frontend
$ 

How should I load files into my Java application?

public static String loadTextFile(File f) {
    try {
        BufferedReader r = new BufferedReader(new FileReader(f));
        StringWriter w = new StringWriter();

        try {
            String line = reader.readLine();
            while (null != line) {
                w.append(line).append("\n");
                line = r.readLine();
            }

            return w.toString();
        } finally {
            r.close();
            w.close();
        }
    } catch (Exception ex) {
        ex.printStackTrace();

        return "";
    }
}

How to select a schema in postgres when using psql?

if you in psql just type

set schema 'temp';

and after that \d shows all relations in "temp

Export tables to an excel spreadsheet in same directory

Lawrence has given you a good answer. But if you want more control over what gets exported to where in Excel see Modules: Sample Excel Automation - cell by cell which is slow and Modules: Transferring Records to Excel with Automation You can do things such as export the recordset starting in row 2 and insert custom text in row 1. As well as any custom formatting required.

How to trim a string in SQL Server before 2017?

SELECT LTRIM(RTRIM(Names)) AS Names FROM Customer

Avoid dropdown menu close on click inside

In Bootstrap 4 you can also do this:

$('#dd-link').on('hide.bs.dropdown', onListHide)

function onListHide(e)
{
  if(e.clickEvent && $.contains(e.relatedTarget.parentNode, e.clickEvent.target)) {
  e.preventDefault()
  }
}

where #dd-link is the anchor element or button that has the data-toggle="drowndown" property.

java: run a function after a specific number of seconds

you could use the Thread.Sleep() function

Thread.sleep(4000);
myfunction();

Your function will execute after 4 seconds. However this might pause the entire program...

Where is my m2 folder on Mac OS X Mavericks

It's in your home folder but it's hidden by default.

Typing the below commands in the terminal made it visible for me (only the .m2 folder that is, not all the other hidden folders).

> mv ~/.m2 ~/m2
> ln -s ~/m2 ~/.m2         

Source

Best way to compare dates in Android

You can use compareTo()

CompareTo method must return negative number if current object is less than other object, positive number if current object is greater than other object and zero if both objects are equal to each other.

// Get Current Date Time
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm aa");
String getCurrentDateTime = sdf.format(c.getTime());
String getMyTime="05/19/2016 09:45 PM ";
Log.d("getCurrentDateTime",getCurrentDateTime); 
// getCurrentDateTime: 05/23/2016 18:49 PM

if (getCurrentDateTime.compareTo(getMyTime) < 0)
{

}
else
{
 Log.d("Return","getMyTime older than getCurrentDateTime "); 
}

Default settings Raspberry Pi /etc/network/interfaces

Assuming that you have a DHCP server running at your router I would use:

# /etc/network/interfaces
auto lo eth0
iface lo inet loopback

iface eth0 inet dhcp

After changing the file issue (as root):

/etc/init.d/networking restart

How to handle Pop-up in Selenium WebDriver using Java

When the toastr message poped up on the screen of firefox. the below tag was displayed in fire bug.

<div class="toast-message">Invalid Credentials, Please check Password</div>.

I took the screenshot at that time. And did the below changes in selenium java code.

String alertText = "";
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("toast-message")));
WebElement toast1 = driver.findElement(By.className("toast-message"));  
alertText = toast1.getText();
System.out.println( alertText);

And my issue of toastr popup got resolved.

How to navigate to a directory in C:\ with Cygwin?

You already accepted an answer, but I just thought I'd mention that the following also works in Cygwin:

cd "C:\Foo"

I think the cd /cygdrive/c method is better, but sometimes it's useful to know that you can do this too.

ViewPager PagerAdapter not updating the View

Something that worked for me was to override the finishUpdate method, which is called at the end of a transition and do the notifyDataSetChanged() there:

public class MyPagerAdapter extends FragmentPagerAdapter {
    ...
    @Override
    public void finishUpdate(ViewGroup container) {
        super.finishUpdate(container);
        this.notifyDataSetChanged();
    }
    ...
}

Exit a while loop in VBS/VBA

While Loop is an obsolete structure, I would recommend you to replace "While loop" to "Do While..loop", and you will able to use Exit clause.

check = 0 

Do while not rs.EOF 
   if rs("reg_code") = rcode then 
      check = 1 
      Response.Write ("Found") 
      Exit do
   else 
      rs.MoveNext 
    end if 
Loop 

if check = 0 then 
   Response.Write "Not Found" 
end if}

Placing Unicode character in CSS content value

Why don't you just save/serve the CSS file as UTF-8?

nav a:hover:after {
    content: "?";
}

If that's not good enough, and you want to keep it all-ASCII:

nav a:hover:after {
    content: "\2193";
}

The general format for a Unicode character inside a string is \000000 to \FFFFFF – a backslash followed by six hexadecimal digits. You can leave out leading 0 digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.


Relevant part of the CSS2 spec:

Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:

  1. with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
  2. by providing exactly 6 hexadecimal digits: "\000026B" ("&B")

In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.

If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).

  • Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
    The identifier "te\st" is exactly the same identifier as "test".

Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).

How to efficiently concatenate strings in go

s := fmt.Sprintf("%s%s", []byte(s1), []byte(s2))

Change status bar text color to light in iOS 9 with Objective-C

  1. Add a key in your info.plist file UIViewControllerBasedStatusBarAppearance and set it to YES.

  2. In viewDidLoad method of your ViewController add a method call:

    [self setNeedsStatusBarAppearanceUpdate];
    
  3. Then paste the following method in viewController file:

    - (UIStatusBarStyle)preferredStatusBarStyle
    { 
        return UIStatusBarStyleLightContent; 
    }
    

Java Delegates?

Have you read this :

Delegates are a useful construct in event-based systems. Essentially Delegates are objects that encode a method dispatch on a specified object. This document shows how java inner classes provide a more generic solution to such problems.

What is a Delegate? Really it is very similar to a pointer to member function as used in C++. But a delegate contains the target object alongwith the method to be invoked. Ideally it would be nice to be able to say:

obj.registerHandler(ano.methodOne);

..and that the method methodOne would be called on ano when some specific event was received.

This is what the Delegate structure achieves.

Java Inner Classes

It has been argued that Java provides this functionality via anonymous inner classes and thus does not need the additional Delegate construct.

obj.registerHandler(new Handler() {
        public void handleIt(Event ev) {
            methodOne(ev);
        }
      } );

At first glance this seems correct but at the same time a nuisance. Because for many event processing examples the simplicity of the Delegates syntax is very attractive.

General Handler

However, if event-based programming is used in a more pervasive manner, say, for example, as a part of a general asynchronous programming environment, there is more at stake.

In such a general situation, it is not sufficient to include only the target method and target object instance. In general there may be other parameters required, that are determined within the context when the event handler is registered.

In this more general situation, the java approach can provide a very elegant solution, particularly when combined with use of final variables:

void processState(final T1 p1, final T2 dispatch) { 
  final int a1 = someCalculation();

  m_obj.registerHandler(new Handler() {
    public void handleIt(Event ev) {
     dispatch.methodOne(a1, ev, p1);
    }
  } );
}

final * final * final

Got your attention?

Note that the final variables are accessible from within the anonymous class method definitions. Be sure to study this code carefully to understand the ramifications. This is potentially a very powerful technique. For example, it can be used to good effect when registering handlers in MiniDOM and in more general situations.

By contrast, the Delegate construct does not provide a solution for this more general requirement, and as such should be rejected as an idiom on which designs can be based.

What's the best three-way merge tool?

Ultracompare. It is really good, handles large files (more than 1 GB) well, is available for Windows/Mac/Linux, and it's commercial, but it is worth it.

Screen shot of UltraCompare Professional on Windows

Does overflow:hidden applied to <body> work on iPhone Safari?

Some solutions listed here had some strange glitches when stretching the elastic scrolling. To fix that I used:

body.lock-position {
  height: 100%;
  overflow: hidden;
  width: 100%;
  position: fixed;
}

Source: http://www.teamtownend.com/2013/07/ios-prevent-scrolling-on-body/

How do you set a default value for a MySQL Datetime column?

Working fine with MySQL 8.x

CREATE TABLE `users` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `dateCreated` datetime DEFAULT CURRENT_TIMESTAMP,
      `dateUpdated` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`),
      UNIQUE KEY `mobile_UNIQUE` (`mobile`)
    ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

What is the best alternative IDE to Visual Studio

I still like Source Insight a lot, but I'm hesitant to recommend it anymore as I'm not sure anybody's still maintaining it. They released a very minor update back in March but haven't had a major release in years. And there seems to be no web community presence. It's a shame because I still like its auto-completion-friendly file open and symbol browsing panels (as well as syntax formatting) better than anything else I've ever used.

Linux Shell Script For Each File in a Directory Grab the filename and execute a program

bash:

for f in *.xls ; do xls2csv "$f" "${f%.xls}.csv" ; done

Remove Item in Dictionary based on Value

In my case I use this

  var key=dict.FirstOrDefault(m => m.Value == s).Key;
            dict.Remove(key);

Can't get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

It looks like you have a certificate in DER format instead of PEM. This is why it works correctly when you provide the -inform PEM command line argument (which tells openssl what input format to expect).

It's likely that your private key is using the same encoding. It looks as if the openssl rsa command also accepts a -inform argument, so try:

openssl rsa -text -in file.key -inform DER

A PEM encoded file is a plain-text encoding that looks something like:

-----BEGIN RSA PRIVATE KEY-----
MIGrAgEAAiEA0tlSKz5Iauj6ud3helAf5GguXeLUeFFTgHrpC3b2O20CAwEAAQIh
ALeEtAIzebCkC+bO+rwNFVORb0bA9xN2n5dyTw/Ba285AhEA9FFDtx4VAxMVB2GU
QfJ/2wIRANzuXKda/nRXIyRw1ArE2FcCECYhGKRXeYgFTl7ch7rTEckCEQDTMShw
8pL7M7DsTM7l3HXRAhAhIMYKQawc+Y7MNE4kQWYe
-----END RSA PRIVATE KEY-----

While DER is a binary encoding format.

Update

Sometimes keys are distributed in PKCS#8 format (which can be either PEM or DER encoded). Try this and see what you get:

openssl pkcs8 -in file.key -inform der

jQuery: Best practice to populate drop down?

$.get(str, function(data){ 
            var sary=data.split('|');
            document.getElementById("select1").options.length = 0;
            document.getElementById("select1").options[0] = new Option('Select a State');
            for(i=0;i<sary.length-1;i++){
                document.getElementById("select1").options[i+1] = new Option(sary[i]);
                document.getElementById("select1").options[i+1].value = sary[i];
            }
            });

How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

(I realise the question relates to C# however, if anyone reading needs to do the same thing with Java then the following may be useful)

It turns out that this can easily be done using the the "CellReference" class in Jakarta POI. Also, the conversion can be done both ways.

// Convert row and column numbers (0-based) to an Excel cell reference
CellReference numbers = new CellReference(3, 28);
System.out.println(numbers.formatAsString());

// Convert an Excel cell reference back into digits
CellReference reference = new CellReference("AC4");
System.out.println(reference.getRow() + ", " + reference.getCol());

How to simulate "Press any key to continue?"

If you're on Windows, you can use kbhit() which is part of the Microsoft run-time library. If you're on Linux, you can implement kbhit thus (source):

#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>

int kbhit(void)
{
  struct termios oldt, newt;
  int ch;
  int oldf;

  tcgetattr(STDIN_FILENO, &oldt);
  newt = oldt;
  newt.c_lflag &= ~(ICANON | ECHO);
  tcsetattr(STDIN_FILENO, TCSANOW, &newt);
  oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
  fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);

  ch = getchar();

  tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
  fcntl(STDIN_FILENO, F_SETFL, oldf);

  if(ch != EOF)
  {
    ungetc(ch, stdin);
    return 1;
  }

  return 0;
}

Update: The above function works on OS X (at least, on OS X 10.5.8 - Leopard, so I would expect it to work on more recent versions of OS X). This gist can be saved as kbhit.c and compiled on both Linux and OS X with

gcc -o kbhit kbhit.c

When run with

./kbhit

It prompts you for a keypress, and exits when you hit a key (not limited to Enter or printable keys).

@Johnsyweb - please elaborate what you mean by "detailed canonical answer" and "all the concerns". Also, re "cross-platform": With this implementation of kbhit() you can have the same functionality in a C++ program on Linux/Unix/OS X/Windows - which other platforms might you be referring to?

Further update for @Johnsyweb: C++ applications do not live in a hermetically sealed C++ environment. A big reason for C++'s success is interoperability with C. All mainstream platforms are implemented with C interfaces (even if internal implementation is using C++) so your talk of "legacy" seems out of place. Plus, as we are talking about a single function, why do you need C++ for this ("C with classes")? As I pointed out, you can write in C++ and access this functionality easily, and your application's users are unlikely to care how you implemented it.

What are the undocumented features and limitations of the Windows FINDSTR command?

The findstr command sets the ErrorLevel (or exit code) to one of the following values, given that there are no invalid or incompatible switches and no search string exceeds the applicable length limit:

  • 0 when at least a single match is encountered in one line throughout all specified files;
  • 1 otherwise;

A line is considered to contain a match when:

  • no /V option is given and the search expression occurs at least once;
  • the /V option is given and the search expression does not occur;

This means that the /V option also changes the returned ErrorLevel, but it does not just revert it!

For example, when you have got a file test.txt with two lines, one of which contains the string text but the other one does not, both findstr "text" "test.txt" and findstr /V "text" "test.txt" return an ErrorLevel of 0.

Basically you can say: if findstr returns at least a line, ErrorLevel is set to 0, else to 1.

Note that the /M option does not affect the ErrorLevel value, it just alters the output.

(Just for the sake of completeness: the find command behaves exactly the same way with respect to the /V option and ErrorLevel; the /C option does not affect ErrorLevel.)

PHP Unset Array value effect on other indexes

This might be a little bit out of context but in unsetting values from a global array, apply the answer by Michael Berkowski above but in use with $GLOBALS instead of the the global value you declared with global $variable_name. So it will be something like:

unset($GLOBALS['variable_name']['array_key']);

Instead of:

global $variable_name; unset($variable_name['array_key']);

NB: This works only if you're using global variables.

Export data from Chrome developer tool

Note that ≪Copy all as HAR≫ does not contain response body.

You can get response body via ≪Save as HAR with Content≫, but it breaks if you have any more than a trivial amount of logs (I tried once with only 8k requests and it doesn't work.) To solve this, you can script an output yourself using _request.contentData().

When there's too many logs, even _request.contentData() and ≪Copy response≫ would fail, hopefully they would fix this problem. Until then, inspecting any more than a trivial amount of network logs cannot be properly done with Chrome Network Inspector and its best to use another tool.

Angular: Can't find Promise, Map, Set and Iterator

I had a same problem when creating a promise object inside my class. By changing target name to "es5" from "es6" solved my issue.

MySQL ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)

For me, this problem was caused by a new feature of MySQL 5.7.2: user entries are ignored if their plugin field is empty.

Set it to e.g. mysql_native_password to reenable them:

UPDATE user SET plugin='mysql_native_password' WHERE user='foo';
FLUSH PRIVILEGES;

See the release notes for MySQL 5.7.2, under «Authentication Notes».

For some reason (maybe because my pre-4.1 password hashes were removed), the mysql_upgrade script didn't set a default plugin value.

I found out by noticing the following warning message in /var/log/mysql/error.log:

[Warning] User entry 'foo'@'%' has an empty plugin value. The user will be ignored and no one can login with this user anymore.

I post this answer here to maybe save someone from using the same ridiculous amount of time on this as I did.

What is the maximum length of a String in PHP?

To properly answer this qustion you need to consider PHP internals or the target that PHP is built for.

To answer this from a typical Linux perspective on x86...

Sizes of types in C: https://usrmisc.wordpress.com/2012/12/27/integer-sizes-in-c-on-32-bit-and-64-bit-linux/

Types used in PHP for variables: http://php.net/manual/en/internals2.variables.intro.php

Strings are always 2GB as the length is always 32bits and a bit is wasted because it uses int rather than uint. int is impractical for lengths over 2GB as it requires a cast to avoid breaking arithmetic or "than" comparisons. The extra bit is likely being used for overflow checks.

Strangely, hash keys might internally support 4GB as uint is used although I have never put this to the test. PHP hash keys have a +1 to the length for a trailing null byte which to my knowledge gets ignored so it may need to be unsigned for that edge case rather than to allow longer keys.

A 32bit system may impose more external limits.

Delete all local git branches

I wrote a shell script in order to remove all local branches except develop

branches=$(git branch | tr -d " *")
output=""
for branch in $branches 
do
  if [[ $branch != "develop" ]]; then
    output="$output $branch"
  fi
done
git branch -d $output

How to sort strings in JavaScript

Use String.prototype.localeCompare a per your example:

list.sort(function (a, b) {
    return ('' + a.attr).localeCompare(b.attr);
})

We force a.attr to be a string to avoid exceptions. localeCompare has been supported since Internet Explorer 6 and Firefox 1. You may also see the following code used that doesn't respect a locale:

if (item1.attr < item2.attr)
  return -1;
if ( item1.attr > item2.attr)
  return 1;
return 0;

When should you use 'friend' in C++?

To do TDD many times I've used 'friend' keyword in C++.

Can a friend know everything about me?


Updated: I found this valuable answer about "friend" keyword from Bjarne Stroustrup site.

"Friend" is an explicit mechanism for granting access, just like membership.

Messagebox with input field

You can reference Microsoft.VisualBasic.dll.

Then using the code below.

Microsoft.VisualBasic.Interaction.InputBox("Question?","Title","Default Text");

Alternatively, by adding a using directive allowing for a shorter syntax in your code (which I'd personally prefer).

using Microsoft.VisualBasic;
...
Interaction.InputBox("Question?","Title","Default Text");

Or you can do what Pranay Rana suggests, that's what I would've done too...

Add onClick event to document.createElement("th")

var newTH = document.createElement('th');
newTH.onclick = function() {
      //Your code here
}

C# List<string> to string with delimiter

You can use String.Join. If you have a List<string> then you can call ToArray first:

List<string> names = new List<string>() { "John", "Anna", "Monica" };
var result = String.Join(", ", names.ToArray());

In .NET 4 you don't need the ToArray anymore, since there is an overload of String.Join that takes an IEnumerable<string>.

Results:


John, Anna, Monica

Property getters and setters

You are recursively defining x with x. As if someone asks you how old are you? And you answer "I am twice my age". Which is meaningless.

You must say I am twice John's age or any other variable but yourself.

computed variables are always dependent on another variable.


The rule of the thumb is never access the property itself from within the getter ie get. Because that would trigger another get which would trigger another . . . Don't even print it. Because printing also requires to 'get' the value before it can print it!

struct Person{
    var name: String{
        get{
            print(name) // DON'T do this!!!!
            return "as"
        }
        set{
        }
    }
}

let p1 = Person()

As that would give the following warning:

Attempting to access 'name' from within it's own getter.

The error looks vague like this:

enter image description here

As an alternative you might want to use didSet. With didSet you'll get a hold to the value that is was set before and just got set to. For more see this answer.

What does the 'L' in front a string mean in C++?

L is a prefix used for wide strings. Each character uses several bytes (depending on the size of wchar_t). The encoding used is independent from this prefix. I mean it must not be necessarily UTF-16 unlike stated in other answers here.

How to get a complete list of object's methods and attributes?

For the complete list of attributes, the short answer is: no. The problem is that the attributes are actually defined as the arguments accepted by the getattr built-in function. As the user can reimplement __getattr__, suddenly allowing any kind of attribute, there is no possible generic way to generate that list. The dir function returns the keys in the __dict__ attribute, i.e. all the attributes accessible if the __getattr__ method is not reimplemented.

For the second question, it does not really make sense. Actually, methods are callable attributes, nothing more. You could though filter callable attributes, and, using the inspect module determine the class methods, methods or functions.

How to Git stash pop specific stash in 1.8.3?

First check the list:-

git stash list

copy the index you wanted to pop from the stash list

git stash pop stash@{index_number}

eg.:

git stash pop stash@{1}

How can I include css files using node, express, and ejs?

IMHO answering this question with the use of ExpressJS is to give a superficial answer. I am going to answer the best I can with out the use of any frameworks or modules. The reason this question is often answerd with the use of a framework is becuase it takes away the requirment of understanding 'Hypertext-Transfer-Protocall'.

  1. The first thing that should be pointed out is that this is more a problem surrounding "Hypertext-Transfer-Protocol" than it is Javascript. When request are made the url is sent, aswell as the content-type that is expected.
  2. The second thing to understand is where request come from. Iitialy a person will request a HTML document, but depending on what is written inside the document, the document itsself might make requests of the server, such as: Images, stylesheets and more. This question refers to CSS so we will keep our focus there. In a tag that links a CSS file to an HTML file there are 3 properties. rel="stylesheet" type="text/css" and href="http://localhost/..." for this example we are going to focus on type and href. Type sends a request to the server that lets the server know it is requesting 'text/css', and 'href' is telling it where the request is being made too.

so with that pointed out we now know what information is being sent to the server now we can now seperate css request from html request on our serverside using a bit of javascript.

var http = require('http');
var url = require('url');
var fs = require('fs');




    function onRequest(request, response){  
        if(request.headers.accept.split(',')[0] == 'text/css') {
             console.log('TRUE');

             fs.readFile('index.css', (err, data)=>{
                 response.writeHeader(200, {'Content-Type': 'text/css'});
                 response.write(data);
                 response.end();
             });  
        }

        else {
            console.log('FALSE');    

            fs.readFile('index.html', function(err, data){
                response.writeHead(200, {'Content_type': 'text/html'});
                response.write(data);
                response.end();
            });
        };
    };

    http.createServer(onRequest).listen(8888);
    console.log('[SERVER] - Started!');


Here is a quick sample of one way I might seperate request. Now remember this is a quick example that would typically be split accross severfiles, some of which would have functions as dependancys to others, but for the sack of 'all in a nutshell' this is the best I could do. I tested it and it worked. Remember that index.css and index.html can be swapped with any html/css files you want.

Iterating through map in template

As Herman pointed out, you can get the index and element from each iteration.

{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}

Working example:

package main

import (
    "html/template"
    "os"
)

type EntetiesClass struct {
    Name string
    Value int32
}

// In the template, we use rangeStruct to turn our struct values
// into a slice we can iterate over
var htmlTemplate = `{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}`

func main() {
    data := map[string][]EntetiesClass{
        "Yoga": {{"Yoga", 15}, {"Yoga", 51}},
        "Pilates": {{"Pilates", 3}, {"Pilates", 6}, {"Pilates", 9}},
    }

    t := template.New("t")
    t, err := t.Parse(htmlTemplate)
    if err != nil {
        panic(err)
    }

    err = t.Execute(os.Stdout, data)
    if err != nil {
        panic(err)
    }

}

Output:

Pilates
3
6
9

Yoga
15
51

Playground: http://play.golang.org/p/4ISxcFKG7v

Clear icon inside input text

Since none of the solutions flying around really met our requirements, we came up with a simple jQuery plugin called jQuery-ClearSearch -

using it is as easy as:

<input class="clearable" type="text" placeholder="search">

<script type="text/javascript">
    $('.clearable').clearSearch();
</script>

? Example: http://jsfiddle.net/wldaunfr/FERw3/

How to parse JSON in Java

Please do something like this:

JSONParser jsonParser = new JSONParser();
JSONObject obj = (JSONObject) jsonParser.parse(contentString);
String product = (String) jsonObject.get("productId");

JavaScript private methods

You have to put a closure around your actual constructor-function, where you can define your private methods. To change data of the instances through these private methods, you have to give them "this" with them, either as an function argument or by calling this function with .apply(this) :

var Restaurant = (function(){
    var private_buy_food = function(that){
        that.data.soldFood = true;
    }
    var private_take_a_shit = function(){
        this.data.isdirty = true;   
    }
    // New Closure
    function restaurant()
    {
        this.data = {
            isdirty : false,
            soldFood: false,
        };
    }

    restaurant.prototype.buy_food = function()
    {
       private_buy_food(this);
    }
    restaurant.prototype.use_restroom = function()
    {
       private_take_a_shit.call(this);
    }
    return restaurant;
})()

// TEST:

var McDonalds = new Restaurant();
McDonalds.buy_food();
McDonalds.use_restroom();
console.log(McDonalds);
console.log(McDonalds.__proto__);

How to store directory files listing into an array?

I'd use

files=(*)

And then if you need data about the file, such as size, use the stat command on each file.

slf4j: how to log formatted message, object array, exception

As of SLF4J 1.6.0, in the presence of multiple parameters and if the last argument in a logging statement is an exception, then SLF4J will presume that the user wants the last argument to be treated as an exception and not a simple parameter. See also the relevant FAQ entry.

So, writing (in SLF4J version 1.7.x and later)

 logger.error("one two three: {} {} {}", "a", "b", 
              "c", new Exception("something went wrong"));

or writing (in SLF4J version 1.6.x)

 logger.error("one two three: {} {} {}", new Object[] {"a", "b", 
              "c", new Exception("something went wrong")});

will yield

one two three: a b c
java.lang.Exception: something went wrong
    at Example.main(Example.java:13)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at ...

The exact output will depend on the underlying framework (e.g. logback, log4j, etc) as well on how the underlying framework is configured. However, if the last parameter is an exception it will be interpreted as such regardless of the underlying framework.

java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer

Coming back to the original problem - java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer

As rightly said above, in JAX 2.x version, the ServletContainer class has been moved to the package - org.glassfish.jersey.servlet.ServletContainer. The related jar is jersey-container-servlet-core.jar which comes bundled within the jaxrs-ri-2.2.1.zip

JAX RS can be worked out without mvn by manually copying all jars contained within zip file jaxrs-ri-2.2.1.zip (i have used this version, would work with any 2.x version) to WEB-INF/lib folder. Copying libs to right folder makes them available at runtime.

This is required if you are using eclipse to build and deploy your project.

Internal and external fragmentation

First of all the term fragmentation cues there's an entity divided into parts — fragments.

  • Internal fragmentation: Typical paper book is a collection of pages (text divided into pages). When a chapter's end isn't located at the end of page and new chapter starts from new page, there's a gap between those chapters and it's a waste of space — a chunk (page for a book) has unused space inside (internally) — "white space"

  • External fragmentation: Say you have a paper diary and you didn't write your thoughts sequentially page after page, but, rather randomly. You might end up with a situation when you'd want to write 3 pages in row, but you can't since there're no 3 clean pages one-by-one, you might have 15 clean pages in the diary totally, but they're not contiguous

Declaring and initializing arrays in C

There is no such particular way in which you can initialize the array after declaring it once.

There are three options only:

1.) initialize them in different lines :

int array[SIZE];

array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
//...
//...
//...

But thats not what you want i guess.

2.) Initialize them using a for or while loop:

for (i = 0; i < MAX ; i++)  {
    array[i] = i;
}

This is the BEST WAY by the way to achieve your goal.

3.) In case your requirement is to initialize the array in one line itself, you have to define at-least an array with initialization. And then copy it to your destination array, but I think that there is no benefit of doing so, in that case you should define and initialize your array in one line itself.

And can I ask you why specifically you want to do so???

Difference between OpenJDK and Adoptium/AdoptOpenJDK

Update: AdoptOpenJDK has changed its name to Adoptium, as part of its move to the Eclipse Foundation.


OpenJDK ? source code
Adoptium/AdoptOpenJDK ? builds

Difference between OpenJDK and AdoptOpenJDK

The first provides source-code, the other provides builds of that source-code.

Several vendors of Java & OpenJDK

Adoptium of the Eclipse Foundation, formerly known as AdoptOpenJDK, is only one of several vendors distributing implementations of the Java platform. These include:

  • Eclipse Foundation (Adoptium/AdoptOpenJDK)
  • Azul Systems
  • Oracle
  • Red Hat / IBM
  • BellSoft
  • SAP
  • Amazon AWS
  • … and more

See this flowchart of mine to help guide you in picking a vendor for an implementation of the Java platform. Click/tap to zoom.

Flowchart guiding you in choosing a vendor for a Java 11 implementation

Another resource: This comparison matrix by Azul Systems is useful, and seems true and fair to my mind.

Here is a list of considerations and motivations to consider in choosing a vendor and implementation.

Motivations in choosing a vendor for Java

Some vendors offer you a choice of JIT technologies.

Diagram showing history of HotSpot & JRockit merging, and OpenJ9 both available in AdoptOpenJDK

To understand more about this Java ecosystem, read Java Is Still Free

Why can't radio buttons be "readonly"?

For the non-selected radio buttons, flag them as disabled. This prevents them from responding to user input and clearing out the checked radio button. For example:

<input type="radio" name="var" checked="yes" value="Yes"></input>
<input type="radio" name="var" disabled="yes" value="No"></input>

Convert base64 png data to javascript file objects

You can create a Blob from your base64 data, and then read it asDataURL:

var img_b64 = canvas.toDataURL('image/png');
var png = img_b64.split(',')[1];

var the_file = new Blob([window.atob(png)],  {type: 'image/png', encoding: 'utf-8'});

var fr = new FileReader();
fr.onload = function ( oFREvent ) {
    var v = oFREvent.target.result.split(',')[1]; // encoding is messed up here, so we fix it
    v = atob(v);
    var good_b64 = btoa(decodeURIComponent(escape(v)));
    document.getElementById("uploadPreview").src = "data:image/png;base64," + good_b64;
};
fr.readAsDataURL(the_file);

Full example (includes junk code and console log): http://jsfiddle.net/tTYb8/


Alternatively, you can use .readAsText, it works fine, and its more elegant.. but for some reason text does not sound right ;)

fr.onload = function ( oFREvent ) {
    document.getElementById("uploadPreview").src = "data:image/png;base64,"
    + btoa(oFREvent.target.result);
};
fr.readAsText(the_file, "utf-8"); // its important to specify encoding here

Full example: http://jsfiddle.net/tTYb8/3/

Determine which element the mouse pointer is on top of in JavaScript

The target of the mousemove DOM event is the top-most DOM element under the cursor when the mouse moves:

(function(){
    //Don't fire multiple times in a row for the same element
    var prevTarget=null;
    document.addEventListener('mousemove', function(e) {
        //This will be the top-most DOM element under cursor
        var target=e.target;
        if(target!==prevTarget){
            console.log(target);
            prevTarget=target;
        }
    });
})();

This is similar to @Philip Walton's solution, but doesn't require jQuery or a setInterval.

Trigger insert old values- values that was updated

ALTER trigger ETU on Employee FOR UPDATE AS insert into Log (EmployeeId, LogDate, OldName) select EmployeeId, getdate(), name from deleted go

How do I restart a program based on user input?

Try this:

while True:
    # main program
    while True:
        answer = str(input('Run again? (y/n): '))
        if answer in ('y', 'n'):
            break
        print("invalid input.")
    if answer == 'y':
        continue
    else:
        print("Goodbye")
        break

The inner while loop loops until the input is either 'y' or 'n'. If the input is 'y', the while loop starts again (continue keyword skips the remaining code and goes straight to the next iteration). If the input is 'n', the program ends.

Is there a simple way to remove multiple spaces in a string?

sentence = "The   fox jumped   over    the log."
word = sentence.split()
result = ""
for string in word:
   result += string+" "
print(result)

How to make an embedded Youtube video automatically start playing?

Add &autoplay=1 to your syntax, like this

<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/zGPuazETKkI&amp;autoplay=1" frameborder="0" allowfullscreen></iframe>

Best Practices: working with long, multiline strings in PHP?

Sure, you could use HEREDOC, but as far as code readability goes it's not really any better than the first example, wrapping the string across multiple lines.

If you really want your multi-line string to look good and flow well with your code, I'd recommend concatenating strings together as such:

$text = "Hello, {$vars->name},\r\n\r\n"
    . "The second line starts two lines below.\r\n"
    . ".. Third line... etc";

This might be slightly slower than HEREDOC or a multi-line string, but it will flow well with your code's indentation and make it easier to read.

What is bootstrapping?

In terms of it in regards to using the popular Twitter Bootstrap I feel like this type of bootstrapping is the action of integrating a modular component into a Web application without the Web application having to even acknowledge the modular component exists until it needs it or references it.

The developer can seamlessly integrate a default copy of the CSS Twitter Bootstrap theme by simply loading (referencing) it into the Web application. Vuola! Then you may need to override some of these changes, but you can do so in such a way that the resource/component is untouched and completely reusable.

This same concept is how Web Devs implement jQuery APIs and so on, but it's not really expressed by Devs as bootstrapping per se. What it does is it improves flexibility and reusability while allowing the isolation of different components/resources of an app to reside freely either on the same server/s or possibly on a CDN.

NOTE: In computing bootstrapping deals with the MBR and in UNIX it requires a special bootloader or manager which is a small program in ROM that loads the OS into RAM. If you think about it the same concept takes places in the action of the bootstrap loader checking the MBR and loading the OS based on this table which occurs without the OS having any idea that this takes place.

how to read certain columns from Excel using Pandas - Python

You can use column indices (letters) like this:

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

[Corresponding documentation][1]:

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

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

    New in version 0.24.0.

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

Returns a subset of the columns according to behavior above.

New in version 0.24.0.

Failed to load resource: the server responded with a status of 404 (Not Found)

Your files are not under the jsp folder that's why it is not found. You have to go back again 1 folder Try this:

     <script  src="../../Jquery/prettify.js"></script>

How to get the size of the current screen in WPF?

double screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
double screenhight= System.Windows.SystemParameters.PrimaryScreenHeight;

How can I multiply and divide using only bit shifting and adding?

Take two numbers, lets say 9 and 10, write them as binary - 1001 and 1010.

Start with a result, R, of 0.

Take one of the numbers, 1010 in this case, we'll call it A, and shift it right by one bit, if you shift out a one, add the first number, we'll call it B, to R.

Now shift B left by one bit and repeat until all bits have been shifted out of A.

It's easier to see what's going on if you see it written out, this is the example:

      0
   0000      0
  10010      1
 000000      0
1001000      1
 ------
1011010

Convert all first letter to upper case, rest lower for each word

In addition to first answer, remember to change string selectionstart index to the end of the word or you will get reverse order of letters in the string.

s.SelectionStart=s.Length;

How to get a index value from foreach loop in jstl

I face Similar problem now I understand we have some more option : varStatus="loop", Here will be loop will variable which will hold the index of lop.

It can use for use to read for Zeor base index or 1 one base index.

${loop.count}` it will give 1 starting base index.

${loop.index} it will give 0 base index as normal Index of array start from 0.

For Example :

<c:forEach var="currentImage" items="${cityBannerImages}" varStatus="loop">
<picture>
   <source srcset="${currentImage}" media="(min-width: 1000px)"></source>
   <source srcset="${cityMobileImages[loop.count]}" media="(min-width:600px)"></source>
   <img srcset="${cityMobileImages[loop.count]}" alt=""></img>
</picture>
</c:forEach>

For more Info please refer this link

java.lang.Exception: No runnable methods exception in running JUnits

You can also get this if you mix org.junit and org.junit.jupiter annotations inadvertently.

Import data.sql MySQL Docker Container

Mount your sql-dump under/docker-entrypoint-initdb.d/yourdump.sql utilizing a volume mount

mysql:
  image: mysql:latest
  container_name: mysql-container
  ports:
    - 3306:3306
  volumes:
    - ./dump.sql:/docker-entrypoint-initdb.d/dump.sql
  environment:
    MYSQL_ROOT_PASSWORD: secret
    MYSQL_DATABASE: name_db
    MYSQL_USER: user
    MYSQL_PASSWORD: password

This will trigger an import of the sql-dump during the start of the container, see https://hub.docker.com/_/mysql/ under "Initializing a fresh instance"

A more useful statusline in vim?

set statusline=%<%f%m\ \[%{&ff}:%{&fenc}:%Y]\ %{getcwd()}\ \ \[%{strftime('%Y/%b/%d\ %a\ %I:%M\ %p')}\]\ %=\ Line:%l\/%L\ Column:%c%V\ %P

This is mine, give as a suggestion

File Upload ASP.NET MVC 3.0

Often you want to pass a viewmodel also, and not the only one file. In the code below you'll find some other useful features:

  • checking if the file has been attached
  • checking if file size is 0
  • checking if file size is above 4 MB
  • checking if file size is less than 100 bytes
  • checking file extensions

It could be done via the following code:

[HttpPost]
public ActionResult Index(MyViewModel viewModel)
{
    // if file's content length is zero or no files submitted

    if (Request.Files.Count != 1 || Request.Files[0].ContentLength == 0)
    {
        ModelState.AddModelError("uploadError", "File's length is zero, or no files found");
        return View(viewModel);
    }

    // check the file size (max 4 Mb)

    if (Request.Files[0].ContentLength > 1024 * 1024 * 4)
    {
        ModelState.AddModelError("uploadError", "File size can't exceed 4 MB");
        return View(viewModel);
    }

    // check the file size (min 100 bytes)

    if (Request.Files[0].ContentLength < 100)
    {
        ModelState.AddModelError("uploadError", "File size is too small");
        return View(viewModel);
    }

    // check file extension

    string extension = Path.GetExtension(Request.Files[0].FileName).ToLower();

    if (extension != ".pdf" && extension != ".doc" && extension != ".docx" && extension != ".rtf" && extension != ".txt")
    {
        ModelState.AddModelError("uploadError", "Supported file extensions: pdf, doc, docx, rtf, txt");
        return View(viewModel);
    }

    // extract only the filename
    var fileName = Path.GetFileName(Request.Files[0].FileName);

    // store the file inside ~/App_Data/uploads folder
    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);

    try
    {
        if (System.IO.File.Exists(path))
            System.IO.File.Delete(path);

        Request.Files[0].SaveAs(path);
    }
    catch (Exception)
    {
        ModelState.AddModelError("uploadError", "Can't save file to disk");
    }

    if(ModelState.IsValid)
    {
        // put your logic here

        return View("Success");
    }

    return View(viewModel);         
}

Make sure you have

@Html.ValidationMessage("uploadError")

in your view for validation errors.

Also keep in mind that default maximum request length is 4MB (maxRequestLength = 4096), to upload larger files you have to change this parameter in web.config:

<system.web>
    <httpRuntime maxRequestLength="40960" executionTimeout="1100" />

(40960 = 40 MB here).

Execution timeout is the whole number of seconds. You may want to change it to allow huge files uploads.

How do I find a particular value in an array and return its index?

#include <vector>
#include <algorithm>

int main()
{
     int arr[5] = {4, 1, 3, 2, 6};
     int x = -1;
     std::vector<int> testVector(arr, arr + sizeof(arr) / sizeof(int) );

     std::vector<int>::iterator it = std::find(testVector.begin(), testVector.end(), 3);
     if (it != testVector.end())
     {
          x = it - testVector.begin();
     }
     return 0;
}

Or you can just build a vector in a normal way, without creating it from an array of ints and then use the same solution as shown in my example.

How to check if a variable is NULL, then set it with a MySQL stored procedure?

@last_run_time is a 9.4. User-Defined Variables and last_run_time datetime one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.

Try: SELECT last_run_time;

UPDATE

Example:

/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$

CREATE PROCEDURE `sp_test`()
BEGIN
    DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
    DECLARE last_run_time DATETIME DEFAULT NULL;
    DECLARE current_run_time DATETIME DEFAULT NOW();

    -- Define the last run time
    SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);

    -- if there is no last run time found then use yesterday as starting point
    IF(last_run_time IS NULL) THEN
        SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
    END IF;

    SELECT last_run_time;

    -- Insert variables in table2
    INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$

DELIMITER ;

How do I use Notepad++ (or other) with msysgit?

Follow these instructions,

  1. First make sure you have notepad++ installed on your system and that it is the default programme to open .txt files.

  2. Then Install gitpad on your system. Note the last I checked the download link was broken, so download it from here as explained.

Then while committing you should see your favorite text editor popping up.

postgresql: INSERT INTO ... (SELECT * ...)

If you are looking for PERFORMANCE, give where condition inside the db link query. Otherwise it fetch all data from the foreign table and apply the where condition.

INSERT INTO tblA (id,time) 
SELECT id, time FROM  dblink('dbname=dbname port=5432 host=10.10.90.190 user=postgresuser password=pass123', 
'select id, time from tblB  where time>'''||1000||'''')
AS t1(id integer, time integer)  

Allowing the "Enter" key to press the submit button, as opposed to only using MouseClick

In the ActionListener Class you can simply add

public void actionPerformed(ActionEvent event) {
    if (event.getSource()==textField){
        textButton.doClick();
    }
    else if (event.getSource()==textButton) {
        //do something
    }
}

How do I check if file exists in Makefile so I can delete it?

I was trying:

[ -f $(PROGRAM) ] && cp -f $(PROGRAM) $(INSTALLDIR)

And the positive case worked but my ubuntu bash shell calls this TRUE and breaks on the copy:

[ -f  ] && cp -f  /home/user/proto/../bin/
cp: missing destination file operand after '/home/user/proto/../bin/'

After getting this error, I google how to check if a file exists in make, and this is the answer...

Unable to import path from django.urls

For someone having the same problem -

import name 'path' from 'django.urls' 
(C:\Python38\lib\site-packages\django\urls\__init__.py)

You can also try installing django-urls by

pipenv install django-urls

Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here

You can use:

@Override
public void onDestroy() {
    super.onDestroy();

    if (mServiceConn != null) {
        unbindService(mServiceConn);
    }
}

Add a new line to the end of a JtextArea

Instead of using JTextArea.setText(String text), use JTextArea.append(String text).

Appends the given text to the end of the document. Does nothing if the model is null or the string is null or empty.

This will add text on to the end of your JTextArea.

Another option would be to use getText() to get the text from the JTextArea, then manipulate the String (add or remove or change the String), then use setText(String text) to set the text of the JTextArea to be the new String.

How to set cookie in node js using express framework?

Set Cookie?

res.cookie('cookieName', 'cookieValue')

Read Cookie?

req.cookies

Demo

const express('express')
    , cookieParser = require('cookie-parser'); // in order to read cookie sent from client

app.get('/', (req,res)=>{

    // read cookies
    console.log(req.cookies) 

    let options = {
        maxAge: 1000 * 60 * 15, // would expire after 15 minutes
        httpOnly: true, // The cookie only accessible by the web server
        signed: true // Indicates if the cookie should be signed
    }

    // Set cookie
    res.cookie('cookieName', 'cookieValue', options) // options is optional
    res.send('')

})

Effective swapping of elements of an array in Java

This is just "hack" style method:

int d[][] = new int[n][n];

static int swap(int a, int b) {
  return a;
}
...

in main class --> 

d[i][j + 1] = swap(d[i][j], d[i][j] = d[i][j + 1])

An unhandled exception occurred during the execution of the current web request. ASP.NET

  1. If you are facing this problem (Enter windows + R) an delete temp(%temp%)and windows temp.
  2. Some file is not deleted that time stop IIS(Internet information service) and delete that all remaining files .

Check your problem is solved.

how to add value to combobox item

Yeah, for most cases, you don't need to create a class with getters and setters. Just create a new Dictionary and bind it to the data source. Here's an example in VB using a for loop to set the DisplayMember and ValueMember of a combo box from a list:

        Dim comboSource As New Dictionary(Of String, String)()
        cboMenu.Items.Clear()
        For I = 0 To SomeList.GetUpperBound(0)
            comboSource.Add(SomeList(I).Prop1, SomeList(I).Prop2)
        Next I
        cboMenu.DataSource = New BindingSource(comboSource, Nothing)
        cboMenu.DisplayMember = "Value"
        cboMenu.ValueMember = "Key"

Then you can set up a data grid view's rows according to the value or whatever you need by calling a method on click:

Private Sub cboMenu_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboMenu.SelectionChangeCommitted
    SetListGrid(cboManufMenu.SelectedValue)
End Sub

How to know if .keyup() is a character key (jQuery)

I wanted to do exactly this, and I thought of a solution involving both the keyup and the keypress events.

(I haven't tested it in all browsers, but I used the information compiled at http://unixpapa.com/js/key.html)

Edit: rewrote it as a jQuery plugin.

(function($) {
    $.fn.normalkeypress = function(onNormal, onSpecial) {
        this.bind('keydown keypress keyup', (function() {
            var keyDown = {}, // keep track of which buttons have been pressed
                lastKeyDown;
            return function(event) {
                if (event.type == 'keydown') {
                    keyDown[lastKeyDown = event.keyCode] = false;
                    return;
                }
                if (event.type == 'keypress') {
                    keyDown[lastKeyDown] = event; // this keydown also triggered a keypress
                    return;
                }

                // 'keyup' event
                var keyPress = keyDown[event.keyCode];
                if ( keyPress &&
                     ( ( ( keyPress.which >= 32 // not a control character
                           //|| keyPress.which == 8  || // \b
                           //|| keyPress.which == 9  || // \t
                           //|| keyPress.which == 10 || // \n
                           //|| keyPress.which == 13    // \r
                           ) &&
                         !( keyPress.which >= 63232 && keyPress.which <= 63247 ) && // not special character in WebKit < 525
                         !( keyPress.which == 63273 )                            && //
                         !( keyPress.which >= 63275 && keyPress.which <= 63277 ) && //
                         !( keyPress.which === event.keyCode && // not End / Home / Insert / Delete (i.e. in Opera < 10.50)
                            ( keyPress.which == 35  || // End
                              keyPress.which == 36  || // Home
                              keyPress.which == 45  || // Insert
                              keyPress.which == 46  || // Delete
                              keyPress.which == 144    // Num Lock
                              )
                            )
                         ) ||
                       keyPress.which === undefined // normal character in IE < 9.0
                       ) &&
                     keyPress.charCode !== 0 // not special character in Konqueror 4.3
                     ) {

                    // Normal character
                    if (onNormal) onNormal.call(this, keyPress, event);
                } else {
                    // Special character
                    if (onSpecial) onSpecial.call(this, event);
                }
                delete keyDown[event.keyCode];
            };
        })());
    };
})(jQuery);

Cloning an Object in Node.js

Looking for a true clone option, I stumbled across ridcully's link to here:

http://my.opera.com/GreyWyvern/blog/show.dml/1725165

I modified the solution on that page so that the function attached to the Object prototype is not enumerable. Here is my result:

Object.defineProperty(Object.prototype, 'clone', {
    enumerable: false,
    value: function() {
        var newObj = (this instanceof Array) ? [] : {};
        for (i in this) {
        if (i == 'clone') continue;
            if (this[i] && typeof this[i] == "object") {
                newObj[i] = this[i].clone();
            } else newObj[i] = this[i]
        } return newObj;
    }
});

Hopefully this helps someone else as well. Note that there are some caveats... particularly with properties named "clone". This works well for me. I don't take any credit for writing it. Again, I only changed how it was being defined.

How to compare data between two table in different databases using Sql Server 2008?

In order to compare two databases, I've written the procedures bellow. If you want to compare two tables you can use procedure 'CompareTables'. Example :

EXEC master.dbo.CompareTables 'DB1', 'dbo', 'table1', 'DB2', 'dbo', 'table2'

If you want to compare two databases, use the procedure 'CompareDatabases'. Example :

EXEC master.dbo.CompareDatabases 'DB1', 'DB2'

Note : - I tried to make the procedures secure, but anyway, those procedures are only for testing and debugging. - If you want a complete solution for comparison use third party like (Visual Studio, ...)

USE [master]
GO

create proc [dbo].[CompareDatabases]
    @FirstDatabaseName nvarchar(50),
    @SecondDatabaseName nvarchar(50)
    as
begin
    -- Check that databases exist
    if not exists(SELECT name FROM sys.databases WHERE name=@FirstDatabaseName)
        return 0
    if not exists(SELECT name FROM sys.databases WHERE name=@SecondDatabaseName)
        return 0

    declare @result table (TABLE_NAME nvarchar(256))
    SET NOCOUNT ON
    insert into @result EXEC('(Select distinct TABLE_NAME from ' + @FirstDatabaseName  + '.INFORMATION_SCHEMA.COLUMNS '
                                    +'Where TABLE_SCHEMA=''dbo'')'
                            + 'intersect'
                            + '(Select distinct TABLE_NAME from ' + @SecondDatabaseName  + '.INFORMATION_SCHEMA.COLUMNS '
                                    +'Where TABLE_SCHEMA=''dbo'')')

    DECLARE @TABLE_NAME nvarchar(256)
    DECLARE curseur CURSOR FOR
        SELECT TABLE_NAME FROM @result
    OPEN curseur
    FETCH curseur INTO @TABLE_NAME
        WHILE @@FETCH_STATUS = 0
            BEGIN
                print 'TABLE : ' + @TABLE_NAME
                EXEC master.dbo.CompareTables @FirstDatabaseName, 'dbo', @TABLE_NAME, @SecondDatabaseName, 'dbo', @TABLE_NAME
                FETCH curseur INTO @TABLE_NAME
            END
        CLOSE curseur
    DEALLOCATE curseur
    SET NOCOUNT OFF
end
GO

.

USE [master]
GO

CREATE PROC [dbo].[CompareTables]
    @FirstTABLE_CATALOG nvarchar(256),
    @FirstTABLE_SCHEMA nvarchar(256),
    @FirstTABLE_NAME nvarchar(256),
    @SecondTABLE_CATALOG nvarchar(256),
    @SecondTABLE_SCHEMA nvarchar(256),
    @SecondTABLE_NAME nvarchar(256)
    AS
BEGIN
    -- Verify if first table exist
    DECLARE @table1 nvarchar(256) = @FirstTABLE_CATALOG + '.' + @FirstTABLE_SCHEMA + '.' + @FirstTABLE_NAME
    DECLARE @return_status int
    EXEC @return_status = master.dbo.TableExist @FirstTABLE_CATALOG, @FirstTABLE_SCHEMA, @FirstTABLE_NAME
    IF @return_status = 0
        BEGIN
            PRINT @table1 + ' : Table Not FOUND'
            RETURN 0
        END



    -- Verify if second table exist
    DECLARE @table2 nvarchar(256) = @SecondTABLE_CATALOG + '.' + @SecondTABLE_SCHEMA + '.' + @SecondTABLE_NAME
    EXEC @return_status = master.dbo.TableExist @SecondTABLE_CATALOG, @SecondTABLE_SCHEMA, @SecondTABLE_NAME
    IF @return_status = 0
        BEGIN
            PRINT @table2 + ' : Table Not FOUND'
            RETURN 0
        END

    -- Compare the two tables
    DECLARE @sql AS NVARCHAR(MAX)
    SELECT @sql = '('
                + '(SELECT ''' + @table1 + ''' as _Table, * FROM ' + @FirstTABLE_CATALOG + '.' + @FirstTABLE_SCHEMA + '.' + @FirstTABLE_NAME + ')'
                + 'EXCEPT'
                + '(SELECT ''' + @table1 + ''' as _Table, * FROM ' + @SecondTABLE_CATALOG + '.' + @SecondTABLE_SCHEMA + '.' + @SecondTABLE_NAME + ')'
                + ')'
                + 'UNION'
                + '('
                + '(SELECT ''' + @table2 + ''' as _Table, * FROM ' + @SecondTABLE_CATALOG + '.' + @SecondTABLE_SCHEMA + '.' + @SecondTABLE_NAME + ')'
                + 'EXCEPT'
                + '(SELECT ''' + @table2 + ''' as _Table, * FROM ' + @FirstTABLE_CATALOG + '.' + @FirstTABLE_SCHEMA + '.' + @FirstTABLE_NAME + ')'
                + ')'
    DECLARE @wrapper AS NVARCHAR(MAX) = 'if exists (' + @sql + ')' + char(10) + '    (' + @sql + ')ORDER BY 2'
    Exec(@wrapper)
END
GO

.

USE [master]
GO

CREATE PROC [dbo].[TableExist]
    @TABLE_CATALOG nvarchar(256),
    @TABLE_SCHEMA nvarchar(256),
    @TABLE_NAME nvarchar(256)
    AS
BEGIN
    IF NOT EXISTS(SELECT name FROM sys.databases WHERE name=@TABLE_CATALOG)
        RETURN 0

    declare @result table (TABLE_SCHEMA nvarchar(256), TABLE_NAME nvarchar(256))
    SET NOCOUNT ON
    insert into @result EXEC('Select TABLE_SCHEMA, TABLE_NAME from ' + @TABLE_CATALOG  + '.INFORMATION_SCHEMA.COLUMNS')
    SET NOCOUNT OFF

    IF EXISTS(SELECT TABLE_SCHEMA, TABLE_NAME FROM @result
                WHERE TABLE_SCHEMA=@TABLE_SCHEMA AND TABLE_NAME=@TABLE_NAME)
        RETURN 1

    RETURN 0
END

GO

What does hash do in python?

The hash is used by dictionaries and sets to quickly look up the object. A good starting point is Wikipedia's article on hash tables.