Programs & Examples On #Fieldset

The fieldset tag is used to group related elements in HTML and XHTML documents. The fieldset tag draws a box around the related elements.

Is there any way to have a fieldset width only be as wide as the controls in them?

i fixed my issue by override legend style as Below

.ui-fieldset-legend
{
  font-size: 1.2em;
  font-weight: bold;
  display: inline-block;
  width: auto;`enter code here`
}

Service located in another namespace

It is so simple to do it

if you want to use it as host and want to resolve it

If you are using ambassador to any other API gateway for service located in another namespace it's always suggested to use :

            Use : <service name>
            Use : <service.name>.<namespace name>
            Not : <service.name>.<namespace name>.svc.cluster.local

it will be like : servicename.namespacename.svc.cluster.local

this will send request to a particular service inside the namespace you have mention.

example:

kind: Service
apiVersion: v1
metadata:
  name: service
spec:
  type: ExternalName
  externalName: <servicename>.<namespace>.svc.cluster.local

Here replace the <servicename> and <namespace> with the appropriate value.

In Kubernetes, namespaces are used to create virtual environment but all are connect with each other.

Why does flexbox stretch my image rather than retaining aspect ratio?

I faced the same issue with a Foundation menu. align-self: center; didn't work for me.

My solution was to wrap the image with a <div style="display: inline-table;">...</div>

How do I use CMake?

Yes, cmake and make are different programs. cmake is (on Linux) a Makefile generator (and Makefile-s are the files driving the make utility). There are other Makefile generators (in particular configure and autoconf etc...). And you can find other build automation programs (e.g. ninja).

HTML Form: Select-Option vs Datalist-Option

Datalist includes autocomplete and suggestions natively, it can also allow a user to enter a value that is not defined in the suggestions.

Select only gives you pre-defined options the user has to select from

How to redirect siteA to siteB with A or CNAME records

Try changing it to "subdomain -> subdomain.hosttwo.com"

The CNAME is an alias for a certain domain, so when you go to the control panel for hostone.com, you shouldn't have to enter the whole name into the CNAME alias.

As far as the error you are getting, can you log onto subdomain.hostwo.com and check the logs?

How to programmatically round corners and set random background colors

Copying @cimlman's comment into a top-level answer for more visibility:

PaintDrawable(Color.CYAN).apply {
  setCornerRadius(24f)
}

FYI: ShapeDrawable (and its subtype, PaintDrawable) uses default intrinsic width and height of 0. If the drawable does not show up in your usecase, you might have to set the dimensions manually:

PaintDrawable(Color.CYAN).apply {
  intrinsicWidth = -1
  intrinsicHeight = -1
  setCornerRadius(24f)
}

-1 is a magic constant which indicates that a Drawable has no intrinsic width and height of its own (Source).

Postgres ERROR: could not open file for reading: Permission denied

You must grant the pg_read_server_files permission to the user if you are not using postgres superuser.

Example:

GRANT pg_read_server_files TO my_user WITH ADMIN OPTION;

Using <style> tags in the <body> with other HTML

As others have already mentioned, HTML 4 requires the <style> tag to be placed in the <head> section (even though most browsers allow <style> tags within the body).

However, HTML 5 includes the scoped attribute (see update below), which allows you to create style sheets that are scoped within the parent element of the <style> tag. This also enables you to place <style> tags within the <body> element:

<!DOCTYPE html>
<html>
<head></head>
<body>

<div id="scoped-content">
    <style type="text/css" scoped>
        h1 { color: red; } 
    </style>

    <h1>Hello</h1>
</div>

    <h1>
      World
    </h1>

</body>
</html>

If you render the above code in an HTML-5 enabled browser that supports scoped, you will see the limited scope of the style sheet.

There's just one major caveat...

At the time I'm writing this answer (May, 2013) almost no mainstream browser currently supports the scoped attribute. (Although apparently developer builds of Chromium support it.)

HOWEVER, there is an interesting implication of the scoped attribute that pertains to this question. It means that future browsers are mandated via the standard to allow <style> elements within the <body> (as long as the <style> elements are scoped.)

So, given that:

  • Almost every existing browser currently ignores the scoped attribute
  • Almost every existing browser currently allows <style> tags within the <body>
  • Future implementations will be required to allow (scoped) <style> tags within the <body>

...then there is literally no harm * in placing <style> tags within the body, as long as you future proof them with a scoped attribute. The only problem is that current browsers won't actually limit the scope of the stylesheet - they'll apply it to the whole document. But the point is that, for all practical purposes, you can include <style> tags within the <body> provided that you:

  • Future-proof your HTML by including the scoped attribute
  • Understand that as of now, the stylesheet within the <body> will not actually be scoped (because no mainstream browser support exists yet)


* except of course, for pissing off HTML validators...


Finally, regarding the common (but subjective) claim that embedding CSS within HTML is poor practice, it should be noted that the whole point of the scoped attribute is to accommodate typical modern development frameworks that allow developers to import chunks of HTML as modules or syndicated content. It is very convenient to have embedded CSS that only applies to a particular chunk of HTML, in order to develop encapsulated, modular components with specific stylings.


Update as of Feb 2019, according to the Mozilla documentation, the scoped attribute is deprecated. Chrome stopped supporting it in version 36 (2014) and Firefox in version 62 (2018). In both cases, the feature had to be explicitly enabled by the user in the browsers' settings. No other major browser ever supported it.

How do I discover memory usage of my application in Android?

1) I guess not, at least not from Java.
2)

ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
MemoryInfo mi = new MemoryInfo();
activityManager.getMemoryInfo(mi);
Log.i("memory free", "" + mi.availMem);

Suppress warning messages using mysql from within Terminal, but password written in bash script

You can also just redirect the standard error STDERR output to /dev/null

So just do:

mysql -u $user -p$password -e "statement" 2> /dev/null

How to write unit testing for Angular / TypeScript for private methods with Jasmine

I agree with @toskv: I wouldn't recommend to do that:-)

But if you really want to test your private method, you can be aware that the corresponding code for the TypeScript correspond to a method of the constructor function prototype. This means that it can be used at runtime (whereas you will probably have some compilation errors).

For example:

export class FooBar {
  private _status: number;

  constructor( private foo : Bar ) {
    this.initFooBar({});
  }

  private initFooBar(data){
    this.foo.bar( data );
    this._status = this.foo.foo();
  }
}

will be transpiled into:

