Programs & Examples On #Cglayer

Angular 2 filter/search list

Search by multiple fields

Assuming Data:

items = [
  {
    id: 1,
    text: 'First item'
  },
  {
    id: 2,
    text: 'Second item'
  },
  {
    id: 3,
    text: 'Third item'
  }
];

Markup:

<input [(ngModel)]="query">
<div *ngFor="let item of items | search:'id,text':query">{{item.text}}</div>

Pipe:

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
  name: 'search'
})
export class SearchPipe implements PipeTransform {
  public transform(value, keys: string, term: string) {

    if (!term) return value;
    return (value || []).filter(item => keys.split(',').some(key => item.hasOwnProperty(key) && new RegExp(term, 'gi').test(item[key])));

  }
}

One line for everything!

git push says "everything up-to-date" even though I have local changes

See VonC's answer above - I needed an extra step:

$ git log -1
- note the SHA-1 of latest commit
$ git checkout master
- reset your branch head to your previously detached commit
$ git reset --hard <commit-id>

I did this, but when I then tried to git push remoterepo master, it said "error: failed to push some refs. To prevent you from losing history, non-fast-forward updates were rejected, Merge the remote changes (e.g. 'git pull') before pushing again."

So I did 'git pull remoterepo master', and it found a conflict. I did git reset --hard <commit-id> again, copied the conflicted files to a backup folder, did git pull remoterepo master again, copied the conflicted files back into my project, did git commit, then git push remoterepo master, and this time it worked.

Git stopped saying 'everything is up to date' - and it stopped complaining about 'fast forwards'.

Batch script to delete files

Lets say you saved your software onto your desktop.
if you want to remove an entire folder like an uninstaller program you could use this.

cd C:\Users\User\Detsktop\
rd /s /q SOFTWARE

this will delete the entire folder called software and all of its files and subfolders

Make Sure You Delete The Correct Folder Cause This Does Not Have A Yes / No Option

Difference between except: and except Exception as e: in Python

except:

accepts all exceptions, whereas

except Exception as e:

only accepts exceptions that you're meant to catch.

Here's an example of one that you're not meant to catch:

>>> try:
...     input()
... except:
...     pass
... 
>>> try:
...     input()
... except Exception as e:
...     pass
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyboardInterrupt

The first one silenced the KeyboardInterrupt!

Here's a quick list:

issubclass(BaseException, BaseException)
#>>> True
issubclass(BaseException, Exception)
#>>> False


issubclass(KeyboardInterrupt, BaseException)
#>>> True
issubclass(KeyboardInterrupt, Exception)
#>>> False


issubclass(SystemExit, BaseException)
#>>> True
issubclass(SystemExit, Exception)
#>>> False

If you want to catch any of those, it's best to do

except BaseException:

to point out that you know what you're doing.


All exceptions stem from BaseException, and those you're meant to catch day-to-day (those that'll be thrown for the programmer) inherit too from Exception.

How to replace NaNs by preceding values in pandas DataFrame?

You could use the fillna method on the DataFrame and specify the method as ffill (forward fill):

>>> df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]])
>>> df.fillna(method='ffill')
   0  1  2
0  1  2  3
1  4  2  3
2  4  2  9

This method...

propagate[s] last valid observation forward to next valid

To go the opposite way, there's also a bfill method.

This method doesn't modify the DataFrame inplace - you'll need to rebind the returned DataFrame to a variable or else specify inplace=True:

df.fillna(method='ffill', inplace=True)

How to set cursor to input box in Javascript?

In JavaScript first focus on the control and then select the control to display the cursor on texbox...

document.getElementById(frmObj.id).focus();
document.getElementById(frmObj.id).select();

or by using jQuery

$("#textboxID").focus();

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

You have added the service provider in config/app.php for the package that is not installed in the system.

You must have this line in your config/app.php. You can either remove it or install the package GeneaLabs\LaravelCaffeine\LaravelCaffeineServiceProvider

See https://github.com/GeneaLabs/laravel-caffeine.

Run the line below via CLI to install the package.

 composer require genealabs/laravel-caffeine

Warning: mysqli_query() expects parameter 1 to be mysqli, resource given

You are mixing mysqli and mysql extensions, which will not work.

You need to use

$myConnection= mysqli_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql"); 

mysqli_select_db($myConnection, "mrmagicadam") or die ("no database");   

mysqli has many improvements over the original mysql extension, so it is recommended that you use mysqli.

submitting a form when a checkbox is checked

Submit form when your checkbox is checked

$(document).ready(function () {   
$("#yoursubmitbuttonid").click(function(){           
                if( $(".yourcheckboxclass").is(":checked") )
                {
                    $("#yourformId").submit();

                }else{
                    alert("Please select !!!");
                    return false;
                }
                return false;
            }); 
});

Go to Matching Brace in Visual Studio?

In Visual Studio Code on german keyboard it's ctrl+shift+^

But you have to open a file with correct extension - it's not working in new unsaved files for example.

Formatting a float to 2 decimal places

string outString= number.ToString("####0.00");

Select Multiple Fields from List in Linq

var result = listObject.Select( i => new{ i.category_name, i.category_id } )

This uses anonymous types so you must the var keyword, since the resulting type of the expression is not known in advance.

How to iterate through property names of Javascript object?

Use for...in loop:

for (var key in obj) {
   console.log(' name=' + key + ' value=' + obj[key]);

   // do some more stuff with obj[key]
}

Check if key exists in JSON object using jQuery

Use JavaScript's hasOwnProperty() function:

if (json_object.hasOwnProperty('name')) {
    //do struff
}

Generate a dummy-variable

Package mlr includes createDummyFeatures for this purpose:

library(mlr)
df <- data.frame(var = sample(c("A", "B", "C"), 10, replace = TRUE))
df

#    var
# 1    B
# 2    A
# 3    C
# 4    B
# 5    C
# 6    A
# 7    C
# 8    A
# 9    B
# 10   C

createDummyFeatures(df, cols = "var")

#    var.A var.B var.C
# 1      0     1     0
# 2      1     0     0
# 3      0     0     1
# 4      0     1     0
# 5      0     0     1
# 6      1     0     0
# 7      0     0     1
# 8      1     0     0
# 9      0     1     0
# 10     0     0     1

createDummyFeatures drops original variable.

https://www.rdocumentation.org/packages/mlr/versions/2.9/topics/createDummyFeatures
.....

Download Excel file via AJAX MVC

using ClosedXML.Excel;

   public ActionResult Downloadexcel()
    {   
        var Emplist = JsonConvert.SerializeObject(dbcontext.Employees.ToList());
        DataTable dt11 = (DataTable)JsonConvert.DeserializeObject(Emplist, (typeof(DataTable)));
        dt11.TableName = "Emptbl";
        FileContentResult robj;
        using (XLWorkbook wb = new XLWorkbook())
        {
            wb.Worksheets.Add(dt11);
            using (MemoryStream stream = new MemoryStream())
            {
                wb.SaveAs(stream);
                var bytesdata = File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "myFileName.xlsx");
                robj = bytesdata;
            }
        }


        return Json(robj, JsonRequestBehavior.AllowGet);
    }

How to check if a file exists in Go?

basicly


package main

import (
    "fmt"
    "os"
)

func fileExists(path string) bool {
    _, err := os.Stat(path)
    return !os.IsNotExist(err)
}

func main() {

    var file string = "foo.txt"
    exist := fileExists(file)
    
    if exist {
        fmt.Println("file exist")
    } else {

        fmt.Println("file not exists")
    }

}

run example

other way

with os.Open

package main

import (
    "fmt"
    "os"
)

func fileExists(path string) bool {
    _, err := os.Open(path) // For read access.
    return err == nil

}

func main() {

    fmt.Println(fileExists("d4d.txt"))

}


run it

PLS-00103: Encountered the symbol "CREATE"

Run package declaration and body separately.

AngularJS - pass function to directive

How about passing the controller function with bidirectional binding? Then you can use it in the directive exactly the same way as in a regular template (I stripped irrelevant parts for simplicity):

<div ng-controller="testCtrl">

   <!-- pass the function with no arguments -->
   <test color1="color1" update-fn="updateFn"></test>
</div>

<script>
   angular.module('dr', [])
   .controller("testCtrl", function($scope) {
      $scope.updateFn = function(msg) {
         alert(msg);
      }
   })
   .directive('test', function() {
      return {
         scope: {
            updateFn: '=' // '=' bidirectional binding
         },
         template: "<button ng-click='updateFn(1337)'>Click</button>"
      }
   });
</script>

I landed at this question, because I tried the method above befire, but somehow it didn't work. Now it works perfectly.

Open mvc view in new window from controller

This cannot be done from within the controller itself, but rather from your View. As I see it, you have two options:

  1. Decorate your link with the "_blank" attribute (examples using HTML helper and straight HMTL syntax)

    • @Html.ActionLink("linkText", "Action", new {controller="Controller"}, new {target="_blank"})
    • <a href="@Url.Action("Action", "Controller")" target="_blank">Link Text</a>
  2. Use Javascript to open a new window

    window.open("Link URL")

Open Source Javascript PDF viewer

There is an open source HTML5/javascript reader available called Trapeze though its still in its early stages.

Demo site: https://brendandahl.github.io/trapeze-reader/demos/

Github page: https://github.com/brendandahl/trapeze-reader

Disclaimer: I'm the author.

How to trim white spaces of array values in php

array_map and trim can do the job

$trimmed_array = array_map('trim', $fruit);
print_r($trimmed_array);

What is ANSI format?

I remember when "ANSI" text referred to the pseudo VT-100 escape codes usable in DOS through the ANSI.SYS driver to alter the flow of streaming text.... Probably not what you are referring to but if it is see http://en.wikipedia.org/wiki/ANSI_escape_code

Leaflet changing Marker color

In R, use the addAwesomeMarkers() function. Sample code producing red marker:

leaflet() %>%
addTiles() %>%
addAwesomeMarkers(lng = -77.03654, lat = 38.8973, icon = awesomeIcons(icon = 'ion-ionic', library = 'ion', markerColor = 'red'))

Link for ion icons: http://ionicons.com/

Convert integer value to matching Java Enum

You will have to make a new static method where you iterate PcapLinkType.values() and compare:

public static PcapLinkType forCode(int code) {
    for (PcapLinkType typ? : PcapLinkType.values()) {
        if (type.getValue() == code) {
            return type;
        }
    }
    return null;
 }

That would be fine if it is called rarely. If it is called frequently, then look at the Map optimization suggested by others.

Viewing all defined variables

globals(), locals(), vars(), and dir() may all help you in what you want.

"Auth Failed" error with EGit and GitHub

I resolved it by selecting http as the protocol and giving my GitHub username and password.

google console error `OR-IEH-01`

i found that my google payment account was not activated. i activated it and the error was solved. link for vitrification: google account verification

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

Instead of:

input:not(disabled)not:[type="submit"]:focus {}

Use:

input:not([disabled]):not([type="submit"]):focus {}

disabled is an attribute so it needs the brackets, and you seem to have mixed up/missing colons and parentheses on the :not() selector.

Demo: http://jsfiddle.net/HSKPx/

One thing to note: I may be wrong, but I don't think disabled inputs can normally receive focus, so that part may be redundant.

Alternatively, use :enabled

input:enabled:not([type="submit"]):focus { /* styles here */ }

Again, I can't think of a case where disabled input can receive focus, so it seems unnecessary.

Which is the best library for XML parsing in java

Nikita's point is an excellent one: don't confuse mature with bad. XML hasn't changed much.

JDOM would be another alternative to DOM4J.

Comparison of C++ unit test frameworks

There are some relevant C++ unit testing resources at http://www.progweap.com/resources.html

Plot Normal distribution with Matplotlib

Assuming you're getting norm from scipy.stats, you probably just need to sort your list:

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

h = [186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
     187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
     161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]
h.sort()
hmean = np.mean(h)
hstd = np.std(h)
pdf = stats.norm.pdf(h, hmean, hstd)
plt.plot(h, pdf) # including h here is crucial

And so I get: enter image description here

Why does jQuery or a DOM method such as getElementById not find the element?

When I tried your code, it worked.

The only reason that your event is not working, may be that your DOM was not ready and your button with id "event-btn" was not yet ready. And your javascript got executed and tried to bind the event with that element.

Before using the DOM element for binding, that element should be ready. There are many options to do that.

Option1: You can move your event binding code within document ready event. Like:

document.addEventListener('DOMContentLoaded', (event) => {
  //your code to bind the event
});

Option2: You can use timeout event, so that binding is delayed for few seconds. like:

setTimeout(function(){
  //your code to bind the event
}, 500);

Option3: move your javascript include to the bottom of your page.

I hope this helps you.

How to call a function, PostgreSQL

The function call still should be a valid SQL statement:

SELECT "saveUser"(3, 'asd','asd','asd','asd','asd');

How to execute mongo commands through shell scripts?

Recently migrated from mongodb to Postgres. This is how I used the scripts.

mongo < scripts.js > inserts.sql

Read the scripts.js and output redirect to inserts.sql.

scripts.js looks like this

use myDb;
var string = "INSERT INTO table(a, b) VALUES";
db.getCollection('collectionName').find({}).forEach(function (object) {
    string += "('" + String(object.description) + "','" + object.name + "'),";
});
print(string.substring(0, string.length - 1), ";");

inserts.sql looks like this

INSERT INTO table(a, b) VALUES('abc', 'Alice'), ('def', 'Bob'), ('ghi', 'Claire');

Python - How to concatenate to a string in a for loop?

That's not how you do it.

>>> ''.join(['first', 'second', 'other'])
'firstsecondother'

is what you want.

If you do it in a for loop, it's going to be inefficient as string "addition"/concatenation doesn't scale well (but of course it's possible):

>>> mylist = ['first', 'second', 'other']
>>> s = ""
>>> for item in mylist:
...    s += item
...
>>> s
'firstsecondother'

How to deep merge instead of shallow merge?

https://lodash.com/docs/4.17.15#defaultsDeep

Note: This method mutates source.

_.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });
// => { 'a': { 'b': 2, 'c': 3 } }

Converting integer to binary in python

.. or if you're not sure it should always be 8 digits, you can pass it as a parameter:

>>> '%0*d' % (8, int(bin(6)[2:]))
'00000110'

Rerouting stdin and stdout from C

This is the most readily available, handy and useful way to do

freopen("dir","r",stdin);

How to Deserialize XML document

Here's a working version. I changed the XmlElementAttribute labels to XmlElement because in the xml the StockNumber, Make and Model values are elements, not attributes. Also I removed the reader.ReadToEnd(); (that function reads the whole stream and returns a string, so the Deserialize() function couldn't use the reader anymore...the position was at the end of the stream). I also took a few liberties with the naming :).

Here are the classes:

[Serializable()]
public class Car
{
    [System.Xml.Serialization.XmlElement("StockNumber")]
    public string StockNumber { get; set; }

    [System.Xml.Serialization.XmlElement("Make")]
    public string Make { get; set; }

    [System.Xml.Serialization.XmlElement("Model")]
    public string Model { get; set; }
}


[Serializable()]
[System.Xml.Serialization.XmlRoot("CarCollection")]
public class CarCollection
{
    [XmlArray("Cars")]
    [XmlArrayItem("Car", typeof(Car))]
    public Car[] Car { get; set; }
}

The Deserialize function:

CarCollection cars = null;
string path = "cars.xml";

XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));

StreamReader reader = new StreamReader(path);
cars = (CarCollection)serializer.Deserialize(reader);
reader.Close();

And the slightly tweaked xml (I needed to add a new element to wrap <Cars>...Net is picky about deserializing arrays):

<?xml version="1.0" encoding="utf-8"?>
<CarCollection>
<Cars>
  <Car>
    <StockNumber>1020</StockNumber>
    <Make>Nissan</Make>
    <Model>Sentra</Model>
  </Car>
  <Car>
    <StockNumber>1010</StockNumber>
    <Make>Toyota</Make>
    <Model>Corolla</Model>
  </Car>
  <Car>
    <StockNumber>1111</StockNumber>
    <Make>Honda</Make>
    <Model>Accord</Model>
  </Car>
</Cars>
</CarCollection>

The I/O operation has been aborted because of either a thread exit or an application request

995 is an error reported by the IO Completion Port. The error comes since you try to continue read from the socket when it has most likely been closed.

Receiving 0 bytes from EndRecieve means that the socket has been closed, as does most exceptions that EndRecieve will throw.

You need to start dealing with those situations.

Never ever ignore exceptions, they are thrown for a reason.

Update

There is nothing that says that the server does anything wrong. A connection can be lost for a lot of reasons such as idle connection being closed by a switch/router/firewall, shaky network, bad cables etc.

What I'm saying is that you MUST handle disconnections. The proper way of doing so is to dispose the socket and try to connect a new one at certain intervals.

As for the receive callback a more proper way of handling it is something like this (semi pseudo code):

public void OnDataReceived(IAsyncResult asyn)
{
    BLCommonFunctions.WriteLogger(0, "In :- OnDataReceived", ref swReceivedLogWriter, strLogPath, 0);

    try
    {
        SocketPacket client = (SocketPacket)asyn.AsyncState;

        int bytesReceived = client.thisSocket.EndReceive(asyn); //Here error is coming
        if (bytesReceived == 0)
        {
          HandleDisconnect(client);
          return;
        }
    }
    catch (Exception err)
    {
       HandleDisconnect(client);
    }

    try
    {
        string strHEX = BLCommonFunctions.ByteArrToHex(theSockId.dataBuffer);                    

        //do your handling here
    }
    catch (Exception err)
    {
        // Your logic threw an exception. handle it accordinhly
    }

    try
    {
       client.thisSocket.BeginRecieve(.. all parameters ..);
    }
    catch (Exception err)
    {
       HandleDisconnect(client);
    }
}

the reason to why I'm using three catch blocks is simply because the logic for the middle one is different from the other two. Exceptions from BeginReceive/EndReceive usually indicates socket disconnection while exceptions from your logic should not stop the socket receiving.

Git diff against a stash

One way to do this without moving anything is to take advantage of the fact that patch can read git diff's (unified diffs basically)

git stash show -p | patch -p1 --verbose --dry-run

This will show you a step-by-step preview of what patch would ordinarily do. The added benefit to this is that patch won't prevent itself from writing the patch to the working tree either, if for some reason you just really need git to shut up about commiting-before-modifying, go ahead and remove --dry-run and follow the verbose instructions.

Get access to parent control from user control - C#

If you want to get any parent by any child control you can use this code, and when you find the UserControl/Form/Panel or others you can call funnctions or set/get values:

Control myControl= this;
while (myControl.Parent != null)
{

    if (myControl.Parent!=null)
    {
        myControl = myControl.Parent;
        if  (myControl.Name== "MyCustomUserControl")
        {
            ((MyCustomUserControl)myControl).lblTitle.Text = "FOUND IT";
        }
    }

}

Matching strings with wildcard

*X*YZ* = string contains X and contains YZ

@".*X.*YZ"

X*YZ*P = string starts with X, contains YZ and ends with P.

@"^X.*YZ.*P$"

Why does javascript replace only first instance when using replace?

You can use:

String.prototype.replaceAll = function(search, replace) {
if (replace === undefined) {
    return this.toString();
}
return this.split(search).join(replace);
}

Can an Android NFC phone act as an NFC tag?

You can definitely make an Android phone write to a tag reader using the NDEFPush functionality in the peer-to-peer support - but you will need to write the code on the tag reader side to use peer-to-peer as well (llcp).

What does %>% mean in R

Use ?'%*%' to get the documentation.

%*% is matrix multiplication. For matrix multiplication, you need an m x n matrix times an n x p matrix.

Repository access denied. access via a deployment key is read-only

Deployment keys are read only. To enable write access you need to:

  • Remove this deployment key from your repository settings. You won't be able to write to this repo with this key anyway.

  • Go to "Avatar -> Settings -> SSH Keys" and add the same key

  • Now try to push to remove branch

You were able to write to repositories before but this is a change in BitBucket where you're no longer able to write with deploy key.

angularjs to output plain text instead of html

You want to use the built-in browser HTML strip for that instead of applying yourself a regexp. It is more secure since the ever green browser does the work for you.

angular.module('myApp.filters', []).
  filter('htmlToPlaintext', function() {
    return function(text) {
      return stripHtml(text);
    };
  }
);

var stripHtml = (function () {
  var tmpEl = $document[0].createElement("DIV");
  function strip(html) {
    if (!html) {
      return "";
    }
    tmpEl.innerHTML = html;
    return tmpEl.textContent || tmpEl.innerText || "";
  }
  return strip;
}());

The reason for wrapping it in an self-executing function is for reusing the element creation.

Module AppRegistry is not registered callable module (calling runApplication)

Deleting node_modules and reinstalling it fixed the error(or at least gave me more specific ones)

PHP save image file

No need to create a GD resource, as someone else suggested.

$input = 'http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com';
$output = 'google.com.jpg';
file_put_contents($output, file_get_contents($input));

Note: this solution only works if you're setup to allow fopen access to URLs. If the solution above doesn't work, you'll have to use cURL.

PG::ConnectionBad - could not connect to server: Connection refused

This is what really helped me.

$ cd /usr/local/var/postgres/
$ rm postmaster.pid

Reference: http://alumni.lewagon.org/questions/60

How to extract week number in sql

Use 'dd-mon-yyyy' if you are using the 2nd date format specified in your answer. Ex:

to_date(<column name>,'dd-mon-yyyy')

moment.js get current time in milliseconds?

From the docs: http://momentjs.com/docs/#/parsing/unix-timestamp-milliseconds/

So use either of these:


moment(...).valueOf()

to parse a preexisting date and convert the representation to a unix timestamp


moment().valueOf()

for the current unix timestamp

How to make HTML code inactive with comments

Use:

<!-- This is a comment for an HTML page and it will not display in the browser -->

For more information, I think 3 On SGML and HTML may help you.

how to find seconds since 1970 in java

Another option is to use the TimeUtils utility method:

TimeUtils.millisToUnit(System.currentTimeMillis(), TimeUnit.SECONDS)

How to check if a number is between two values?

Here is the shortest method possible:

if (Math.abs(v-550)<50) console.log('short')
if ((v-500)*(v-600)<0) console.log('short')

Parametrized:

if (Math.abs(v-max+v-min)<max+min) console.log('short')
if ((v-min)*(v-max)<0) console.log('short')

You can divide both sides by 2 if you don't understand how the first one works;)

How to avoid variable substitution in Oracle SQL Developer with 'trinidad & tobago'

Call this before the query:

set define off;

Alternatively, hacky:

update t set country = 'Trinidad and Tobago' where country = 'trinidad &' || ' tobago';

From Tuning SQL*Plus:

SET DEFINE OFF disables the parsing of commands to replace substitution variables with their values.

How to drop columns using Rails migration

in rails 5 you can use this command in the terminal:

rails generate migration remove_COLUMNNAME_from_TABLENAME COLUMNNAME:DATATYPE

for example to remove the column access_level(string) from table users:

rails generate migration remove_access_level_from_users access_level:string

and then run:

rake db:migrate

Convert string to date in Swift

just Step 1 > get the String value from JSON or dataSource

Step 2 > create a local variable and assign it.

let startDate = CurrentDashBoard.startdate

Step 3> create an instance of DateFormatter.

let dateFormatter = DateFormatter()

step 4> call the dateFormat from dateFormatter and provide saved date dataType.

dateFormatter.dateFormat = "MM-dd-yyyy HH:mm:ss"("may be String formate")

step 5> Assign the Local variable to this variable to convert.

let dateFromStringstartDate : NSDate = dateFormatter.date(from: startDate)! as NSDate

Step 6> provide your required date Formate by the following code.

dateFormatter.dateFormat = "MM/dd/yyyy HH:mm:ss"

Step 6> Assign it to label/text

cell.lblStartDate.text = String(format: "%@", strstartDate)

Code:

let startDate = CurrentDashBoard.startdate let dateFormatter = DateFormatter() 
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm:ss" let dateFromStringstartDate : 
NSDate = dateFormatter.date(from: startDate)! as NSDate
dateFormatter.dateFormat = "MM/dd/yyyy HH:mm:ss"
let strstartDate = dateFormatter.string(from: dateFromStringstartDate as Date)

"Please try running this command again as Root/Administrator" error when trying to install LESS

I kept having this problem because windows was setting my node_modules folder to Readonly. Make sure you uncheck this.

enter image description here

Histogram with Logarithmic Scale and custom breaks

I've put together a function that behaves identically to hist in the default case, but accepts the log argument. It uses several tricks from other posters, but adds a few of its own. hist(x) and myhist(x) look identical.

The original problem would be solved with:

myhist(mydata$V3, breaks=c(0,1,2,3,4,5,25), log="xy")

The function:

myhist <- function(x, ..., breaks="Sturges",
                   main = paste("Histogram of", xname),
                   xlab = xname,
                   ylab = "Frequency") {
  xname = paste(deparse(substitute(x), 500), collapse="\n")
  h = hist(x, breaks=breaks, plot=FALSE)
  plot(h$breaks, c(NA,h$counts), type='S', main=main,
       xlab=xlab, ylab=ylab, axes=FALSE, ...)
  axis(1)
  axis(2)
  lines(h$breaks, c(h$counts,NA), type='s')
  lines(h$breaks, c(NA,h$counts), type='h')
  lines(h$breaks, c(h$counts,NA), type='h')
  lines(h$breaks, rep(0,length(h$breaks)), type='S')
  invisible(h)
}

Exercise for the reader: Unfortunately, not everything that works with hist works with myhist as it stands. That should be fixable with a bit more effort, though.

git rm - fatal: pathspec did not match any files

To remove the tracked and old committed file from git you can use the below command. Here in my case, I want to untrack and remove all the file from dist directory.

git filter-branch --force --index-filter 'git rm -r --cached --ignore-unmatch dist' --tag-name-filter cat -- --all

Then, you need to add it into your .gitignore so it won't be tracked further.

How to check if a file exists in a folder?

To check file exists or not you can use

System.IO.File.Exists(path)

What special characters must be escaped in regular expressions?

Maybe an old thread, but this code might be useful to visitors who want to create without regex

def listToString(s):  
    
    # initialize an empty string 
    str1 = "" 
    
    # return string   
    return (str1.join(s))


r = "Hello! How are you? *Smiling_Face* *Heart* erwer"
r1 = list(r)
i = 0
r2 = list()
start = True

for string in r1:
    if string == "*":
        if(start):
            start = False
        else:
            start = True
    else:
        if(start):
            r2.append(string)
        else:
            print("skipped" + string)
            
 
print(listToString(r2))

Getting Gradle dependencies in IntelliJ IDEA using Gradle build

After adding dependencies open "Gradle" ('View'->Tool Windows->Gradle) tab and hit "refresh"

example of adding (compile 'io.reactivex:rxjava:1.1.0'):

hit refresh

If Idea still can not resolve dependency, hence it is possibly the dependency is not in mavenCentral() repository and you need add repository where this dependency located into repositories{}

How to use MapView in android using google map V2?

I created dummy sample for Google Maps v2 Android with Kotlin and AndroidX

You can find complete project here: github-link

MainActivity.kt

class MainActivity : AppCompatActivity() {

val position = LatLng(-33.920455, 18.466941)

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    with(mapView) {
        // Initialise the MapView
        onCreate(null)
        // Set the map ready callback to receive the GoogleMap object
        getMapAsync{
            MapsInitializer.initialize(applicationContext)
            setMapLocation(it)
        }
    }
}

private fun setMapLocation(map : GoogleMap) {
    with(map) {
        moveCamera(CameraUpdateFactory.newLatLngZoom(position, 13f))
        addMarker(MarkerOptions().position(position))
        mapType = GoogleMap.MAP_TYPE_NORMAL
        setOnMapClickListener {
            Toast.makeText(this@MainActivity, "Clicked on map", Toast.LENGTH_SHORT).show()
        }
    }
}

override fun onResume() {
    super.onResume()
    mapView.onResume()
}

override fun onPause() {
    super.onPause()
    mapView.onPause()
}

override fun onDestroy() {
    super.onDestroy()
    mapView.onDestroy()
}

override fun onLowMemory() {
    super.onLowMemory()
    mapView.onLowMemory()
 }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools" package="com.murgupluoglu.googlemap">

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="GoogleAppIndexingWarning">
    <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="API_KEY_HERE" />
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
</application>

</manifest>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

<com.google.android.gms.maps.MapView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/mapView"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

How to handle windows file upload using Selenium WebDriver?

Find the element (must be an input element with type="file" attribute) and send the path to the file.

WebElement fileInput = driver.findElement(By.id("uploadFile"));
fileInput.sendKeys("/path/to/file.jpg");

NOTE: If you're using a RemoteWebDriver, you will also have to set a file detector. The default is UselessFileDetector

WebElement fileInput = driver.findElement(By.id("uploadFile"));
driver.setFileDetector(new LocalFileDetector());
fileInput.sendKeys("/path/to/file.jpg");

How do a LDAP search/authenticate against this LDAP in Java

You can also use the following code :

package com.agileinfotech.bsviewer.ldap;

import java.util.Hashtable;
import java.util.ResourceBundle;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

public class LDAPLoginAuthentication {
    public LDAPLoginAuthentication() {
        // TODO Auto-generated constructor
    }

    ResourceBundle resBundle = ResourceBundle.getBundle("settings");

    @SuppressWarnings("unchecked")
    public String authenticateUser(String username, String password) {
        String strUrl = "success";
        Hashtable env = new Hashtable(11);
        boolean b = false;
        String Securityprinciple = "cn=" + username + "," + resBundle.getString("UserSearch");
        env.put(Context.INITIAL_CONTEXT_FACTORY, resBundle.getString("InitialContextFactory"));
        env.put(Context.PROVIDER_URL, resBundle.getString("Provider_url"));
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, Securityprinciple);
        env.put(Context.SECURITY_CREDENTIALS, password);

        try {
            // Create initial context
            DirContext ctx = new InitialDirContext(env);
            // Close the context when we're done
            b = true;
            ctx.close();

        } catch (NamingException e) {
            b = false;
        } finally {
            if (b) {
                strUrl = "success";
            } else {
                strUrl = "failer";
            }
        }
        return strUrl;
    }
}

How to set environment variables from within package.json?

This will work in Windows console:

"scripts": {
  "setAndStart": "set TMP=test&& node index.js",
  "otherScriptCmd": "echo %TMP%"
}

npm run aaa

output: test

See this answer for details.

TypeScript: Creating an empty typed container array

The issue of correctly pre-allocating a typed array in TypeScript was somewhat obscured for due to the array literal syntax, so it wasn't as intuitive as I first thought.

The correct way would be

var arr : Criminal[] = [];

This will give you a correctly typed, empty array stored in the variable 'arr'

Hope this helps others!

C# : 'is' keyword and checking for Not

While the IS operator is normally the best way, there is an alternative that you can use in some cirumstances. You can use the as operator and test for null.

MyClass mc = foo as MyClass;
if ( mc == null ) { }
else {}

Java: get all variable names in a class

You can use any of the two based on your need:

Field[] fields = ClassName.class.getFields(); // returns inherited members but not private members.
Field[] fields = ClassName.class.getDeclaredFields(); // returns all members including private members but not inherited members.

To filter only the public fields from the above list (based on requirement) use below code:

List<Field> fieldList = Arrays.asList(fields).stream().filter(field -> Modifier.isPublic(field.getModifiers())).collect(
    Collectors.toList());

About catching ANY exception

You can do this to handle general exceptions

try:
    a = 2/0
except Exception as e:
    print e.__doc__
    print e.message

The page cannot be displayed because an internal server error has occurred on server

I think the best first approach is to make sure to turn on detailed error messages via your web.config file, like this:

<configuration>
    <system.webServer>
        <httpErrors errorMode="Detailed"></httpErrors>
    </system.webServer>
</configuration>

After doing this, you should get a more detailed error message from the server.

In my particular case, the more detailed error pointed out that my <defaultDocument> section of the web.config file was not allowed at the folder level where I'd placed my web.config. It said

This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false". "

How to align a div to the top of its parent but keeping its inline-block behaviour?

Try the vertical-align CSS property.

#box1 {
    width: 50px;
    height: 50px;
    background: #999;
    display: inline-block;
    vertical-align: top; /* here */
}

Apply it to #box3 too.

How can I download a specific Maven artifact in one command line?

To copy artifact in specified location use copy instead of get.

mvn org.apache.maven.plugins:maven-dependency-plugin:3.1.2:copy \
  -DrepoUrl=someRepositoryUrl \
  -Dartifact="com.acme:foo:RELEASE:jar" -Dmdep.stripVersion -DoutputDirectory=/tmp/

"Insert if not exists" statement in SQLite

insert into bookmarks (users_id, lessoninfo_id)

select 1, 167
EXCEPT
select user_id, lessoninfo_id
from bookmarks
where user_id=1
and lessoninfo_id=167;

This is the fastest way.

For some other SQL engines, you can use a Dummy table containing 1 record. e.g:

select 1, 167 from ONE_RECORD_DUMMY_TABLE

PHP Fatal error: Uncaught exception 'Exception'

For

throw new Exception('test exception');