(function(System) {(function(__moduleName){System.register([], function(exports_1, context_1) {
  "use strict";
  var __moduleName = context_1 && context_1.id;
  var FooBar;
  return {
    setters:[],
    execute: function() {
      FooBar = (function () {
        function FooBar(foo) {
          this.foo = foo;
          this.initFooBar({});
        }
        FooBar.prototype.initFooBar = function (data) {
          this.foo.bar(data);
          this._status = this.foo.foo();
        };
        return FooBar;
      }());
      exports_1("FooBar", FooBar);
    }
  }
})(System);

See this plunkr: https://plnkr.co/edit/calJCF?p=preview.

Starting the week on Monday with isoWeekday()

thought I would add this for any future peeps. It will always make sure that its monday if needed, can also be used to always ensure sunday. For me I always need monday, but local is dependant on the machine being used, and this is an easy fix:

var begin = moment().isoWeekday(1).startOf('week');
var begin2 = moment().startOf('week');
// could check to see if day 1 = Sunday  then add 1 day
// my mac on bst still treats day 1 as sunday    

var firstDay = moment().startOf('week').format('dddd') === 'Sunday' ?     
moment().startOf('week').add('d',1).format('dddd DD-MM-YYYY') : 
moment().startOf('week').format('dddd DD-MM-YYYY');

document.body.innerHTML = '<b>could be monday or sunday depending on client: </b><br />' + 
begin.format('dddd DD-MM-YYYY') + 
'<br /><br /> <b>should be monday:</b> <br>' + firstDay + 
'<br><br> <b>could also be sunday or monday </b><br> ' + 
begin2.format('dddd DD-MM-YYYY');

Iterating through list of list in Python

two nested for loops?

 for a in x:
     print "--------------"
     for b in a:
             print b

It would help if you gave an example of what you want to do with the lists

jquery $.each() for objects

Basically you need to do two loops here. The one you are doing already is iterating each element in the 0th array element.

You have programs: [ {...}, {...} ] so programs[0] is { "name":"zonealarm", "price":"500" } So your loop is just going over that.

You could do an outer loop over the array

$.each(data.programs, function(index) {

    // then loop over the object elements
    $.each(data.programs[index], function(key, value) {
        console.log(key + ": " + value);
    }

}

Nested ifelse statement

With data.table, the solutions is:

DT[, idnat2 := ifelse(idbp %in% "foreign", "foreign", 
        ifelse(idbp %in% c("colony", "overseas"), "overseas", "mainland" ))]

The ifelse is vectorized. The if-else is not. Here, DT is:

    idnat     idbp
1  french mainland
2  french   colony
3  french overseas
4 foreign  foreign

This gives:

   idnat     idbp   idnat2
1:  french mainland mainland
2:  french   colony overseas
3:  french overseas overseas
4: foreign  foreign  foreign

React won't load local images

Here is what worked for me. First, let us understand the problem. You cannot use a variable as argument to require. Webpack needs to know what files to bundle at compile time.

When I got the error, I thought it may be related to path issue as in absolute vs relative. So I passed a hard-coded value to require like below: <img src={require("../assets/images/photosnap.svg")} alt="" />. It was working fine. But in my case the value is a variable coming from props. I tried to pass a string literal variable as some suggested. It did not work. Also I tried to define a local method using switch case for all 10 values (I knew it was not best solution, but I just wanted it to work somehow). That too did not work. Then I came to know that we can NOT pass variable to the require.

As a workaround I have modified the data in the data.json file to confine it to just the name of my image. This image name which is coming from the props as a String literal. I concatenated it to the hard coded value, like so:

import React from "react";

function JobCard(props) {  

  const { logo } = props;
  
  return (
      <div className="jobCards">
          <img src={require(`../assets/images/${logo}`)} alt="" /> 
      </div>
    )
} 
  

The actual value contained in the logo would be coming from data.json file and would refer to some image name like photosnap.svg.

Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response

In Post API call we are sending data in request body. So if we will send data by adding any extra header to an API call. Then first OPTIONS API call will happen and then post call will happen. Therefore, you have to handle OPTION API call first.

You can handle the issue by writing a filter and inside that you have to check for option call API call and return a 200 OK status. Below is the sample code:

package com.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.connector.Response;

public class CustomFilter implements Filter {
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest httpRequest = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type");
        if (httpRequest.getMethod().equalsIgnoreCase("OPTIONS")) {
            response.setStatus(Response.SC_OK);
        }
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {
        // TODO
    }

    public void destroy() {
        // Todo
    }

}

Can not find module “@angular-devkit/build-angular”

D:project/contactlist npm install then D:project/contactlist ng new client

D:project/contactlist/client ng serve

this worked for me for some reason i had to delete the client folder and start npm install from the contactlist folder. i tried every thing even clearing the cache and finally this worked.

How to add anything in <head> through jquery/javascript?

In the latest browsers (IE9+) you can also use document.head:

Example:

var favicon = document.createElement('link');
favicon.id = 'myFavicon';
favicon.rel = 'shortcut icon';
favicon.href = 'http://www.test.com/my-favicon.ico';

document.head.appendChild(favicon);

Error 'LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt' after installing Visual Studio 2012 Release Preview

Check the version of cvtrs.exe:

dir "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\cvtres.exe"

Wrong version:
date: 03/18/2010
time: 01:16 PM
size: 31,048 bytes
name: cvtres.exe

Correct version:
date: 02/21/2011
time: 06:03 PM
size: 31,056 bytes
name: cvtres.exe

If you have wrong version you should copy the correct version from:

C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin\cvtres.exe

and replace the one here:

C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\cvtres.exe

i.e.

copy "C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin\cvtres.exe" "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\cvtres.exe"

How to check what version of jQuery is loaded?

if (typeof jQuery != 'undefined') {  
    // jQuery is loaded => print the version
    alert(jQuery.fn.jquery);
}

Splitting on first occurrence

You can also use str.partition:

>>> text = "123mango abcd mango kiwi peach"

>>> text.partition("mango")
('123', 'mango', ' abcd mango kiwi peach')

>>> text.partition("mango")[-1]
' abcd mango kiwi peach'

>>> text.partition("mango")[-1].lstrip()  # if whitespace strip-ing is needed
'abcd mango kiwi peach'

The advantage of using str.partition is that it's always gonna return a tuple in the form:

(<pre>, <separator>, <post>)

So this makes unpacking the output really flexible as there's always going to be 3 elements in the resulting tuple.

How do I use method overloading in Python?

Python 3.x includes standard typing library which allows for method overloading with the use of @overload decorator. Unfortunately, this is to make the code more readable, as the @overload decorated methods will need to be followed by a non-decorated method that handles different arguments. More can be found here here but for your example:

from typing import overload
from typing import Any, Optional
class A(object):
    @overload
    def stackoverflow(self) -> None:    
        print('first method')
    @overload
    def stackoverflow(self, i: Any) -> None:
        print('second method', i)
    def stackoverflow(self, i: Optional[Any] = None) -> None:
        if not i:
            print('first method')
        else:
            print('second method', i)

ob=A()
ob.stackoverflow(2)

Getting and removing the first character of a string

substring is definitely best, but here's one strsplit alternative, since I haven't seen one yet.

> x <- 'hello stackoverflow'
> strsplit(x, '')[[1]][1]
## [1] "h"

or equivalently

> unlist(strsplit(x, ''))[1]
## [1] "h"

And you can paste the rest of the string back together.

> paste0(strsplit(x, '')[[1]][-1], collapse = '')
## [1] "ello stackoverflow"

Execute CMD command from code

As mentioned by the other answers you can use:

  Process.Start("notepad somefile.txt");

However, there is another way.

You can instance a Process object and call the Start instance method:

  Process process = new Process();
  process.StartInfo.FileName = "notepad.exe";
  process.StartInfo.WorkingDirectory = "c:\temp";
  process.StartInfo.Arguments = "somefile.txt";
  process.Start();

Doing it this way allows you to configure more options before starting the process. The Process object also allows you to retrieve information about the process whilst it is executing and it will give you a notification (via the Exited event) when the process has finished.

Addition: Don't forget to set 'process.EnableRaisingEvents' to 'true' if you want to hook the 'Exited' event.

Login with facebook android sdk app crash API 4

The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):

Mikhail,

The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.

Good luck with your implementation.

How to center an image horizontally and align it to the bottom of the container?

have you tried:

.image_block{
text-align: center;
vertical-align: bottom;
}

Embedding Windows Media Player for all browsers

You could use conditional comments to get IE and Firefox to do different things

<![if !IE]>
<p> Firefox only code</p>
<![endif]>

<!--[if IE]>
<p>Internet Explorer only code</p>
<![endif]-->

The browsers themselves will ignore code that isn't meant for them to read.

How to use GROUP BY to concatenate strings in SQL Server?

I ran into a couple of problems when I tried converting Kevin Fairchild's suggestion to work with strings containing spaces and special XML characters (&, <, >) which were encoded.

The final version of my code (which doesn't answer the original question but may be useful to someone) looks like this:

CREATE TABLE #YourTable ([ID] INT, [Name] VARCHAR(MAX), [Value] INT)

INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'Oranges & Lemons',4)
INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'1 < 2',8)
INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (2,'C',9)

SELECT  [ID],
  STUFF((
    SELECT ', ' + CAST([Name] AS VARCHAR(MAX))
    FROM #YourTable WHERE (ID = Results.ID) 
    FOR XML PATH(''),TYPE 
     /* Use .value to uncomment XML entities e.g. &gt; &lt; etc*/
    ).value('.','VARCHAR(MAX)') 
  ,1,2,'') as NameValues
FROM    #YourTable Results
GROUP BY ID

DROP TABLE #YourTable

Rather than using a space as a delimiter and replacing all the spaces with commas, it just pre-pends a comma and space to each value then uses STUFF to remove the first two characters.

The XML encoding is taken care of automatically by using the TYPE directive.

How to change xampp localhost to another folder ( outside xampp folder)?

Please follow @Sourav's advice.

If after restarting the server you get errors, you may need to set your directory options as well. This is done in the <Directory> tag in httpd.conf. Make sure the final config looks like this:

DocumentRoot "C:\alan"
<Directory "C:\alan">
    Options Indexes FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>

Mongod complains that there is no /data/db folder

To fix that error on OS X, I restarted and stopped the service: $ brew services restart mongodb $ brew services stop mongodb

Then I ran mongod --config /usr/local/etc/mongod.conf, and the problem was gone.

The error seemed to arise after upgrading the mongodb homebrew package.

Babel command not found

For those using Yarn as their package manager instead of npm:

yarn global add babel-cli

With ng-bind-html-unsafe removed, how do I inject HTML?

  1. You need to make sure that sanitize.js is loaded. For example, load it from https://ajax.googleapis.com/ajax/libs/angularjs/[LAST_VERSION]/angular-sanitize.min.js
  2. you need to include ngSanitize module on your app eg: var app = angular.module('myApp', ['ngSanitize']);
  3. you just need to bind with ng-bind-html the original html content. No need to do anything else in your controller. The parsing and conversion is automatically done by the ngBindHtml directive. (Read the How does it work section on this: $sce). So, in your case <div ng-bind-html="preview_data.preview.embed.html"></div> would do the work.

How to merge a list of lists with same type of items to a single list of items?

Use the SelectMany extension method

list = listOfList.SelectMany(x => x).ToList();

Two Radio Buttons ASP.NET C#

Set the GroupName property of both radio buttons to the same value. You could also try using a RadioButtonGroup, which does this for you automatically.

error: member access into incomplete type : forward declaration of

You must have the definition of class B before you use the class. How else would the compiler otherwise know that there exists such a function as B::add?

Either define class B before class A, or move the body of A::doSomething to after class B have been defined, like

class B;

class A
{
    B* b;

    void doSomething();
};

class B
{
    A* a;

    void add() {}
};

void A::doSomething()
{
    b->add();
}

SQL select max(date) and corresponding value

You can use a subquery. The subquery will get the Max(CompletedDate). You then take this value and join on your table again to retrieve the note associate with that date:

select ET1.TrainingID,
  ET1.CompletedDate,
  ET1.Notes
from HR_EmployeeTrainings ET1
inner join
(
  select Max(CompletedDate) CompletedDate, TrainingID
  from HR_EmployeeTrainings
  --where AvantiRecID IS NULL OR AvantiRecID = @avantiRecID
  group by TrainingID
) ET2
  on ET1.TrainingID = ET2.TrainingID
  and ET1.CompletedDate = ET2.CompletedDate
where ET1.AvantiRecID IS NULL OR ET1.AvantiRecID = @avantiRecID

How do I check if an array includes a value in JavaScript?

Update from 2019: This answer is from 2008 (11 years old!) and is not relevant for modern JS usage. The promised performance improvement was based on a benchmark done in browsers of that time. It might not be relevant to modern JS execution contexts. If you need an easy solution, look for other answers. If you need the best performance, benchmark for yourself in the relevant execution environments.

As others have said, the iteration through the array is probably the best way, but it has been proven that a decreasing while loop is the fastest way to iterate in JavaScript. So you may want to rewrite your code as follows:

function contains(a, obj) {
    var i = a.length;
    while (i--) {
       if (a[i] === obj) {
           return true;
       }
    }
    return false;
}

Of course, you may as well extend Array prototype:

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
}

And now you can simply use the following:

alert([1, 2, 3].contains(2)); // => true
alert([1, 2, 3].contains('2')); // => false

How to find the lowest common ancestor of two nodes in any binary tree?

Code for A Breadth First Search to make sure both nodes are in the tree. Only then move forward with the LCA search. Please comment if you have any suggestions to improve. I think we can probably mark them visited and restart the search at a certain point where we left off to improve for the second node (if it isn't found VISITED)

public class searchTree {
    static boolean v1=false,v2=false;
    public static boolean bfs(Treenode root, int value){
         if(root==null){
           return false;
     }
    Queue<Treenode> q1 = new LinkedList<Treenode>();

    q1.add(root);
    while(!q1.isEmpty())
    {
        Treenode temp = q1.peek();

        if(temp!=null) {
            q1.remove();
            if (temp.value == value) return true;
            if (temp.left != null) q1.add(temp.left);
            if (temp.right != null) q1.add(temp.right);
        }
    }
    return false;

}
public static Treenode lcaHelper(Treenode head, int x,int y){

    if(head==null){
        return null;
    }

    if(head.value == x || head.value ==y){
        if (head.value == y){
            v2 = true;
            return head;
        }
        else {
            v1 = true;
            return head;
        }
    }

    Treenode left = lcaHelper(head.left, x, y);
    Treenode right = lcaHelper(head.right,x,y);

    if(left!=null && right!=null){
        return head;
    }
    return (left!=null) ? left:right;
}

public static int lca(Treenode head, int h1, int h2) {
    v1 = bfs(head,h1);
    v2 = bfs(head,h2);
    if(v1 && v2){
        Treenode lca = lcaHelper(head,h1,h2);
        return lca.value;
    }
    return -1;
}
}

Create SQL script that create database and tables

In SQL Server Management Studio you can right click on the database you want to replicate, and select "Script Database as" to have the tool create the appropriate SQL file to replicate that database on another server. You can repeat this process for each table you want to create, and then merge the files into a single SQL file. Don't forget to add a using statement after you create your Database but prior to any table creation.

In more recent versions of SQL Server you can get this in one file in SSMS.

  1. Right click a database.
  2. Tasks
  3. Generate Scripts

This will launch a wizard where you can script the entire database or just portions. There does not appear to be a T-SQL way of doing this.

Generate SQL Server Scripts

How to put multiple statements in one line?

For a python -c oriented solution, and provided you use Bash shell, yes you can have a simple one-line syntax like in this example:

Suppose you would like to do something like this (very similar to your sample, including except: pass instruction):

python -c  "from __future__ import print_function\ntry: import numpy; print( numpy.get_include(), end='\n' )\nexcept:pass\n" OUTPUT_VARIABLE __numpy_path

This will NOT work and produce this Error:

  File "<string>", line 1
    from __future__ import print_function\ntry: import numpy; print( numpy.get_include(), end='\n' )\nexcept:pass\n
                                                                                                                  ^
SyntaxError: unexpected character after line continuation character `

This is because the competition between Bash and Python Interpretation of \n escape sequences. To solve the problem one can use the $'string' Bash syntax to force \n Bash interpretation BEFORE the Python one. To make the example more challenging I added a typical Python end=..\n.. specification in the Python print call: at the end you will be able to get BOTH \n interpretations from bash and Python working together, each on its piece of text of concern. So that finally the proper solution is like this :

python -c  $'from __future__ import print_function\ntry:\n import numpy;\n print( numpy.get_include(), end="\\n" )\n print( "Hello" )\nexcept:pass\n' OUTPUT_VARIABLE __numpy_path

That leads to the proper clean output with no error:

/Softs/anaconda/lib/python3.7/site-packages/numpy/core/include
Hello

Note: this should work as well with exec oriented solutions, because the problem is still the same (Bash and Python interpreters competition).

Note2: one could workaround the problem by replacing some \n by some ; but it will not work anytime (depending on Python constructs), while my solution allows to always "one-line" any piece of classic multi-line Python program.

Note3: of course, when one-lining, one has always to take care of Python spaces and indentation, because in fact we are not strictly "one-lining" here, BUT doing a proper mixed-management of \n escape sequence between bash and Python. This is how we can deal with any piece of classic multi-line Python program. The solution sample illustrates this as well.

Defining a variable with or without export

export will make the variable available to all shells forked from the current shell.

How do I 'foreach' through a two-dimensional array?

Here's a simple extension method that returns each row as an IEnumerable<T>. This has the advantage of not using any extra memory:

public static class Array2dExt
{
    public static IEnumerable<IEnumerable<T>> Rows<T>(this T[,] array)
    {
        for (int r = array.GetLowerBound(0); r <= array.GetUpperBound(0); ++r)
            yield return row(array, r);
    }

    static IEnumerable<T> row<T>(T[,] array, int r)
    {
        for (int c = array.GetLowerBound(1); c <= array.GetUpperBound(1); ++c)
            yield return array[r, c];
    }
}

Sample usage:

static void Main()
{
    string[,] siblings = { { "Mike", "Amy" }, { "Mary", "Albert" }, {"Fred", "Harry"} };

    foreach (var row in siblings.Rows())
        Console.WriteLine("{" + string.Join(", ", row) + "}");
}

How to resolve compiler warning 'implicit declaration of function memset'

A good way to findout what header file you are missing:

 man <section> <function call>

To find out the section use:

apropos <function call>

Example:

 man 3 memset
 man 2 send

Edit in response to James Morris:

  • Section | Description
  • 1 General commands
  • 2 System calls
  • 3 C library functions
  • 4 Special files (usually devices, those found in /dev) and drivers
  • 5 File formats and conventions
  • 6 Games and screensavers
  • 7 Miscellanea
  • 8 System administration commands and daemons

Source: Wikipedia Man Page

Create new XML file and write data to it?

PHP has several libraries for XML Manipulation.

The Document Object Model (DOM) approach (which is a W3C standard and should be familiar if you've used it in other environments such as a Web Browser or Java, etc). Allows you to create documents as follows

<?php
    $doc = new DOMDocument( );
    $ele = $doc->createElement( 'Root' );
    $ele->nodeValue = 'Hello XML World';
    $doc->appendChild( $ele );
    $doc->save('MyXmlFile.xml');
?>

Even if you haven't come across the DOM before, it's worth investing some time in it as the model is used in many languages/environments.

Keeping ASP.NET Session Open / Alive

If you are using ASP.NET MVC – you do not need an additional HTTP handler and some modifications of the web.config file. All you need – just to add some simple action in a Home/Common controller:

[HttpPost]
public JsonResult KeepSessionAlive() {
    return new JsonResult {Data = "Success"};
}

, write a piece of JavaScript code like this one (I have put it in one of site’s JavaScript file):

var keepSessionAlive = false;
var keepSessionAliveUrl = null;

function SetupSessionUpdater(actionUrl) {
    keepSessionAliveUrl = actionUrl;
    var container = $("#body");
    container.mousemove(function () { keepSessionAlive = true; });
    container.keydown(function () { keepSessionAlive = true; });
    CheckToKeepSessionAlive();
}

function CheckToKeepSessionAlive() {
    setTimeout("KeepSessionAlive()", 5*60*1000);
}

function KeepSessionAlive() {
    if (keepSessionAlive && keepSessionAliveUrl != null) {
        $.ajax({
            type: "POST",
            url: keepSessionAliveUrl,
            success: function () { keepSessionAlive = false; }
        });
    }
    CheckToKeepSessionAlive();
}

, and initialize this functionality by calling a JavaScript function:

SetupSessionUpdater('/Home/KeepSessionAlive');

Please note! I have implemented this functionality only for authorized users (there is no reason to keep session state for guests in most cases) and decision to keep session state active is not only based on – is browser open or not, but authorized user must do some activity on the site (move a mouse or type some key).

How to scroll HTML page to given anchor?

a vue2 solution ... add simple data property to simply force the update

  const app = new Vue({ 
  ... 

  , updated: function() {
           this.$nextTick(function() {
           var uri = window.location.href
           var anchor = ( uri.indexOf('#') === -1 ) ? '' : uri.split('#')[1]
           if ( String(anchor).length > 0 && this.updater === 'page_load' ) {
              this.updater = "" // only on page-load !
              location.href = "#"+String(anchor)
           }
         })
        }
     });
     app.updater = "page_load"

 /* smooth scrolling in css - works in html5 only */
 html, body {
     scroll-behavior: smooth;
 }

AngularJS - Building a dynamic table based on a json

<table class="table table-striped table-condensed table-hover">
    <thead>
    <tr>
        <th ng-repeat="header in headers | filter:headerFilter | orderBy:headerOrder" width="{{header.width}}">{{header.label}}</th>
    </tr>
    </thead>
    <tbody>
    <tr ng-repeat="user in users" ng-class-odd="'trOdd'" ng-class-even="'trEven'" ng-dblclick="rowDoubleClicked(user)">
        <td ng-repeat="(key,val) in user | orderBy:userOrder(key)">{{val}}</td>
    </tr>
    </tbody>
    <tfoot>

    </tfoot>
</table>

refer this https://gist.github.com/ebellinger/4399082

Objective-C Static Class Level variables

u can rename the class as classA.mm and add C++ features in it.

Php - Your PHP installation appears to be missing the MySQL extension which is required by WordPress

When you upgarde your php version, make sure, apache2 follows. You can create a phpinfo() file which could show that apache is still using the old php version.

In this case you should use the a2dismod php-old-version and a2enmon php-mod-version commands

Exemple :

in ubuntu, your grab the old version from /etc/apache2/mods-enabled, or from the version shown by the phpinfo file, and you grab the new one from /etc/apache2/mods-available

> sudo a2dismod php5.6
> sudo a2enmod php7.1
> sudo service apache2 restart

How do I resolve a TesseractNotFoundError?

One simple thing that actually worked for me in Jupyter Notebook, was using double backslash instead of a single backslash in the pytesseract.pytesseract.tesseract_cmd path:

pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe'

How to rename a file using svn?

This message will appear if you are using a case-insensitive file system (e.g. on a Mac) and you're trying to capitalize the name (or another change of case). In which case you need to rename to a third, dummy, name:

svn mv file-name file-name_
svn mv file-name_ FILE_Name
svn commit

ComboBox: Adding Text and Value to an Item (no Binding Source)

You must create your own class type and override the ToString() method to return the text you want. Here is a simple example of a class you can use:

public class ComboboxItem
{
    public string Text { get; set; }
    public object Value { get; set; }

    public override string ToString()
    {
        return Text;
    }
}

The following is a simple example of its usage:

private void Test()
{
    ComboboxItem item = new ComboboxItem();
    item.Text = "Item text1";
    item.Value = 12;

    comboBox1.Items.Add(item);

    comboBox1.SelectedIndex = 0;

    MessageBox.Show((comboBox1.SelectedItem as ComboboxItem).Value.ToString());
}

How to change facet labels?

Here's how I did it with facet_grid(yfacet~xfacet) using ggplot2, version 2.2.1:

facet_grid(
    yfacet~xfacet,
    labeller = labeller(
        yfacet = c(`0` = "an y label", `1` = "another y label"),
        xfacet = c(`10` = "an x label", `20` = "another x label")
    )
)

Note that this does not contain a call to as_labeller() -- something that I struggled with for a while.

This approach is inspired by the last example on the help page Coerce to labeller function.

X-Frame-Options Allow-From multiple domains

Necromancing.
The provided answers are incomplete.

First, as already said, you cannot add multiple allow-from hosts, that's not supported.
Second, you need to dynamically extract that value from the HTTP referrer, which means that you can't add the value to Web.config, because it's not always the same value.

It will be necessary to do browser-detection to avoid adding allow-from when the browser is Chrome (it produces an error on the debug - console, which can quickly fill the console up, or make the application slow). That also means you need to modify the ASP.NET browser detection, as it wrongly identifies Edge as Chrome.

This can be done in ASP.NET by writing a HTTP-module which runs on every request, that appends a http-header for every response, depending on the request's referrer. For Chrome, it needs to add Content-Security-Policy.

// https://stackoverflow.com/questions/31870789/check-whether-browser-is-chrome-or-edge
public class BrowserInfo
{

    public System.Web.HttpBrowserCapabilities Browser { get; set; }
    public string Name { get; set; }
    public string Version { get; set; }
    public string Platform { get; set; }
    public bool IsMobileDevice { get; set; }
    public string MobileBrand { get; set; }
    public string MobileModel { get; set; }


    public BrowserInfo(System.Web.HttpRequest request)
    {
        if (request.Browser != null)
        {
            if (request.UserAgent.Contains("Edge")
                && request.Browser.Browser != "Edge")
            {
                this.Name = "Edge";
            }
            else
            {
                this.Name = request.Browser.Browser;
                this.Version = request.Browser.MajorVersion.ToString();
            }
            this.Browser = request.Browser;
            this.Platform = request.Browser.Platform;
            this.IsMobileDevice = request.Browser.IsMobileDevice;
            if (IsMobileDevice)
            {
                this.Name = request.Browser.Browser;
            }
        }
    }


}


void context_EndRequest(object sender, System.EventArgs e)
{
    if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Response != null)
    {
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;

        try
        {
            // response.Headers["P3P"] = "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"":
            // response.Headers.Set("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");
            // response.AddHeader("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");
            response.AppendHeader("P3P", "CP=\\\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\\\"");

            // response.AppendHeader("X-Frame-Options", "DENY");
            // response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
            // response.AppendHeader("X-Frame-Options", "AllowAll");

            if (System.Web.HttpContext.Current.Request.UrlReferrer != null)
            {
                // "X-Frame-Options": "ALLOW-FROM " Not recognized in Chrome 
                string host = System.Web.HttpContext.Current.Request.UrlReferrer.Scheme + System.Uri.SchemeDelimiter
                            + System.Web.HttpContext.Current.Request.UrlReferrer.Authority
                ;

                string selfAuth = System.Web.HttpContext.Current.Request.Url.Authority;
                string refAuth = System.Web.HttpContext.Current.Request.UrlReferrer.Authority;

                // SQL.Log(System.Web.HttpContext.Current.Request.RawUrl, System.Web.HttpContext.Current.Request.UrlReferrer.OriginalString, refAuth);

                if (IsHostAllowed(refAuth))
                {
                    BrowserInfo bi = new BrowserInfo(System.Web.HttpContext.Current.Request);

                    // bi.Name = Firefox
                    // bi.Name = InternetExplorer
                    // bi.Name = Chrome

                    // Chrome wants entire path... 
                    if (!System.StringComparer.OrdinalIgnoreCase.Equals(bi.Name, "Chrome"))
                        response.AppendHeader("X-Frame-Options", "ALLOW-FROM " + host);    

                    // unsafe-eval: invalid JSON https://github.com/keen/keen-js/issues/394
                    // unsafe-inline: styles
                    // data: url(data:image/png:...)

                    // https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet
                    // https://www.ietf.org/rfc/rfc7034.txt
                    // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
                    // https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP

                    // https://stackoverflow.com/questions/10205192/x-frame-options-allow-from-multiple-domains
                    // https://content-security-policy.com/
                    // http://rehansaeed.com/content-security-policy-for-asp-net-mvc/

                    // This is for Chrome:
                    // response.AppendHeader("Content-Security-Policy", "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: *.msecnd.net vortex.data.microsoft.com " + selfAuth + " " + refAuth);


                    System.Collections.Generic.List<string> ls = new System.Collections.Generic.List<string>();
                    ls.Add("default-src");
                    ls.Add("'self'");
                    ls.Add("'unsafe-inline'");
                    ls.Add("'unsafe-eval'");
                    ls.Add("data:");

                    // http://az416426.vo.msecnd.net/scripts/a/ai.0.js

                    // ls.Add("*.msecnd.net");
                    // ls.Add("vortex.data.microsoft.com");

                    ls.Add(selfAuth);
                    ls.Add(refAuth);

                    string contentSecurityPolicy = string.Join(" ", ls.ToArray());
                    response.AppendHeader("Content-Security-Policy", contentSecurityPolicy);
                }
                else
                {
                    response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
                }

            }
            else
                response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
        }
        catch (System.Exception ex)
        {
            // WTF ? 
            System.Console.WriteLine(ex.Message); // Suppress warning
        }

    } // End if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Response != null)

} // End Using context_EndRequest


private static string[] s_allowedHosts = new string[] 
{
     "localhost:49533"
    ,"localhost:52257"
    ,"vmcompany1"
    ,"vmcompany2"
    ,"vmpostalservices"
    ,"example.com"
};


public static bool IsHostAllowed(string host)
{
    return Contains(s_allowedHosts, host);
} // End Function IsHostAllowed 


public static bool Contains(string[] allowed, string current)
{
    for (int i = 0; i < allowed.Length; ++i)
    {
        if (System.StringComparer.OrdinalIgnoreCase.Equals(allowed[i], current))
            return true;
    } // Next i 

    return false;
} // End Function Contains 

You need to register the context_EndRequest function in the HTTP-module Init function.

public class RequestLanguageChanger : System.Web.IHttpModule
{


    void System.Web.IHttpModule.Dispose()
    {
        // throw new NotImplementedException();
    }


    void System.Web.IHttpModule.Init(System.Web.HttpApplication context)
    {
        // https://stackoverflow.com/questions/441421/httpmodule-event-execution-order
        context.EndRequest += new System.EventHandler(context_EndRequest);
    }

    // context_EndRequest Code from above comes here


}

Next you need to add the module to your application. You can either do this programmatically in Global.asax by overriding the Init function of the HttpApplication, like this:

namespace ChangeRequestLanguage
{


    public class Global : System.Web.HttpApplication
    {

        System.Web.IHttpModule mod = new libRequestLanguageChanger.RequestLanguageChanger();

        public override void Init()
        {
            mod.Init(this);
            base.Init();
        }



        protected void Application_Start(object sender, System.EventArgs e)
        {

        }

        protected void Session_Start(object sender, System.EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, System.EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, System.EventArgs e)
        {

        }

        protected void Application_Error(object sender, System.EventArgs e)
        {

        }

        protected void Session_End(object sender, System.EventArgs e)
        {

        }

        protected void Application_End(object sender, System.EventArgs e)
        {

        }


    }


}

or you can add entries to Web.config if you don't own the application source-code:

      <httpModules>
        <add name="RequestLanguageChanger" type= "libRequestLanguageChanger.RequestLanguageChanger, libRequestLanguageChanger" />
      </httpModules>
    </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>

    <modules runAllManagedModulesForAllRequests="true">
      <add name="RequestLanguageChanger" type="libRequestLanguageChanger.RequestLanguageChanger, libRequestLanguageChanger" />
    </modules>
  </system.webServer>
</configuration>

The entry in system.webServer is for IIS7+, the other in system.web is for IIS 6.
Note that you need to set runAllManagedModulesForAllRequests to true, for that it works properly.

The string in type is in the format "Namespace.Class, Assembly". Note that if you write your assembly in VB.NET instead of C#, VB creates a default-Namespace for each project, so your string will look like

"[DefaultNameSpace.Namespace].Class, Assembly"

If you want to avoid this problem, write the DLL in C#.

javax.faces.application.ViewExpiredException: View could not be restored

I add the following configuration to web.xml and it got resolved.

<context-param>
    <param-name>com.sun.faces.numberOfViewsInSession</param-name>
    <param-value>500</param-value>
</context-param>
<context-param>
    <param-name>com.sun.faces.numberOfLogicalViews</param-name>
    <param-value>500</param-value>
</context-param>

Query EC2 tags from within instance

You can add this script to your cloud-init user data to download EC2 tags to a local file:

#!/bin/sh
INSTANCE_ID=`wget -qO- http://instance-data/latest/meta-data/instance-id`
REGION=`wget -qO- http://instance-data/latest/meta-data/placement/availability-zone | sed 's/.$//'`
aws ec2 describe-tags --region $REGION --filter "Name=resource-id,Values=$INSTANCE_ID" --output=text | sed -r 's/TAGS\t(.*)\t.*\t.*\t(.*)/\1="\2"/' > /etc/ec2-tags

You need the AWS CLI tools installed on your system: you can either install them with a packages section in a cloud-config file before the script, use an AMI that already includes them, or add an apt or yum command at the beginning of the script.

In order to access EC2 tags you need a policy like this one in your instance's IAM role:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1409309287000",
      "Effect": "Allow",
      "Action": [
        "ec2:DescribeTags"
      ],
      "Resource": [
        "*"
      ]
    }
  ]
}

The instance's EC2 tags will available in /etc/ec2-tags in this format:

FOO="Bar"
Name="EC2 tags with cloud-init"

You can include the file as-is in a shell script using . /etc/ec2-tags, for example:

#!/bin/sh
. /etc/ec2-tags
echo $Name

The tags are downloaded during instance initialization, so they will not reflect subsequent changes.


The script and IAM policy are based on itaifrenkel's answer.

Check if a row exists, otherwise insert

INSERT INTO table ( column1, column2, column3 )
SELECT $column1, $column2, $column3
EXCEPT SELECT column1, column2, column3
FROM table

Validation of file extension before uploading file

Here is a more reusable way, assuming you use jQuery

Library function (does not require jQuery):

function stringEndsWithValidExtension(stringToCheck, acceptableExtensionsArray, required) {
    if (required == false && stringToCheck.length == 0) { return true; }
    for (var i = 0; i < acceptableExtensionsArray.length; i++) {
        if (stringToCheck.toLowerCase().endsWith(acceptableExtensionsArray[i].toLowerCase())) { return true; }
    }
    return false;
}


String.prototype.startsWith = function (str) { return (this.match("^" + str) == str) }

String.prototype.endsWith = function (str) { return (this.match(str + "$") == str) }

Page function (requires jQuery (barely)):

$("[id*='btnSaveForm']").click(function () {
    if (!stringEndsWithValidExtension($("[id*='fileUploader']").val(), [".png", ".jpeg", ".jpg", ".bmp"], false)) {
        alert("Photo only allows file types of PNG, JPG and BMP.");
        return false;
    }
    return true;
});

Difference between array_map, array_walk and array_filter

The following revision seeks to more clearly delineate PHP's array_filer(), array_map(), and array_walk(), all of which originate from functional programming:

array_filter() filters out data, producing as a result a new array holding only the desired items of the former array, as follows:

<?php
$array = array(1, "apples",2, "oranges",3, "plums");

$filtered = array_filter( $array, "ctype_alpha");
var_dump($filtered);
?>

live code here

All numeric values are filtered out of $array, leaving $filtered with only types of fruit.

array_map() also creates a new array but unlike array_filter() the resulting array contains every element of the input $filtered but with altered values, owing to applying a callback to each element, as follows:

<?php

$nu = array_map( "strtoupper", $filtered);
var_dump($nu);
?>

live code here

The code in this case applies a callback using the built-in strtoupper() but a user-defined function is another viable option, too. The callback applies to every item of $filtered and thereby engenders $nu whose elements contain uppercase values.

In the next snippet, array walk() traverses $nu and makes changes to each element vis a vis the reference operator '&'. The changes occur without creating an additional array. Every element's value changes in place into a more informative string specifying its key, category and value.

<?php

$f = function(&$item,$key,$prefix) {
    $item = "$key: $prefix: $item";
}; 
array_walk($nu, $f,"fruit");
var_dump($nu);    
?>    

See demo

Note: the callback function with respect to array_walk() takes two parameters which will automatically acquire an element's value and its key and in that order, too when invoked by array_walk(). (See more here).

How to override trait function and call it from the overridden function?

An alternative approach if interested - with an extra intermediate class to use the normal OOO way. This simplifies the usage with parent::methodname

trait A {
    function calc($v) {
        return $v+1;
    }
}

// an intermediate class that just uses the trait
class IntClass {
    use A;
}

// an extended class from IntClass
class MyClass extends IntClass {
    function calc($v) {
        $v++;
        return parent::calc($v);
    }
}

Sort a list alphabetically

You can sort a list in-place just by calling List<T>.Sort:

list.Sort();

That will use the natural ordering of elements, which is fine in your case.

EDIT: Note that in your code, you'd need

_details.Sort();

as the Sort method is only defined in List<T>, not IList<T>. If you need to sort it from the outside where you don't have access to it as a List<T> (you shouldn't cast it as the List<T> part is an implementation detail) you'll need to do a bit more work.

I don't know of any IList<T>-based in-place sorts in .NET, which is slightly odd now I come to think of it. IList<T> provides everything you'd need, so it could be written as an extension method. There are lots of quicksort implementations around if you want to use one of those.

If you don't care about a bit of inefficiency, you could always use:

public void Sort<T>(IList<T> list)
{
    List<T> tmp = new List<T>(list);
    tmp.Sort();
    for (int i = 0; i < tmp.Count; i++)
    {
        list[i] = tmp[i];
    }
}

In other words, copy, sort in place, then copy the sorted list back.


You can use LINQ to create a new list which contains the original values but sorted:

var sortedList = list.OrderBy(x => x).ToList();

It depends which behaviour you want. Note that your shuffle method isn't really ideal:

  • Creating a new Random within the method runs into some of the problems shown here
  • You can declare val inside the loop - you're not using that default value
  • It's more idiomatic to use the Count property when you know you're working with an IList<T>
  • To my mind, a for loop is simpler to understand than traversing the list backwards with a while loop

There are other implementations of shuffling with Fisher-Yates on Stack Overflow - search and you'll find one pretty quickly.

Best PHP IDE for Mac? (Preferably free!)

Komodo is wonderful, and it runs on OS X; they have a free version, Komodo Edit.

UPDATE from 2015: I've switched to PHPStorm from Jetbrains, the same folks that built IntelliJ IDEA and Resharper. It's better. Not just better. It's well worth the money.

Filter output in logcat by tagname

In case someone stumbles in on this like I did, you can filter on multiple tags by adding a comma in between, like so:

adb logcat -s "browser","webkit"