I got 500 (but didn't see anything in the browser), until I put

php_flag display_errors on

in my .htaccess (just for a subfolder). There are also more detailed settings, see Enabling error display in php via htaccess only

SQL Inner Join On Null Values

I'm pretty sure that the join doesn't even do what you want. If there are 100 records in table a with a null qid and 100 records in table b with a null qid, then the join as written should make a cross join and give 10,000 results for those records. If you look at the following code and run the examples, I think that the last one is probably more the result set you intended:

create table #test1 (id int identity, qid int)
create table #test2 (id int identity, qid int)

Insert #test1 (qid)
select null
union all
select null
union all
select 1
union all
select 2
union all
select null

Insert #test2 (qid)
select null
union all
select null
union all
select 1
union all
select 3
union all
select null


select * from #test2 t2
join #test1 t1 on t2.qid = t1.qid

select * from #test2 t2
join #test1 t1 on isnull(t2.qid, 0) = isnull(t1.qid, 0)


select * from #test2 t2
join #test1 t1 on 
 t1.qid = t2.qid OR ( t1.qid IS NULL AND t2.qid IS NULL )


select t2.id, t2.qid, t1.id, t1.qid from #test2 t2
join #test1 t1 on t2.qid = t1.qid
union all
select null, null,id, qid from #test1 where qid is null
union all
select id, qid, null, null from #test2  where qid is null

Listview Scroll to the end of the list after updating the list

The simplest solution is :

    listView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
    listView.setStackFromBottom(true);

Is it possible to set a custom font for entire of application?

As of Android O this is now possible to define directly from the XML and my bug is now closed!

See here for details

TL;DR:

First you must add your fonts to the project

Second you add a font family, like so:

<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
    <font
        android:fontStyle="normal"
        android:fontWeight="400"
        android:font="@font/lobster_regular" />
    <font
        android:fontStyle="italic"
        android:fontWeight="400"
        android:font="@font/lobster_italic" />
</font-family>

Finally, you can use the font in a layout or style:

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="@font/lobster"/>

<style name="customfontstyle" parent="@android:style/TextAppearance.Small">
    <item name="android:fontFamily">@font/lobster</item>
</style>

Enjoy!

OnClick vs OnClientClick for an asp:CheckBox?

You can assign function to all checkboxes then ask for confirmation inside of it. If they choose yes, checkbox is allowed to be changed if no it remains unchanged.

In my case I am also using ASP .Net checkbox inside a repeater (or grid) with Autopostback="True" attribute, so on server side I need to compare the value submitted vs what's currently in db in order to know what confirmation value they chose and update db only if it was "yes".

$(document).ready(function () {
    $('input[type=checkbox]').click(function(){                
        var areYouSure = confirm('Are you sure you want make this change?');
        if (areYouSure) {
            $(this).prop('checked', this.checked);
        } else {
            $(this).prop('checked', !this.checked);
        }
    });
}); 


<asp:CheckBox ID="chk" AutoPostBack="true" onCheckedChanged="chk_SelectedIndexChanged" runat="server" Checked='<%#Eval("FinancialAid") %>' />

protected void chk_SelectedIndexChanged(Object sender, EventArgs e)
{
    using (myDataContext db = new myDataDataContext())
    {
        CheckBox chk = (CheckBox)sender;
        RepeaterItem row = (RepeaterItem) chk.NamingContainer;            
        var studentID = ((Label) row.FindControl("lblID")).Text;
        var z = (from b in db.StudentApplicants
        where b.StudentID == studentID
        select b).FirstOrDefault();                
        if(chk != null && chk.Checked != z.FinancialAid){
            z.FinancialAid = chk.Checked;                
            z.ModifiedDate = DateTime.Now;
            db.SubmitChanges();
            BindGrid();
        }
        gvData.DataBind();
    }
}

Put a Delay in Javascript

Use a AJAX function which will call a php page synchronously and then in that page you can put the php usleep() function which will act as a delay.

function delay(t){

var xmlhttp;

if (window.XMLHttpRequest)

{// code for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp=new XMLHttpRequest();

}

else

{// code for IE6, IE5

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}

xmlhttp.open("POST","http://www.hklabs.org/files/delay.php?time="+t,false);

//This will call the page named delay.php and the response will be sent to a division with ID as "response"

xmlhttp.send();

document.getElementById("response").innerHTML=xmlhttp.responseText;

}

http://www.hklabs.org/articles/put-delay-in-javascript

Basic HTML - how to set relative path to current folder?

For anyone who has found this thread, addressing relative paths has always created arguments over what is correct or not.

Depending on where you use the path to be addressed, it will depend on how you address the path.

Generally :

. and ./ do the same thing, however you wouldn't use . with a file name. Otherwise you will have the browser requesting .filename.ext as a file from the server. The proper method would be ./filename.ext.

../ addresses the path up one level from the current folder. If you were in the path /cheese/crackers/yummy.html, and your link code asked for ../butter/spread.html in the document yummy.html, then you would be addressing the path /cheese/butter/spread.html, as far as the server was concerned.

/ will always address the root of the site.

How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script?

With bash 4.2 and newer you can use something like this to strip the trailing CR, which only uses bash built-ins:

if [[ "${str: -1}" == $'\r' ]]; then
    str="${str:: -1}"
fi

Taking the record with the max date

The analytic function approach would look something like

SELECT a, some_date_column
  FROM (SELECT a,
               some_date_column,
               rank() over (partition by a order by some_date_column desc) rnk
          FROM tablename)
 WHERE rnk = 1

Note that depending on how you want to handle ties (or whether ties are possible in your data model), you may want to use either the ROW_NUMBER or the DENSE_RANK analytic function rather than RANK.

What are the Ruby File.open modes and options?

In Ruby IO module documentation, I suppose.

Mode |  Meaning
-----+--------------------------------------------------------
"r"  |  Read-only, starts at beginning of file  (default mode).
-----+--------------------------------------------------------
"r+" |  Read-write, starts at beginning of file.
-----+--------------------------------------------------------
"w"  |  Write-only, truncates existing file
     |  to zero length or creates a new file for writing.
-----+--------------------------------------------------------
"w+" |  Read-write, truncates existing file to zero length
     |  or creates a new file for reading and writing.
-----+--------------------------------------------------------
"a"  |  Write-only, starts at end of file if file exists,
     |  otherwise creates a new file for writing.
-----+--------------------------------------------------------
"a+" |  Read-write, starts at end of file if file exists,
     |  otherwise creates a new file for reading and
     |  writing.
-----+--------------------------------------------------------
"b"  |  Binary file mode (may appear with
     |  any of the key letters listed above).
     |  Suppresses EOL <-> CRLF conversion on Windows. And
     |  sets external encoding to ASCII-8BIT unless explicitly
     |  specified.
-----+--------------------------------------------------------
"t"  |  Text file mode (may appear with
     |  any of the key letters listed above except "b").

How to Find Item in Dictionary Collection?

It's possible to find the element in Dictionary collection by using ContainsKey or TryGetValue as follows:

class Program
{
    protected static Dictionary<string, string> _tags = new Dictionary<string,string>();

    static void Main(string[] args)
    {
        string strValue;

        _tags.Add("101", "C#");
        _tags.Add("102", "ASP.NET");

        if (_tags.ContainsKey("101"))
        {
            strValue = _tags["101"];
            Console.WriteLine(strValue);
        }

        if (_tags.TryGetValue("101", out strValue))
        {
            Console.WriteLine(strValue);
        }
    }
}

get the value of input type file , and alert if empty

<script type="text/javascript">
$(document).ready(function() {
    $('#upload').bind("click",function() 
    { 
        var imgVal = $('#uploadImage').val(); 
        if(imgVal=='') 
        { 
            alert("empty input file"); 

        } 
        return false; 

    }); 
});
</script> 

<input type="file" name="image" id="uploadImage" size="30" /> 
<input type="submit" name="upload" id="upload"  class="send_upload" value="upload" /> 

How to get the caret column (not pixels) position in a textarea, in characters, from the start?

With Firefox, Safari (and other Gecko based browsers) you can easily use textarea.selectionStart, but for IE that doesn't work, so you will have to do something like this:

function getCaret(node) {
  if (node.selectionStart) {
    return node.selectionStart;
  } else if (!document.selection) {
    return 0;
  }

  var c = "\001",
      sel = document.selection.createRange(),
      dul = sel.duplicate(),
      len = 0;

  dul.moveToElementText(node);
  sel.text = c;
  len = dul.text.indexOf(c);
  sel.moveStart('character',-1);
  sel.text = "";
  return len;
}

(complete code here)

I also recommend you to check the jQuery FieldSelection Plugin, it allows you to do that and much more...

Edit: I actually re-implemented the above code:

function getCaret(el) { 
  if (el.selectionStart) { 
    return el.selectionStart; 
  } else if (document.selection) { 
    el.focus(); 

    var r = document.selection.createRange(); 
    if (r == null) { 
      return 0; 
    } 

    var re = el.createTextRange(), 
        rc = re.duplicate(); 
    re.moveToBookmark(r.getBookmark()); 
    rc.setEndPoint('EndToStart', re); 

    return rc.text.length; 
  }  
  return 0; 
}

Check an example here.

"Sub or Function not defined" when trying to run a VBA script in Outlook

This probably does not answer your question, but I had the same question and it answered mine.

I changed Private Function to Public Function and it worked.

Java rounding up to an int using Math.ceil

Nobody has mentioned the most intuitive:

int x = (int) Math.round(Math.ceil((double) 157 / 32));

This solution fixes the double division imprecision.

Get cart item name, quantity all details woocommerce

Since WooCommerce 2.1 (2014) you should use the WC function instead of the global. You can also call more appropriate functions:

foreach ( WC()->cart->get_cart() as $cart_item ) {
   $item_name = $cart_item['data']->get_title();
   $quantity = $cart_item['quantity'];
   $price = $cart_item['data']->get_price();
   ...

This will not only be clean code, but it will be better than accessing the post_meta directly because it will apply filters if necessary.

Difference between "\n" and Environment.NewLine

Exact implementation of Environment.NewLine from the source code:

The implementation in .NET 4.6.1:

/*===================================NewLine====================================
**Action: A property which returns the appropriate newline string for the given
**        platform.
**Returns: \r\n on Win32.
**Arguments: None.
**Exceptions: None.
==============================================================================*/
public static String NewLine {
    get {
        Contract.Ensures(Contract.Result<String>() != null);
        return "\r\n";
    }
}

source


The implementation in .NET Core:

/*===================================NewLine====================================
**Action: A property which returns the appropriate newline string for the
**        given platform.
**Returns: \r\n on Win32.
**Arguments: None.
**Exceptions: None.
==============================================================================*/
public static String NewLine {
    get {
        Contract.Ensures(Contract.Result() != null);
#if !PLATFORM_UNIX
        return "\r\n";
#else
        return "\n";
#endif // !PLATFORM_UNIX
    }
}

source (in System.Private.CoreLib)

public static string NewLine => "\r\n";

source (in System.Runtime.Extensions)

Android ListView with different layouts for each row

Since you know how many types of layout you would have - it's possible to use those methods.

getViewTypeCount() - this methods returns information how many types of rows do you have in your list

getItemViewType(int position) - returns information which layout type you should use based on position

Then you inflate layout only if it's null and determine type using getItemViewType.

Look at this tutorial for further information.

To achieve some optimizations in structure that you've described in comment I would suggest:

  • Storing views in object called ViewHolder. It would increase speed because you won't have to call findViewById() every time in getView method. See List14 in API demos.
  • Create one generic layout that will conform all combinations of properties and hide some elements if current position doesn't have it.

I hope that will help you. If you could provide some XML stub with your data structure and information how exactly you want to map it into row, I would be able to give you more precise advise. By pixel.

How to read values from the querystring with ASP.NET Core?

Some of the comments mention this as well, but asp net core does all this work for you.

If you have a query string that matches the name it will be available in the controller.

https://myapi/some-endpoint/123?someQueryString=YayThisWorks

[HttpPost]
[Route("some-endpoint/{someValue}")]
public IActionResult SomeEndpointMethod(int someValue, string someQueryString)
    {
        Debug.WriteLine(someValue);
        Debug.WriteLine(someQueryString);
        return Ok();
    }

Ouputs:

123

YayThisWorks

Angular2: How to load data before rendering the component?

A nice solution that I've found is to do on UI something like:

<div *ngIf="isDataLoaded">
 ...Your page...
</div

Only when: isDataLoaded is true the page is rendered.

Checking images for similarity with OpenCV

A little bit off topic but useful is the pythonic numpy approach. Its robust and fast but just does compare pixels and not the objects or data the picture contains (and it requires images of same size and shape):

A very simple and fast approach to do this without openCV and any library for computer vision is to norm the picture arrays by

import numpy as np
picture1 = np.random.rand(100,100)
picture2 = np.random.rand(100,100)
picture1_norm = picture1/np.sqrt(np.sum(picture1**2))
picture2_norm = picture2/np.sqrt(np.sum(picture2**2))

After defining both normed pictures (or matrices) you can just sum over the multiplication of the pictures you like to compare:

1) If you compare similar pictures the sum will return 1:

In[1]: np.sum(picture1_norm**2)
Out[1]: 1.0

2) If they aren't similar, you'll get a value between 0 and 1 (a percentage if you multiply by 100):

In[2]: np.sum(picture2_norm*picture1_norm)
Out[2]: 0.75389941124629822

Please notice that if you have colored pictures you have to do this in all 3 dimensions or just compare a greyscaled version. I often have to compare huge amounts of pictures with arbitrary content and that's a really fast way to do so.

Cannot connect to Database server (mysql workbench)

It looks like there are a lot of causes of this error.

My Cause / Solution

In my case, the cause was that my server was configured to only accept connections from localhost. I fixed it by following this article: How Do I Enable Remote Access To MySQL Database Server?. My my.cnf file had no skip-networking line, so I just changed the line

bind-address = 127.0.0.1

to

bind-address = 0.0.0.0

This allows connections from any IP, not just 127.0.0.1.

Then, I created a MySql user that could connect from my client machine by running the following terminal commands:

# mysql -u root -p
mysql> CREATE USER 'username'@'1.2.3.4' IDENTIFIED BY 'password';
    -> GRANT ALL PRIVILEGES ON *.* TO 'username'@'1.2.3.4' WITH GRANT OPTION;
    -> \q

where 1.2.3.4 is the IP of the client you are trying to connect from. If you really have trouble, you can use '%' instead of '1.2.3.4' to allow the user to connect from any IP.

Other Causes