Fast and simple String encrypt/decrypt in JAVA

If you are using Android then you can use android.util.Base64 class.

Encode:

passwd = Base64.encodeToString( passwd.getBytes(), Base64.DEFAULT );

Decode:

passwd = new String( Base64.decode( passwd, Base64.DEFAULT ) );

A simple and fast single line solution.

In what cases will HTTP_REFERER be empty

BalusC's list is solid. One additional way this field frequently appears empty is when the user is behind a proxy server. This is similar to being behind a firewall but is slightly different so I wanted to mention it for the sake of completeness.

How to declare an array in Python?

You don't declare anything in Python. You just use it. I recommend you start out with something like http://diveintopython.net.

versionCode vs versionName in Android Manifest

Reference Link

android:versionCode

An internal version number. This number is used only to determine whether one version is more recent than another, with higher numbers indicating more recent versions. This is not the version number shown to users; that number is set by the versionName attribute. The value must be set as an integer, such as "100". You can define it however you want, as long as each successive version has a higher number. [...]

android:versionName

The version name shown to users. This attribute can be set as a raw string or as a reference to a string resource. The string has no other purpose than to be displayed to users. The versionCode attribute holds the significant version number used internally.

Reading that it's pretty clear that versionName is just something that's shown to the user, versionCode is what matters. Just keep increasing it and everything should be good.

how to solve Error cannot add duplicate collection entry of type add with unique key attribute 'value' in iis 7

I got the same error and when I unknowingly removed all the default pages of the DefaultAppPool itself.

Resolution

I have clicked the DefaultAppPool and opened the Default Document. Then clicked on the Revert to Parent link on the Actions pane. The default documents have came again, and thus it solves the issue. I'm not sure this is the best way, but this one was the error which I have just met and hope to share with you. I hope this may help some one.

Parsing HTML using Python

I would use EHP

https://github.com/iogf/ehp

Here it is:

from ehp import *

doc = '''<html>
<head>Heading</head>
<body attr1='val1'>
    <div class='container'>
        <div id='class'>Something here</div>
        <div>Something else</div>
    </div>
</body>
</html>
'''

html = Html()
dom = html.feed(doc)
for ind in dom.find('div', ('class', 'container')):
    print ind.text()

Output:

Something here
Something else

Error: Unable to run mksdcard SDK tool

In case of lubuntu 14.04 use

sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0 lib32stdc++6

P.S-no need to restart the system.

Redirect HTTP to HTTPS on default virtual host without ServerName

Try adding this in your vhost config:

RewriteEngine On
RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L]

How to calculate a Mod b in Casio fx-991ES calculator

Calculate x/y (your actual numbers here), and press a b/c key, which is 3rd one below Shift key.

Why is it OK to return a 'vector' from a function?

Pre C++11:

The function will not return the local variable, but rather a copy of it. Your compiler might however perform an optimization where no actual copy action is made.

See this question & answer for further details.

C++11:

The function will move the value. See this answer for further details.

Subscript out of bounds - general definition and solution?

Only an addition to the above responses: A possibility in such cases is that you are calling an object, that for some reason is not available to your query. For example you may subset by row names or column names, and you will receive this error message when your requested row or column is not part of the data matrix or data frame anymore. Solution: As a short version of the responses above: you need to find the last working row name or column name, and the next called object should be the one that could not be found. If you run parallel codes like "foreach", then you need to convert your code to a for loop to be able to troubleshoot it.

How to select only the records with the highest date in LINQ

If you just want the last date for each account, you'd use this:

var q = from n in table
        group n by n.AccountId into g
        select new {AccountId = g.Key, Date = g.Max(t=>t.Date)};

If you want the whole record:

var q = from n in table
        group n by n.AccountId into g
        select g.OrderByDescending(t=>t.Date).FirstOrDefault();

How to write a switch statement in Ruby

We can write switch statement for multiple conditions.

For Example,

x = 22

CASE x
  WHEN 0..14 THEN puts "#{x} is less than 15"    
  WHEN 15 THEN puts "#{x} equals 15" 
  WHEN 15 THEN puts "#{x} equals 15" 
  WHEN 15..20 THEN puts "#{x} is greater than 15" 
  ELSE puts "Not in the range, value #{x} " 
END

"Could not find or load main class" Error while running java program using cmd prompt

Execute your Java program using java -d . HelloWorld command.

This command works when you have declared package.

. represent current directory/.

How to parse a JSON file in swift?

Codable

In Swift 4+ is strongly recommended to use Codable instead of JSONSerialization.

This Codable includes two protocols: Decodable and Encodable. This Decodable protocol allows you to decode Data in JSON format to custom struct/class conforming to this protocol.

For example imagine situation that we have this simple Data (array of two objects)

let data = Data("""
[
    {"name":"Steve","age":56}, 
    {"name":"iPhone","age":11}
]
""".utf8)

then have following struct and implement protocol Decodable

struct Person: Decodable {
    let name: String
    let age: Int
}

now you can decode your Data to your array of Person using JSONDecoder where first parameter is type conforming to Decodable and to this type should Data be decoded

do {
    let people = try JSONDecoder().decode([Person].self, from: data)
} catch { print(error) }

... note that decoding has to be marked with try keyword since you could for example make some mistake with naming and then your model can't be decoded correctly ... so you should put it inside do-try-catch block


Cases that key in json is different from name of property:

  • If key is in named using snake_case, you can set decoder's keyDecodingStrategy to convertFromSnakeCase which changes key from property_name to camelCase propertyName

    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let people = try decoder.decode([Person].self, from: data)
    
  • If you need unique name you can use coding keys inside struct/class where you declare name of key

    let data = Data(""" 
    { "userName":"Codable", "age": 1 } 
    """.utf8)
    
    struct Person: Decodable {
    
        let name: String
        let age: Int
    
        enum CodingKeys: String, CodingKey {
            case name = "userName"
            case age
        }
    }
    

What is the inclusive range of float and double in Java?

From Primitives Data Types:

  • float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.

  • double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.

For the range of values, see the section 4.2.3 Floating-Point Types, Formats, and Values of the JLS.

Apply formula to the entire column

Just so I don't lose my answer that works:

  1. Select the cell to copy
  2. Select the final cell in the column
  3. Press CTRL+D

How to get just the responsive grid from Bootstrap 3?

It's been a while since this question was asked, but maybe now you can forego Bootstrap altogether and use CSS Grid! (it's simpler, neater, more flexible and faster). See this cool article: Stop using Bootstrap — create a practical CSS Grid template for your component based UI

Chrome, Javascript, window.open in new tab

It is sometimes useful to force the use of a tab, if the user likes that. As Prakash stated above, this is sometimes dictated by the use of a non-user-initiated event, but there are ways around that.

For example:

$("#theButton").button().click( function(event) {
   $.post( url, data )
   .always( function( response ) {
      window.open( newurl + response, '_blank' );
   } );
} );

will always open "newurl" in a new browser window since the "always" function is not considered user-initiated. However, if we do this:

$("#theButton").button().click( function(event) {
   var newtab = window.open( '', '_blank' );
   $.post( url, data )
   .always( function( response ) {
      newtab.location = newurl + response;
   } );
} );

we open the new browser window or create the new tab, as determined by the user preference in the button click which IS user-initiated. Then we just set the location to the desired URL after returning from the AJAX post. Voila, we force the use of a tab if the user likes that.

python: creating list from string

Try this:

b = [ entry.split(',') for entry in a ]
b = [ b[i] if i % 3 == 0 else int(b[i]) for i in xrange(0, len(b)) ]

Where to find free public Web Services?

Here you can find some public REST services for encryption and security related things: http://security.jelastic.servint.net

Resolve host name to an ip address

Go to your client machine and type in:

nslookup server.company.com

substituting the real host name of your server for server.company.com, of course.

That should tell you which DNS server your client is using (if any) and what it thinks the problem is with the name.

To force an application to use an IP address, generally you just configure it to use the IP address instead of a host name. If the host name is hard-coded, or the application insists on using a host name in preference to an IP address (as one of your other comments seems to indicate), then you're probably out of luck there.

However, you can change the way that most machine resolve the host names, such as with /etc/resolv.conf and /etc/hosts on UNIXy systems and a local hosts file on Windows-y systems.

How to update the value of a key in a dictionary in Python?

n = eval(input('Num books: '))
books = {}
for i in range(n):
    titlez = input("Enter Title: ")
    copy = eval(input("Num of copies: "))
    books[titlez] = copy

prob = input('Sell a book; enter YES or NO: ')
if prob == 'YES' or 'yes':
    choice = input('Enter book title: ')
    if choice in books:
        init_num = books[choice]
        init_num -= 1
        books[choice] = init_num
        print(books)

Escape double quotes in parameter

Another way to escape quotes (though probably not preferable), which I've found used in certain places is to use multiple double-quotes. For the purpose of making other people's code legible, I'll explain.

Here's a set of basic rules:

  1. When not wrapped in double-quoted groups, spaces separate parameters:
    program param1 param2 param 3 will pass four parameters to program.exe:
         param1, param2, param, and 3.
  2. A double-quoted group ignores spaces as value separators when passing parameters to programs:
    program one two "three and more" will pass three parameters to program.exe:
         one, two, and three and more.
  3. Now to explain some of the confusion:
  4. Double-quoted groups that appear directly adjacent to text not wrapped with double-quotes join into one parameter:
    hello"to the entire"world acts as one parameter: helloto the entireworld.
  5. Note: The previous rule does NOT imply that two double-quoted groups can appear directly adjacent to one another.
  6. Any double-quote directly following a closing quote is treated as (or as part of) plain unwrapped text that is adjacent to the double-quoted group, but only one double-quote:
    "Tim says, ""Hi!""" will act as one parameter: Tim says, "Hi!"

Thus there are three different types of double-quotes: quotes that open, quotes that close, and quotes that act as plain-text.
Here's the breakdown of that last confusing line:

"   open double-quote group
T   inside ""s
i   inside ""s
m   inside ""s
    inside ""s - space doesn't separate
s   inside ""s
a   inside ""s
y   inside ""s
s   inside ""s
,   inside ""s
    inside ""s - space doesn't separate
"   close double-quoted group
"   quote directly follows closer - acts as plain unwrapped text: "
H   outside ""s - gets joined to previous adjacent group
i   outside ""s - ...
!   outside ""s - ...
"   open double-quote group
"   close double-quote group
"   quote directly follows closer - acts as plain unwrapped text: "

Thus, the text effectively joins four groups of characters (one with nothing, however):
Tim says,  is the first, wrapped to escape the spaces
"Hi! is the second, not wrapped (there are no spaces)
 is the third, a double-quote group wrapping nothing
" is the fourth, the unwrapped close quote.

As you can see, the double-quote group wrapping nothing is still necessary since, without it, the following double-quote would open up a double-quoted group instead of acting as plain-text.

From this, it should be recognizable that therefore, inside and outside quotes, three double-quotes act as a plain-text unescaped double-quote:

"Tim said to him, """What's been happening lately?""""

will print Tim said to him, "What's been happening lately?" as expected. Therefore, three quotes can always be reliably used as an escape.
However, in understanding it, you may note that the four quotes at the end can be reduced to a mere two since it technically is adding another unnecessary empty double-quoted group.

Here are a few examples to close it off:

program a b                       REM sends (a) and (b)
program """a"""                   REM sends ("a")
program """a b"""                 REM sends ("a) and (b")
program """"Hello,""" Mike said." REM sends ("Hello," Mike said.)
program ""a""b""c""d""            REM sends (abcd) since the "" groups wrap nothing
program "hello to """quotes""     REM sends (hello to "quotes")
program """"hello world""         REM sends ("hello world")
program """hello" world""         REM sends ("hello world")
program """hello "world""         REM sends ("hello) and (world")
program "hello ""world"""         REM sends (hello "world")
program "hello """world""         REM sends (hello "world")

Final note: I did not read any of this from any tutorial - I came up with all of it by experimenting. Therefore, my explanation may not be true internally. Nonetheless all the examples above evaluate as given, thus validating (but not proving) my theory.

I tested this on Windows 7, 64bit using only *.exe calls with parameter passing (not *.bat, but I would suppose it works the same).

Integrating the ZXing library directly into my Android application

Here is a step-by-step guide on how to generate and display QR code using ZXing library without having to install the third-party application. Note: you don't have to build ZXing with ANT or any other build tool. The file core.jar is available in the released zip archive (read below).

  1. Download the latest release of ZXing. -- (ZXing-*.zip)
  2. Extract this zip archive and find core.jar under core/ directory.
  3. If you are using Eclipse IDE, drag and drop core.jar to the libs directory of your Android project. When asked, select Copy.
  4. Copy the two classes given below (Contents.java & QRCodeEncoder.java) to the main package of your Android project.
  5. Create an ImageView item in your Activity to display the generated QR code in if you don't have one already. An example is given below:
  6. Use the code snippet below to generate the QR code in Bitmap format and display it in an ImageView.

Here is an ImageView element to add to your Activity layout XML file:

<ImageView 
    android:id="@+id/qrCode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="50dp"
    android:layout_centerHorizontal="true"/>

Code snippet:

// ImageView to display the QR code in.  This should be defined in 
// your Activity's XML layout file
ImageView imageView = (ImageView) findViewById(R.id.qrCode);

String qrData = "Data I want to encode in QR code";
int qrCodeDimention = 500;

QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(qrData, null,
        Contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(), qrCodeDimention);

try {
    Bitmap bitmap = qrCodeEncoder.encodeAsBitmap();
    imageView.setImageBitmap(bitmap);
} catch (WriterException e) {
    e.printStackTrace();
}

Here is Contents.java

//
// * Copyright (C) 2008 ZXing authors
// * 
// * Licensed under the Apache License, Version 2.0 (the "License");
// * you may not use this file except in compliance with the License.
// * You may obtain a copy of the License at
// * 
// * http://www.apache.org/licenses/LICENSE-2.0
// * 
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// 

import android.provider.ContactsContract;

public final class Contents {
    private Contents() {
    }

    public static final class Type {

     // Plain text. Use Intent.putExtra(DATA, string). This can be used for URLs too, but string
     // must include "http://" or "https://".
        public static final String TEXT = "TEXT_TYPE";

        // An email type. Use Intent.putExtra(DATA, string) where string is the email address.
        public static final String EMAIL = "EMAIL_TYPE";

        // Use Intent.putExtra(DATA, string) where string is the phone number to call.
        public static final String PHONE = "PHONE_TYPE";

        // An SMS type. Use Intent.putExtra(DATA, string) where string is the number to SMS.
        public static final String SMS = "SMS_TYPE";

        public static final String CONTACT = "CONTACT_TYPE";

        public static final String LOCATION = "LOCATION_TYPE";

        private Type() {
        }
    }

    public static final String URL_KEY = "URL_KEY";

    public static final String NOTE_KEY = "NOTE_KEY";

    // When using Type.CONTACT, these arrays provide the keys for adding or retrieving multiple phone numbers and addresses.
    public static final String[] PHONE_KEYS = {
            ContactsContract.Intents.Insert.PHONE, ContactsContract.Intents.Insert.SECONDARY_PHONE,
            ContactsContract.Intents.Insert.TERTIARY_PHONE
    };

    public static final String[] PHONE_TYPE_KEYS = {
            ContactsContract.Intents.Insert.PHONE_TYPE,
            ContactsContract.Intents.Insert.SECONDARY_PHONE_TYPE,
            ContactsContract.Intents.Insert.TERTIARY_PHONE_TYPE
    };

    public static final String[] EMAIL_KEYS = {
            ContactsContract.Intents.Insert.EMAIL, ContactsContract.Intents.Insert.SECONDARY_EMAIL,
            ContactsContract.Intents.Insert.TERTIARY_EMAIL
    };

    public static final String[] EMAIL_TYPE_KEYS = {
            ContactsContract.Intents.Insert.EMAIL_TYPE,
            ContactsContract.Intents.Insert.SECONDARY_EMAIL_TYPE,
            ContactsContract.Intents.Insert.TERTIARY_EMAIL_TYPE
    };
}

And QRCodeEncoder.java

/*
 * Copyright (C) 2008 ZXing authors
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import android.provider.ContactsContract;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.telephony.PhoneNumberUtils;

import java.util.Collection;
import java.util.EnumMap;
import java.util.HashSet;
import java.util.Map;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

public final class QRCodeEncoder {
    private static final int WHITE = 0xFFFFFFFF;
    private static final int BLACK = 0xFF000000;

    private int dimension = Integer.MIN_VALUE;
    private String contents = null;
    private String displayContents = null;
    private String title = null;
    private BarcodeFormat format = null;
    private boolean encoded = false;

    public QRCodeEncoder(String data, Bundle bundle, String type, String format, int dimension) {
        this.dimension = dimension;
        encoded = encodeContents(data, bundle, type, format);
    }

    public String getContents() {
        return contents;
    }

    public String getDisplayContents() {
        return displayContents;
    }

    public String getTitle() {
        return title;
    }

    private boolean encodeContents(String data, Bundle bundle, String type, String formatString) {
        // Default to QR_CODE if no format given.
        format = null;
        if (formatString != null) {
            try {
                format = BarcodeFormat.valueOf(formatString);
            } catch (IllegalArgumentException iae) {
                // Ignore it then
            }
        }
        if (format == null || format == BarcodeFormat.QR_CODE) {
            this.format = BarcodeFormat.QR_CODE;
            encodeQRCodeContents(data, bundle, type);
        } else if (data != null && data.length() > 0) {
            contents = data;
            displayContents = data;
            title = "Text";
        }
        return contents != null && contents.length() > 0;
    }

    private void encodeQRCodeContents(String data, Bundle bundle, String type) {
        if (type.equals(Contents.Type.TEXT)) {
            if (data != null && data.length() > 0) {
                contents = data;
                displayContents = data;
                title = "Text";
            }
        } else if (type.equals(Contents.Type.EMAIL)) {
            data = trim(data);
            if (data != null) {
                contents = "mailto:" + data;
                displayContents = data;
                title = "E-Mail";
            }
        } else if (type.equals(Contents.Type.PHONE)) {
            data = trim(data);
            if (data != null) {
                contents = "tel:" + data;
                displayContents = PhoneNumberUtils.formatNumber(data);
                title = "Phone";
            }
        } else if (type.equals(Contents.Type.SMS)) {
            data = trim(data);
            if (data != null) {
                contents = "sms:" + data;
                displayContents = PhoneNumberUtils.formatNumber(data);
                title = "SMS";
            }
        } else if (type.equals(Contents.Type.CONTACT)) {
            if (bundle != null) {
                StringBuilder newContents = new StringBuilder(100);
                StringBuilder newDisplayContents = new StringBuilder(100);

                newContents.append("MECARD:");

                String name = trim(bundle.getString(ContactsContract.Intents.Insert.NAME));
                if (name != null) {
                    newContents.append("N:").append(escapeMECARD(name)).append(';');
                    newDisplayContents.append(name);
                }

                String address = trim(bundle.getString(ContactsContract.Intents.Insert.POSTAL));
                if (address != null) {
                    newContents.append("ADR:").append(escapeMECARD(address)).append(';');
                    newDisplayContents.append('\n').append(address);
                }

                Collection<String> uniquePhones = new HashSet<String>(Contents.PHONE_KEYS.length);
                for (int x = 0; x < Contents.PHONE_KEYS.length; x++) {
                    String phone = trim(bundle.getString(Contents.PHONE_KEYS[x]));
                    if (phone != null) {
                        uniquePhones.add(phone);
                    }
                }
                for (String phone : uniquePhones) {
                    newContents.append("TEL:").append(escapeMECARD(phone)).append(';');
                    newDisplayContents.append('\n').append(PhoneNumberUtils.formatNumber(phone));
                }

                Collection<String> uniqueEmails = new HashSet<String>(Contents.EMAIL_KEYS.length);
                for (int x = 0; x < Contents.EMAIL_KEYS.length; x++) {
                    String email = trim(bundle.getString(Contents.EMAIL_KEYS[x]));
                    if (email != null) {
                        uniqueEmails.add(email);
                    }
                }
                for (String email : uniqueEmails) {
                    newContents.append("EMAIL:").append(escapeMECARD(email)).append(';');
                    newDisplayContents.append('\n').append(email);
                }

                String url = trim(bundle.getString(Contents.URL_KEY));
                if (url != null) {
                    // escapeMECARD(url) -> wrong escape e.g. http\://zxing.google.com
                    newContents.append("URL:").append(url).append(';');
                    newDisplayContents.append('\n').append(url);
                }

                String note = trim(bundle.getString(Contents.NOTE_KEY));
                if (note != null) {
                    newContents.append("NOTE:").append(escapeMECARD(note)).append(';');
                    newDisplayContents.append('\n').append(note);
                }

                // Make sure we've encoded at least one field.
                if (newDisplayContents.length() > 0) {
                    newContents.append(';');
                    contents = newContents.toString();
                    displayContents = newDisplayContents.toString();
                    title = "Contact";
                } else {
                    contents = null;
                    displayContents = null;
                }

            }
        } else if (type.equals(Contents.Type.LOCATION)) {
            if (bundle != null) {
                // These must use Bundle.getFloat(), not getDouble(), it's part of the API.
                float latitude = bundle.getFloat("LAT", Float.MAX_VALUE);
                float longitude = bundle.getFloat("LONG", Float.MAX_VALUE);
                if (latitude != Float.MAX_VALUE && longitude != Float.MAX_VALUE) {
                    contents = "geo:" + latitude + ',' + longitude;
                    displayContents = latitude + "," + longitude;
                    title = "Location";
                }
            }
        }
    }

    public Bitmap encodeAsBitmap() throws WriterException {
        if (!encoded) return null;

        Map<EncodeHintType, Object> hints = null;
        String encoding = guessAppropriateEncoding(contents);
        if (encoding != null) {
            hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
            hints.put(EncodeHintType.CHARACTER_SET, encoding);
        }
        MultiFormatWriter writer = new MultiFormatWriter();
        BitMatrix result = writer.encode(contents, format, dimension, dimension, hints);
        int width = result.getWidth();
        int height = result.getHeight();
        int[] pixels = new int[width * height];
        // All are 0, or black, by default
        for (int y = 0; y < height; y++) {
            int offset = y * width;
            for (int x = 0; x < width; x++) {
                pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
            }
        }

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }

    private static String guessAppropriateEncoding(CharSequence contents) {
        // Very crude at the moment
        for (int i = 0; i < contents.length(); i++) {
            if (contents.charAt(i) > 0xFF) { return "UTF-8"; }
        }
        return null;
    }

    private static String trim(String s) {
        if (s == null) { return null; }
        String result = s.trim();
        return result.length() == 0 ? null : result;
    }

    private static String escapeMECARD(String input) {
        if (input == null || (input.indexOf(':') < 0 && input.indexOf(';') < 0)) { return input; }
        int length = input.length();
        StringBuilder result = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            char c = input.charAt(i);
            if (c == ':' || c == ';') {
                result.append('\\');
            }
            result.append(c);
        }
        return result.toString();
    }
}

Right HTTP status code to wrong input

404 - Not Found - can be used for The URI requested is invalid or the resource requested such as a user, does not exists.

Can HTTP POST be limitless?

POST allows for an arbitrary length of data to be sent to a server, but there are limitations based on timeouts/bandwidth etc.

I think basically, it's safer to assume that it's not okay to send lots of data.

libstdc++.so.6: cannot open shared object file: No such file or directory

I presume you're running Linux on an amd64 machine. The Folder your executable is residing in (lib32) suggests a 32-bit executable which requires 32-bit libraries.

These seem not to be present on your system, so you need to install them manually. The package name depends on your distribution, for Debian it's ia32-libs, for Fedora libstdc++.<version>.i686.

JAVA - using FOR, WHILE and DO WHILE loops to sum 1 through 100

Your for loop looks good.

A possible while loop to accomplish the same thing:

int sum = 0;
int i = 1;
while (i <= 100) {
    sum += i;
    i++;
}
System.out.println("The sum is " + sum);

A possible do while loop to accomplish the same thing:

int sum = 0;
int i = 1;
do {
    sum += i;
    i++;
} while (i <= 100);
System.out.println("The sum is " + sum);

The difference between the while and the do while is that, with the do while, at least one iteration is sure to occur.

Populate data table from data reader

If you're trying to load a DataTable, then leverage the SqlDataAdapter instead:

DataTable dt = new DataTable();

using (SqlConnection c = new SqlConnection(cString))
using (SqlDataAdapter sda = new SqlDataAdapter(sql, c))
{
    sda.SelectCommand.CommandType = CommandType.StoredProcedure;
    sda.SelectCommand.Parameters.AddWithValue("@parm1", val1);
    ...

    sda.Fill(dt);
}

You don't even need to define the columns. Just create the DataTable and Fill it.

Here, cString is your connection string and sql is the stored procedure command.

How to call code behind server method from a client side JavaScript function?

Yes, you can make a web method like..

[WebMethod]
public static String SetName(string name)
{
    return "Your String"
}

And then call it in JavaScript like,

PageMethods.SetName(parameterValueIfAny, onSuccessMethod,onFailMethod);

This is also required :

<asp:ScriptManager ID="ScriptMgr" runat="server" EnablePageMethods="true"></asp:ScriptManager>

MySQL - Using If Then Else in MySQL UPDATE or SELECT Queries

Here's a query to update a table based on a comparison of another table. If record is not found in tableB, it will update the "active" value to "n". If it's found, will set the value to NULL

UPDATE tableA
LEFT JOIN tableB ON tableA.id = tableB.id
SET active = IF(tableB.id IS NULL, 'n', NULL)";

Hope this helps someone else.

Android: I am unable to have ViewPager WRAP_CONTENT

I have an version of WrapContentHeightViewPager that was working correctly before API 23 that will resize the parent view's height base on the current child view selected.

After upgrading to API 23, it stopped working. It turns out the old solution was using getChildAt(getCurrentItem()) to get the current child view to measure which is not working. See solution here: https://stackoverflow.com/a/16512217/1265583

Below works with API 23:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int height = 0;
    ViewPagerAdapter adapter = (ViewPagerAdapter)getAdapter();
    View child = adapter.getItem(getCurrentItem()).getView();
    if(child != null) {
        child.measure(widthMeasureSpec,  MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        height = child.getMeasuredHeight();
    }
    heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

Node Sass couldn't find a binding for your current environment

Just refresh your npm cache and:

npm cache clean --force  
npm install

It always works for me in the same case.

UPD: Your problem may also be by reason of absence of a global sasslib.

npm install -g sass

What's the use of "enum" in Java?

an Enum is a safe-type so you can't assign a new value at the runtime. Moreover you can use it in a switch statement (like an int).

Convert a RGB Color Value to a Hexadecimal String

A one liner but without String.format for all RGB colors:

Color your_color = new Color(128,128,128);

String hex = "#"+Integer.toHexString(your_color.getRGB()).substring(2);

You can add a .toUpperCase()if you want to switch to capital letters. Note, that this is valid (as asked in the question) for all RGB colors.

When you have ARGB colors you can use:

Color your_color = new Color(128,128,128,128);

String buf = Integer.toHexString(your_color.getRGB());
String hex = "#"+buf.substring(buf.length()-6);

A one liner is theoretically also possible but would require to call toHexString twice. I benchmarked the ARGB solution and compared it with String.format():

enter image description here

moving changed files to another branch for check-in

git stash is your friend.

If you have not made the commit yet, just run git stash. This will save away all of your changes.

Switch to the branch you want the changes on and run git stash pop.

There are lots of uses for git stash. This is certainly one of the more useful reasons.

An example:

# work on some code
git stash
git checkout correct-branch
git stash pop

How to show what a commit did?

I found out that "git show --stat" is the best out of all here, gives you a brief summary of the commit, what files did you add and modify without giving you whole bunch of stuff, especially if you changed a lot files.

New og:image size for Facebook share?

Relying on the PDF that @CBroe posted earlier:

For best og:image results (retina ready & without being cropped) with the current Facebook Standard use:

Size: minimum 1200 x 630px

Ratio: 1.91:1

Swap x and y axis without manually swapping values

  1. Click somewhere on the chart to select it.

  2. You should now see 3 new tabs appear at the top of the screen called "Design", "Layout" and "Format".

  3. Click on the "Design" tab.

  4. There will be a button called "Switch Row/Column" within the "data" group, click it.

How to check if a string is a number?

Forget about ASCII code checks, use isdigit or isnumber (see man isnumber). The first function checks whether the character is 0–9, the second one also accepts various other number characters depending on the current locale.

There may even be better functions to do the check – the important lesson is that this is a bit more complex than it looks, because the precise definition of a “number string” depends on the particular locale and the string encoding.

How to get the real path of Java application at runtime?

/*****************************************************************************
     * return application path
     * @return
     *****************************************************************************/
    public static String getApplcatonPath(){
        CodeSource codeSource = MainApp.class.getProtectionDomain().getCodeSource();
        File rootPath = null;
        try {
            rootPath = new File(codeSource.getLocation().toURI().getPath());
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }           
        return rootPath.getParentFile().getPath();
    }//end of getApplcatonPath()

How to clear an EditText on click?

For me the easiest way... Create an public EditText, for Example "myEditText1"

public EditText myEditText1;

Then, connect it with the EditText which should get cleared

myEditText1 = (EditText) findViewById(R.id.numberfield);

After that, create an void which reacts to an click to the EditText an let it clear the Text inside it when its Focused, for Example

@OnClick(R.id.numberfield)
        void textGone(){
            if (myEditText1.isFocused()){
                myEditText1.setText("");

        }
    }

Hope i could help you, Have a nice Day everyone

Status bar and navigation bar appear over my view's bounds in iOS 7

In your apps plist file add a row, call it "View controller-based status bar appearance" and set it to NO.

How to destroy an object?

Short answer: Both are needed.

I feel like the right answer was given but minimally. Yeah generally unset() is best for "speed", but if you want to reclaim memory immediately (at the cost of CPU) should want to use null.

Like others mentioned, setting to null doesn't mean everything is reclaimed, you can have shared memory (uncloned) objects that will prevent destruction of the object. Moreover, like others have said, you can't "destroy" the objects explicitly anyway so you shouldn't try to do it anyway.