For a fairly extensive list, see Causes of Access-Denied Errors.

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''')' at line 2

That's called SQL INJECTION. The ' tries to open/close a string in your mysql query. You should always escape any string that gets into your queries.

for example,

instead of this:

"VALUES ('$sender_id') "

do this:

"VALUES ('". mysql_real_escape_string($sender_id)  ."') "

(or equivalent, of course)

However, it's better to automate this, using PDO, named parameters, prepared statements or many other ways. Research about this and SQL Injection (here you have some techniques).

Hope it helps. Cheers

CSS to keep element at "fixed" position on screen

position: fixed;

Will make this happen.

It handles like position:absolute; with the exception that it will scroll with the window as the user scrolls down the content.

MySQL SELECT WHERE datetime matches day (and not necessarily time)

... WHERE date_column >='2012-12-25' AND date_column <'2012-12-26' may potentially work better(if you have an index on date_column) than DATE.

ConfigurationManager.AppSettings - How to modify and save?

Remember that ConfigurationManager uses only one app.config - one that is in startup project.

If you put some app.config to a solution A and make a reference to it from another solution B then if you run B, app.config from A will be ignored.

So for example unit test project should have their own app.config.

What causes javac to issue the "uses unchecked or unsafe operations" warning

This warning also could be raised due to

new HashMap() or new ArrayList() that is generic type has to be specific otherwise the compiler will generate warning.

Please make sure that if you code contains the following you have to change accordingly

new HashMap() => Map map = new HashMap() new HashMap() => Map map = new HashMap<>()

new ArrayList() => List map = new ArrayList() new ArrayList() => List map = new ArrayList<>()

How to quickly edit values in table in SQL Server Management Studio?

In Mgmt Studio, when you are editing the top 200, you can view the SQL pane - either by right clicking in the grid and choosing Pane->SQL or by the button in the upper left. This will allow you to write a custom query to drill down to the row(s) you want to edit.

But ultimately mgmt studio isn't a data entry/update tool which is why this is a little cumbersome.

Print string and variable contents on the same line in R

The {glue} package offers string interpolation. In the example, {wd} is substituted with the contents of the variable. Complex expressions are also supported.

library(glue)

wd <- getwd()
glue("Current working dir: {wd}")
#> Current working dir: /tmp/RtmpteMv88/reprex46156826ee8c

Created on 2019-05-13 by the reprex package (v0.2.1)

Note how the printed output doesn't contain the [1] artifacts and the " quotes, for which other answers use cat().

error: expected declaration or statement at end of input in c

For me I just noticed that it was my .h archive with a '{'. Maye that can help someone =)

How to align texts inside of an input?

Try this in your CSS:

input {
text-align: right;
}

To align the text in the center:

input {
text-align: center;
}

But, it should be left-aligned, as that is the default - and appears to be the most user friendly.

Check if SQL Connection is Open or Closed

To check OleDbConnection State use this:

if (oconn.State == ConnectionState.Open)
{
    oconn.Close();
}

State return the ConnectionState

public override ConnectionState State { get; }

Here are the other ConnectionState enum

public enum ConnectionState
    {
        //
        // Summary:
        //     The connection is closed.
        Closed = 0,
        //
        // Summary:
        //     The connection is open.
        Open = 1,
        //
        // Summary:
        //     The connection object is connecting to the data source. (This value is reserved
        //     for future versions of the product.)
        Connecting = 2,
        //
        // Summary:
        //     The connection object is executing a command. (This value is reserved for future
        //     versions of the product.)
        Executing = 4,
        //
        // Summary:
        //     The connection object is retrieving data. (This value is reserved for future
        //     versions of the product.)
        Fetching = 8,
        //
        // Summary:
        //     The connection to the data source is broken. This can occur only after the connection
        //     has been opened. A connection in this state may be closed and then re-opened.
        //     (This value is reserved for future versions of the product.)
        Broken = 16
    }

nodeJs callbacks simple example

_x000D_
_x000D_
//delay callback function_x000D_
function delay (seconds, callback){_x000D_
    setTimeout(() =>{_x000D_
      console.log('The long delay ended');_x000D_
      callback('Task Complete');_x000D_
    }, seconds*1000);_x000D_
}_x000D_
//Execute delay function_x000D_
delay(1, res => {  _x000D_
    console.log(res);  _x000D_
})
_x000D_
_x000D_
_x000D_

Finding index of character in Swift String

If you want to know the position of a character in a string as an int value use this:

let loc = newString.range(of: ".").location

Best way to retrieve variable values from a text file?

How reliable is your format? If the seperator is always exactly ': ', the following works. If not, a comparatively simple regex should do the job.

As long as you're working with fairly simple variable types, Python's eval function makes persisting variables to files surprisingly easy.

(The below gives you a dictionary, btw, which you mentioned was one of your prefered solutions).

def read_config(filename):
    f = open(filename)
    config_dict = {}
    for lines in f:
        items = lines.split(': ', 1)
        config_dict[items[0]] = eval(items[1])
    return config_dict

Autocompletion of @author in Intellij

Check Enable Live Templates and leave the cursor at the position desired and click Apply then OK

enter image description here

How to use su command over adb shell?

for my use case, i wanted to grab the SHA1 hash from the magisk config file. the below worked for me.

adb shell "su -c "cat /sbin/.magisk/config | grep SHA | awk -F= '{ print $2 }'""

Converting 'ArrayList<String> to 'String[]' in Java

in case some extra manipulation of the data is desired, for which the user wants a function, this approach is not perfect (as it requires passing the class of the element as second parameter), but works:

import java.util.ArrayList; import java.lang.reflect.Array;

public class Test {
  public static void main(String[] args) {
    ArrayList<Integer> al = new ArrayList<>();
    al.add(1);
    al.add(2);
    Integer[] arr = convert(al, Integer.class);
    for (int i=0; i<arr.length; i++)
      System.out.println(arr[i]);
  }

  public static <T> T[] convert(ArrayList<T> al, Class clazz) {
    return (T[]) al.toArray((T[])Array.newInstance(clazz, al.size()));
  }
}

Assign width to half available screen width declaratively

give width as 0dp to make sure its size is exactly as per its weight this will make sure that even if content of child views get bigger, they'll still be limited to exactly half(according to is weight)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="1"
     >

    <Button
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="click me"
    android:layout_weight="0.5"/>


    <TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="Hello World"
    android:layout_weight="0.5"/>
  </LinearLayout>

PHP, getting variable from another php-file

You could also use a session for passing small bits of info. You will need to have session_start(); at the top of the PHP pages that use the session else the variables will not be accessable

page1.php

<?php

   session_start();
   $_SESSION['superhero'] = "batman";

?>
<a href="page2.php" title="">Go to the other page</a>

page2.php

<?php 

   session_start(); // this NEEDS TO BE AT THE TOP of the page before any output etc
   echo $_SESSION['superhero'];

?>

C# SQL Server - Passing a list to a stored procedure

CREATE TYPE [dbo].[StringList1] AS TABLE(
[Item] [NVARCHAR](MAX) NULL,
[counts][nvarchar](20) NULL);

create a TYPE as table and name it as"StringList1"

create PROCEDURE [dbo].[sp_UseStringList1]
@list StringList1 READONLY
AS
BEGIN
    -- Just return the items we passed in
    SELECT l.item,l.counts FROM @list l;
    SELECT l.item,l.counts into tempTable FROM @list l;
 End

The create a procedure as above and name it as "UserStringList1" s

String strConnection = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString.ToString();
            SqlConnection con = new SqlConnection(strConnection);
            con.Open();
            var table = new DataTable();

            table.Columns.Add("Item", typeof(string));
            table.Columns.Add("count", typeof(string));

            for (int i = 0; i < 10; i++)
            {
                table.Rows.Add(i.ToString(), (i+i).ToString());

            }
                SqlCommand cmd = new SqlCommand("exec sp_UseStringList1 @list", con);


                    var pList = new SqlParameter("@list", SqlDbType.Structured);
                    pList.TypeName = "dbo.StringList1";
                    pList.Value = table;

                    cmd.Parameters.Add(pList);
                    string result = string.Empty;
                    string counts = string.Empty;
                    var dr = cmd.ExecuteReader();

                    while (dr.Read())
                    {
                        result += dr["Item"].ToString();
                        counts += dr["counts"].ToString();
                    }

in the c#,Try this

How to create a library project in Android Studio and an application project that uses the library project

Check out this link about multi project setups.

Some things to point out, make sure you have your settings.gradle updated to reference both the app and library modules.

settings.gradle: include ':app', ':libraries:lib1', ':libraries:lib2'

Also make sure that the app's build.gradle has the followng:

dependencies {
     compile project(':libraries:lib1')
}

You should have the following structure:

 MyProject/
  | settings.gradle
  + app/
    | build.gradle
  + libraries/
    + lib1/
       | build.gradle
    + lib2/
       | build.gradle

The app's build.gradle should use the com.android.application plugin while any libraries' build.gradle should use the com.android.library plugin.

The Android Studio IDE should update if you're able to build from the command line with this setup.

System not declared in scope?

You need to add:

 #include <cstdlib>

in order for the compiler to see the prototype for system().

Get the ID of a drawable in ImageView

Digging StackOverflow for answers on the similar issue I found people usually suggesting 2 approaches:

  • Load a drawable into memory and compare ConstantState or bitmap itself to other one.
  • Set a tag with drawable id into a view and compare tags when you need that.

Personally, I like the second approach for performance reason but tagging bunch of views with appropriate tags is painful and time consuming. This could be very frustrating in a big project. In my case I need to write a lot of Espresso tests which require comparing TextView drawables, ImageView resources, View background and foreground. A lot of work.

So I eventually came up with a solution to delegate a 'dirty' work to the custom inflater. In every inflated view I search for a specific attributes and and set a tag to the view with a resource id if any is found. This approach is pretty much the same guys from Calligraphy used. I wrote a simple library for that: TagView

If you use it, you can retrieve any of predefined tags, containing drawable resource id that was set in xml layout file:

TagViewUtils.getTag(view, ViewTag.IMAGEVIEW_SRC.id)
TagViewUtils.getTag(view, ViewTag.TEXTVIEW_DRAWABLE_LEFT.id)
TagViewUtils.getTag(view, ViewTag.TEXTVIEW_DRAWABLE_TOP.id)
TagViewUtils.getTag(view, ViewTag.TEXTVIEW_DRAWABLE_RIGHT.id)
TagViewUtils.getTag(view, ViewTag.TEXTVIEW_DRAWABLE_BOTTOM.id)
TagViewUtils.getTag(view, ViewTag.VIEW_BACKGROUND.id)
TagViewUtils.getTag(view, ViewTag.VIEW_FOREGROUND.id)

The library supports any attribute, actually. You can add them manually, just look into the Custom attributes section on Github. If you set a drawable in runtime you can use convenient library methods:

setImageViewResource(ImageView view, int id)

In this case tagging is done for you internally. If you use Kotlin you can write a handy extensions to call view itself. Something like this:

fun ImageView.setImageResourceWithTag(@DrawableRes int id) {
    TagViewUtils.setImageViewResource(this, id)
}

You can find additional info in Tagging in runtime

Waiting for Target Device to Come Online

Go to the Sdk manager--> SDKtools --> instal the emulator 25.3.1

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

Upgrading MySQL fixed it for me. On RHEL-based servers, just run:

sudo yum upgrade mysql-server

np.mean() vs np.average() in Python NumPy?

In some version of numpy there is another imporant difference that you must be aware:

average do not take in account masks, so compute the average over the whole set of data.

mean takes in account masks, so compute the mean only over unmasked values.

g = [1,2,3,55,66,77]
f = np.ma.masked_greater(g,5)

np.average(f)
Out: 34.0

np.mean(f)
Out: 2.0

PostgreSQL 'NOT IN' and subquery

You could also use a LEFT JOIN and IS NULL condition:

SELECT 
  mac, 
  creation_date 
FROM 
  logs
    LEFT JOIN consols ON logs.mac = consols.mac
WHERE 
  logs_type_id=11
AND
  consols.mac IS NULL;

An index on the "mac" columns might improve performance.

How do I remove a file from the FileList

This is extemporary, but I had the same problem which I solved this way. In my case I was uploading the files via XMLHttp request, so I was able to post the FileList cloned data through formdata appending. Functionality is that you can drag and drop or select multiple files as many times as you want (selecting files again won't reset the cloned FileList), remove any file you want from the (cloned) file list, and submit via xmlhttprequest whatever was left there. This is what I did. It is my first post here so code is a little messy. Sorry. Ah, and I had to use jQuery instead of $ as it was in Joomla script.

// some global variables
var clon = {};  // will be my FileList clone
var removedkeys = 0; // removed keys counter for later processing the request
var NextId = 0; // counter to add entries to the clone and not replace existing ones

jQuery(document).ready(function(){
    jQuery("#form input").change(function () {

    // making the clone
    var curFiles = this.files;
    // temporary object clone before copying info to the clone
    var temparr = jQuery.extend(true, {}, curFiles);
    // delete unnecessary FileList keys that were cloned
    delete temparr["length"];
    delete temparr["item"];

    if (Object.keys(clon).length === 0){
       jQuery.extend(true, clon, temparr);
    }else{
       var keysArr = Object.keys(clon);
       NextId = Math.max.apply(null, keysArr)+1; // FileList keys are numbers
       if (NextId < curFiles.length){ // a bug I found and had to solve for not replacing my temparr keys...
          NextId = curFiles.length;
       }
       for (var key in temparr) { // I have to rename new entries for not overwriting existing keys in clon
          if (temparr.hasOwnProperty(key)) {
             temparr[NextId] = temparr[key];
             delete temparr[key];
                // meter aca los cambios de id en los html tags con el nuevo NextId
                NextId++;
          }
       } 
       jQuery.extend(true, clon, temparr); // copy new entries to clon
    }

// modifying the html file list display

if (NextId === 0){
    jQuery("#filelist").html("");
    for(var i=0; i<curFiles.length; i++) {
        var f = curFiles[i];
        jQuery("#filelist").append("<p id=\"file"+i+"\" style=\'margin-bottom: 3px!important;\'>" + f.name + "<a style=\"float:right;cursor:pointer;\" onclick=\"BorrarFile("+i+")\">x</a></p>"); // the function BorrarFile will handle file deletion from the clone by file id
    }
}else{
    for(var i=0; i<curFiles.length; i++) {
        var f = curFiles[i];
        jQuery("#filelist").append("<p id=\"file"+(i+NextId-curFiles.length)+"\" style=\'margin-bottom: 3px!important;\'>" + f.name + "<a style=\"float:right;cursor:pointer;\" onclick=\"BorrarFile("+(i+NextId-curFiles.length)+")\">x</a></p>"); // yeap, i+NextId-curFiles.length actually gets it right
    }        
}
// update the total files count wherever you want
jQuery("#form p").text(Object.keys(clon).length + " file(s) selected");
    });
});

function BorrarFile(id){ // handling file deletion from clone
    jQuery("#file"+id).remove(); // remove the html filelist element
    delete clon[id]; // delete the entry
    removedkeys++; // add to removed keys counter
    if (Object.keys(clon).length === 0){
        jQuery("#form p").text(Object.keys(clon).length + " file(s) selected");
        jQuery("#fileToUpload").val(""); // I had to reset the form file input for my form check function before submission. Else it would send even though my clone was empty
    }else{
        jQuery("#form p").text(Object.keys(clon).length + " file(s) selected");
    }
}
// now my form check function

function check(){
    if( document.getElementById("fileToUpload").files.length == 0 ){
        alert("No file selected");
        return false;
    }else{
        var _validFileExtensions = [".pdf", ".PDF"]; // I wanted pdf files
        // retrieve input files
        var arrInputs = clon;

       // validating files
       for (var i = 0; i < Object.keys(arrInputs).length+removedkeys; i++) {
         if (typeof arrInputs[i]!="undefined"){
           var oInput = arrInputs[i];
           if (oInput.type == "application/pdf") {
               var sFileName = oInput.name;
               if (sFileName.length > 0) {
                   var blnValid = false;
                   for (var j = 0; j < _validFileExtensions.length; j++) {
                     var sCurExtension = _validFileExtensions[j];
                     if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
                       blnValid = true;
                       break;
                     }
                   }
                  if (!blnValid) {
                    alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
                    return false;
                  }
              }
           }else{
           alert("Sorry, " + arrInputs[0].name + " is invalid, allowed extensions are: " + _validFileExtensions.join(" or "));
           return false;
           }
         }
       }

    // proceed with the data appending and submission
    // here some hidden input values i had previously set. Now retrieving them for submission. My form wasn't actually even a form...
    var fecha = jQuery("#fecha").val();
    var vendor = jQuery("#vendor").val();
    var sku = jQuery("#sku").val();
    // create the formdata object
    var formData = new FormData();
    formData.append("fecha", fecha);
    formData.append("vendor", encodeURI(vendor));
    formData.append("sku", sku);
    // now appending the clone file data (finally!)
    var fila = clon; // i just did this because I had already written the following using the "fila" object, so I copy my clone again
    // the interesting part. As entries in my clone object aren't consecutive numbers I cannot iterate normally, so I came up with the following idea
    for (i = 0; i < Object.keys(fila).length+removedkeys; i++) { 
        if(typeof fila[i]!="undefined"){
            formData.append("fileToUpload[]", fila[i]); // VERY IMPORTANT the formdata key for the files HAS to be an array. It will be later retrieved as $_FILES['fileToUpload']['temp_name'][i]
        }
    }
    jQuery("#submitbtn").fadeOut("slow"); // remove the upload btn so it can't be used again
    jQuery("#drag").html(""); // clearing the output message element
    // start the request
    var xhttp = new XMLHttpRequest();
    xhttp.addEventListener("progress", function(e) {
            var done = e.position || e.loaded, total = e.totalSize || e.total;
        }, false);
        if ( xhttp.upload ) {
            xhttp.upload.onprogress = function(e) {
                var done = e.position || e.loaded, total = e.totalSize || e.total;
                var percent = done / total;
                jQuery("#drag").html(Math.round(percent * 100) + "%");
            };
        }
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
         var respuesta = this.responseText;
         jQuery("#drag").html(respuesta);
        }
      };
      xhttp.open("POST", "your_upload_handler.php", true);  
      xhttp.send(formData);
    return true;
    }
};

Now the html and styles for this. I'm quite a newbie but all this actually worked for me and took me a while to figure it out.

<div id="form" class="formpos">
<!--    Select the pdf to upload:-->
  <input type="file" name="fileToUpload[]" id="fileToUpload" accept="application/pdf" multiple>
  <div><p id="drag">Drop your files here or click to select them</p>
  </div>
  <button id="submitbtn" onclick="return check()" >Upload</button>
// these inputs are passed with different names on the formdata. Be aware of that
// I was echoing this, so that's why I use the single quote for php variables
  <input type="hidden" id="fecha" name="fecha_copy" value="'.$fecha.'" />
  <input type="hidden" id="vendor" name="vendorname" value="'.$vendor.'" />
  <input type="hidden" id="sku" name="sku" value="'.$sku.'"" />
</div>
<h1 style="width: 500px!important;margin:20px auto 0px!important;font-size:24px!important;">File list:</h1>
<div id="filelist" style="width: 500px!important;margin:10px auto 0px!important;">Nothing selected yet</div>

The styles for that. I had to mark some of them !important to override Joomla behavior.

.formpos{
  width: 500px;
  height: 200px;
  border: 4px dashed #999;
  margin: 30px auto 100px;
 }
.formpos  p{
  text-align: center!important;
  padding: 80px 30px 0px;
  color: #000;
}
.formpos  div{
  width: 100%!important;
  height: 100%!important;
  text-align: center!important;
  margin-bottom: 30px!important;
}
.formpos input{
  position: absolute!important;
  margin: 0!important;
  padding: 0!important;
  width: 500px!important;
  height: 200px!important;
  outline: none!important;
  opacity: 0!important;
}
.formpos button{
  margin: 0;
  color: #fff;
  background: #16a085;
  border: none;
  width: 508px;
  height: 35px;
  margin-left: -4px;
  border-radius: 4px;
  transition: all .2s ease;
  outline: none;
}
.formpos button:hover{
  background: #149174;
  color: #0C5645;
}
.formpos button:active{
  border:0;
}

I hope this helps.

Modulo operator in Python

same as a normal modulo 3.14 % 6.28 = 3.14, just like 3.14%4 =3.14 3.14%2 = 1.14 (the remainder...)

How to catch segmentation fault in Linux?

On Linux we can have these as exceptions, too.

Normally, when your program performs a segmentation fault, it is sent a SIGSEGV signal. You can set up your own handler for this signal and mitigate the consequences. Of course you should really be sure that you can recover from the situation. In your case, I think, you should debug your code instead.

Back to the topic. I recently encountered a library (short manual) that transforms such signals to exceptions, so you can write code like this:

try
{
    *(int*) 0 = 0;
}
catch (std::exception& e)
{
    std::cerr << "Exception caught : " << e.what() << std::endl;
}

Didn't check it, though. Works on my x86-64 Gentoo box. It has a platform-specific backend (borrowed from gcc's java implementation), so it can work on many platforms. It just supports x86 and x86-64 out of the box, but you can get backends from libjava, which resides in gcc sources.

AngularJS error: 'argument 'FirstCtrl' is not a function, got undefined'

remove ng-app="" from

<div ng-app="">

and simply make it

<div>

Can promises have multiple arguments to onFulfilled?

Here is a CoffeeScript solution.

I was looking for the same solution and found seomething very intersting from this answer: Rejecting promises with multiple arguments (like $http) in AngularJS

the answer of this guy Florian

promise = deferred.promise

promise.success = (fn) ->
  promise.then (data) ->
   fn(data.payload, data.status, {additional: 42})
  return promise

promise.error = (fn) ->
  promise.then null, (err) ->
    fn(err)
  return promise

return promise 

And to use it:

service.get().success (arg1, arg2, arg3) ->
    # => arg1 is data.payload, arg2 is data.status, arg3 is the additional object
service.get().error (err) ->
    # => err

How display only years in input Bootstrap Datepicker?

format: "YYYY" 

Should be capital instead of "yyyy"

How to redirect DNS to different ports

Since I had troubles understanding this post here is a simple explanation for people like me. It is useful if:

  • You DO NOT need Load Balacing.
  • You DO NOT want to use nginx to do port forwarding.
  • You DO want to do PORT FORWARDING according to specific subdomains using SRV record.

Then here is what you need to do:

SRV records:

_minecraft._tcp.1.12          IN SRV    1 100 25567 1.12.<your-domain-name.com>.
_minecraft._tcp.1.13          IN SRV    1 100 25566 1.13.<your-domain-name.com>.

(I did not need a srv record for 1.14 since my 1.14 minecraft server was already on the 25565 port which is the default port of minecraft.)

And the A records:

1.12                          IN A      <your server IP>
1.13                          IN A      <your server IP>
1.14                          IN A      <your server IP>

What is let-* in Angular 2 templates?

The Angular microsyntax lets you configure a directive in a compact, friendly string. The microsyntax parser translates that string into attributes on the <ng-template>. The let keyword declares a template input variable that you reference within the template.

How can I print each command before executing?

set -x is fine, but if you do something like:

set -x;
command;
set +x;

it would result in printing

+ command
+ set +x;

You can use a subshell to prevent that such as:

(set -x; command)

which would just print the command.

Mysql 1050 Error "Table already exists" when in fact, it does not

gosh, i had the same problem with osCommerce install script until i figured out the mysql system has many databases and the create table query copies itself into each one and thus droping only the working table on active db didnt help, i had to drop the table from all dbs

Programmatically change the src of an img tag

<img src="../template/edit.png" name="edit-save" onclick="this.src = '../template/save.png'" />

in_array multiple values

IMHO Mark Elliot's solution's best one for this problem. If you need to make more complex comparison operations between array elements AND you're on PHP 5.3, you might also think about something like the following:

<?php

// First Array To Compare
$a1 = array('foo','bar','c');

// Target Array
$b1 = array('foo','bar');


// Evaluation Function - we pass guard and target array
$b=true;
$test = function($x) use (&$b, $b1) {
        if (!in_array($x,$b1)) {
                $b=false;
        }
};


// Actual Test on array (can be repeated with others, but guard 
// needs to be initialized again, due to by reference assignment above)
array_walk($a1, $test);
var_dump($b);

This relies on a closure; comparison function can become much more powerful. Good luck!

Build error: "The process cannot access the file because it is being used by another process"

For those who are developing in VS with Docker, restart the docker for windows service and the problem will be solved immediately.

Before restarting docker I tried all the mentioned answers, didn't find a msbuild.exe process running, also tried restarting VS without avail, only restarting docker worked.

Iterating each character in a string using Python

If you ever run in a situation where you need to get the next char of the word using __next__(), remember to create a string_iterator and iterate over it and not the original string (it does not have the __next__() method)

In this example, when I find a char = [ I keep looking into the next word while I don't find ], so I need to use __next__

here a for loop over the string wouldn't help

myString = "'string' 4 '['RP0', 'LC0']' '[3, 4]' '[3, '4']'"
processedInput = ""
word_iterator = myString.__iter__()
for idx, char in enumerate(word_iterator):
    if char == "'":
        continue

    processedInput+=char

    if char == '[':
        next_char=word_iterator.__next__()
        while(next_char != "]"):
          processedInput+=next_char
          next_char=word_iterator.__next__()
        else:
          processedInput+=next_char

How can I convert a PFX certificate file for use with Apache on a linux server?

With OpenSSL you can convert pfx to Apache compatible format with next commands:

openssl pkcs12 -in domain.pfx -clcerts -nokeys -out domain.cer
openssl pkcs12 -in domain.pfx -nocerts -nodes  -out domain.key   

First command extracts public key to domain.cer.
Second command extracts private key to domain.key.

Update your Apache configuration file with:

<VirtualHost 192.168.0.1:443>
 ...
 SSLEngine on
 SSLCertificateFile /path/to/domain.cer
 SSLCertificateKeyFile /path/to/domain.key
 ...
</VirtualHost>

ReferenceError: variable is not defined

Variables are available only in the scope you defined them. If you define a variable inside a function, you won't be able to access it outside of it.

Define variable with var outside the function (and of course before it) and then assign 10 to it inside function:

var value;
$(function() {
  value = "10";
});
console.log(value); // 10

Note that you shouldn't omit the first line in this code (var value;), because otherwise you are assigning value to undefined variable. This is bad coding practice and will not work in strict mode. Defining a variable (var variable;) and assigning value to a variable (variable = value;) are two different things. You can't assign value to variable that you haven't defined.

It might be irrelevant here, but $(function() {}) is a shortcut for $(document).ready(function() {}), which executes a function as soon as document is loaded. If you want to execute something immediately, you don't need it, otherwise beware that if you run it before DOM has loaded, value will be undefined until it has loaded, so console.log(value); placed right after $(function() {}) will return undefined. In other words, it would execute in following order:

var value;
console.log(value);
value = "10";

See also:

Change font color and background in html on mouseover

It would be great if you use :hover pseudo class over the onmouseover event

td:hover
{
   background-color:white
}

and for the default styling just use

td
{
  background-color:black
}

As you want to use these styling not over all the td elements then you need to specify the class to those elements and add styling to that class like this

.customTD
{
   background-color:black
}
.customTD:hover
{
  background-color:white;
}

You can also use :nth-child selector to select the td elements

Numpy isnan() fails on an array of floats (from pandas dataframe apply)

A great substitute for np.isnan() and pd.isnull() is

for i in range(0,a.shape[0]):
    if(a[i]!=a[i]):
       //do something here
       //a[i] is nan

since only nan is not equal to itself.

How to atomically delete keys matching a pattern using Redis

@itamar's answer is great, but the parsing of the reply wasn't working for me, esp. in the case where there are no keys found in a given scan. A possibly simpler solution, directly from the console:

redis-cli -h HOST -p PORT  --scan --pattern "prefix:*" | xargs -n 100 redis-cli DEL

This also uses SCAN, which is preferable to KEYS in production, but is not atomic.

Convert String to Uri

What are you going to do with the URI?

If you're just going to use it with an HttpGet for example, you can just use the string directly when creating the HttpGet instance.

HttpGet get = new HttpGet("http://stackoverflow.com");

How to convert a string to an integer in JavaScript?

There are many ways in JavaScript to convert a string to a number value... All simple and handy, choose the way which one works for you:

var num = Number("999.5"); //999.5
var num = parseInt("999.5", 10); //999
var num = parseFloat("999.5"); //999.5
var num = +"999.5"; //999.5

Also any Math operation converts them to number, for example...

var num = "999.5" / 1; //999.5
var num = "999.5" * 1; //999.5
var num = "999.5" - 1 + 1; //999.5
var num = "999.5" - 0; //999.5
var num = Math.floor("999.5"); //999
var num = ~~"999.5"; //999

My prefer way is using + sign, which is the elegant way to convert a string to number in JavaScript.

How to add Tomcat Server in eclipse

This is very simple steps involved as you mentioned you have already installed JAVAEE plugin so the first step for you is go to Windows->Show View->Server in add select the AppacheTOMcat and select the tomcat version you have downloaded and set the path and start the server after that.

How to respond to clicks on a checkbox in an AngularJS directive?

Liviu's answer was extremely helpful for me. Hope this is not bad form but i made a fiddle that may help someone else out in the future.

Two important pieces that are needed are:

    $scope.entities = [{
    "title": "foo",
    "id": 1
}, {
    "title": "bar",
    "id": 2
}, {
    "title": "baz",
    "id": 3
}];
$scope.selected = [];

How to round a numpy array?

If you want the output to be

array([1.6e-01, 9.9e-01, 3.6e-04])

the problem is not really a missing feature of NumPy, but rather that this sort of rounding is not a standard thing to do. You can make your own rounding function which achieves this like so:

def my_round(value, N):
    exponent = np.ceil(np.log10(value))
    return 10**exponent*np.round(value*10**(-exponent), N)

For a general solution handling 0 and negative values as well, you can do something like this:

def my_round(value, N):
    value = np.asarray(value).copy()
    zero_mask = (value == 0)
    value[zero_mask] = 1.0
    sign_mask = (value < 0)
    value[sign_mask] *= -1
    exponent = np.ceil(np.log10(value))
    result = 10**exponent*np.round(value*10**(-exponent), N)
    result[sign_mask] *= -1
    result[zero_mask] = 0.0
    return result

Setting the default page for ASP.NET (Visual Studio) server configuration

This One Method For Published Solution To Show SpeciFic Page on startup.

Here Is the Route Example to Redirect to Specific Page...

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            namespaces: new[] { "YourSolutionName.Controllers" }
        );
    }
}

By Default Home Controllers Index method is executed when application is started, Here You Can Define yours.

Note : I am Using Visual Studio 2013 and "YourSolutionName" is to changed to your project Name..

Get a Div Value in JQuery

your div looks like this:

<div id="someId">Some Value</div>

With jquery:

   <script type="text/javascript">
     $(function(){
         var text = $('#someId').html(); 
         //or
         var text = $('#someId').text();
       };
  </script> 

Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment

I have lost hours today to find the reason, fortunately this issue is not because of MapFragment implementation, fnfortunately, this does not work because nested fragments are only supported through support library from rev 11.

My implementation has an activity with actionbar (in tabbed mode) with two tabs (no viewpager), one having the map and the other having a list of entries. Of course I've been quite naive to use MapFragment inside my tab-fragments, et voila the app crashed everytime I switched back to map-tab.

( The same issue I also would have in case my tab-fragment would inflate any layout containing any other fragment ).

One option is to use the MapView (instead of MapFragment), with some overhead though ( see MapView Docs as drop-in replacement in the layout.xml, another option is to use support-library up from rev. 11 but then take programmatic approach since nested fragments are neither supported via layout. Or just working around programmatically by explicitely destroying the fragment (like in the answer from Matt / Vidar), btw: same effect is achieved using the MapView (option 1).

But actually, I did not want to loose the map everytime I tab away, that is, I wanted to keep it in memory and cleanup only upon activity close, so I decided to simply hide/show the map while tabbing, see FragmentTransaction / hide

Getting Current date, time , day in laravel

It's very simple:

Carbon::now()->toDateString()

This will give you a perfectly formatted date string such as 2020-10-29.

In Laravel 5.5 and above you can use now() as a global helper instead of Carbon::now(), like this:

now()->toDateString()

GROUP BY to combine/concat a column

SELECT
     [User], Activity,
     STUFF(
         (SELECT DISTINCT ',' + PageURL
          FROM TableName
          WHERE [User] = a.[User] AND Activity = a.Activity
          FOR XML PATH (''))
          , 1, 1, '')  AS URLList
FROM TableName AS a
GROUP BY [User], Activity

Please enter a commit message to explain why this merge is necessary, especially if it merges an updated upstream into a topic branch

Instead, you could git CtrlZ and retry the commit but this time add " -m " with a message in quotes after it, then it will commit without prompting you with that page.

How to get instance variables in Python?

Every object has a __dict__ variable containing all the variables and its values in it.

Try this

>>> hi_obj = hi()
>>> hi_obj.__dict__.keys()

C convert floating point to int

my_var = (int)my_var;

As simple as that. Basically you don't need it if the variable is int.

Convert Bitmap to File

Hope it will help u:

//create a file to write bitmap data
File f = new File(context.getCacheDir(), filename);
f.createNewFile();

//Convert bitmap to byte array
Bitmap bitmap = your bitmap;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();

//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();

Adding a regression line on a ggplot

I found this function on a blog

 ggplotRegression <- function (fit) {

    `require(ggplot2)

    ggplot(fit$model, aes_string(x = names(fit$model)[2], y = names(fit$model)[1])) + 
      geom_point() +
      stat_smooth(method = "lm", col = "red") +
      labs(title = paste("Adj R2 = ",signif(summary(fit)$adj.r.squared, 5),
                         "Intercept =",signif(fit$coef[[1]],5 ),
                         " Slope =",signif(fit$coef[[2]], 5),
                         " P =",signif(summary(fit)$coef[2,4], 5)))
    }`

once you loaded the function you could simply

ggplotRegression(fit)

you can also go for ggplotregression( y ~ x + z + Q, data)

Hope this helps.

SQL SERVER: Check if variable is null and then assign statement for Where Clause

is null is the syntax I use for such things, when COALESCE is of no help.

Try:

if (@zipCode is null)
  begin
    ([Portal].[dbo].[Address].Position.Filter(@radiusBuff) = 1)   
  end
else 
  begin
    ([Portal].[dbo].[Address].PostalCode=@zipCode )
  end  

How to change the current URL in javascript?

What you're doing is appending a "1" (the string) to your URL. If you want page 1.html link to page 2.html you need to take the 1 out of the string, add one to it, then reassemble the string.

Why not do something like this:

var url = 'http://mywebsite.com/1.html';
var pageNum = parseInt( url.split("/").pop(),10 );
var nextPage = 'http://mywebsite.com/'+(pageNum+1)+'.html';

nextPage will contain the url http://mywebsite.com/2.html in this case. Should be easy to put in a function if needed.

Create or update mapping in elasticsearch

In later Elasticsearch versions (7.x), types were removed. Updating a mapping can becomes:

curl -XPUT "http://localhost:9200/test/_mapping" -H 'Content-Type: application/json' -d'{
  "properties": {
    "new_geo_field": {
      "type": "geo_point"
    }
  }
}'

As others have pointed out, if the field exists, you typically have to reindex. There are exceptions, such as adding a new sub-field or changing analysis settings.

You can't "create a mapping", as the mapping is created with the index. Typically, you'd define the mapping when creating the index (or via index templates):

curl -XPUT "http://localhost:9200/test" -H 'Content-Type: application/json' -d'{
  "mappings": {
    "properties": {
      "foo_field": {
        "type": "text"
      }
    }
  }
}'

That's because, in production at least, you'd want to avoid letting Elasticsearch "guess" new fields. Which is what generated this question: geo data was read as an array of long values.

How to copy an object by value, not by reference

I know this is a little bit too late but it might just help someone.

In my case I already had a method to make the Object from a json Object and make json from the object. with this you can simply create a new instance of the object and use it to restore. For instance in a function parsing a final object

_x000D_
_x000D_
public void update(final Object object){ _x000D_
  final Object original = Object.makeFromJSON(object.toJSON()); _x000D_
  // the original is not affected by changes made to object _x000D_
}
_x000D_
_x000D_
_x000D_

Javascript decoding html entities

I think you are looking for this ?

$('#your_id').html('&lt;p&gt;name&lt;/p&gt;&lt;p&gt;&lt;span style="font-size:xx-small;"&gt;ajde&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;da&lt;/em&gt;&lt;/p&gt;').text();

How to Disable landscape mode in Android?

I was not aware of the AndroidManifest.xml file switch until reading this post, so in my apps I have used this instead:

setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);     //  Fixed Portrait orientation

What are type hints in Python 3.5?

Type hints are for maintainability and don't get interpreted by Python. In the code below, the line def add(self, ic:int) doesn't result in an error until the next return... line:

class C1:
    def __init__(self):
        self.idn = 1
    def add(self, ic: int):
        return self.idn + ic

c1 = C1()
c1.add(2)

c1.add(c1)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 5, in add
TypeError: unsupported operand type(s) for +: 'int' and 'C1'

Draw a line in a div

Its working for me

_x000D_
_x000D_
 .line{_x000D_
width: 112px;_x000D_
height: 47px;_x000D_
border-bottom: 1px solid black;_x000D_
position: absolute;_x000D_
}
_x000D_
<div class="line"></div>
_x000D_
_x000D_
_x000D_

Detect element content changes with jQuery

Try this, it was created by James Padolsey(J-P here on SO) and does exactly what you want (I think)

http://james.padolsey.com/javascript/monitoring-dom-properties/

No Main class found in NetBeans

In project properties, under the run tab, specify your main class. Moreover, To avoid this issue, you need to check "Create main class" during creating new project. Specifying main class in properties should always work, but if in some rare case it doesn't work, then the issue could be resolved by re-creating the project and not forgetting to check "Create main class" if it is unchecked.

Disabling right click on images using jquery

The better way of doing this without jQuery:

const images = document.getElementsByTagName('img');
for (let i = 0; i < images.length; i++) {
    images[i].addEventListener('contextmenu', event => event.preventDefault());
}

Remove all items from a FormArray in Angular

You can easily define a getter for your array and clear it as follows:

  formGroup: FormGroup    
  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.formGroup = this.fb.group({
      sliders: this.fb.array([])
    })
  }
  get sliderForms() {
    return this.formGroup.get('sliders') as FormArray
  }

  clearAll() {
    this.formGroup.reset()
    this.sliderForms.clear()
  }

ipynb import another ipynb file

You can use import nbimporter then import notebookName

How to Iterate over a Set/HashSet without an Iterator?

You can use functional operation for a more neat code

Set<String> set = new HashSet<String>();

set.forEach((s) -> {
     System.out.println(s);
});

Make button width fit to the text

I like Roger Cruz's answer of:

width: fit-content;

and I just want to add that you can use

padding: 0px 10px;

to add a nice 10px padding on the right and left side of the text in the button. Otherwise the text would be right up along the edge of the button and that wouldn't look good.

How to deserialize a JObject to .NET object

From the documentation I found this

JObject o = new JObject(
   new JProperty("Name", "John Smith"),
   new JProperty("BirthDate", new DateTime(1983, 3, 20))
);

JsonSerializer serializer = new JsonSerializer();
Person p = (Person)serializer.Deserialize(new JTokenReader(o), typeof(Person));

Console.WriteLine(p.Name);

The class definition for Person should be compatible to the following:

class Person {
    public string Name { get; internal set; }
    public DateTime BirthDate { get; internal set; }
}

Edit

If you are using a recent version of JSON.net and don't need custom serialization, please see TienDo's answer above (or below if you upvote me :P ), which is more concise.

Calculating moving average

You could use RcppRoll for very quick moving averages written in C++. Just call the roll_mean function. Docs can be found here.

Otherwise, this (slower) for loop should do the trick:

ma <- function(arr, n=15){
  res = arr
  for(i in n:length(arr)){
    res[i] = mean(arr[(i-n):i])
  }
  res
}

jQuery Set Selected Option Using Next

$('#my_sel').val($('#my_sel option:selected').next().val());
$('#my_sel').val($('#my_sel option:selected').prev().val());

How to fill background image of an UIView

For Swift 2.1 use this...

    UIGraphicsBeginImageContext(self.view.frame.size)
    UIImage(named: "Cyan.jpg")?.drawInRect(self.view.bounds)

    let image: UIImage! = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

    self.view.backgroundColor = UIColor(patternImage: image)

Add CSS or JavaScript files to layout head from views or partial views

Here is a NuGet plugin called Cassette, which among other things provides you the ability to reference scripts and styles in partials.

Though there are a number of configurations available for this plugin, which makes it highly flexible. Here is the simplest way of referring script or stylesheet files:

Bundles.Reference("scripts/app");

According to the documentation:

Calls to Reference can appear anywhere in a page, layout or partial view.

The path argument can be one of the following:

  • A bundle path
  • An asset path - the whole bundle containing this asset is referenced
  • A URL

How do you get a directory listing sorted by creation date in python?

For completeness with os.scandir (2x faster over pathlib):

import os
sorted(os.scandir('/tmp/test'), key=lambda d: d.stat().st_mtime)

Fetch: POST json data

After spending some times, reverse engineering jsFiddle, trying to generate payload - there is an effect.

Please take eye (care) on line return response.json(); where response is not a response - it is promise.

var json = {
    json: JSON.stringify({
        a: 1,
        b: 2
    }),
    delay: 3
};

fetch('/echo/json/', {
    method: 'post',
    headers: {
        'Accept': 'application/json, text/plain, */*',
        'Content-Type': 'application/json'
    },
    body: 'json=' + encodeURIComponent(JSON.stringify(json.json)) + '&delay=' + json.delay
})
.then(function (response) {
    return response.json();
})
.then(function (result) {
    alert(result);
})
.catch (function (error) {
    console.log('Request failed', error);
});

jsFiddle: http://jsfiddle.net/egxt6cpz/46/ && Firefox > 39 && Chrome > 42

Ruby: How to post a file via HTTP as multipart/form-data?

Ok, here's a simple example using curb.

require 'yaml'
require 'curb'

# prepare post data
post_data = fields_hash.map { |k, v| Curl::PostField.content(k, v.to_s) }
post_data << Curl::PostField.file('file', '/path/to/file'), 

# post
c = Curl::Easy.new('http://localhost:3000/foo')
c.multipart_form_post = true
c.http_post(post_data)

# print response
y [c.response_code, c.body_str]

node.js - request - How to "emitter.setMaxListeners()"?

Try to use:

require('events').EventEmitter.defaultMaxListeners = Infinity; 

How can I run PowerShell with the .NET 4 runtime?

Please be VERY careful with using the registry key approach. These are machine-wide keys and forcibily migrate ALL applications to .NET 4.0.

Many products do not work if forcibily migrated and this is a testing aid and not a production quality mechanism. Visual Studio 2008 and 2010, MSBuild, turbotax, and a host of websites, SharePoint and so on should not be automigrated.

If you need to use PowerShell with 4.0, this should be done on a per-application basis with a configuration file, you should check with the PowerShell team on the precise recommendation. This is likely to break some existing PowerShell commands.

What does a bitwise shift (left or right) do and what is it used for?

Left shift: It is equal to the product of the value which has to be shifted and 2 raised to the power of number of bits to be shifted.

Example:

1 << 3
0000 0001  ---> 1
Shift by 1 bit
0000 0010 ----> 2 which is equal to 1*2^1
Shift By 2 bits
0000 0100 ----> 4 which is equal to 1*2^2
Shift by 3 bits
0000 1000 ----> 8 which is equal to 1*2^3

Right shift: It is equal to quotient of value which has to be shifted by 2 raised to the power of number of bits to be shifted.

Example:

8 >> 3
0000 1000  ---> 8 which is equal to 8/2^0
Shift by 1 bit
0000 0100 ----> 4 which is equal to 8/2^1
Shift By 2 bits
0000 0010 ----> 2 which is equal to 8/2^2
Shift by 3 bits
0000 0001 ----> 1 which is equal to 8/2^3

How do a send an HTTPS request through a proxy in Java?

HTTPS proxy doesn't make sense because you can't terminate your HTTP connection at the proxy for security reasons. With your trust policy, it might work if the proxy server has a HTTPS port. Your error is caused by connecting to HTTP proxy port with HTTPS.

You can connect through a proxy using SSL tunneling (many people call that proxy) using proxy CONNECT command. However, Java doesn't support newer version of proxy tunneling. In that case, you need to handle the tunneling yourself. You can find sample code here,

http://www.javaworld.com/javaworld/javatips/jw-javatip111.html

EDIT: If you want defeat all the security measures in JSSE, you still need your own TrustManager. Something like this,

 public SSLTunnelSocketFactory(String proxyhost, String proxyport){
      tunnelHost = proxyhost;
      tunnelPort = Integer.parseInt(proxyport);
      dfactory = (SSLSocketFactory)sslContext.getSocketFactory();
 }

 ...

 connection.setSSLSocketFactory( new SSLTunnelSocketFactory( proxyHost, proxyPort ) );
 connection.setDefaultHostnameVerifier( new HostnameVerifier()
 {
    public boolean verify( String arg0, SSLSession arg1 )
    {
        return true;
    }
 }  );

EDIT 2: I just tried my program I wrote a few years ago using SSLTunnelSocketFactory and it doesn't work either. Apparently, Sun introduced a new bug sometime in Java 5. See this bug report,

http://bugs.sun.com/view_bug.do?bug_id=6614957

The good news is that the SSL tunneling bug is fixed so you can just use the default factory. I just tried with a proxy and everything works as expected. See my code,

public class SSLContextTest {

    public static void main(String[] args) {

        System.setProperty("https.proxyHost", "proxy.xxx.com");
        System.setProperty("https.proxyPort", "8888");

        try {

            SSLContext sslContext = SSLContext.getInstance("SSL");

            // set up a TrustManager that trusts everything
            sslContext.init(null, new TrustManager[] { new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    System.out.println("getAcceptedIssuers =============");
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] certs,
                        String authType) {
                    System.out.println("checkClientTrusted =============");
                }

                public void checkServerTrusted(X509Certificate[] certs,
                        String authType) {
                    System.out.println("checkServerTrusted =============");
                }
            } }, new SecureRandom());

            HttpsURLConnection.setDefaultSSLSocketFactory(
                    sslContext.getSocketFactory());

            HttpsURLConnection
                    .setDefaultHostnameVerifier(new HostnameVerifier() {
                        public boolean verify(String arg0, SSLSession arg1) {
                            System.out.println("hostnameVerifier =============");
                            return true;
                        }
                    });

            URL url = new URL("https://www.verisign.net");
            URLConnection conn = url.openConnection();
            BufferedReader reader = 
                new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }
}

This is what I get when I run the program,

checkServerTrusted =============
hostnameVerifier =============
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
......

As you can see, both SSLContext and hostnameVerifier are getting called. HostnameVerifier is only involved when the hostname doesn't match the cert. I used "www.verisign.net" to trigger this.

No operator matches the given name and argument type(s). You might need to add explicit type casts. -- Netbeans, Postgresql 8.4 and Glassfish

I had this issue in a very simple DELETE statement, and it is now solved.

My issue was due to using backticks around the column (this column was named "id").

This query DID NOT WORK and resulted in "No operator matches the given name and argument type(s)"

DELETE FROM mytable WHERE `id` = 3      -- DO NOT USE BACKTICKS

Coming from mysql, in dynamic queries, I always `backtick` columns.

The following query DID WORK (with backticks removed):

DELETE FROM mytable WHERE id = 3

Run batch file from Java code

import java.lang.Runtime;

Process run = Runtime.getRuntime().exec("cmd.exe", "/c", "Start", "path of the bat file");

This will work for you and is easy to use.

Can't find @Nullable inside javax.annotation.*

you can add latest version of this by adding following line inside your gradle.build.

implementation group: 'com.google.code.findbugs', name: 'jsr305', version: '3.0.2'

Group list by values

>>> import collections
>>> D1 = collections.defaultdict(list)
>>> for element in L1:
...     D1[element[1]].append(element[0])
... 
>>> L2 = D1.values()
>>> print L2
[['A', 'C'], ['B'], ['D', 'E']]
>>> 

React.js create loop through Array

As @Alexander solves, the issue is one of async data load - you're rendering immediately and you will not have participants loaded until the async ajax call resolves and populates data with participants.

The alternative to the solution they provided would be to prevent render until participants exist, something like this:

    render: function() {
        if (!this.props.data.participants) {
            return null;
        }
        return (
            <ul className="PlayerList">
            // I'm the Player List {this.props.data}
            // <Player author="The Mini John" />
            {
                this.props.data.participants.map(function(player) {
                    return <li key={player}>{player}</li>
                })
            }
            </ul>
        );
    }

How to specify the actual x axis values to plot as x axis ticks in R

Take a closer look at the ?axis documentation. If you look at the description of the labels argument, you'll see that it is:

"a logical value specifying whether (numerical) annotations are 
to be made at the tickmarks,"

So, just change it to true, and you'll get your tick labels.

x <- seq(10,200,10)
y <- runif(x)
plot(x,y,xaxt='n')
axis(side = 1, at = x,labels = T)
# Since TRUE is the default for labels, you can just use axis(side=1,at=x)

Be careful that if you don't stretch your window width, then R might not be able to write all your labels in. Play with the window width and you'll see what I mean.


It's too bad that you had such trouble finding documentation! What were your search terms? Try typing r axis into Google, and the first link you will get is that Quick R page that I mentioned earlier. Scroll down to "Axes", and you'll get a very nice little guide on how to do it. You should probably check there first for any plotting questions, it will be faster than waiting for a SO reply.

Adding Google Play services version to your app's manifest?

I did following steps to recover from this:

1) Import google play services as project into your android sdk. In my system it is found at C:\adt-bundle-windows-x86_64-20140702\sdk\extras\google\google_play_services\libproject\google-play-services_lib

2) Your android application-> properties -> android

In the window

2.1) Click on Google APIs in project build target 2.2) Add google-play services in bottom frame and click on OK

Hope it gives clear instruction on what to do !!

Thanks.

How to echo JSON in PHP

Native JSON support has been included in PHP since 5.2 in the form of methods json_encode() and json_decode(). You would use the first to output a PHP variable in JSON.

Sublime Text 3 how to change the font size of the file sidebar?

You need to change it at "class": "sidebar_label" Example, in your .sublime-theme file:

// Sidebar entry
{
    "class": "sidebar_label",
    "color": [212, 212, 213],
    "shadow_offset": [0, 0],
    "font.size":13
}

Credit

fatal error: Python.h: No such file or directory

If you use a virtualenv with a 3.6 python (edge right now), be sure to install the matching python 3.6 dev sudo apt-get install python3.6-dev, otherwise executing sudo python3-dev will install the python dev 3.3.3-1, which won't solve the issue.

how to check if item is selected from a comboBox in C#

You can try

if(combo1.Text == "")
{

}

What exactly does Perl's "bless" do?

bless associates a reference with a package.

It doesn't matter what the reference is to, it can be to a hash (most common case), to an array (not so common), to a scalar (usually this indicates an inside-out object), to a regular expression, subroutine or TYPEGLOB (see the book Object Oriented Perl: A Comprehensive Guide to Concepts and Programming Techniques by Damian Conway for useful examples) or even a reference to a file or directory handle (least common case).

The effect bless-ing has is that it allows you to apply special syntax to the blessed reference.

For example, if a blessed reference is stored in $obj (associated by bless with package "Class"), then $obj->foo(@args) will call a subroutine foo and pass as first argument the reference $obj followed by the rest of the arguments (@args). The subroutine should be defined in package "Class". If there is no subroutine foo in package "Class", a list of other packages (taken form the array @ISA in the package "Class") will be searched and the first subroutine foo found will be called.