You will need to figure out which is best for you. Also you can use __destruct() for an object which will be called on unset or null but it should be used carefully and like others said, never be called directly!

see:

http://www.stoimen.com/blog/2011/11/14/php-dont-call-the-destructor-explicitly/

What is difference between assigning NULL and unset?

How to set the color of an icon in Angular Material?

color="white" is not a known attribute to Angular Material.

color attribute can changed to primary, accent, and warn. as said in this doc

your icon inside button works because its parent class button has css class of color:white, or may be your color="accent" is white. check the developer tools to find it.

By default, icons will use the current font color

Getting multiple selected checkbox values in a string in javascript and PHP

I you are using jQuery you can put the checkboxes in a form and then use something like this:

var formData = jQuery("#" + formId).serialize();

$.ajax({
      type: "POST",
      url: url,
      data: formData,
      success: success
}); 

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory in ionic 3

In my case it was a recursion that was causing react to use up all memory.

This happened when I was refactoring my code and didn't notice this.

const SumComponent = () => {
  return (
    <>
      <SumComponent />
    </>
  ) 
}

In other node apps this might look like:

const someFunction = () => {
  ...
  someFunction(); 
  ...
}

How can you zip or unzip from the script using ONLY Windows' built-in capabilities?

This one worked for me (in 2021):

tar -xf test.zip

This will unzip the test in the current directory.

Mongodb find() query : return only unique values (no duplicates)

I think you can use db.collection.distinct(fields,query)

You will be able to get the distinct values in your case for NetworkID.

It should be something like this :

Db.collection.distinct('NetworkID')

Error with multiple definitions of function

This problem happens because you are calling fun.cpp instead of fun.hpp. So c++ compiler finds func.cpp definition twice and throws this error.

Change line 3 of your main.cpp file, from #include "fun.cpp" to #include "fun.hpp" .

How to link an image and target a new window

Assuming you want to show an Image thumbnail which is 50x50 pixels and link to the the actual image you can do

<a href="path/to/image.jpg" alt="Image description" target="_blank" style="display: inline-block; width: 50px; height; 50px; background-image: url('path/to/image.jpg');"></a>

Of course it's best to give that link a class or id and put it in your css

Subtract days, months, years from a date in JavaScript

You are simply reducing the values from a number. So substracting 6 from 3 (date) will return -3 only.

You need to individually add/remove unit of time in date object

var date = new Date();
date.setDate( date.getDate() - 6 );
date.setFullYear( date.getFullYear() - 1 );
$("#searchDateFrom").val((date.getMonth() ) + '/' + (date.getDate()) + '/' + (date.getFullYear()));

Writing data to a local text file with javascript

Our HTML:

<div id="addnew">
    <input type="text" id="id">
    <input type="text" id="content">
    <input type="button" value="Add" id="submit">
</div>

<div id="check">
    <input type="text" id="input">
    <input type="button" value="Search" id="search">
</div>

JS (writing to the txt file):

function writeToFile(d1, d2){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 8, false, 0);
    fh.WriteLine(d1 + ',' + d2);
    fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
    var id      = document.getElementById("id").value;
    var content = document.getElementById("content").value;
    writeToFile(id, content);
}

checking a particular row:

function readFile(){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 1, false, 0);
    var lines = "";
    while (!fh.AtEndOfStream) {
        lines += fh.ReadLine() + "\r";
    }
    fh.Close();
    return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
    var input   = document.getElementById("input").value;
    if (input != "") {
        var text    = readFile();
        var lines   = text.split("\r");
        lines.pop();
        var result;
        for (var i = 0; i < lines.length; i++) {
            if (lines[i].match(new RegExp(input))) {
                result = "Found: " + lines[i].split(",")[1];
            }
        }
        if (result) { alert(result); }
        else { alert(input + " not found!"); }
    }
}

Put these inside a .hta file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.

Git log to get commits only for a specific branch

I finally found the way to do what the OP wanted. It's as simple as:

git log --graph [branchname]

The command will display all commits that are reachable from the provided branch in the format of graph. But, you can easily filter all commits on that branch by looking at the commits graph whose * is the first character in the commit line.

For example, let's look at the excerpt of git log --graph master on cakephp GitHub repo below:

D:\Web Folder\cakephp>git log --graph master
*   commit 8314c2ff833280bbc7102cb6d4fcf62240cd3ac4
|\  Merge: c3f45e8 0459a35
| | Author: José Lorenzo Rodríguez <[email protected]>
| | Date:   Tue Aug 30 08:01:59 2016 +0200
| |
| |     Merge pull request #9367 from cakephp/fewer-allocations
| |
| |     Do fewer allocations for simple default values.
| |
| * commit 0459a35689fec80bd8dca41e31d244a126d9e15e
| | Author: Mark Story <[email protected]>
| | Date:   Mon Aug 29 22:21:16 2016 -0400
| |
| |     The action should only be defaulted when there are no patterns
| |
| |     Only default the action name when there is no default & no pattern
| |     defined.
| |
| * commit 80c123b9dbd1c1b3301ec1270adc6c07824aeb5c
| | Author: Mark Story <[email protected]>
| | Date:   Sun Aug 28 22:35:20 2016 -0400
| |
| |     Do fewer allocations for simple default values.
| |
| |     Don't allocate arrays when we are only assigning a single array key
| |     value.
| |
* |   commit c3f45e811e4b49fe27624b57c3eb8f4721a4323b
|\ \  Merge: 10e5734 43178fd
| |/  Author: Mark Story <[email protected]>
|/|   Date:   Mon Aug 29 22:15:30 2016 -0400
| |
| |       Merge pull request #9322 from cakephp/add-email-assertions
| |
| |       Add email assertions trait
| |
| * commit 43178fd55d7ef9a42706279fa275bb783063cf34
| | Author: Jad Bitar <[email protected]>
| | Date:   Mon Aug 29 17:43:29 2016 -0400
| |
| |     Fix `@since` in new files docblocks
| |

As you can see, only commits 8314c2ff833280bbc7102cb6d4fcf62240cd3ac4 and c3f45e811e4b49fe27624b57c3eb8f4721a4323b have the * being the first character in the commit lines. Those commits are from the master branch while the other four are from some other branches.

How to clear all inputs, selects and also hidden fields in a form using jQuery?

for empty all input tags such as input,select,textatea etc. run this code

$('#message').val('').change();

Explaining the 'find -mtime' command

The POSIX specification for find says:

-mtimen The primary shall evaluate as true if the file modification time subtracted from the initialization time, divided by 86400 (with any remainder discarded), is n.

Interestingly, the description of find does not further specify 'initialization time'. It is probably, though, the time when find is initialized (run).

In the descriptions, wherever n is used as a primary argument, it shall be interpreted as a decimal integer optionally preceded by a plus ( '+' ) or minus-sign ( '-' ) sign, as follows:

+n More than n.
  n Exactly n.
-n Less than n.

At the given time (2014-09-01 00:53:44 -4:00, where I'm deducing that AST is Atlantic Standard Time, and therefore the time zone offset from UTC is -4:00 in ISO 8601 but +4:00 in ISO 9945 (POSIX), but it doesn't matter all that much):

1409547224 = 2014-09-01 00:53:44 -04:00
1409457540 = 2014-08-30 23:59:00 -04:00

so:

1409547224 - 1409457540 = 89684
89684 / 86400 = 1

Even if the 'seconds since the epoch' values are wrong, the relative values are correct (for some time zone somewhere in the world, they are correct).

The n value calculated for the 2014-08-30 log file therefore is exactly 1 (the calculation is done with integer arithmetic), and the +1 rejects it because it is strictly a > 1 comparison (and not >= 1).

Get access to parent control from user control - C#

Control has a property called Parent, which will give the parent control. http://msdn.microsoft.com/en-us/library/system.windows.forms.control.parent.aspx

eg Control p = this.Parent;

variable is not declared it may be inaccessible due to its protection level

Pay close attention to the first part of the error: "variable is not declared"

Ignore the second part: "it may be inaccessible due to its protection level". It's a red herring.

Some questions... (the answers might be in that image you posted, but I can't seem to make it larger and my eyes don't read that small of print... Any chance you can post the code in a way these older eyes can read it? Makes it hard to know the total picture. In particular I am suspicious of your Page directives.)

We know that 1stReasonTypes is a listbox, but for some reason it seems like we don't know WHICH listbox. This is why I want to see your page directives.

But also, how are you calling the private method FormRefresh()? It's not an event handler, which makes me wonder if you are trying to reference a listbox in a form that is not handled properly in this code behind.

You may need to find the control 1stReasonTypes. Try maybe putting your listbox inside something like

<div id="MyFormDiv" runat="server">.....</div>

then in FormRefresh(), do a...

Dim 1stReasonTypesNew As listbox = MyFormDiv.FindControl("1stReasonTypes")

Or use an existing control, object, or page instead of a div. More info on FindControl: http://msdn.microsoft.com/en-us/library/486wc64h(v=vs.110).aspx

But no matter how you slice it, there is something funky going here such that 1stReasonTypes doesn't know which exact listbox it's supposed to be.

How do you store Java objects in HttpSession?

Here you can do it by using HttpRequest or HttpSession. And think your problem is within the JSP.

If you are going to use the inside servlet do following,

Object obj = new Object();
session.setAttribute("object", obj);

or

HttpSession session = request.getSession();
Object obj = new Object();
session.setAttribute("object", obj);

and after setting your attribute by using request or session, use following to access it in the JSP,

<%= request.getAttribute("object")%>

or

<%= session.getAttribute("object")%>

So seems your problem is in the JSP.

If you want use scriptlets it should be as follows,

<%
Object obj = request.getSession().getAttribute("object");
out.print(obj);
%>

Or can use expressions as follows,

<%= session.getAttribute("object")%>

or can use EL as follows, ${object} or ${sessionScope.object}

CodeIgniter -> Get current URL relative to base url

// For current url
echo base_url(uri_string());

How do you test running time of VBA code?

Seconds with 2 decimal spaces:

Dim startTime As Single 'start timer
MsgBox ("run time: " & Format((Timer - startTime) / 1000000, "#,##0.00") & " seconds") 'end timer

seconds format

Milliseconds:

Dim startTime As Single 'start timer
MsgBox ("run time: " & Format((Timer - startTime), "#,##0.00") & " milliseconds") 'end timer

milliseconds format

Milliseconds with comma seperator:

Dim startTime As Single 'start timer
MsgBox ("run time: " & Format((Timer - startTime) * 1000, "#,##0.00") & " milliseconds") 'end timer

Milliseconds with comma seperator

Just leaving this here for anyone that was looking for a simple timer formatted with seconds to 2 decimal spaces like I was. These are short and sweet little timers I like to use. They only take up one line of code at the beginning of the sub or function and one line of code again at the end. These aren't meant to be crazy accurate, I generally don't care about anything less then 1/100th of a second personally, but the milliseconds timer will give you the most accurate run time of these 3. I've also read you can get the incorrect read out if it happens to run while crossing over midnight, a rare instance but just FYI.

jQuery UI - Close Dialog When Clicked Outside

This doesn't use jQuery UI, but does use jQuery, and may be useful for those who aren't using jQuery UI for whatever reason. Do it like so:

function showDialog(){
  $('#dialog').show();
  $('*').on('click',function(e){
    $('#zoomer').hide();
  });
}

$(document).ready(function(){

  showDialog();    

});

So, once I've shown a dialog, I add a click handler that only looks for the first click on anything.

Now, it would be nicer if I could get it to ignore clicks on anything on #dialog and its contents, but when I tried switching $('*') with $(':not("#dialog,#dialog *")'), it still detected #dialog clicks.

Anyway, I was using this purely for a photo lightbox, so it worked okay for that purpose.

HTML5 LocalStorage: Checking if a key exists

The MDN documentation shows how the getItem method is implementated:

Object.defineProperty(oStorage, "getItem", {
      value: function (sKey) { return sKey ? this[sKey] : null; },
      writable: false,
      configurable: false,
      enumerable: false
    });

If the value isn't set, it returns null. You are testing to see if it is undefined. Check to see if it is null instead.

if(localStorage.getItem("username") === null){

How to check if a file is a valid image file?

Additionally to the PIL image check you can also add file name extension check like this:

filename.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif'))

Note that this only checks if the file name has a valid image extension, it does not actually open the image to see if it's a valid image, that's why you need to use additionally PIL or one of the libraries suggested in the other answers.

Jenkins - passing variables between jobs?

You can use Parameterized Trigger Plugin which will let you pass parameters from one task to another.

You need also add this parameter you passed from upstream in downstream.

Calling a method every x minutes

Example of using a Timer:

using System;
using System.Timers;

static void Main(string[] args)
{
    Timer t = new Timer(TimeSpan.FromMinutes(5).TotalMilliseconds); // Set the time (5 mins in this case)
    t.AutoReset = true;
    t.Elapsed += new System.Timers.ElapsedEventHandler(your_method);
    t.Start();
}

// This method is called every 5 mins
private static void your_method(object sender, ElapsedEventArgs e)
{
    Console.WriteLine("..."); 
}

Loop through a date range with JavaScript

Let us assume you got the start date and end date from the UI and stored it in the scope variable in the controller.

Then declare an array which will get reset on every function call so that on the next call for the function the new data can be stored.

var dayLabel = [];

Remember to use new Date(your starting variable) because if you dont use the new date and directly assign it to variable the setDate function will change the origional variable value in each iteration`

for (var d = new Date($scope.startDate); d <= $scope.endDate; d.setDate(d.getDate() + 1)) {
                dayLabel.push(new Date(d));
            }

How can I select the first day of a month in SQL?

I like to use FORMAT, you can even specify a time

SELECT FORMAT(@myDate,'yyyy-MM-01 06:00') first_of_a_month

Oracle: If Table Exists

A block like this could be useful to you.

DECLARE
    table_exist INT;

BEGIN
    SELECT Count(*)
    INTO   table_exist
    FROM   dba_tables
    WHERE  owner = 'SCHEMA_NAME' 
    AND table_name = 'EMPLOYEE_TABLE';

    IF table_exist = 1 THEN
      EXECUTE IMMEDIATE 'drop table EMPLOYEE_TABLE';
    END IF;
END;  

How to verify if $_GET exists?

You can use isset function:

if(isset($_GET['id'])) {
    // id index exists
}

You can create a handy function to return default value if index doesn't exist:

function Get($index, $defaultValue) {
    return isset($_GET[$index]) ? $_GET[$index] : $defaultValue;
}

// prints "invalid id" if $_GET['id'] is not set
echo Get('id', 'invalid id');

You can also try to validate it at the same time:

function GetInt($index, $defaultValue) {
    return isset($_GET[$index]) && ctype_digit($_GET[$index])
            ? (int)$_GET[$index] 
            : $defaultValue;
}

// prints 0 if $_GET['id'] is not set or is not numeric
echo GetInt('id', 0);

What is the difference between 127.0.0.1 and localhost

Wikipedia sums this up well:

On modern computer systems, localhost as a hostname translates to an IPv4 address in the 127.0.0.0/8 (loopback) net block, usually 127.0.0.1, or ::1 in IPv6.

The only difference is that it would be looking up in the DNS for the system what localhost resolves to. This lookup is really, really quick. For instance, to get to stackoverflow.com you typed in that to the address bar (or used a bookmarklet that pointed here). Either way, you got here through a hostname. localhost provides a similar functionality.

Set default heap size in Windows

Try setting a Windows System Environment variable called _JAVA_OPTIONS with the heap size you want. Java should be able to find it and act accordingly.

How to check the version of GitLab?

It can be retrieved using REST, see Version API :

curl --header "PRIVATE-TOKEN: 9koXpg98eAheJpvBs5tK" https://gitlab.example.com/api/v4/version

For authentication see Personal access tokens documentation.

"FATAL: Module not found error" using modprobe

Insert this in your Makefile

 $(MAKE) -C $(KDIR) M=$(PWD) modules_install                      

 it will install the module in the directory /lib/modules/<var>/extra/
 After make , insert module with modprobe module_name (without .ko extension)

OR

After your normal make, you copy module module_name.ko into   directory  /lib/modules/<var>/extra/

then do modprobe module_name (without .ko extension)

iPhone Debugging: How to resolve 'failed to get the task for process'?

I have had problems debugging binaries on the device via XCode when the app includes an Entitlements.plist file, which is not necessary to install onto the device for debugging. In general, then, I have included this file for release builds (where it is required for the App Store) and removed it for debugging (so I can debug the app from XCode). That may be your problem here.

Update: As of (at least) August 2010 (iPhone 4.1 SDK) the Entitlements.plist is no longer necessary to include in your application in many cases (e.g., distribution through the App Store.) See here for more information on the cases when Entitlements.plist is required:

IMPORTANT: An Entitlements file is generally only needed when building for Ad Hoc Distribution or enabling Keychain data sharing. If neither of these is true, delete the entry in Code Signing Entitlements. (emphasis mine)

The Role Manager feature has not been enabled

If you got here because you're using the new ASP.NET Identity UserManager, what you're actually looking for is the RoleManager:

var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

roleManager will give you access to see if the role exists, create, etc, plus it is created for the UserManager

Windows batch: call more than one command in a FOR loop?

SilverSkin and Anders are both correct. You can use parentheses to execute multiple commands. However, you have to make sure that the commands themselves (and their parameters) do not contain parentheses. cmd greedily searches for the first closing parenthesis, instead of handling nested sets of parentheses gracefully. This may cause the rest of the command line to fail to parse, or it may cause some of the parentheses to get passed to the commands (e.g. DEL myfile.txt)).

A workaround for this is to split the body of the loop into a separate function. Note that you probably need to jump around the function body to avoid "falling through" into it.

FOR /r %%X IN (*.txt) DO CALL :loopbody %%X
REM Don't "fall through" to :loopbody.
GOTO :EOF

:loopbody
ECHO %1
DEL %1
GOTO :EOF

Can I delete a git commit but keep the changes?

For those using zsh, you'll have to use the following:

git reset --soft HEAD\^

Explained here: https://github.com/robbyrussell/oh-my-zsh/issues/449

In case the URL becomes dead, the important part is:

Escape the ^ in your command

You can alternatively can use HEAD~ so that you don't have to escape it each time.

How to compare dates in c#

If you have date in DateTime variable then its a DateTime object and doesn't contain any format. Formatted date are expressed as string when you call DateTime.ToString method and provide format in it.

Lets say you have two DateTime variable, you can use the compare method for comparision,

DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 2, 0, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;

if (result < 0)
   relationship = "is earlier than";
else if (result == 0)
   relationship = "is the same time as";         
else
   relationship = "is later than";

Code snippet taken from msdn.

How do I change column default value in PostgreSQL?

If you want to remove the default value constraint, you can do:

ALTER TABLE <table> ALTER COLUMN <column> DROP DEFAULT;

ActiveMQ or RabbitMQ or ZeroMQ or

I've used ActiveMQ in a production environment for about 3 years now. While it gets the job done, lining up versions of the client libraries that work properly and are bug free can be an issue. Were currently looking to transition to RabbitMQ.

moment.js get current time in milliseconds?

See this link http://momentjs.com/docs/#/displaying/unix-timestamp-milliseconds/

valueOf() is the function you're looking for.

Editing my answer (OP wants milliseconds of today, not since epoch)

You want the milliseconds() function OR you could go the route of moment().valueOf()

CSS border less than 1px

A pixel is the smallest unit value to render something with, but you can trick thickness with optical illusions by modifying colors (the eye can only see up to a certain resolution too).

Here is a test to prove this point:

_x000D_
_x000D_
div { border-color: blue; border-style: solid; margin: 2px; }

div.b1 { border-width: 1px; }
div.b2 { border-width: 0.1em; }
div.b3 { border-width: 0.01em; }
div.b4 { border-width: 1px; border-color: rgb(160,160,255); }
_x000D_
<div class="b1">Some text</div>
<div class="b2">Some text</div>
<div class="b3">Some text</div>
<div class="b4">Some text</div>
_x000D_
_x000D_
_x000D_

Output

enter image description here

Which gives the illusion that the last DIV has a smaller border width, because the blue border blends more with the white background.


Edit: Alternate solution

Alpha values may also be used to simulate the same effect, without the need to calculate and manipulate RGB values.

_x000D_
_x000D_
.container {
  border-style: solid;
  border-width: 1px;
  
  margin-bottom: 10px;
}

.border-100 { border-color: rgba(0,0,255,1); }
.border-75 { border-color: rgba(0,0,255,0.75); }
.border-50 { border-color: rgba(0,0,255,0.5); }
.border-25 { border-color: rgba(0,0,255,0.25); }
_x000D_
<div class="container border-100">Container 1 (alpha = 1)</div>
<div class="container border-75">Container 2 (alpha = 0.75)</div>
<div class="container border-50">Container 3 (alpha = 0.5)</div>
<div class="container border-25">Container 4 (alpha = 0.25)</div>
_x000D_
_x000D_
_x000D_

Export and Import all MySQL databases at one time

Export:

mysqldump -u root -p --all-databases > alldb.sql

Look up the documentation for mysqldump. You may want to use some of the options mentioned in comments:

mysqldump -u root -p --opt --all-databases > alldb.sql
mysqldump -u root -p --all-databases --skip-lock-tables > alldb.sql

Import:

mysql -u root -p < alldb.sql

How to list the size of each file and directory and sort by descending size in Bash?

I tend to use du in a simple way.

du -sh */ | sort -n

This provides me with an idea of what directories are consuming the most space. I can then run more precise searches later.

Update TextView Every Second

It would be better if you just used an AsyncTask running using a Timer something like this

 Timer LAIATT = new Timer();
    TimerTask LAIATTT = new TimerTask()
    {
        @Override
        public void run()
        {
            LoadAccountInformationAsyncTask LAIAT = new LoadAccountInformationAsyncTask();
            LAIAT.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
    };
    LAIATT.schedule(LAIATTT, 0, 1000);

iOS - Ensure execution on main thread

there any rule I can follow to be sure that my app executes my own code just in the main thread?

Typically you wouldn't need to do anything to ensure this — your list of things is usually enough. Unless you're interacting with some API that happens to spawn a thread and run your code in the background, you'll be running on the main thread.

If you want to be really sure, you can do things like

[self performSelectorOnMainThread:@selector(myMethod:) withObject:anObj waitUntilDone:YES];

to execute a method on the main thread. (There's a GCD equivalent too.)

How do I cancel form submission in submit button onclick event?

With JQuery is even more simple: works in Asp.Net MVC and Asp.Core

<script>
    $('#btnSubmit').on('click', function () {

        if (ValidData) {
            return true;   //submit the form
        }
        else {
            return false;  //cancel the submit
        }
    });
</script>

python: after installing anaconda, how to import pandas

You can only import a library which has been installed in your environment.

If you have created a new environment, e.g. to run an older version of Python, maybe you lack 'pandas' package, which is in the 'base' environment of Anaconda by default.

Fix through GUI

To add it to your environment, from the GUI, select your environment, select "All" in the dropdown list, type pandas in the text field, select the pandas package and Apply.

Afterwards, select 'Installed' to verify that the package has been correctly installed.

How to check a boolean condition in EL?

Both works. Instead of == you can write eq

Is there anyway to exclude artifacts inherited from a parent POM?

We can add the parent pom as a dependency with type pom and make exclusion on that. Because anyhow parent pom is downloaded. This worked for me

<dependency>
  <groupId>com.abc.boot</groupId>
  <artifactId>abc-boot-starter-parent</artifactId>
  <version>2.1.5.RELEASE</version>
  <type>pom</type>
  <exclusions>
    <exclusion>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
    </exclusion>
  </exclusions>   
</dependency>

Unresolved Import Issues with PyDev and Eclipse

I fixed my pythonpath and everything was dandy when I imported stuff through the console, but all these previously unresolved imports were still marked as errors in my code, no matter how many times I restarted eclipse or refreshed/cleaned the project.

I right clicked the project->Pydev->Remove error markers and it got rid of that problem. Don't worry, if your code contains actual errors they will be re-marked.

Primitive type 'short' - casting in Java

EDIT: Okay, now we know it's Java...

Section 4.2.2 of the Java Language Specification states:

The Java programming language provides a number of operators that act on integral values:

[...]

  • The numerical operators, which result in a value of type int or long:
  • [...]
  • The additive operators + and - (§15.18)

  • In other words, it's like C# - the addition operator (when applied to integral types) only ever results in int or long, which is why you need to cast to assign to a short variable.

    Original answer (C#)

    In C# (you haven't specified the language, so I'm guessing), the only addition operators on primitive types are:

    int operator +(int x, int y);
    uint operator +(uint x, uint y);
    long operator +(long x, long y);
    ulong operator +(ulong x, ulong y);
    float operator +(float x, float y);
    double operator +(double x, double y);
    

    These are in the C# 3.0 spec, section 7.7.4. In addition, decimal addition is defined:

    decimal operator +(decimal x, decimal y);
    

    (Enumeration addition, string concatenation and delegate combination are also defined there.)

    As you can see, there's no short operator +(short x, short y) operator - so both operands are implicitly converted to int, and the int form is used. That means the result is an expression of type "int", hence the need to cast.

    How to add default signature in Outlook

    Most of the other answers are simply concatenating their HTML body with the HTML signature. However, this does not work with images, and it turns out there is a more "standard" way of doing this.1

    Microsoft Outlook pre-2007 which is configured with WordEditor as its editor, and Microsoft Outlook 2007 and beyond, use a slightly cut-down version of the Word Editor to edit emails. This means we can use the Microsoft Word Document Object Model to make changes to the email.

    Set objMsg = Application.CreateItem(olMailItem)
    objMsg.GetInspector.Display 'Displaying an empty email will populate the default signature
    Set objSigDoc = objMsg.GetInspector.WordEditor
    Set objSel = objSigDoc.Windows(1).Selection
    With objSel
       .Collapse wdCollapseStart
       .MoveEnd WdUnits.wdStory, 1
       .Copy 'This will copy the signature
    End With
    objMsg.HTMLBody = "<p>OUR HTML STUFF HERE</p>"
    With objSel
       .Move WdUnits.wdStory, 1 'Move to the end of our new message
       .PasteAndFormat wdFormatOriginalFormatting 'Paste the copied signature
    End With 
    'I am not a VB programmer, wrote this originally in another language so if it does not
    'compile it is because this is my first VB method :P
    

    Microsoft Outlook 2007 Programming (S. Mosher)> Chapter 17, Working with Item Bodies: Working with Outlook Signatures

    How to handle button clicks using the XML onClick within Fragments

    I would rather go for the click handling in code than using the onClick attribute in XML when working with fragments.

    This becomes even easier when migrating your activities to fragments. You can just call the click handler (previously set to android:onClick in XML) directly from each case block.

    findViewById(R.id.button_login).setOnClickListener(clickListener);
    ...
    
    OnClickListener clickListener = new OnClickListener() {
        @Override
        public void onClick(final View v) {
            switch(v.getId()) {
               case R.id.button_login:
                  // Which is supposed to be called automatically in your
                  // activity, which has now changed to a fragment.
                  onLoginClick(v);
                  break;
    
               case R.id.button_logout:
                  ...
            }
        }
    }
    

    When it comes to handling clicks in fragments, this looks simpler to me than android:onClick.

    How can I make the contents of a fixed element scrollable only when it exceeds the height of the viewport?

    Try this on your position:fixed element.

    overflow-y: scroll;
    max-height: 100%;
    

    How to update UI from another thread running in another class

    Everything that interacts with the UI must be called in the UI thread (unless it is a frozen object). To do that, you can use the dispatcher.

    var disp = /* Get the UI dispatcher, each WPF object has a dispatcher which you can query*/
    disp.BeginInvoke(DispatcherPriority.Normal,
            (Action)(() => /*Do your UI Stuff here*/));
    

    I use BeginInvoke here, usually a backgroundworker doesn't need to wait that the UI updates. If you want to wait, you can use Invoke. But you should be careful not to call BeginInvoke to fast to often, this can get really nasty.

    By the way, The BackgroundWorker class helps with this kind of taks. It allows Reporting changes, like a percentage and dispatches this automatically from the Background thread into the ui thread. For the most thread <> update ui tasks the BackgroundWorker is a great tool.

    With CSS, how do I make an image span the full width of the page as a background image?

    If you're hoping to use background-image: url(...);, I don't think you can. However, if you want to play with layering, you can do something like this:

    <img class="bg" src="..." />
    

    And then some CSS:

    .bg
    {
      width: 100%;
      z-index: 0;
    }
    

    You can now layer content above the stretched image by playing with z-indexes and such. One quick note, the image can't be contained in any other elements for the width: 100%; to apply to the whole page.

    Here's a quick demo if you can't rely on background-size: http://jsfiddle.net/bB3Uc/

    C# windows application Event: CLR20r3 on application start

    Have been fighting this all morning and now have it solved and why it happened. Posting with the hope it helps others

    I installed the Krypton.Toolkit which added the tools to the Visual studio toolbox automatically. I then added the tools to the designer, which automatically added the dll to the projrect references, however the toolkit was marked as CopyLocal=false

    I built an installer, using all dlls in the release build folder (of course the above dll wasn't there).

    Setting copylocal=true, then rebuilding the installer, everything worked fine.

    MySQL Update Column +1?

    update post set count = count + 1 where id = 101
    

    How to insert selected columns from a CSV file to a MySQL database using LOAD DATA INFILE

    Load data into a table in MySQL and specify columns:

    LOAD DATA LOCAL INFILE 'file.csv' INTO TABLE t1 
    FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'  
    (@col1,@col2,@col3,@col4) set name=@col4,id=@col2 ;
    

    @col1,2,3,4 are variables to hold the csv file columns (assume 4 ) name,id are table columns.

    cout is not a member of std

    I had a similar issue and it turned out that i had to add an extra entry in cmake to include the files.

    Since i was also using the zmq library I had to add this to the included libraries as well.

    How do you set autocommit in an SQL Server session?

    You can turn autocommit ON by setting implicit_transactions OFF:

    SET IMPLICIT_TRANSACTIONS OFF
    

    When the setting is ON, it returns to implicit transaction mode. In implicit transaction mode, every change you make starts a transactions which you have to commit manually.

    Maybe an example is clearer. This will write a change to the database:

    SET IMPLICIT_TRANSACTIONS ON
    UPDATE MyTable SET MyField = 1 WHERE MyId = 1
    COMMIT TRANSACTION
    

    This will not write a change to the database:

    SET IMPLICIT_TRANSACTIONS ON
    UPDATE MyTable SET MyField = 1 WHERE MyId = 1
    ROLLBACK TRANSACTION
    

    The following example will update a row, and then complain that there's no transaction to commit:

    SET IMPLICIT_TRANSACTIONS OFF
    UPDATE MyTable SET MyField = 1 WHERE MyId = 1
    ROLLBACK TRANSACTION
    

    Like Mitch Wheat said, autocommit is the default for Sql Server 2000 and up.

    Facebook Oauth Logout

    Here's an alternative to the accepted answer that works in the current (2.12) version of the API.

    <a href="#" onclick="logoutFromFacebookAndRedirect('/logout')">Logout</a>
    
    <script>
        FB.init({
            appId: '{your-app-id}',
            cookie: true,
            xfbml: true,
            version: 'v2.12'
        });
    
        function logoutFromFacebookAndRedirect(redirectUrl) {
            FB.getLoginStatus(function (response) {
                if (response.status == 'connected')
                    FB.logout(function (response) {
                        window.location.href = redirectUrl;
                    });
                else
                    window.location.href = redirectUrl;
            });
        }
    </script>
    

    Bootstrap 3 Align Text To Bottom of Div

    I collected some ideas from other SO question (largely from here and this css page)

    Fiddle

    The idea is to use relative and absolute positioning to move your line to the bottom:

    @media (min-width: 768px ) {
    .row {
        position: relative;
    }
    
    #bottom-align-text {
        position: absolute;
        bottom: 0;
        right: 0;
      }}
    

    The display:flex option is at the moment a solution to make the div get the same size as its parent. This breaks on the other hand the bootstrap possibilities to auto-linebreak on small devices by adding col-sx-12 class. (This is why the media query is needed)

    How do I tell if a variable has a numeric value in Perl?

    Check out the CPAN module Regexp::Common. I think it does exactly what you need and handles all the edge cases (e.g. real numbers, scientific notation, etc). e.g.

    use Regexp::Common;
    if ($var =~ /$RE{num}{real}/) { print q{a number}; }
    

    Improve subplot size/spacing with many subplots in matplotlib

    You can use plt.subplots_adjust to change the spacing between the subplots (source)

    call signature:

    subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)
    

    The parameter meanings (and suggested defaults) are:

    left  = 0.125  # the left side of the subplots of the figure
    right = 0.9    # the right side of the subplots of the figure
    bottom = 0.1   # the bottom of the subplots of the figure
    top = 0.9      # the top of the subplots of the figure
    wspace = 0.2   # the amount of width reserved for blank space between subplots
    hspace = 0.2   # the amount of height reserved for white space between subplots
    

    The actual defaults are controlled by the rc file

    NuGet Packages are missing

    I couldn't find any solutions to this so I added a copy of the nuget.exe and a powershell script to the root directory of the solution called prebuild.ps1 with the following content.

    $nugetexe = 'nuget.exe'
    $args = 'restore SOLUTION_NAME_HERE.sln'
    Start-Process $nugetexe -ArgumentList $args
    

    I called this powershell script in my build in the Pre-Build script path enter image description here

    Tools to selectively Copy HTML+CSS+JS From A Specific Element of DOM

    Just copy the part you want from the webpage and paste it in the wysiwyg editor. Check the html source by clicking on the "source" button on the editor toolbar.

    I've found this most easiest way when I was working on a Drupal site. I use wysiwyg CKeditor.

    Bootstrap visible and hidden classes not working properly

    Your mobile class Isn't correct:

    .mobile {
      display: none !important;
      visibility: hidden !important; //This is what's keeping the div from showing, remove this.
    }
    

    How do I generate a constructor from class fields using Visual Studio (and/or ReSharper)?

    As of Visual Studio 2017, this looks to be a built-in feature. Hit Ctrl + . while your cursor is in the class body, and select "Generate Constructor" from the Quick Actions and Refactorings dropdown.

    how do I get eclipse to use a different compiler version for Java?

    First off, are you setting your desired JRE or your desired JDK?

    Even if your Eclipse is set up properly, there might be a wacky project-specific setting somewhere. You can open up a context menu on a given Java project in the Project Explorer and select Properties > Java Compiler to check on that.

    If none of that helps, leave a comment and I'll take another look.

    Can not deserialize instance of java.lang.String out of START_OBJECT token

    You're mapping this JSON

    {
        "id": 2,
        "socket": "0c317829-69bf-43d6-b598-7c0c550635bb",
        "type": "getDashboard",
        "data": {
            "workstationUuid": "ddec1caa-a97f-4922-833f-632da07ffc11"
        },
        "reply": true
    }
    

    that contains an element named data that has a JSON object as its value. You are trying to deserialize the element named workstationUuid from that JSON object into this setter.

    @JsonProperty("workstationUuid")
    public void setWorkstation(String workstationUUID) {
    

    This won't work directly because Jackson sees a JSON_OBJECT, not a String.

    Try creating a class Data

    public class Data { // the name doesn't matter 
        @JsonProperty("workstationUuid")
        private String workstationUuid;
        // getter and setter
    }
    

    the switch up your method

    @JsonProperty("data")
    public void setWorkstation(Data data) {
        // use getter to retrieve it
    

    Convert array to JSON string in swift

    Hint: To convert an NSArray containing JSON compatible objects to an NSData object containing a JSON document, use the appropriate method of NSJSONSerialization. JSONObjectWithData is not it.

    Hint 2: You rarely want that data as a string; only for debugging purposes.

    Can you force a React component to rerender without calling setState?

    Another way is calling setState, AND preserve state:

    this.setState(prevState=>({...prevState}));

    How to change Vagrant 'default' machine name?

    You can change vagrant default machine name by changing value of config.vm.define.

    Here is the simple Vagrantfile which uses getopts and allows you to change the name dynamically:

    # -*- mode: ruby -*-
    require 'getoptlong'
    
    opts = GetoptLong.new(
      [ '--vm-name',        GetoptLong::OPTIONAL_ARGUMENT ],
    )
    vm_name        = ENV['VM_NAME'] || 'default'
    
    begin
      opts.each do |opt, arg|
        case opt
          when '--vm-name'
            vm_name = arg
        end
      end
      rescue
    end
    
    Vagrant.configure(2) do |config|
      config.vm.define vm_name
      config.vm.provider "virtualbox" do |vbox, override|
        override.vm.box = "ubuntu/wily64"
        # ...
      end
      # ...
    end
    

    So to use different name, you can run for example:

    vagrant --vm-name=my_name up --no-provision
    

    Note: The --vm-name parameter needs to be specified before up command.

    or:

    VM_NAME=my_name vagrant up --no-provision
    

    Detect if value is number in MySQL

    you can do using CAST

      SELECT * from tbl where col1 = concat(cast(col1 as decimal), "")
    

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

    No issues with the latest kartoza/qgis-desktop

    I ran

    docker pull kartoza/qgis-desktop
    

    followed by

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

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

    How to make UIButton's text alignment center? Using IB

    Use the line:

    myButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    

    This should center the content (horizontally).

    And if you want to set the text inside the label to the center as well, use:

    [labelOne setTextAlignment:UITextAlignmentCenter];

    If you want to use IB, I've got a small example here which is linked in XCode 4 but should provide enough detail (also mind, on top of that properties screen it shows the property tab. You can find the same tabs in XCode 3.x): enter image description here

    Reading file using fscanf() in C

    fscanf will treat 2 arguments, and thus return 2. Your while statement will be false, hence never displaying what has been read, plus as it has read only 1 line, if is not at EOF, resulting in what you see.

    Bash scripting, multiple conditions in while loop

    The correct options are (in increasing order of recommendation):

    # Single POSIX test command with -o operator (not recommended anymore).
    # Quotes strongly recommended to guard against empty or undefined variables.
    while [ "$stats" -gt 300 -o "$stats" -eq 0 ]
    
    # Two POSIX test commands joined in a list with ||.
    # Quotes strongly recommended to guard against empty or undefined variables.
    while [ "$stats" -gt 300 ] || [ "$stats" -eq 0 ]
    
    # Two bash conditional expressions joined in a list with ||.
    while [[ $stats -gt 300 ]] || [[ $stats -eq 0 ]]
    
    # A single bash conditional expression with the || operator.
    while [[ $stats -gt 300 || $stats -eq 0 ]]
    
    # Two bash arithmetic expressions joined in a list with ||.
    # $ optional, as a string can only be interpreted as a variable
    while (( stats > 300 )) || (( stats == 0 ))
    
    # And finally, a single bash arithmetic expression with the || operator.
    # $ optional, as a string can only be interpreted as a variable
    while (( stats > 300 || stats == 0 ))
    

    Some notes:

    1. Quoting the parameter expansions inside [[ ... ]] and ((...)) is optional; if the variable is not set, -gt and -eq will assume a value of 0.

    2. Using $ is optional inside (( ... )), but using it can help avoid unintentional errors. If stats isn't set, then (( stats > 300 )) will assume stats == 0, but (( $stats > 300 )) will produce a syntax error.

    How to downgrade Xcode to previous version?

    I'm assuming you are having at least OSX 10.7, so go ahead into the applications folder (Click on Finder icon > On the Sidebar, you'll find "Applications", click on it ), delete the "Xcode" icon. That will remove Xcode from your system completely. Restart your mac.

    Now go to https://developer.apple.com/download/more/ and download an older version of Xcode, as needed and install. You need an Apple ID to login to that portal.

    Why can't decimal numbers be represented exactly in binary?

    The number 61.0 does indeed have an exact floating-point operation—but that's not true for all integers. If you wrote a loop that added one to both a double-precision floating point number and a 64-bit integer, eventually you'd reach a point where the 64-bit integer perfectly represents a number, but the floating point doesn't—because there aren't enough significant bits.

    It's just much easier to reach the point of approximation on the right side of the decimal point. If you started writing out all the numbers in binary floating point, it'd make more sense.

    Another way of thinking about it is that when you note that 61.0 is perfectly representable in base 10, and shifting the decimal point around doesn't change that, you're performing multiplication by powers of ten (10^1, 10^-1). In floating point, multiplying by powers of two does not affect the precision of the number. Try taking 61.0 and dividing it by three repeatedly for an illustration of how a perfectly precise number can lose its precise representation.

    Convert NaN to 0 in javascript

    _x000D_
    _x000D_
        var i = [NaN, 1,2,3];
    
        var j = i.map(i =>{ return isNaN(i) ? 0 : i});
        
        console.log(j)
    _x000D_
    _x000D_
    _x000D_

    Can PHP cURL retrieve response headers AND body in a single request?

    Just in case you can't / don't use CURLOPT_HEADERFUNCTION or other solutions;

    $nextCheck = function($body) {
        return ($body && strpos($body, 'HTTP/') === 0);
    };
    
    [$headers, $body] = explode("\r\n\r\n", $result, 2);
    if ($nextCheck($body)) {
        do {
            [$headers, $body] = explode("\r\n\r\n", $body, 2);
        } while ($nextCheck($body));
    }
    

    How to check if a "lateinit" variable has been initialized?

    If you have a lateinit property in one class and need to check if it is initialized from another class

    if(foo::file.isInitialized) // this wouldn't work
    

    The workaround I have found is to create a function to check if the property is initialized and then you can call that function from any other class.

    Example:

    class Foo() {
    
        private lateinit var myFile: File
    
        fun isFileInitialised() = ::file.isInitialized
    }
    
     // in another class
    class Bar() {
    
        val foo = Foo()
    
        if(foo.isFileInitialised()) // this should work
    }
    

    Group list by values

    I don't know about elegant, but it's certainly doable:

    oldlist = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]]
    # change into: list = [["A", "C"], ["B"], ["D", "E"]]
    
    order=[]
    dic=dict()
    for value,key in oldlist:
      try:
        dic[key].append(value)
      except KeyError:
        order.append(key)
        dic[key]=[value]
    newlist=map(dic.get, order)
    
    print newlist
    

    This preserves the order of the first occurence of each key, as well as the order of items for each key. It requires the key to be hashable, but does not otherwise assign meaning to it.

    Printing PDFs from Windows Command Line

    The error message is telling you.

    Try just

    "C:\Program Files (x86)\Adobe\Reader 10.0\Reader\AcroRd32.exe" /t "$pdf"
    

    When you enclose the string in single-quotes, this makes everything inside a valid string, including the " chars. By removing the single-quotes, the shell will process the dbl-quotes as string "wrappers".

    I would also wrap the filename variable in dbl-quotes so you can easily process files with spaces in their names, i.e.

    "C:\Program Files (x86)\Adobe\Reader 10.0\Reader\AcroRd32.exe" /t "$pdf"
    

    IHTH

    Tracing XML request/responses with JAX-WS

    You need to implement a javax.xml.ws.handler.LogicalHandler, this handler then needs to be referenced in a handler configuration file, which in turn is referenced by an @HandlerChain annotation in your service endpoint (interface or implementation). You can then either output the message via system.out or a logger in your processMessage implementation.

    See

    http://publib.boulder.ibm.com/infocenter/wasinfo/v7r0/index.jsp?topic=/com.ibm.websphere.express.doc/info/exp/ae/twbs_jaxwshandler.html

    http://java.sun.com/mailers/techtips/enterprise/2006/TechTips_June06.html

    Hosting a Maven repository on github

    Another alternative is to use any web hosting with webdav support. You will need some space for this somewhere of course but it is straightforward to set up and a good alternative to running a full blown nexus server.

    add this to your build section

         <extensions>
            <extension>
            <artifactId>wagon-webdav-jackrabbit</artifactId>
            <groupId>org.apache.maven.wagon</groupId>
            <version>2.2</version>
            </extension>
        </extensions>
    

    Add something like this to your distributionManagement section

    <repository>
        <id>release.repo</id>
        <url>dav:http://repo.jillesvangurp.com/releases/</url>
    </repository>
    

    Finally make sure to setup the repository access in your settings.xml

    add this to your servers section

        <server>
            <id>release.repo</id>
            <username>xxxx</username>
            <password>xxxx</password>
        </server>
    

    and a definition to your repositories section

                <repository>
                    <id>release.repo</id>
                    <url>http://repo.jillesvangurp.com/releases</url>
                    <releases>
                        <enabled>true</enabled>
                    </releases>
                    <snapshots>
                        <enabled>false</enabled>
                    </snapshots>
                </repository>
    

    Finally, if you have any standard php hosting, you can use something like sabredav to add webdav capabilities.

    Advantages: you have your own maven repository Downsides: you don't have any of the management capabilities in nexus; you need some webdav setup somewhere

    Extract Google Drive zip from Google colab notebook

    in my idea, you must go to a certain path for example:

    from google.colab import drive drive.mount('/content/drive/') cd drive/MyDrive/f/

    then :

    !apt install unzip !unzip zip_folder.zip -d unzip_folder enter image description here