Programs & Examples On #Image formats

Image file formats are standardized means of organizing and storing digital images. Image files are composed of digital data in one of these formats that can be rasterized for use on a computer display or printer.

JPG vs. JPEG image formats

There is no difference between them, it just a file extension for image/jpeg mime type. In fact file extension for image/jpeg is .jpg, .jpeg, .jpe .jif, .jfif, .jfi

Why doesn't java.util.Set have get(int index)?

You can do new ArrayList<T>(set).get(index)

Removing a model in rails (reverse of "rails g model Title...")

For future questioners: If you can't drop the tables from the console, try to create a migration that drops the tables for you. You should create a migration and then in the file note tables you want dropped like this:

class DropTables < ActiveRecord::Migration
  def up
    drop_table :table_you_dont_want
  end

  def down
    raise ActiveRecord::IrreversibleMigration
  end
end

Creating runnable JAR with Gradle

I checked quite some links for the solution, finally did the below mentioned steps to get it working. I am using Gradle 2.9.

Make the following changes in your build,gradle file :

  1. Mention plugin:

    apply plugin: 'eu.appsatori.fatjar'
    
  2. Provide the Buildscript:

    buildscript {
    repositories {
        jcenter()
    }
    
    dependencies {
        classpath "eu.appsatori:gradle-fatjar-plugin:0.3"
    }
    }
    
  3. Provide the Main Class:

    fatJar {
      classifier 'fat'
      manifest {
        attributes 'Main-Class': 'my.project.core.MyMainClass'
      }
      exclude 'META-INF/*.DSA', 'META-INF/*.RSA', 'META-INF/*.SF'
    }
    
  4. Create the fatjar:

    ./gradlew clean fatjar
    
  5. Run the fatjar from /build/libs/ :

    java -jar MyFatJar.jar
    

How to show Error & Warning Message Box in .NET/ How to Customize MessageBox

Try this:

MessageBox.Show("Some text", "Some title", 
    MessageBoxButtons.OK, MessageBoxIcon.Error);

python inserting variable string as file name

And with the new string formatting method...

f = open('{0}.csv'.format(name), 'wb')

javax.persistence.PersistenceException: No Persistence provider for EntityManager named customerManager

If you are using Maven you may have both src/{main,test}/resources/META-INF/persistence.xml. This is a common setup: test your JPA code with h2 or Derby and deploy it with PostgreSQL or some other full DBMS. If you're using this pattern, do make sure the two files have different unit names, else some versions of the Persistence class will try to load BOTH (because of course your test-time CLASSPATH includes both classes and test-classes); this will cause conflicting definitions of the persistence unit, resulting in the dreaded annoying message that we all hate so much!

Worse: this may "work" with some older versions of e.g., Hibernate, but fail with current versions. Worth getting it right anyway...

how to add script src inside a View when using Layout

You can add the script tags like how we use in the asp.net while doing client side validations like below.

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<script type="text/javascript" src="~/Scripts/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
    $(function () {
       //Your code
    });
</script>

How do I remove background-image in css?

div#a {
  background-image: url('../images/spacer.png');
  background-image: none !important;
}

I use a transparent spacer image in addition to the rule to remove the background image because IE6 seems to ignore the background-image: none even though it is marked !important.

Cannot download Docker images behind a proxy

To solve the problem with curl in Docker build, I added the following inside the Dockerfile:

ENV http_proxy=http://infoprx2:8080
ENV https_proxy=http://infoprx2:8080
RUN apt-get update && apt-get install -y curl vim

Note that the ENV statement is BEFORE the RUN statement.

And in order to make the Docker daemon able to access the Internet (I use Kitematic with boot2docker), I added the following into /var/lib/boot2docker/profile:

export HTTP_PROXY=http://infoprx2:8080
export HTTPS_PROXY=http://infoprx2:8080

Then I restarted Docker with sudo /etc/init.d/docker restart.

Kotlin Ternary Conditional Operator

There is no ternary operation in Kotlin, but there are some fun ways to work around that. As others have pointed out, a direct translation into Kotlin would look like this:

val x = if (condition) result1 else result2

But, personally, I think that can get a bit cluttered and hard to read. There are some other options built into the library. You can use takeIf {} with an elvis operator:

val x = result1.takeIf { condition } ?: result2

What is happening there is that the takeIf { } command returns either your result1 or null, and the elvis operator handles the null option. There are some additional options, takeUnless { }, for example:

val x = result1.takeUnless { condition } ?: result2

The language is clear, you know what that's doing.

If it's a commonly used condition, you could also do something fun like use an inline extension method. Let's assume we want to track a game score as an Int, for example, and we want to always return 0 if a given condition is not met:

inline fun Int.zeroIfFalse(func: () -> Boolean) : Int = if (!func.invoke()) 0 else this     

Ok, that seems ugly. But consider how it looks when it is used:

var score = 0
val twoPointer = 2
val threePointer = 3

score += twoPointer.zeroIfFalse { scoreCondition } 
score += threePointer.zeroIfFalse { scoreCondition } 

As you can see, Kotlin offers a lot of flexibility in how you choose to express your code. There are countless variations of my examples and probably ways I haven't even discovered yet. I hope this helps!

integrating barcode scanner into php application?

I've been using something like this. Just set up a simple HTML page with an textinput. Make sure that the textinput always has focus. When you scan a barcode with your barcode scanner you will receive the code and after that a 'enter'. Realy simple then; just capture the incoming keystrokes and when the 'enter' comes in you can use AJAX to handle your code.

what is the difference between XSD and WSDL

XSD : XML Schema Definition.

XML : eXtensible Markup Language.

WSDL : Web Service Definition Language.

I am not going to answer in technical terms. I am aiming this explanation at beginners.

It is not easy to communicate between two different applications that are developed using two different technologies. For example, a company in Chicago might develop a web application using Java and another company in New York might develop an application in C# and when these two companies decided to share information then XML comes into picture. It helps to store and transport data between two different applications that are developed using different technologies. Note: It is not limited to a programming language, please do research on the information transportation between two different apps.

XSD is a schema definition. By that what I mean is, it is telling users to develop their XML in such a schema. Please see below images, and please watch closely with "load-on-startup" element and its type which is integer. In the XSD image you can see it is meant to be integer value for the "load-on-startup" and hence when user created his/her XML they passed an int value to that particular element. As a reminder, XSD is a schema and style whereas XML is a form to communicate with another application or system. One has to see XSD and create XML in such a way or else it won't communicate with another application or system which has been developed with a different technology. A company in Chicago provides a XSD template for a company in Texas to write or generate their XML in the given XSD format. If the company in Texas failed to adhere with those rules or schema mentioned in XSD then it is impossible to expect correct information from the company in Chicago. There is so much to do after the above said story, which an amateur or newbie have to know while coding for some thing like I said above. If you really want to know what happens later then it is better to sit with senior software engineers who actually developed web services. Next comes WSDL, please follow the images and try to figure out where the WSDL will fit in.

***************========Below is partial XML image ==========*************** XML image partial

***************========Below is partial XSD image ==========***************

XSD image partial

***************========Below is the partial WSDL image =======*************

WSDL image partial

I had to create a sample WSDL for a web service called Book. Note, it is an XSD but you have to call it WSDL (Web Service Definition Language) because it is very specific for Web Services. The above WSDL (or in other words XSD) is created for a class called Book.java and it has created a SOAP service. How the SOAP web service created it is a different topic. One has to write a Java class and before executing it create as a web service the user has to make sure Axis2 API is installed and Tomcat to host web service is in place.

As a servicer (the one who allows others (clients) to access information or data from their systems ) actually gives the client (the one who needs to use servicer information or data) complete access to data through a Web Service, because no company on the earth willing to expose their Database for outsiders. Like my company, decided to give some information about products via Web Services, hence we had to create XSD template and pass-on to few of our clients who wants to work with us. They have to write some code to make complete use of the given XSD and make Web Service calls to fetch data from servicer and convert data returned into their suitable requirement and then display or publish data or information about the product on their website. A simple example would be FLIGHT Ticket booking. An airline will let third parties to use flight data on their site for ticket sales. But again there is much more to it, it is just not letting third party flight ticket agent to sell tickets, there will be synchronize and security in place. If there is no sync then there is 100 % chances more than 1 customer might buy same flight ticket from various sources.

I am hoping experts will contribute to my answer. It is really hard for newbie or novice to understand XML, XSD and then to work on Web Services.

How to supply value to an annotation from a Constant java

Compile constants can only be primitives and Strings:

15.28. Constant Expressions

A compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:

  • Literals of primitive type and literals of type String
  • Casts to primitive types and casts to type String
  • [...] operators [...]
  • Parenthesized expressions whose contained expression is a constant expression.
  • Simple names that refer to constant variables.
  • Qualified names of the form TypeName . Identifier that refer to constant variables.

Actually in java there is no way to protect items in an array. At runtime someone can always do FieldValues.FIELD1[0]="value3", therefore the array cannot be really constant if we look deeper.

SQL Bulk Insert with FIRSTROW parameter skips the following line

Maybe check that the header has the same line-ending as the actual data rows (as specified in ROWTERMINATOR)?

Update: from MSDN:

The FIRSTROW attribute is not intended to skip column headers. Skipping headers is not supported by the BULK INSERT statement. When skipping rows, the SQL Server Database Engine looks only at the field terminators, and does not validate the data in the fields of skipped rows.

How to properly export an ES6 class in Node 4?

If you are using ES6 in Node 4, you cannot use ES6 module syntax without a transpiler, but CommonJS modules (Node's standard modules) work the same.

module.export.AspectType

should be

module.exports.AspectType

hence the error message "Cannot set property 'AspectType' of undefined" because module.export === undefined.

Also, for

var AspectType = class AspectType {
    // ...    
};

can you just write

class AspectType {
    // ...    
}

and get essentially the same behavior.

How to replace a whole line with sed?

If you would like to use awk then this would work too

awk -F= '{$2="xxx";print}' OFS="\=" filename

Annotation @Transactional. How to rollback?

For me rollbackFor was not enough, so I had to put this and it works as expected:

@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)

I hope it helps :-)

Extract source code from .jar file

I know it's an old question Still thought it would help someone

1) Go to your jar file's folder.

2) change it's extension to .zip.

3) You are good to go and can easily extract it by just double clicking it.

Note: I tested this in MAC, it works. Hopefully it will work on windows too.

spring autowiring with unique beans: Spring expected single matching bean but found 2

The issue is because you have a bean of type SuggestionService created through @Component annotation and also through the XML config . As explained by JB Nizet, this will lead to the creation of a bean with name 'suggestionService' created via @Component and another with name 'SuggestionService' created through XML .

When you refer SuggestionService by @Autowired, in your controller, Spring autowires "by type" by default and find two beans of type 'SuggestionService'

You could do the following

  1. Remove @Component from your Service and depend on mapping via XML - Easiest

  2. Remove SuggestionService from XML and autowire the dependencies - use util:map to inject the indexSearchers map.

  3. Use @Resource instead of @Autowired to pick the bean by its name .

     @Resource(name="suggestionService")
     private SuggestionService service;
    

or

    @Resource(name="SuggestionService")
    private SuggestionService service;

both should work.The third is a dirty fix and it's best to resolve the bean conflict through other ways.

There is no argument given that corresponds to the required formal parameter - .NET Error

I got the same error but it was due to me not creating a default constructor. If you haven't already tried that, create the default constructor like this:

public TestClass() {

}

SQL Server Express 2008 Install Side-by-side w/ SQL 2005 Express Fails

Simply remove the Microsoft SQL Server Management Studio Express 2005 from control panel

How can I find the OWNER of an object in Oracle?

You can query the ALL_OBJECTS view:

select owner
     , object_name
     , object_type
  from ALL_OBJECTS
 where object_name = 'FOO'

To find synonyms:

select *
  from ALL_SYNONYMS
 where synonym_name = 'FOO'

Just to clarify, if a user user's SQL statement references an object name with no schema qualification (e.g. 'FOO'), Oracle FIRST checks the user's schema for an object of that name (including synonyms in that user's schema). If Oracle can't resolve the reference from the user's schema, Oracle then checks for a public synonym.

If you are looking specifically for constraints on a particular table_name:

select c.*
  from all_constraints c 
 where c.table_name = 'FOO'
 union all
select cs.*
  from all_constraints cs
  join all_synonyms s 
    on (s.table_name = cs.table_name
     and s.table_owner = cs.owner 
     and s.synonym_name = 'FOO'
       )

HTH

-- addendum:

If your user is granted access to the DBA_ views (e.g. if your user has been granted SELECT_CATALOG_ROLE), you can substitute 'DBA_' in place of 'ALL_' in the preceding SQL examples. The ALL_x views only show objects which you have been granted privileges. The DBA_x views will show all database objects, whether you have privileges on them or not.

What’s the difference between “{}” and “[]” while declaring a JavaScript array?

[ ] - this is used whenever we are declaring an empty array,

{ } - this is used whenever we declare an empty object

typeof([ ]) //object
typeof({ }) //object

but if your run

[ ].constructor.name  //Array

so from this, you will understand it is an array here Array is the name of the base class. The JavaScript Array class is a global object that is used in the construction of arrays which are high-level, list-like objects.

What's the difference between an Angular component and module

Well, it's too late to post an answer, but I feel my explanation will be easy to understand for beginners with Angular. The following is one of the examples that I give during my presentation.

Consider your angular Application as a building. A building can have N number of apartments in it. An apartment is considered as a module. An Apartment can then have N number of rooms which correspond to the building blocks of an Angular application named components.

Now each apartment (Module)` will have rooms (Components), lifts (Services) to enable larger movement in and out the apartments, wires (Pipes) to transform around and make it useful in the apartments.

You will also have places like swimming pool, tennis court which are being shared by all building residents. So these can be considered as components inside SharedModule.

Basically, the difference is as follows,

Table showing key differences between Module and Component

Follow my slides to understand the building blocks of an Angular application

Here is my session on Building Blocks of Angular for beginners

How to pass an array into a function, and return the results with an array

i know a Class is a bit the overkill

class Foo
{

 private $sum = NULL;

 public function __construct($array)
 {
   $this->sum[] = $array;
   return $this;
 }

 public function getSum()
 {
   $sum = $this->sum;
   for($i=0;$i<count($sum);$i++)
   {
      // get the last array index
      $res[$i] = $sum[$i] + $sum[count($sum)-$i];
   }
   return $res;
 }


}


$fo = new Foo($myarray)->getSum();

Selenium Webdriver submit() vs click()

There is a difference between click() and submit().

submit() submits the form and executes the url that is given by the "action" attribute. If you have any javascript-function or jquery-plugin running to submit the form e.g. via ajax, submit() will ignore it. With click() the javascript-functions will be executed.

Send a ping to each IP on a subnet

Broadcast ping:

$ ping 192.168.1.255
PING 192.168.1.255 (192.168.1.255): 56 data bytes
64 bytes from 192.168.1.154: icmp_seq=0 ttl=64 time=0.104 ms
64 bytes from 192.168.1.51: icmp_seq=0 ttl=64 time=2.058 ms (DUP!)
64 bytes from 192.168.1.151: icmp_seq=0 ttl=64 time=2.135 ms (DUP!)
...

(Add a -b option on Linux)

How to know installed Oracle Client is 32 bit or 64 bit?

On 64-bit system:

32-bit Driver: C:\Windows\SysWOW64\odbcad32.exe

64-bit Driver: C:\Windows\System32\odbcad32.exe

Go to Drivers Tab
Version is shown there as well.

Python foreach equivalent

The foreach construct is unfortunately not intrinsic to collections but instead external to them. The result is two-fold:

  • it can not be chained
  • it requires two lines in idiomatic python.

Python does not support a true foreach on collections directly. An example would be

myList.foreach( a => print(a)).map( lambda x:  x*2)

But python does not support it. Partial fixes to this and other missing functionals features in python are provided by various third party libraries including one that I helped author: see https://pypi.org/project/infixpy/

Anaconda version with Python 3.5

You can install any current version of Anaconda. You can then make a conda environment with your particular needs from the documentation

conda create -n tensorflowproject python=3.5 tensorflow ipython

This command has a specific version for python and when this tensorflowproject environment gets updated it will upgrade to Python 3.5999999999 but never go to 3.6 . Then you switch to your environment using either

source activate tensorflowproject

for linux/mac or

activate tensorflowproject

on windows

Is it possible to focus on a <div> using JavaScript focus() function?

window.location.hash = '#tries';

This will scroll to the element in question, essentially "focus"ing it.

Get cookie by name

One approach, which avoids iterating over an array, would be:

function getCookie(name) {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2) return parts.pop().split(';').shift();
}

Walkthrough

Splitting a string by token will produce either, an array with one string (same value), in case token does not exist in a string, or an array with two strings , in case token is found in a string .

The first (left) element is string of what was before the token, and the second one (right) is what is string of what was after the token.

(NOTE: in case string starts with a token, first element is an empty string)

Considering that cookies are stored as follows:

"{name}={value}; {name}={value}; ..."

in order to retrieve specific cookie value, we just need to get string that is after "; {name}=" and before next ";". Before we do any processing, we prepend the cookies string with "; ", so that every cookie name, including the first one, is enclosed with "; " and "=":

"; {name}={value}; {name}={value}; ..."

Now, we can first split by "; {name}=", and if token is found in a cookie string (i.e. we have two elements), we will end up with second element being a string that begins with our cookie value. Then we pull that out from an array (i.e. pop), and repeat the same process, but now with ";" as a token, but this time pulling out the left string (i.e. shift) to get the actual token value.

Node.js: get path from the request

Combining solutions above when using express request:

let url=url.parse(req.originalUrl);
let page = url.parse(uri).path?url.parse(uri).path.match('^[^?]*')[0].split('/').slice(1)[0] : '';

this will handle all cases like

localhost/page
localhost:3000/page/
/page?item_id=1
localhost:3000/
localhost/

etc. Some examples:

> urls
[ 'http://localhost/page',
  'http://localhost:3000/page/',
  'http://localhost/page?item_id=1',
  'http://localhost/',
  'http://localhost:3000/',
  'http://localhost/',
  'http://localhost:3000/page#item_id=2',
  'http://localhost:3000/page?item_id=2#3',
  'http://localhost',
  'http://localhost:3000' ]
> urls.map(uri => url.parse(uri).path?url.parse(uri).path.match('^[^?]*')[0].split('/').slice(1)[0] : '' )
[ 'page', 'page', 'page', '', '', '', 'page', 'page', '', '' ]

open read and close a file in 1 line of code

No need to import any special libraries to do this.

Use normal syntax and it will open the file for reading then close it.

with open("/etc/hostname","r") as f: print f.read() 

or

with open("/etc/hosts","r") as f: x = f.read().splitlines()

which gives you an array x containing the lines, and can be printed like so:

for line in x: print line

These one-liners are very helpful for maintenance - basically self-documenting.

How do I set proxy for chrome in python webdriver?

from selenium import webdriver
from selenium.webdriver.common.proxy import *

myProxy = "86.111.144.194:3128"
proxy = Proxy({
    'proxyType': ProxyType.MANUAL,
    'httpProxy': myProxy,
    'ftpProxy': myProxy,
    'sslProxy': myProxy,
    'noProxy':''})

driver = webdriver.Firefox(proxy=proxy)
driver.set_page_load_timeout(30)
driver.get('http://whatismyip.com')

rotating axis labels in R

As Maciej Jonczyk mentioned, you may also need to increase margins

par(las=2)
par(mar=c(8,8,1,1)) # adjust as needed
plot(...)

Which comes first in a 2D array, rows or columns?

In java the rows are done first, because a 2 dimension array is considered two separate arrays. Starts with the first row 1 dimension array.

How to round up value C# to the nearest integer?

Use a function in place of MidpointRounding.AwayFromZero:

myRound(1.11125,4)

Answer:- 1.1114

public static Double myRound(Double Value, int places = 1000)
{
    Double myvalue = (Double)Value;
    if (places == 1000)
    {
        if (myvalue - (int)myvalue == 0.5)
        {
            myvalue = myvalue + 0.1;
            return (Double)Math.Round(myvalue);
        }
        return (Double)Math.Round(myvalue);
        places = myvalue.ToString().Substring(myvalue.ToString().IndexOf(".") + 1).Length - 1;
    } if ((myvalue * Math.Pow(10, places)) - (int)(myvalue * Math.Pow(10, places)) > 0.49)
    {
        myvalue = (myvalue * Math.Pow(10, places + 1)) + 1;
        myvalue = (myvalue / Math.Pow(10, places + 1));
    }
    return (Double)Math.Round(myvalue, places);
}

Selecting empty text input using jQuery

$(":text[value='']").doStuff();

?

By the way, your call of:

$('input[id=cmdSubmit]')...

can be greatly simplified and speeded up with:

$('#cmdSubmit')...

How to use regex in XPath "contains" function

In Robins's answer ends-with is not supported in xpath 1.0 too.. Only starts-with is supported... So if your condition is not very specific..You can Use like this which worked for me

//*[starts-with(@id,'sometext') and contains(@name,'_text')]`\

datatable jquery - table header width not aligned with body width

Found the solution :

Added table-layout:fixed to the table. And opened the application in IE mode.

__proto__ VS. prototype in JavaScript

[[Prototype]] :

[[Prototype]] is an internal hidden property of objects in JS and it is a reference to another object. Every object at the time of creation receives a non-null value for [[Prototype]]. Remember [[Get]] operation is invoked when we reference a property on an object like, myObject.a. If the object itself has a property, a on it then that property will be used.

let myObject= {
    a: 2
};

console.log(myObject.a);            // 2

But if the object itself directly does not have the requested property then [[Get]] operation will proceed to follow the [[Prototype]] link of the object. This process will continue until either a matching property name is found or the [[Prototype]] chain ends(at the built-in Object.prototype). If no matching property is found then undefined will be returned. Object.create(specifiedObject) creates an object with the [[Prototype]] linkage to the specified object.

let anotherObject= {
    a: 2
};

// create an object linked to anotherObject
let myObject= Object.create(anotherObject);
console.log(myObject.a);                // 2

Both for..in loop and in operator use [[Prototype]] chain lookup process. So if we use for..in loop to iterate over the properties of an object then all the enumerable properties which can be reached via that object's [[Prototype]] chain also will be enumerated along with the enumerable properties of the object itself. And when using in operator to test for the existence of a property on an object then in operator will check all the properties via [[Prototype]] linkage of the object regardless of their enumerability.

// for..in loop uses [[Prototype]] chain lookup process
let anotherObject= {
    a: 2
};

let myObject= Object.create(anotherObject);

for(let k in myObject) {
    console.log("found: " + k);            // found: a
}

// in operator uses [[Prototype]] chain lookup process
console.log("a" in myObject);              // true

.prototype :

.prototype is a property of functions in JS and it refers to an object having constructor property which stores all the properties(and methods) of the function object.

let foo= function(){}

console.log(foo.prototype);        
// returns {constructor: f} object which now contains all the default properties

foo.id= "Walter White";

foo.job= "teacher";

console.log(foo.prototype);       
// returns {constructor: f} object which now contains all the default properties and 2 more properties that we added to the fn object
/*
{constructor: f}
    constructor: f()
        id: "Walter White"
        job: "teacher"
        arguments: null
        caller: null
        length: 0
        name: "foo"
        prototype: {constructor: f}
        __proto__: f()
        [[FunctionLocation]]: VM789:1
        [[Scopes]]: Scopes[2]
    __proto__: Object

*/

But normal objects in JS does not have .prototype property. We know Object.prototype is the root object of all the objects in JS. So clearly Object is a function i.e. typeof Object === "function" . That means we also can create object from the Object function like, let myObj= new Object( ). Similarly Array, Function are also functions so we can use Array.prototype, Function.prototype to store all the generic properties of arrays and functions. So we can say JS is built on functions.

{}.prototype;                            // SyntaxError: Unexpected token '.'

(function(){}).prototype;                // {constructor: f}

Also using new operator if we create objects from a function then internal hidden [[Prototype]] property of those newly created objects will point to the object referenced by the .prototype property of the original function. In the below code, we have created an object, a from a fn, Letter and added 2 properties one to the fn object and another to the prototype object of the fn. Now if we try to access both of the properties on the newly created object, a then we only will be able to access the property added to the prototype object of the function. This is because the prototype object of the function is now on the [[Prototype]] chain of the newly created object, a.

let Letter= function(){}

let a= new Letter();

Letter.from= "Albuquerque";

Letter.prototype.to= "New Hampshire";

console.log(a.from);                // undefined

console.log(a.to);                  // New Hampshire

.__proto__:

.__proto__ is a property of objects in JS and it references the another object in the [[Prototype]] chain. We know [[Prototype]] is an internal hidden property of objects in JS and it references another object in the [[Prototype]] chain. We can get or set the object referred by the internal [[Prototype]] property in 2 ways

  1. Object.getPrototypeOf(obj) / Object.setPrototypeOf(obj)

  2. obj.__proto__

We can traverse the [[Prototype]] chain using: .__proto__.__proto__. . . Along with .constructor, .toString( ), .isPrototypeOf( ) our dunder proto property (__proto__) actually exists on the built-in Object.prototype root object, but available on any particular object. Our .__proto__ is actually a getter/setter. Implementation of .__proto__ in Object.prototype is as below :

Object.defineProperty(Object.prototype, "__proto__", {
    get: function() {
        return Object.getPrototypeOf(this);
    },
    set: function(o) {
        Object.setPrototypeOf(this, o);
        return o;
    }
});

To retrieve the value of obj.__proto__ is like calling, obj.__proto__() which actually returns the calling of the getter fn, Object.getPrototypeOf(obj) which exists on Object.prototype object. Although .__proto__ is a settable property but we should not change [[Prototype]] of an already existing object because of performance issues.

Using new operator if we create objects from a function then internal hidden [[Prototype]] property of those newly created objects will point to the object referenced by the .prototype property of the original function. Using .__proto__ property we can access the other object referenced by internal hidden [[Prototype]] property of the object. But __proto__ is not the same as [[Prototype]] rather a getter/setter for it. Consider below code :

let Letter= function() {}

let a= new Letter();

let b= new Letter();

let z= new Letter();

// output in console
a.__proto__ === Letter.prototype;               // true

b.__proto__ === Letter.prototype;               // true

z.__proto__ === Letter.prototype;               // true

Letter.__proto__ === Function.prototype;        // true

Function.prototype.__proto__ === Object.prototype;        // true

Letter.prototype.__proto__ === Object.prototype;          // true

enter image description here

How to convert JSON to CSV format and store in a variable

Try these Examples

Example 1:

JsonArray = [{
    "AccountNumber": "123",
    "AccountName": "abc",
    "port": "All",
    "source": "sg-a78c04f8"

}, {
    "Account Number": "123",
    "Account Name": "abc",
    "port": 22,
    "source": "0.0.0.0/0",
}]

JsonFields = ["Account Number","Account Name","port","source"]

function JsonToCSV(){
    var csvStr = JsonFields.join(",") + "\n";

    JsonArray.forEach(element => {
        AccountNumber = element.AccountNumber;
        AccountName   = element.AccountName;
        port          = element.port
        source        = element.source

        csvStr += AccountNumber + ',' + AccountName + ','  + port + ',' + source + "\n";
        })
        return csvStr;
}

Example2 :

JsonArray = [{
    "AccountNumber": "1234",
    "AccountName": "abc",
    "inbound": [{
        "port": "All",
        "source": "sg-a78c04f8"
    },
    {
        "port": 22,
        "source": "0.0.0.0/0",
    }]
}]

JsonFields = ["Account Number", "Account Name", "port", "source"]

function JsonToCSV() {
    var csvStr = JsonFields.join(",") + "\n";

    JsonArray.forEach(element => {
        AccountNumber = element.AccountNumber;
        AccountName = element.AccountName;
        
        element.inbound.forEach(inboundELe => {
            port = inboundELe.port
            source = inboundELe.source
            csvStr += AccountNumber + ',' + AccountName + ',' + port + ',' + source + "\n";
        })
    })
    return csvStr;
}

You can even download the csv file using the following code :

function downloadCSV(csvStr) {

    var hiddenElement = document.createElement('a');
    hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvStr);
    hiddenElement.target = '_blank';
    hiddenElement.download = 'output.csv';
    hiddenElement.click();
}

'any' vs 'Object'

Object appears to be a more specific declaration than any. From the TypeScript spec (section 3):

All types in TypeScript are subtypes of a single top type called the Any type. The any keyword references this type. The Any type is the one type that can represent any JavaScript value with no constraints. All other types are categorized as primitive types, object types, or type parameters. These types introduce various static constraints on their values.

Also:

The Any type is used to represent any JavaScript value. A value of the Any type supports the same operations as a value in JavaScript and minimal static type checking is performed for operations on Any values. Specifically, properties of any name can be accessed through an Any value and Any values can be called as functions or constructors with any argument list.

Objects do not allow the same flexibility.

For example:

var myAny : any;

myAny.Something(); // no problemo

var myObject : Object;

myObject.Something(); // Error: The property 'Something' does not exist on value of type 'Object'.

TimeStamp on file name using PowerShell

I needed to export our security log and wanted the date and time in Coordinated Universal Time. This proved to be a challenge to figure out, but so simple to execute:

wevtutil export-log security c:\users\%username%\SECURITYEVENTLOG-%computername%-$(((get-date).ToUniversalTime()).ToString("yyyyMMddTHHmmssZ")).evtx

The magic code is just this part:

$(((get-date).ToUniversalTime()).ToString("yyyyMMddTHHmmssZ"))

Viewing unpushed Git commits

I believe the most typical way of doing this is to run something like:

git cherry --abbrev=7 -v @{upstream}

However, I personally prefer running:

git log --graph --decorate --pretty=oneline --abbrev-commit --all @{upstream}^..

which shows the commits from all branches which are not merged upstream, plus the last commit in upstream (which shows up as a root node for all the other commits). I use it so often that I have created alias noup for it.

git config --global alias.noup \
'log --graph --decorate --pretty=oneline --abbrev-commit --all @{upstream}^..'

Delete multiple rows by selecting checkboxes using PHP

Something that sometimes crops up you may/maynot be aware of

Won't always be picked up by by $_POST['delete'] when using IE. Firefox and chrome should work fine though. I use a seperate isntead which solves the problem for IE

As for your not deleting in your code above you appear to be echoing out 2x sets of check boxes both pulling the same data? Is this just a copy + paste mistake or is this actually how your code is?

If its how your code is that'll be the problem as the user could be ticking one checkbox array item but the other one will be unchecked so the php code for delete is getting confused. Either rename the 2nd check box or delete that block of html surely you don't need to display the same list twice ?

Split string into array of character strings

Maybe you can use a for loop that goes through the String content and extract characters by characters using the charAt method.

Combined with an ArrayList<String> for example you can get your array of individual characters.

How to check if a user is logged in (how to properly use user.is_authenticated)?

Following block should work:

    {% if user.is_authenticated %}
        <p>Welcome {{ user.username }} !!!</p>       
    {% endif %}

How to stop IIS asking authentication for default website on localhost

It is easier to remove the "Default Web Site" and create a new one if you do not have any limitations.

I did it and my problem solved.

Why does javascript replace only first instance when using replace?

You need to set the g flag to replace globally:

date.replace(new RegExp("/", "g"), '')
// or
date.replace(/\//g, '')

Otherwise only the first occurrence will be replaced.

Using variables inside strings

In C# 6 you can use string interpolation:

string name = "John";
string result = $"Hello {name}";

The syntax highlighting for this in Visual Studio makes it highly readable and all of the tokens are checked.

Laravel migration table field's type change

Not really an answer, but just a note about ->change():

Only the following column types can be "changed": bigInteger, binary, boolean, date, dateTime, dateTimeTz, decimal, integer, json, longText, mediumText, smallInteger, string, text, time, unsignedBigInteger, unsignedInteger and unsignedSmallInteger.

https://laravel.com/docs/5.8/migrations#modifying-columns

If your column isn't one of these you will need to either drop the column or use the alter statement as mentioned in other answers.

The PowerShell -and conditional operator

Another option:

if( ![string]::IsNullOrEmpty($user_sam) -and ![string]::IsNullOrEmpty($user_case) )
{
   ...
}

Getting "error": "unsupported_grant_type" when trying to get a JWT by calling an OWIN OAuth secured Web Api via Postman

Old Question, but for angular 6, this needs to be done when you are using HttpClient I am exposing token data publicly here but it would be good if accessed via read-only properties.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { delay, tap } from 'rxjs/operators';
import { Router } from '@angular/router';


@Injectable()
export class AuthService {
    isLoggedIn: boolean = false;
    url = "token";

    tokenData = {};
    username = "";
    AccessToken = "";

    constructor(private http: HttpClient, private router: Router) { }

    login(username: string, password: string): Observable<object> {
        let model = "username=" + username + "&password=" + password + "&grant_type=" + "password";

        return this.http.post(this.url, model).pipe(
            tap(
                data => {
                    console.log('Log In succesful')
                    //console.log(response);
                    this.isLoggedIn = true;
                    this.tokenData = data;
                    this.username = data["username"];
                    this.AccessToken = data["access_token"];
                    console.log(this.tokenData);
                    return true;

                },
                error => {
                    console.log(error);
                    return false;

                }
            )
        );
    }
}

Download Excel file via AJAX MVC

$.ajax({
                type: "GET",
                url: "/Home/Downloadexcel/",
                contentType: "application/json; charset=utf-8",
                data: null,
                success: function (Rdata) {
                    debugger;
                    var bytes = new Uint8Array(Rdata.FileContents); 
                    var blob = new Blob([bytes], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
                    var link = document.createElement('a');
                    link.href = window.URL.createObjectURL(blob);
                    link.download = "myFileName.xlsx";
                    link.click();
                },
                error: function (err) {

                }

            });

How to ISO 8601 format a Date with Timezone Offset in JavaScript?

Just my two sends here

I was facing this issue with datetimes so what I did is this:

const moment = require('moment-timezone')

const date = moment.tz('America/Bogota').format()

Then save date to db to be able to compare it from some query.


To install moment-timezone

npm i moment-timezone

No connection could be made because the target machine actively refused it (PHP / WAMP)

You might need:

  • In wamp\bin\mysql\mysqlX.X.XX\my.ini find these lines:

    [client] ... port = 3308 ... [wampmysqld64] ... port = 3308

As you see, the port number is 3308. You should :

  • use that port in applications, like WordPress: define('DB_HOST', 'localhost:3308')

or

  • change it globally in wamp\bin\apache\apache2.X.XXX\bin\php.ini change mysqli.default_port = ... to 3308

Using number as "index" (JSON)

What about

Game.status[0][0] or Game.status[0]["0"] ?

Does one of these work?

PS: What you have in your question is a Javascript Object, not JSON. JSON is the 'string' version of a Javascript Object.

Pandas every nth row

There is an even simpler solution to the accepted answer that involves directly invoking df.__getitem__.

df = pd.DataFrame('x', index=range(5), columns=list('abc'))
df

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

For example, to get every 2 rows, you can do

df[::2]

   a  b  c
0  x  x  x
2  x  x  x
4  x  x  x

There's also GroupBy.first/GroupBy.head, you group on the index:

df.index // 2
# Int64Index([0, 0, 1, 1, 2], dtype='int64')

df.groupby(df.index // 2).first()
# Alternatively,
# df.groupby(df.index // 2).head(1)

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x

The index is floor-divved by the stride (2, in this case). If the index is non-numeric, instead do

# df.groupby(np.arange(len(df)) // 2).first()
df.groupby(pd.RangeIndex(len(df)) // 2).first()

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x

How can I create an Asynchronous function in Javascript?

Edit: I totally misunderstood the question. In the browser, I would use setTimeout. If it was important that it ran in another thread, I would use Web Workers.

Using variable in SQL LIKE statement

DECLARE @SearchLetter2 char(1)

Set this to a longer char.

angular 2 sort and filter

This is my sort. It will do number sort , string sort and date sort .

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

@Pipe({
  name: 'sortPipe'
 })

export class SortPipe implements PipeTransform {

    transform(array: Array<string>, key: string): Array<string> {

        console.log("Entered in pipe*******  "+ key);


        if(key === undefined || key == '' ){
            return array;
        }

        var arr = key.split("-");
        var keyString = arr[0];   // string or column name to sort(name or age or date)
        var sortOrder = arr[1];   // asc or desc order
        var byVal = 1;


        array.sort((a: any, b: any) => {

            if(keyString === 'date' ){

                let left    = Number(new Date(a[keyString]));
                let right   = Number(new Date(b[keyString]));

                return (sortOrder === "asc") ? right - left : left - right;
            }
            else if(keyString === 'name'){

                if(a[keyString] < b[keyString]) {
                    return (sortOrder === "asc" ) ? -1*byVal : 1*byVal;
                } else if (a[keyString] > b[keyString]) {
                    return (sortOrder === "asc" ) ? 1*byVal : -1*byVal;
                } else {
                    return 0;
                }  
            }
            else if(keyString === 'age'){
                return (sortOrder === "asc") ? a[keyString] - b[keyString] : b[keyString] - a[keyString];
            }

        });

        return array;

  }

}

Detecting request type in PHP (GET, POST, PUT or DELETE)

It is Very Simple just use $_SERVER['REQUEST_METHOD'];

Example:

<?php
$method = $_SERVER['REQUEST_METHOD'];
switch ($method) {
  case 'GET':
    //Here Handle GET Request 
    break;
  case 'POST':
    //Here Handle POST Request 
    break;
  case 'DELETE':
    //Here Handle DELETE Request 
    break;
  case 'PUT':
    //Here Handle PUT Request 
    break;
}
?>

How to configure log4j.properties for SpringJUnit4ClassRunner?

If you don't want to bother with a file, you can do something like this in your code:

static
{
    Logger rootLogger = Logger.getRootLogger();
    rootLogger.setLevel(Level.INFO);
    rootLogger.addAppender(new ConsoleAppender(
               new PatternLayout("%-6r [%p] %c - %m%n")));
}

HTTP requests and JSON parsing in Python

import urllib
import json

url = 'http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false'
result = json.load(urllib.urlopen(url))

How many characters in varchar(max)

See the MSDN reference table for maximum numbers/sizes.

Bytes per varchar(max), varbinary(max), xml, text, or image column: 2^31-1

There's a two-byte overhead for the column, so the actual data is 2^31-3 max bytes in length. Assuming you're using a single-byte character encoding, that's 2^31-3 characters total. (If you're using a character encoding that uses more than one byte per character, divide by the total number of bytes per character. If you're using a variable-length character encoding, all bets are off.)

Is there way to use two PHP versions in XAMPP?

You can download whatever versions of PHP you need and place them into their own directories, e.g.

c:\php5\

c:\php7\

All you need to do is tell your web server (Apache) which version of PHP to use, which you do by loading the appropriate module. In Apache you can do this by finding the file httpd.conf and then editing the appropriate line:

LoadModule php7_module c:\php7\libphp7.so

You'll have to figure out the correct paths of course - this is just for illustration.

Save httpd.conf and restart your server. Note, if you don't restart it, the changes won't take effect.

There's no GUI switch to be able to do this, you need to edit the .conf file and then restart Apache. Doing this only takes a couple of seconds and you could even comment out a version so "switching" only takes a couple of keystrokes, e.g.

Use PHP 5:

LoadModule php5_module c:\php5\libphp5.so
#LoadModule php7_module c:\php7\libphp7.so

Use PHP 7:

#LoadModule php5_module c:\php5\libphp5.so
LoadModule php7_module c:\php7\libphp7.so

You do not need multiple versions of XAMPP, or to dual boot, or use a different machine, or any of the other "solutions" that have suggested convoluted workarounds. The OP wants to use XAMPP and tell it which version of PHP to use. This is the quickest and most efficient way of doing it, and only requires one XAMPP installation.

Edit 1-Nov-2017: Apparently some people are saying there's no .so files on Windows. The answer I gave was adapted from how I have things set up on my Mac (which does use .so files instead of .dll). The principle of the answer however is still exactly correct. You are using Apache's configuration file, httpd.conf to specify where the PHP module (.so or .dll) is located on your system. So the only difference for Windows would be the file name and/or path location. The answer I've given is also correct for a vanilla installation of Apache/PHP (without XAMPP at all).

How to convert CharSequence to String?

You can directly use String.valueOf()

String.valueOf(charSequence)

Though this is same as toString() it does a null check on the charSequence before actually calling toString.

This is useful when a method can return either a charSequence or null value.

Determine project root from a running node.js application

Finding the root path of an electron app could get tricky. Because the root path is different for the main process and renderer under different conditions such as production, development and packaged conditions.

I have written a npm package electron-root-path to capture the root path of an electron app.

$ npm install electron-root-path

or 

$ yarn add electron-root-path


// Import ES6 way
import { rootPath } from 'electron-root-path';

// Import ES2015 way
const rootPath = require('electron-root-path').rootPath;

// e.g:
// read a file in the root
const location = path.join(rootPath, 'package.json');
const pkgInfo = fs.readFileSync(location, { encoding: 'utf8' });

Import Excel Spreadsheet Data to an EXISTING sql table?

You can copy-paste data from en excel-sheet to an SQL-table by doing so:

  • Select the data in Excel and press Ctrl + C
  • In SQL Server Management Studio right click the table and choose Edit Top 200 Rows
  • Scroll to the bottom and select the entire empty row by clicking on the row header
  • Paste the data by pressing Ctrl + V

Note: Often tables have a first column which is an ID-column with an auto generated/incremented ID. When you paste your data it will start inserting the leftmost selected column in Excel into the leftmost column in SSMS thus inserting data into the ID-column. To avoid that keep an empty column at the leftmost part of your selection in order to skip that column in SSMS. That will result in SSMS inserting the default data which is the auto generated ID.

Furthermore you can skip other columns by having empty columns at the same ordinal positions in the Excel sheet selection as those columns to be skipped. That will make SSMS insert the default value (or NULL where no default value is specified).

Oracle SQL Developer: Unable to find a JVM

I just installed SQL Developer 4.0.0.13 and the SetJavaHome can now be overridden by a user-specific configuration file (not sure if this is new to 4.0.0.13 or not).

The location of this user-specific configuration file can be seen in the user.conf property under 'Help -> About' on the 'Properties' tab. For example, mine was set to:

C:\Users\username\AppData\Roaming\sqldeveloper\1.0.0.0.0\product.conf

On Windows 7.

The first section of this file is used to set the JDK that SQLDeveloper should use:

#
# By default, the product launcher will search for a JDK to use, and if none
# can be found, it will ask for the location of a JDK and store its location
# in this file. If a particular JDK should be used instead, uncomment the
# line below and set the path to your preferred JDK.
#
SetJavaHome C:\Program Files (x86)\Java\jdk1.7.0_03

This setting overrides the setting in sqldeveloper.conf

pip connection failure: cannot fetch index base URL http://pypi.python.org/simple/

My problem was the system virtualenv version.

When I created an env with python3 venv everything worked. But when I used virtualenv (by default with python2.7) to create an env I receive those error messages.

In the virtualenv created the pip version was 1.5.6, but my system pip version was 10.0.1

Then I ran (outside any env):

pip install virtualenv --upgrade

It upgraded virtualenv to version 16.0.0 and now my pip install in the envs created with virtualenv and python2.7 work flawlessly. Also, the pip version inside the env is now 10.0.1.

Before upgrade:

Removing first x characters from string?

Example to show last 3 digits of account number.

x = '1234567890'   
x.replace(x[:7], '')

o/p: '890'

Jquery submit form

You can try like:

   $("#myformid").submit(function(){
        //perform anythng
   });

Or even you can try like

$(".nextbutton").click(function() { 
    $('#form1').submit();
});

Display a message in Visual Studio's output window when not debug mode?

The results are not in the Output window but in the Test Results Detail (TestResult Pane at the bottom, right click on on Test Results and go to TestResultDetails).

This works with Debug.WriteLine and Console.WriteLine.

Google Maps API warning: NoApiKeys

Creating and using the key is the way to go. The usage is free until your application reaches 25.000 calls per day on 90 consecutive days.

BTW.: In the google Developer documentation it says you shall add the api key as option {key:yourKey} when calling the API to create new instances. This however doesn't shush the console warning. You have to add the key as a parameter when including the api.

<script src="https://maps.googleapis.com/maps/api/js?key=yourKEYhere"></script>

Get the key here: GoogleApiKey Generation site

Using C# to check if string contains a string in string array

I used the following code to check if the string contained any of the items in the string array:

foreach (string s in stringArray)
{
    if (s != "")
    {
        if (stringToCheck.Contains(s))
        {
            Text = "matched";
        }
    }
}

Can I use a binary literal in C or C++?

You can use the function found in this question to get up to 22 bits in C++. Here's the code from the link, suitably edited:

template< unsigned long long N >
struct binary
{
  enum { value = (N % 8) + 2 * binary< N / 8 > :: value } ;
};

template<>
struct binary< 0 >
{
  enum { value = 0 } ;
};

So you can do something like binary<0101011011>::value.

Is there a <meta> tag to turn off caching in all browsers?

pragma is your best bet:

<meta http-equiv="Pragma" content="no-cache">

How to prevent buttons from submitting forms

The return false prevents the default behavior. but the return false breaks the bubbling of additional click events. This means if there are any other click bindings after this function gets called, those others do not Consider.

 <button id="btnSubmit" type="button">PostData</button>
 <Script> $("#btnSubmit").click(function(){
   // do stuff
   return false;
}); </Script>

Or simply you can put like this

 <button type="submit" onclick="return false"> PostData</button>

How to find top three highest salary in emp table in oracle?

Limit The Query To Display Only The Top 3 Highest Paid Employees. : Query « Oracle PL / SQL

create table employee(
         emp_no                 integer         primary key
        ,lastname               varchar2(20)    not null
        ,salary                 number(3)
);

insert into employee(emp_no,lastname,salary)
              values(1,'Tomy',2);

insert into employee(emp_no,lastname,salary)
              values(2,'Jacky',3);

insert into employee(emp_no,lastname,salary)
              values(3,'Joey',4);

insert into employee(emp_no,lastname,salary)
              values(4,'Janey',5);


select lastname,  salary
from (SELECT lastname, salary FROM employee ORDER BY salary DESC)
where rownum <= 3 ;

OUTPUT

LASTNAME                 SALARY

-------------------- ----------
Janey                         5

Joey                          4

Jacky                         3

drop table employee;

css to make bootstrap navbar transparent

If you are using the latest version of Bootstrap and Ruby on Rails, you can just type it in the html.erb file as so:

<nav class="navbar navbar-transparent">

And that is all you need.

How to Execute stored procedure from SQL Plus?

You have two options, a PL/SQL block or SQL*Plus bind variables:

var z number

execute  my_stored_proc (-1,2,0.01,:z)

print z

"break;" out of "if" statement?

break interacts solely with the closest enclosing loop or switch, whether it be a for, while or do .. while type. It is frequently referred to as a goto in disguise, as all loops in C can in fact be transformed into a set of conditional gotos:

for (A; B; C) D;
// translates to
A;
goto test;
loop: D;
iter: C;
test: if (B) goto loop;
end:

while (B) D;          // Simply doesn't have A or C
do { D; } while (B);  // Omits initial goto test
continue;             // goto iter;
break;                // goto end;

The difference is, continue and break interact with virtual labels automatically placed by the compiler. This is similar to what return does as you know it will always jump ahead in the program flow. Switches are slightly more complicated, generating arrays of labels and computed gotos, but the way break works with them is similar.

The programming error the notice refers to is misunderstanding break as interacting with an enclosing block rather than an enclosing loop. Consider:

for (A; B; C) {
   D;
   if (E) {
       F;
       if (G) break;   // Incorrectly assumed to break if(E), breaks for()
       H;
   }
   I;
}
J;

Someone thought, given such a piece of code, that G would cause a jump to I, but it jumps to J. The intended function would use if (!G) H; instead.

Redirect From Action Filter Attribute

I am using MVC4, I used following approach to redirect a custom html screen upon authorization breach.

Extend AuthorizeAttribute say CutomAuthorizer override the OnAuthorization and HandleUnauthorizedRequest

Register the CustomAuthorizer in the RegisterGlobalFilters.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{

    filters.Add(new CustomAuthorizer());
}

upon identifying the unAuthorized access call HandleUnauthorizedRequestand redirect to the concerned controller action as shown below.


public class CustomAuthorizer : AuthorizeAttribute
{

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        bool isAuthorized = IsAuthorized(filterContext); // check authorization
        base.OnAuthorization(filterContext);
        if (!isAuthorized && !filterContext.ActionDescriptor.ActionName.Equals("Unauthorized", StringComparison.InvariantCultureIgnoreCase)
            && !filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.Equals("LogOn", StringComparison.InvariantCultureIgnoreCase))
        {

            HandleUnauthorizedRequest(filterContext);

        }
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result =
       new RedirectToRouteResult(
           new RouteValueDictionary{{ "controller", "LogOn" },
                                          { "action", "Unauthorized" }

                                         });

    }
}

What's the difference between Apache's Mesos and Google's Kubernetes

Kubernetes and Mesos are a match made in heaven. Kubernetes enables the Pod (group of co-located containers) abstraction, along with Pod labels for service discovery, load-balancing, and replication control. Mesos provides the fine-grained resource allocations for pods across nodes in a cluster, and can make Kubernetes play nicely with other frameworks running on the same cluster resources.

from readme of kubernetes-mesos

const char* concatenation

In your example one and two are char pointers, pointing to char constants. You cannot change the char constants pointed to by these pointers. So anything like:

strcat(one,two); // append string two to string one.

will not work. Instead you should have a separate variable(char array) to hold the result. Something like this:

char result[100];   // array to hold the result.

strcpy(result,one); // copy string one into the result.
strcat(result,two); // append string two to the result.

Clear MySQL query cache without restarting server

according the documentation, this should do it...

RESET QUERY CACHE 

Validating file types by regular expression

Your regexp seems to validate both the file name and the extension. Is that what you need? I'll assume it's just the extension and would use a regexp like this:

\.(jpg|gif|doc|pdf)$

And set the matching to be case insensitive.

ERROR 2006 (HY000): MySQL server has gone away

If you have tried all these solutions, esp. increasing max_allowed_packet up to the maximum supported amount of 1GB and you are still seeing these errors, it might be that your server literally does not have enough free RAM memory available...

The solution = upgrade your server to more RAM memory, and try again.

Note: I'm surprised this simple solution has not been mentioned after 8+ years of discussion on this thread... sometimes we developers tend to overthink things.

How to extract a single value from JSON response?

using json.loads will turn your data into a python dictionary.

Dictionaries values are accessed using ['key']

resp_str = {
  "name" : "ns1:timeSeriesResponseType",
  "declaredType" : "org.cuahsi.waterml.TimeSeriesResponseType",
  "scope" : "javax.xml.bind.JAXBElement$GlobalScope",
  "value" : {
    "queryInfo" : {
      "creationTime" : 1349724919000,
      "queryURL" : "http://waterservices.usgs.gov/nwis/iv/",
      "criteria" : {
        "locationParam" : "[ALL:103232434]",
        "variableParam" : "[00060, 00065]"
      },
      "note" : [ {
        "value" : "[ALL:103232434]",
        "title" : "filter:sites"
      }, {
        "value" : "[mode=LATEST, modifiedSince=null]",
        "title" : "filter:timeRange"
      }, {
        "value" : "sdas01",
        "title" : "server"
      } ]
    }
  },
  "nil" : false,
  "globalScope" : true,
  "typeSubstituted" : false
}

would translate into a python diction

resp_dict = json.loads(resp_str)

resp_dict['name'] # "ns1:timeSeriesResponseType"

resp_dict['value']['queryInfo']['creationTime'] # 1349724919000

Using Math.round to round to one decimal place?

Your method is right, all you have to do is add a .0 after both the tens and it will fix your problem!

double example = Math.round((187/35) * 10.0) / 10.0;

The output would be:

5.3

Find nginx version?

My guess is it's not in your path.
in bash, try:
echo $PATH
and
sudo which nginx
And see if the folder containing nginx is also in your $PATH variable.
If not, either add the folder to your path environment variable, or create an alias (and put it in your .bashrc) ooor your could create a link i guess.
or sudo nginx -v if you just want that...

making a paragraph in html contain a text from a file

Here is a javascript code I have tested successfully :

    var txtFile = new XMLHttpRequest();
    var allText = "file not found";
    txtFile.onreadystatechange = function () {
        if (txtFile.readyState === XMLHttpRequest.DONE && txtFile.status == 200) {
            allText = txtFile.responseText;
            allText = allText.split("\n").join("<br>");
        }

        document.getElementById('txt').innerHTML = allText;
    }
    txtFile.open("GET", '/result/client.txt', true);
    txtFile.send(null);

Count number of rows matching a criteria

Just give a try using subset

nrow(subset(data,condition))

Example

nrow(subset(myData,sCode == "CA"))

Git ignore file for Xcode projects

I included these suggestions in a Gist I created on Github: http://gist.github.com/137348

Feel free to fork it, and make it better.

How can I write variables inside the tasks file in ansible

Whenever you have a module followed by a variable on the same line in ansible the parser will treat the reference variable as the beginning of an in-line dictionary. For example:

- name: some example
  command: {{ myapp }} -a foo

The default here is to parse the first part of {{ myapp }} -a foo as a dictionary instead of a string and you will get an error.

So you must quote the argument like so:

- name: some example
  command: "{{ myapp }} -a foo"

How to post pictures to instagram using API

For anyone who is searching for a solution about posting to Instagram using AWS lambda and puppeteer (chrome-aws-lambda). Noted that this solution allow you to post 1 photo for each post only. If you are not using lambda, just replace chrome-aws-lambda with puppeteer.

For the first launch of lambda, it is normal that will not work because instagram detects “Suspicious login attempt”. Just goto instagram page using your PC and approve it, everything should be fine.

Here's my code, feel free to optimize it:

// instagram.js
const chromium = require('chrome-aws-lambda');

const username = process.env.IG_USERNAME;
const password = process.env.IG_PASSWORD;

module.exports.post = async function(fileToUpload, caption){
    const browser = await chromium.puppeteer.launch({
        args: [...chromium.args, '--window-size=520,700'],
        defaultViewport: chromium.defaultViewport,
        executablePath: await chromium.executablePath,
        headless: false,
        ignoreHTTPSErrors: true,
    });
    const page = await browser.newPage();
    await page.setUserAgent('Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) FxiOS/7.5b3349 Mobile/14F89 Safari/603.2.4');
    await page.goto('https://www.instagram.com/', {waitUntil: 'networkidle2'});
    
    const [buttonLogIn] = await page.$x("//button[contains(., 'Log In')]");
    if (buttonLogIn) {
        await buttonLogIn.click();
    }

    await page.waitFor('input[name="username"]');
    await page.type('input[name="username"]', username)
    await page.type('input[name="password"]', password)
    await page.click('form button[type="submit"]');

    await page.waitFor(3000);
    const [buttonSaveInfo] = await page.$x("//button[contains(., 'Not Now')]");
    if (buttonSaveInfo) {
        await buttonSaveInfo.click();
    }

    await page.waitFor(3000);
    const [buttonNotificationNotNow] = await page.$x("//button[contains(., 'Not Now')]");
    const [buttonNotificationCancel] = await page.$x("//button[contains(., 'Cancel')]");
    if (buttonNotificationNotNow) {
        await buttonNotificationNotNow.click();
    } else if (buttonNotificationCancel) {
        await buttonNotificationCancel.click(); 
    }

    await page.waitFor('form[enctype="multipart/form-data"]');
    const inputUploadHandle = await page.$('form[enctype="multipart/form-data"] input[type=file]');

    await page.waitFor(5000);
    const [buttonPopUpNotNow] = await page.$x("//button[contains(., 'Not Now')]");
    const [buttonPopUpCancel] = await page.$x("//button[contains(., 'Cancel')]");
    if (buttonPopUpNotNow) {
        await buttonPopUpNotNow.click();
    } else if (buttonPopUpCancel) {
        await buttonPopUpCancel.click(); 
    }

    await page.click('[data-testid="new-post-button"]')
    await inputUploadHandle.uploadFile(fileToUpload);

    await page.waitFor(3000);
    const [buttonNext] = await page.$x("//button[contains(., 'Next')]");
    await buttonNext.click();

    await page.waitFor(3000);
    await page.type('textarea', caption);

    const [buttonShare] = await page.$x("//button[contains(., 'Share')]");
    await buttonShare.click();
    await page.waitFor(3000);

    return true;
};
// handler.js

await instagram.post('/tmp/image.png', '#text');

it must be local file path, if it is url, download it to /tmp folder first.

How to import a module in Python with importlib.import_module

I think it's better to use importlib.import_module('.c', __name__) since you don't need to know about a and b.

I'm also wondering that, if you have to use importlib.import_module('a.b.c'), why not just use import a.b.c?

Formula px to dp, dp to px android

If you're looking for an online calculator for converting DP, SP, inches, millimeters, points or pixels to and from one another at different screen densities, this is the most complete tool I know of.

How to change the background color of the options menu?

Thanks Marcus! It works on 2.3 smoothly by fixing some syntax errors, here's the fixed code

    protected void setMenuBackground() {
    getLayoutInflater().setFactory(new Factory() {

        @Override
        public View onCreateView(final String name, final Context context,
                final AttributeSet attrs) {

            if (name.equalsIgnoreCase("com.android.internal.view.menu.IconMenuItemView")) {

                try { // Ask our inflater to create the view
                    final LayoutInflater f = getLayoutInflater();
                    final View[] view = new View[1];
                    try {
                        view[0] = f.createView(name, null, attrs);
                    } catch (InflateException e) {
                        hackAndroid23(name, attrs, f, view);
                    }
                    // Kind of apply our own background
                    new Handler().post(new Runnable() {
                        public void run() {
                            view[0].setBackgroundColor(Color.WHITE);

                        }
                    });
                    return view[0];
                } catch (InflateException e) {
                } catch (ClassNotFoundException e) {

                }
            }
            return null;
        }
    });
}

static void hackAndroid23(final String name,
        final android.util.AttributeSet attrs, final LayoutInflater f,
        final View[] view) {
    // mConstructorArgs[0] is only non-null during a running call to
    // inflate()
    // so we make a call to inflate() and inside that call our dully
    // XmlPullParser get's called
    // and inside that it will work to call
    // "f.createView( name, null, attrs );"!
    try {
        f.inflate(new XmlPullParser() {
            @Override
            public int next() throws XmlPullParserException, IOException {
                try {
                    view[0] = (TextView) f.createView(name, null, attrs);
                } catch (InflateException e) {
                } catch (ClassNotFoundException e) {
                }
                throw new XmlPullParserException("exit");
            }
        }, null, false);
    } catch (InflateException e1) {
        // "exit" ignored
    }
}

How to check the exit status using an if statement

For the record, if the script is run with set -e (or #!/bin/bash -e) and you therefore cannot check $? directly (since the script would terminate on any return code other than zero), but want to handle a specific code, @gboffis comment is great:

/some/command || error_code=$?
if [ "${error_code}" -eq 2 ]; then
   ...

sql query to get earliest date

SELECT TOP 1 ID, Name, Score, [Date]
FROM myTable
WHERE ID = 2
Order BY [Date]

How to write a PHP ternary operator

You wouldn’t: it’s messy and hard to read.

You’re looking for the switch statement in the first case. The second is fine as it is but still could be converted for consistency

Ternary statements are much more suited to boolean values and alternating logic.

Python dictionary: Get list of values for list of keys

A little speed comparison:

Python 2.7.11 |Anaconda 2.4.1 (64-bit)| (default, Dec  7 2015, 14:10:42) [MSC v.1500 64 bit (AMD64)] on win32
In[1]: l = [0,1,2,3,2,3,1,2,0]
In[2]: m = {0:10, 1:11, 2:12, 3:13}
In[3]: %timeit [m[_] for _ in l]  # list comprehension
1000000 loops, best of 3: 762 ns per loop
In[4]: %timeit map(lambda _: m[_], l)  # using 'map'
1000000 loops, best of 3: 1.66 µs per loop
In[5]: %timeit list(m[_] for _ in l)  # a generator expression passed to a list constructor.
1000000 loops, best of 3: 1.65 µs per loop
In[6]: %timeit map(m.__getitem__, l)
The slowest run took 4.01 times longer than the fastest. This could mean that an intermediate result is being cached 
1000000 loops, best of 3: 853 ns per loop
In[7]: %timeit map(m.get, l)
1000000 loops, best of 3: 908 ns per loop
In[33]: from operator import itemgetter
In[34]: %timeit list(itemgetter(*l)(m))
The slowest run took 9.26 times longer than the fastest. This could mean that an intermediate result is being cached 
1000000 loops, best of 3: 739 ns per loop

So list comprehension and itemgetter are the fastest ways to do this.

UPDATE: For large random lists and maps I had a bit different results:

Python 2.7.11 |Anaconda 2.4.1 (64-bit)| (default, Dec  7 2015, 14:10:42) [MSC v.1500 64 bit (AMD64)] on win32
In[2]: import numpy.random as nprnd
l = nprnd.randint(1000, size=10000)
m = dict([(_, nprnd.rand()) for _ in range(1000)])
from operator import itemgetter
import operator
f = operator.itemgetter(*l)
%timeit f(m)
%timeit list(itemgetter(*l)(m))
%timeit [m[_] for _ in l]  # list comprehension
%timeit map(m.__getitem__, l)
%timeit list(m[_] for _ in l)  # a generator expression passed to a list constructor.
%timeit map(m.get, l)
%timeit map(lambda _: m[_], l)
1000 loops, best of 3: 1.14 ms per loop
1000 loops, best of 3: 1.68 ms per loop
100 loops, best of 3: 2 ms per loop
100 loops, best of 3: 2.05 ms per loop
100 loops, best of 3: 2.19 ms per loop
100 loops, best of 3: 2.53 ms per loop
100 loops, best of 3: 2.9 ms per loop

So in this case the clear winner is f = operator.itemgetter(*l); f(m), and clear outsider: map(lambda _: m[_], l).

UPDATE for Python 3.6.4:

import numpy.random as nprnd
l = nprnd.randint(1000, size=10000)
m = dict([(_, nprnd.rand()) for _ in range(1000)])
from operator import itemgetter
import operator
f = operator.itemgetter(*l)
%timeit f(m)
%timeit list(itemgetter(*l)(m))
%timeit [m[_] for _ in l]  # list comprehension
%timeit list(map(m.__getitem__, l))
%timeit list(m[_] for _ in l)  # a generator expression passed to a list constructor.
%timeit list(map(m.get, l))
%timeit list(map(lambda _: m[_], l)
1.66 ms ± 74.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
2.1 ms ± 93.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.58 ms ± 88.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.36 ms ± 60.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.98 ms ± 142 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.7 ms ± 284 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
3.14 ms ± 62.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

So, results for Python 3.6.4 is almost the same.

LINQ to SQL Left Outer Join

You don't need the into statements:

var query = 
    from customer in dc.Customers
    from order in dc.Orders
         .Where(o => customer.CustomerId == o.CustomerId)
         .DefaultIfEmpty()
    select new { Customer = customer, Order = order } 
    //Order will be null if the left join is null

And yes, the query above does indeed create a LEFT OUTER join.

Link to a similar question that handles multiple left joins: Linq to Sql: Multiple left outer joins

How do I run a program from command prompt as a different user and as an admin

The easiest is to create a batch file (.bat) and run that as administrator.

Right click and 'Run as administrator'

Null check in an enhanced for loop

You could potentially write a helper method which returned an empty sequence if you passed in null:

public static <T> Iterable<T> emptyIfNull(Iterable<T> iterable) {
    return iterable == null ? Collections.<T>emptyList() : iterable;
}

Then use:

for (Object object : emptyIfNull(someList)) {
}

I don't think I'd actually do that though - I'd usually use your second form. In particular, the "or throw ex" is important - if it really shouldn't be null, you should definitely throw an exception. You know that something has gone wrong, but you don't know the extent of the damage. Abort early.

Disable back button in android

If looking for a higher api level 2.0 and above this will work great

@Override
public void onBackPressed() {
    // Do Here what ever you want do on back press;
}

If looking for android api level upto 1.6.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
     if (keyCode == KeyEvent.KEYCODE_BACK) {
     //preventing default implementation previous to android.os.Build.VERSION_CODES.ECLAIR
     return true;
     }
     return super.onKeyDown(keyCode, event);    
}

Write above code in your Activity to prevent back button pressed

Jquery find nearest matching element

You could try:

$(this).closest(".column").prev().find(".inputQty").val();

How to center an unordered list?

Let's say the list is:

<ul>
 <li>item1</li>
 <li>item2</li>
 <li>item3</li>
</ul>

For this example. If I understand correctly, you want the list items to be in the middle of the screen, but you want the text IN those list items to be centered to the left of the list item itself. Doing that is actually pretty easy. You just need some CSS:

ul {
    display: table; 
    margin: 0 auto;
    text-align: left;
}

And it works! Here is what is happening. First, we say we want to affect only unordered lists. Then, we do Rafael Herscovici's trick for centering the list items. Finally, we say to align the text to the left of the list items.

Open mvc view in new window from controller

You can use Tommy's method in forms as well:

@using (Html.BeginForm("Action", "Controller", FormMethod.Get, new { target = "_blank" }))
{
//code
}

Append a tuple to a list - what's the difference between two ways?

The tuple function takes only one argument which has to be an iterable

tuple([iterable])

Return a tuple whose items are the same and in the same order as iterable‘s items.

Try making 3,4 an iterable by either using [3,4] (a list) or (3,4) (a tuple)

For example

a_list.append(tuple((3, 4)))

will work

Double quotes within php script echo

You can just forgo the quotes for alphanumeric attributes:

echo "<font color=red> XHTML is not a thing anymore. </font>";
echo "<div class=editorial-note> There, I said it. </div>";

Is perfectly valid in HTML, and though still shunned, absolutely en vogue since HTML5.

CAVEATS

Angular is automatically adding 'ng-invalid' class on 'required' fields

the accepted answer is correct.. for mobile you can also use this (ng-touched rather ng-dirty)

input.ng-invalid.ng-touched{
  border-bottom: 1px solid #e74c3c !important; 
}

Getting the exception value in Python

Another way hasn't been given yet:

try:
    1/0
except Exception, e:
    print e.message

Output:

integer division or modulo by zero

args[0] might actually not be a message.

str(e) might return the string with surrounding quotes and possibly with the leading u if unicode:

'integer division or modulo by zero'

repr(e) gives the full exception representation which is not probably what you want:

"ZeroDivisionError('integer division or modulo by zero',)"

edit

My bad !!! It seems that BaseException.message has been deprecated from 2.6, finally, it definitely seems that there is still not a standardized way to display exception messages. So I guess the best is to do deal with e.args and str(e) depending on your needs (and possibly e.message if the lib you are using is relying on that mechanism).

For instance, with pygraphviz, e.message is the only way to display correctly the exception, using str(e) will surround the message with u''.

But with MySQLdb, the proper way to retrieve the message is e.args[1]: e.message is empty, and str(e) will display '(ERR_CODE, "ERR_MSG")'

How do you unit test private methods?

MS Test has a nice feature built in that makes private members and methods available in the project by creating a file called VSCodeGenAccessors

[System.Diagnostics.DebuggerStepThrough()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TestTools.UnitTestGeneration", "1.0.0.0")]
    internal class BaseAccessor
    {

        protected Microsoft.VisualStudio.TestTools.UnitTesting.PrivateObject m_privateObject;

        protected BaseAccessor(object target, Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType type)
        {
            m_privateObject = new Microsoft.VisualStudio.TestTools.UnitTesting.PrivateObject(target, type);
        }

        protected BaseAccessor(Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType type)
            :
                this(null, type)
        {
        }

        internal virtual object Target
        {
            get
            {
                return m_privateObject.Target;
            }
        }

        public override string ToString()
        {
            return this.Target.ToString();
        }

        public override bool Equals(object obj)
        {
            if (typeof(BaseAccessor).IsInstanceOfType(obj))
            {
                obj = ((BaseAccessor)(obj)).Target;
            }
            return this.Target.Equals(obj);
        }

        public override int GetHashCode()
        {
            return this.Target.GetHashCode();
        }
    }

With classes that derive from BaseAccessor

such as

[System.Diagnostics.DebuggerStepThrough()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TestTools.UnitTestGeneration", "1.0.0.0")]
internal class SomeClassAccessor : BaseAccessor
{

    protected static Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType m_privateType = new Microsoft.VisualStudio.TestTools.UnitTesting.PrivateType(typeof(global::Namespace.SomeClass));

    internal SomeClassAccessor(global::Namespace.Someclass target)
        : base(target, m_privateType)
    {
    }

    internal static string STATIC_STRING
    {
        get
        {
            string ret = ((string)(m_privateType.GetStaticField("STATIC_STRING")));
            return ret;
        }
        set
        {
            m_privateType.SetStaticField("STATIC_STRING", value);
        }
    }

    internal int memberVar    {
        get
        {
            int ret = ((int)(m_privateObject.GetField("memberVar")));
            return ret;
        }
        set
        {
            m_privateObject.SetField("memberVar", value);
        }
    }

    internal int PrivateMethodName(int paramName)
    {
        object[] args = new object[] {
            paramName};
        int ret = (int)(m_privateObject.Invoke("PrivateMethodName", new System.Type[] {
                typeof(int)}, args)));
        return ret;
    }

How do I convert dmesg timestamp to custom date format?

So KevZero requested a less kludgy solution, so I came up with the following:

sed -r 's#^\[([0-9]+\.[0-9]+)\](.*)#echo -n "[";echo -n $(date --date="@$(echo "$(grep btime /proc/stat|cut -d " " -f 2)+\1" | bc)" +"%c");echo -n "]";echo -n "\2"#e'

Here's an example:

$ dmesg|tail | sed -r 's#^\[([0-9]+\.[0-9]+)\](.*)#echo -n "[";echo -n $(date --date="@$(echo "$(grep btime /proc/stat|cut -d " " -f 2)+\1" | bc)" +"%c");echo -n "]";echo -n "\2"#e'
[2015-12-09T04:29:20 COT] cfg80211:   (57240000 KHz - 63720000 KHz @ 2160000 KHz), (N/A, 0 mBm), (N/A)
[2015-12-09T04:29:23 COT] wlp3s0: authenticate with dc:9f:db:92:d3:07
[2015-12-09T04:29:23 COT] wlp3s0: send auth to dc:9f:db:92:d3:07 (try 1/3)
[2015-12-09T04:29:23 COT] wlp3s0: authenticated
[2015-12-09T04:29:23 COT] wlp3s0: associate with dc:9f:db:92:d3:07 (try 1/3)
[2015-12-09T04:29:23 COT] wlp3s0: RX AssocResp from dc:9f:db:92:d3:07 (capab=0x431 status=0 aid=6)
[2015-12-09T04:29:23 COT] wlp3s0: associated
[2015-12-09T04:29:56 COT] thinkpad_acpi: EC reports that Thermal Table has changed
[2015-12-09T04:29:59 COT] i915 0000:00:02.0: BAR 6: [??? 0x00000000 flags 0x2] has bogus alignment
[2015-12-09T05:00:52 COT] thinkpad_acpi: EC reports that Thermal Table has changed

If you want it to perform a bit better, put the timestamp from proc into a variable instead :)

Core dumped, but core file is not in the current directory?

Read /usr/src/linux/Documentation/sysctl/kernel.txt.

[/proc/sys/kernel/]core_pattern is used to specify a core dumpfile pattern name.

  • If the first character of the pattern is a '|', the kernel will treat the rest of the pattern as a command to run. The core dump will be written to the standard input of that program instead of to a file.

Instead of writing the core dump to disk, your system is configured to send it to the abrt program instead. Automated Bug Reporting Tool is possibly not as documented as it should be...

In any case, the quick answer is that you should be able to find your core file in /var/cache/abrt, where abrt stores it after being invoked. Similarly, other systems using Apport may squirrel away cores in /var/crash, and so on.

What does ECU units, CPU core and memory mean when I launch a instance

ECUs (EC2 Computer Units) are a rough measure of processor performance that was introduced by Amazon to let you compare their EC2 instances ("servers").

CPU performance is of course a multi-dimensional measure, so putting a single number on it (like "5 ECU") can only be a rough approximation. If you want to know more exactly how well a processor performs for a task you have in mind, you should choose a benchmark that is similar to your task.

In early 2014, there was a nice benchmarking site comparing cloud hosting offers by tens of different benchmarks, over at CloudHarmony benchmarks. However, this seems gone now (and archive.org can't help as it was a web application). Only an introductory blog post is still available.

Also useful: ec2instances.info, which at least aggregates the ECU information of different EC2 instances for comparison. (Add column "Compute Units (ECU)" to make it work.)

Route.get() requires callback functions but got a "object Undefined"

node js and express 4 use this sequences

express = require('express');
var router = express.Router();

module.exports = router;

last line returns this type of error

How can I align two divs horizontally?

Wrap them both in a container like so:

_x000D_
_x000D_
.container{ _x000D_
    float:left; _x000D_
    width:100%; _x000D_
}_x000D_
.container div{ _x000D_
    float:left;_x000D_
}
_x000D_
<div class='container'>_x000D_
    <div>_x000D_
        <span>source list</span>_x000D_
        <select size="10">_x000D_
            <option />_x000D_
            <option />_x000D_
            <option />_x000D_
        </select>_x000D_
    </div>_x000D_
    <div>_x000D_
        <span>destination list</span>_x000D_
        <select size="10">_x000D_
            <option />_x000D_
            <option />_x000D_
            <option />_x000D_
        </select>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I find the version of the Fedora I use?

cat /etc/issue

Or cat /etc/fedora-release as suggested by @Bruce ONeel

window.onload vs document.onload

Window.onload is the standard, however - the web browser in the PS3 (based on Netfront) doesn't support the window object, so you can't use it there.

How should I set the default proxy to use default credentials?

In my deployment I can't use app.config neither to embed what Andrew Webb suggested.
So I'm doing this:

    IWebProxy proxy = WebRequest.GetSystemWebProxy();
    proxy.Credentials = CredentialCache.DefaultCredentials;

    WebClient wc = new WebClient();
    wc.UseDefaultCredentials = true;
    wc.Proxy = proxy;

Just in case you want to check my IE settings:

enter image description here

What is the most efficient way to store tags in a database?

If space is going to be an issue, have a 3rd table Tags(Tag_Id, Title) to store the text for the tag and then change your Tags table to be (Tag_Id, Item_Id). Those two values should provide a unique composite primary key as well.

What to return if Spring MVC controller method doesn't return value?

You can simply return a ResponseEntity with the appropriate header:

@RequestMapping(value = "/updateSomeData" method = RequestMethod.POST)
public ResponseEntity updateDataThatDoesntRequireClientToBeNotified(...){
....
return new ResponseEntity(HttpStatus.OK)
}

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

We have an extension method to do exactly this in MoreLINQ. You can look at the implementation there, but basically it's a case of iterating through the data, remembering the maximum element we've seen so far and the maximum value it produced under the projection.

In your case you'd do something like:

var item = items.MaxBy(x => x.Height);

This is better (IMO) than any of the solutions presented here other than Mehrdad's second solution (which is basically the same as MaxBy):

  • It's O(n) unlike the previous accepted answer which finds the maximum value on every iteration (making it O(n^2))
  • The ordering solution is O(n log n)
  • Taking the Max value and then finding the first element with that value is O(n), but iterates over the sequence twice. Where possible, you should use LINQ in a single-pass fashion.
  • It's a lot simpler to read and understand than the aggregate version, and only evaluates the projection once per element

Python convert set to string and vice versa

Try like this,

>>> s = set([1,2,3])
>>> s = list(s)
>>> s
[1, 2, 3]

>>> str = ', '.join(str(e) for e in s)
>>> str = 'set(%s)' % str
>>> str
'set(1, 2, 3)'

Comparing two arrays of objects, and exclude the elements who match values into new array in JS

Just using the Array iteration methods built into JS is fine for this:

_x000D_
_x000D_
var result1 = [_x000D_
    {id:1, name:'Sandra', type:'user', username:'sandra'},_x000D_
    {id:2, name:'John', type:'admin', username:'johnny2'},_x000D_
    {id:3, name:'Peter', type:'user', username:'pete'},_x000D_
    {id:4, name:'Bobby', type:'user', username:'be_bob'}_x000D_
];_x000D_
_x000D_
var result2 = [_x000D_
    {id:2, name:'John', email:'[email protected]'},_x000D_
    {id:4, name:'Bobby', email:'[email protected]'}_x000D_
];_x000D_
_x000D_
var props = ['id', 'name'];_x000D_
_x000D_
var result = result1.filter(function(o1){_x000D_
    // filter out (!) items in result2_x000D_
    return !result2.some(function(o2){_x000D_
        return o1.id === o2.id;          // assumes unique id_x000D_
    });_x000D_
}).map(function(o){_x000D_
    // use reduce to make objects with only the required properties_x000D_
    // and map to apply this to the filtered array as a whole_x000D_
    return props.reduce(function(newo, name){_x000D_
        newo[name] = o[name];_x000D_
        return newo;_x000D_
    }, {});_x000D_
});_x000D_
_x000D_
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 4) +_x000D_
        '</pre>';
_x000D_
_x000D_
_x000D_

If you are doing this a lot, then by all means look at external libraries to help you out, but it's worth learning the basics first, and the basics will serve you well here.

Restore the mysql database from .frm files

I made use of mysqlfrm which is a great tool which generates table creation sql code from .frm files. I was getting this nasty table not found error although tables were being listed. Thus I used this tool to regenerate the tables. In ubuntu you need to install this as:

sudo apt install mysql-utilities

then,

mysqlfrm --diagnostic mysql/db_name/ > db_name.sql

Create a new database and then you can use,

mysql -u username -p < db_name.sql

However, this will give you the tables but not the data. In my case this was enough.

Convert 24 Hour time to 12 Hour plus AM/PM indication Oracle SQL

For the 24-hour time, you need to use HH24 instead of HH.

For the 12-hour time, the AM/PM indicator is written as A.M. (if you want periods in the result) or AM (if you don't). For example:

SELECT invoice_date,
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
  FROM invoices
;

For more information on the format models you can use with TO_CHAR on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.

Android: ListView elements with multiple clickable buttons

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

 public class CustomAdapter extends BaseAdapter {

    TextView title;
  Button button1,button2;

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

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

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

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

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

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

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

 // similarly for button 2

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

    });



        return convertView;
    }
}

Remove a file from a Git repository without deleting it from the local filesystem

Git lets you ignore those files by assuming they are unchanged. This is done by running the git update-index --assume-unchanged path/to/file.txt command. Once marking a file as such, git will completely ignore any changes on that file; they will not show up when running git status or git diff, nor will they ever be committed.

(From https://help.github.com/articles/ignoring-files)

Hence, not deleting it, but ignoring changes to it forever. I think this only works locally, so co-workers can still see changes to it unless they run the same command as above. (Still need to verify this though.)

Note: This isn't answering the question directly, but is based on follow up questions in the comments of the other answers.

List files in local git repo?

This command:

git ls-tree --full-tree -r --name-only HEAD

lists all of the already committed files being tracked by your git repo.

Set attribute without value

The accepted answer doesn't create a name-only attribute anymore (as of September 2017).

You should use JQuery prop() method to create name-only attributes.

$(body).prop('data-body', true)

Check if bash variable equals 0

You can try this:

: ${depth?"Error Message"} ## when your depth variable is not even declared or is unset.

NOTE: Here it's just ? after depth.

or

: ${depth:?"Error Message"} ## when your depth variable is declared but is null like: "depth=". 

NOTE: Here it's :? after depth.

Here if the variable depth is found null it will print the error message and then exit.

Make xargs handle filenames that contain spaces

The xargs utility reads space, tab, newline and end-of-file delimited strings from the standard input and executes utility with the strings as arguments.

You want to avoid using space as a delimiter. This can be done by changing the delimiter for xargs. According to the manual:

 -0      Change xargs to expect NUL (``\0'') characters as separators,
         instead of spaces and newlines.  This is expected to be used in
         concert with the -print0 function in find(1).

Such as:

 find . -name "*.mp3" -print0 | xargs -0 mplayer

To answer the question about playing the seventh mp3; it is simpler to run

 mplayer "$(ls *.mp3 | sed -n 7p)"

Python send UDP packet

With Python3x, you need to convert your string to raw bytes. You would have to encode the string as bytes. Over the network you need to send bytes and not characters. You are right that this would work for Python 2x since in Python 2x, socket.sendto on a socket takes a "plain" string and not bytes. Try this:

print("UDP target IP:", UDP_IP)
print("UDP target port:", UDP_PORT)
print("message:", MESSAGE)

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.sendto(bytes(MESSAGE, "utf-8"), (UDP_IP, UDP_PORT))

How to find the location of the Scheduled Tasks folder

For Windows 7 and up, scheduled tasks are not run by cmd.exe, but rather by MMC (Microsoft Management Console). %SystemRoot%\Tasks should work on any other Windows version though.

No module named serial

  1. Firstly uninstall pyserial using the command pip uninstall pyserial
  2. Then go to https://www.lfd.uci.edu/~gohlke/pythonlibs/
  3. download the suitable pyserial version and then go to the directory where the file is downloaded and open cmd there
  4. then type pip install "filename"(without quotes)

Refreshing all the pivot tables in my excel workbook with a macro

You have a PivotTables collection on a the VB Worksheet object. So, a quick loop like this will work:

Sub RefreshPivotTables()
    Dim pivotTable As PivotTable
    For Each pivotTable In ActiveSheet.PivotTables
        pivotTable.RefreshTable
    Next
End Sub

Notes from the trenches:

  1. Remember to unprotect any protected sheets before updating the PivotTable.
  2. Save often.
  3. I'll think of more and update in due course... :)

Good luck!

How to format font style and color in echo

Are you trying to echo out a style or an inline style? An inline style would be like

echo "<p style=\"font-color: #ff0000;\">text here</p>";

Should functions return null or an empty object?

You should throw an exception (only) if a specific contract is broken.
In your specific example, asking for a UserEntity based on a known Id, it would depend on the fact if missing (deleted) users are an expected case. If so, then return null but if it is not an expected case then throw an exception.
Note that if the function was called UserEntity GetUserByName(string name) it would probably not throw but return null. In both cases returning an empty UserEntity would be unhelpful.

For strings, arrays and collections the situation is usually different. I remember some guideline form MS that methods should accept null as an 'empty' list but return collections of zero-length rather than null. The same for strings. Note that you can declare empty arrays: int[] arr = new int[0];

CodeIgniter: Load controller within controller

There are plenty of good answers given here for loading controllers within controllers, but for me, this contradicts the mvc pattern.

The sentence that worries me is;

(filled with data processed by the product controller)

The models are there for processing and returning data. If you put this logic into your product model then you can call it from any controller you like without having to try to pervert the framework.

Once of the most helpful quotes I read was that the controller was like the 'traffic cop', there to route requests and responses between models and views.

Does React Native styles support gradients?

React Native hasn't provided the gradient color yet. But still, you can do it with a nmp package called react-native-linear-gradient or you can click here for more info

  1. npm install react-native-linear-gradient --save
  2. use import LinearGradient from 'react-native-linear-gradient'; in your application file
  3.         <LinearGradient colors={['#4c669f', '#3b5998', '#192f6a']}>
              <Text>
                Your Text Here
              </Text>
            </LinearGradient> 

How do I resolve `The following packages have unmet dependencies`

If sudo apt-get install -f <package-name> doesn't work, try aptitude:

sudo apt-get install aptitude
sudo aptitude install <package-name>

Aptitude will try to resolve the problem.

As an example, in my case, I still receive some error when try to install libcurl4-openssl-dev:

sudo apt-get install -f libcurl4-openssl-dev

So i try aptitude, it turns out I have to downgrade some packages.

The following actions will resolve these dependencies:

    Keep the following packages at their current version:
    1)     libyaml-dev [Not Installed]                        

Accept this solution? [Y/n/q/? (n)

The following actions will resolve these dependencies:

    Downgrade the following packages:                                
    1)     libyaml-0-2 [0.1.4-3ubuntu3.1 (now) -> 0.1.4-3ubuntu3 (trusty)]

Accept this solution? [Y/n/q/?] (Y)

What's the difference between implementation and compile in Gradle?

+--------------------+----------------------+-------------+--------------+-----------------------------------------+
| Name               | Role                 | Consumable? | Resolveable? | Description                             |
+--------------------+----------------------+-------------+--------------+-----------------------------------------+
| api                | Declaring            |      no     |      no      | This is where you should declare        |
|                    | API                  |             |              | dependencies which are transitively     |
|                    | dependencies         |             |              | exported to consumers, for compile.     |
+--------------------+----------------------+-------------+--------------+-----------------------------------------+
| implementation     | Declaring            |      no     |      no      | This is where you should                |
|                    | implementation       |             |              | declare dependencies which are          |
|                    | dependencies         |             |              | purely internal and not                 |
|                    |                      |             |              | meant to be exposed to consumers.       |
+--------------------+----------------------+-------------+--------------+-----------------------------------------+
| compileOnly        | Declaring compile    |     yes     |      yes     | This is where you should                |
|                    | only                 |             |              | declare dependencies                    |
|                    | dependencies         |             |              | which are only required                 |
|                    |                      |             |              | at compile time, but should             |
|                    |                      |             |              | not leak into the runtime.              |
|                    |                      |             |              | This typically includes dependencies    |
|                    |                      |             |              | which are shaded when found at runtime. |
+--------------------+----------------------+-------------+--------------+-----------------------------------------+
| runtimeOnly        | Declaring            |      no     |      no      | This is where you should                |
|                    | runtime              |             |              | declare dependencies which              |
|                    | dependencies         |             |              | are only required at runtime,           |
|                    |                      |             |              | and not at compile time.                |
+--------------------+----------------------+-------------+--------------+-----------------------------------------+
| testImplementation | Test dependencies    |      no     |      no      | This is where you                       |
|                    |                      |             |              | should declare dependencies             |
|                    |                      |             |              | which are used to compile tests.        |
+--------------------+----------------------+-------------+--------------+-----------------------------------------+
| testCompileOnly    | Declaring test       |     yes     |      yes     | This is where you should                |
|                    | compile only         |             |              | declare dependencies                    |
|                    | dependencies         |             |              | which are only required                 |
|                    |                      |             |              | at test compile time,                   |
|                    |                      |             |              | but should not leak into the runtime.   |
|                    |                      |             |              | This typically includes dependencies    |
|                    |                      |             |              | which are shaded when found at runtime. |
+--------------------+----------------------+-------------+--------------+-----------------------------------------+
| testRuntimeOnly    | Declaring test       |      no     |      no      | This is where you should                |
|                    | runtime dependencies |             |              | declare dependencies which              |
|                    |                      |             |              | are only required at test               |
|                    |                      |             |              | runtime, and not at test compile time.  |
+--------------------+----------------------+-------------+--------------+-----------------------------------------+

jQuery - Trigger event when an element is removed from the DOM

For those who use jQuery UI:

jQuery UI has overridden some of the jQuery methods to implement a remove event that gets handled not only when you explicitly remove the given element, but also if the element gets removed from the DOM by any self-cleaning jQuery methods (e.g. replace, html, etc.). This basically allows you to put a hook into the same events that get fired when jQuery is "cleaning up" the events and data associated with a DOM element.

John Resig has indicated that he's open to the idea of implementing this event in a future version of jQuery core, but I'm not sure where it stands currently.

How to position a DIV in a specific coordinates?

well it depends if all you want is to position a div and then nothing else, you don't need to use java script for that. You can achieve this by CSS only. What matters is relative to what container you want to position your div, if you want to position it relative to document body then your div must be positioned absolute and its container must not be positioned relatively or absolutely, in that case your div will be positioned relative to the container.

Otherwise with Jquery if you want to position an element relative to document you can use offset() method.

$(".mydiv").offset({ top: 10, left: 30 });

if relative to offset parent position the parent relative or absolute. then use following...

var pos = $('.parent').offset();
var top = pos.top + 'no of pixel you want to give the mydiv from top relative to parent';
var left = pos.left + 'no of pixel you want to give the mydiv from left relative to parent';

$('.mydiv').css({
  position:'absolute',
  top:top,
  left:left
});

Using an array as needles in strpos

Just an upgrade from above answers

function strsearch($findme, $source){
    if(is_array($findme)){
        if(str_replace($findme, '', $source) != $source){
            return true;
        }
    }else{
        if(strpos($source,$findme)){
            return true;
        }
    }
    return false;
}

Flask raises TemplateNotFound error even though template file exists

I don't know why, but I had to use the following folder structure instead. I put "templates" one level up.

project/
    app/
        hello.py
        static/
            main.css
    templates/
        home.html
    venv/

This probably indicates a misconfiguration elsewhere, but I couldn't figure out what that was and this worked.

Git: "Corrupt loose object"

I just experienced this - my machine crashed whilst writing to the Git repo, and it became corrupted. I fixed it as follows.

I started with looking at how many commits I had not pushed to the remote repo, thus:

gitk &

If you don't use this tool it is very handy - available on all operating systems as far as I know. This indicated that my remote was missing two commits. I therefore clicked on the label indicating the latest remote commit (usually this will be /remotes/origin/master) to get the hash (the hash is 40 chars long, but for brevity I am using 10 here - this usually works anyway).

Here it is:

14c0fcc9b3

I then click on the following commit (i.e. the first one that the remote does not have) and get the hash there:

04d44c3298

I then use both of these to make a patch for this commit:

git diff 14c0fcc9b3 04d44c3298 > 1.patch

I then did likewise with the other missing commit, i.e. I used the hash of the commit before and the hash of the commit itself:

git diff 04d44c3298 fc1d4b0df7 > 2.patch

I then moved to a new directory, cloned the repo from the remote:

git clone [email protected]:username/repo.git

I then moved the patch files into the new folder, and applied them and committed them with their exact commit messages (these can be pasted from git log or the gitk window):

patch -p1 < 1.patch
git commit

patch -p1 < 2.patch
git commit

This restored things for me (and note there's probably a faster way to do it for a large number of commits). However I was keen to see if the tree in the corrupted repo can be repaired, and the answer is it can. With a repaired repo available as above, run this command in the broken folder:

git fsck 

You will get something like this:

error: object file .git/objects/ca/539ed815fefdbbbfae6e8d0c0b3dbbe093390d is empty
error: unable to find ca539ed815fefdbbbfae6e8d0c0b3dbbe093390d
error: sha1 mismatch ca539ed815fefdbbbfae6e8d0c0b3dbbe093390d

To do the repair, I would do this in the broken folder:

rm .git/objects/ca/539ed815fefdbbbfae6e8d0c0b3dbbe093390d
cp ../good-repo/.git/objects/ca/539ed815fefdbbbfae6e8d0c0b3dbbe093390d .git/objects/ca/539ed815fefdbbbfae6e8d0c0b3dbbe093390d

i.e. remove the corrupted file and replace it with a good one. You may have to do this several times. Finally there will be a point where you can run fsck without errors. You will probably have "dangling commit" and "dangling blob" lines in the report, these are a consequence of your rebases and amends in this folder, and are OK. The garbage collector will remove them in due course.

Thus (at least in my case) a corrupted tree does not mean unpushed commits are lost.

How do I vertically align text in a paragraph?

You can use line-height for that. Just set it up to the exact height of your p tag.

p.event_desc {
  line-height:35px;
}

Imported a csv-dataset to R but the values becomes factors

When importing csv data files the import command should reflect both the data seperation between each column (;) and the float-number seperator for your numeric values (for numerical variable = 2,5 this would be ",").

The command for importing a csv, therefore, has to be a bit more comprehensive with more commands:

    stuckey <- read.csv2("C:/kalle/R/stuckey.csv", header=TRUE, sep=";", dec=",")

This should import all variables as either integers or numeric.

Can I use complex HTML with Twitter Bootstrap's Tooltip?

Just as normal, using data-original-title:

Html:

<div rel='tooltip' data-original-title='<h1>big tooltip</h1>'>Visible text</div>

Javascript:

$("[rel=tooltip]").tooltip({html:true});

The html parameter specifies how the tooltip text should be turned into DOM elements. By default Html code is escaped in tooltips to prevent XSS attacks. Say you display a username on your site and you show a small bio in a tooltip. If the html code isn't escaped and the user can edit the bio themselves they could inject malicious code.

Angular2 change detection: ngOnChanges not firing for nested object

ok so my solution for this was:

this.arrayWeNeed.DoWhatWeNeedWithThisArray();
const tempArray = [...arrayWeNeed];
this.arrayWeNeed = [];
this.arrayWeNeed = tempArray;

And this trigger me ngOnChanges

Download pdf file using jquery ajax

For those looking a more modern approach, you can use the fetch API. The following example shows how to download a PDF file. It is easily done with the following code.

fetch(url, {
    body: JSON.stringify(data),
    method: 'POST',
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    },
})
.then(response => response.blob())
.then(response => {
    const blob = new Blob([response], {type: 'application/pdf'});
    const downloadUrl = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = downloadUrl;
    a.download = "file.pdf";
    document.body.appendChild(a);
    a.click();
})

I believe this approach to be much easier to understand than other XMLHttpRequest solutions. Also, it has a similar syntax to the jQuery approach, without the need to add any additional libraries.

Of course, I would advise checking to which browser you are developing, since this new approach won't work on IE. You can find the full browser compatibility list on the following [link][1].

Important: In this example I am sending a JSON request to a server listening on the given url. This url must be set, on my example I am assuming you know this part. Also, consider the headers needed for your request to work. Since I am sending a JSON, I must add the Content-Type header and set it to application/json; charset=utf-8, as to let the server know the type of request it will receive.

How to get 0-padded binary representation of an integer in java?

I do not know "right" solution but I can suggest you a fast patch.

String.format("%16s", Integer.toBinaryString(1)).replace(" ", "0");

I have just tried it and saw that it works fine.

Remove redundant paths from $PATH variable

If you just want to remove any duplicate paths, I use this script I wrote a while back since I was having trouble with multiple perl5/bin paths:

#!/bin/bash
#
# path-cleanup
#
# This must be run as "source path-cleanup" or ". path-cleanup"
# so the current shell gets the changes.

pathlist=`echo $PATH | sed 's/:/\n/g' | uniq`

# echo "Starting PATH: $PATH"
# echo "pathlist: $pathlist"
unset PATH
# echo "After unset, PATH: $PATH"
for dir in $pathlist
do
    if test -d $dir ; then
        if test -z $PATH; then
            PATH=$dir
        else
            PATH=$PATH:$dir
        fi
    fi
done
export PATH
# echo "After loop, PATH: $PATH"

And I put it in my ~/.profile at the end. Since I use BASH almost exclusively, I haven't tried it in other shells.

How do you increase the max number of concurrent connections in Apache?

change the MaxClients directive. it is now on 256.

PHP calculate age

If you don't need great precision, just the number of years, you could consider using the code below ...

 print floor((time() - strtotime("1971-11-20")) / (60*60*24*365));

You only need to put this into a function and replace the date "1971-11-20" with a variable.

Please note that precision of the code above is not high because of the leap years, i.e. about every 4 years the days are 366 instead of 365. The expression 60*60*24*365 calculates the number of seconds in one year - you can replace it with 31536000.

Another important thing is that because of the use of UNIX Timestamp it has both the Year 1901 and Year 2038 problem which means the the expression above will not work correctly for dates before year 1901 and after year 2038.

If you can live with the limitations mentioned above that code should work for you.

Validate IPv4 address in Java

This is for Android, testing for IPv4 and IPv6

Note: the commonly used InetAddressUtils is deprecated. Use new InetAddress classes

public static Boolean isIPv4Address(String address) {
    if (address.isEmpty()) {
        return false;
    }
    try {
        Object res = InetAddress.getByName(address);
        return res instanceof Inet4Address || res instanceof Inet6Address;
    } catch (final UnknownHostException exception) {
        return false;
    }
}

How to download and save a file from Internet using Java?

public void saveUrl(final String filename, final String urlString)
        throws MalformedURLException, IOException {
    BufferedInputStream in = null;
    FileOutputStream fout = null;
    try {
        in = new BufferedInputStream(new URL(urlString).openStream());
        fout = new FileOutputStream(filename);

        final byte data[] = new byte[1024];
        int count;
        while ((count = in.read(data, 0, 1024)) != -1) {
            fout.write(data, 0, count);
        }
    } finally {
        if (in != null) {
            in.close();
        }
        if (fout != null) {
            fout.close();
        }
    }
}

You'll need to handle exceptions, probably external to this method.

Bootstrap Element 100% Width

This is how you can achieve your desired setup with Bootstrap 3:

<div class="container-fluid">
    <div class="row"> <!-- Give this div your desired background color -->
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    ... your content here ...
                </div>
            </div>
        </div>
    </div>
</div>

The container-fluid part makes sure that you can change the background over the full width. The container part makes sure that your content is still wrapped in a fixed width.

This approach works, but personally I don't like all the nesting. However, I haven't found a better solution so far.

Animate an element's width from 0 to 100%, with it and it's wrapper being only as wide as they need to be, without a pre-set width, in CSS3 or jQuery

http://jsfiddle.net/tVHYg/5/

.wrapper {
    background:#DDD;
    padding:1%;
    display:inline;
    height:20px;
}


span {
    width: 1%;
}

.contents {
    background:#c3c;
    overflow:hidden;
    white-space:nowrap;
    display:inline-block;
    width:0%;
}



.wrapper:hover .contents {
    -webkit-transition: width 1s ease-in-out;
    -moz-transition: width 1s ease-in-out;
    -o-transition: width 1s ease-in-out;
    transition: width 1s ease-in-out;

    width:90%;
}

JavaScript module pattern with example

In order to approach to Modular design pattern, you need to understand these concept first:

Immediately-Invoked Function Expression (IIFE):

(function() {
      // Your code goes here 
}());

There are two ways you can use the functions. 1. Function declaration 2. Function expression.

Here are using function expression.

What is namespace? Now if we add the namespace to the above piece of code then

var anoyn = (function() {
}());

What is closure in JS?

It means if we declare any function with any variable scope/inside another function (in JS we can declare a function inside another function!) then it will count that function scope always. This means that any variable in outer function will be read always. It will not read the global variable (if any) with the same name. This is also one of the objective of using modular design pattern avoiding naming conflict.

var scope = "I am global";
function whatismyscope() {
    var scope = "I am just a local";
    function func() {return scope;}
    return func;
}
whatismyscope()()

Now we will apply these three concepts I mentioned above to define our first modular design pattern:

var modularpattern = (function() {
    // your module code goes here
    var sum = 0 ;

    return {
        add:function() {
            sum = sum + 1;
            return sum;
        },
        reset:function() {
            return sum = 0;    
        }  
    }   
}());
alert(modularpattern.add());    // alerts: 1
alert(modularpattern.add());    // alerts: 2
alert(modularpattern.reset());  // alerts: 0

jsfiddle for the code above.

The objective is to hide the variable accessibility from the outside world.

Hope this helps. Good Luck.

Java image resize, maintain aspect ratio

This is my solution:

/*
Change dimension of Image
*/
public static Image resizeImage(Image image, int scaledWidth, int scaledHeight, boolean preserveRatio) {  

    if (preserveRatio) { 
        double imageHeight = image.getHeight();
        double imageWidth = image.getWidth();

        if (imageHeight/scaledHeight > imageWidth/scaledWidth) {
            scaledWidth = (int) (scaledHeight * imageWidth / imageHeight);
        } else {
            scaledHeight = (int) (scaledWidth * imageHeight / imageWidth);
        }        
    }                   
    BufferedImage inputBufImage = SwingFXUtils.fromFXImage(image, null);     
    // creates output image
    BufferedImage outputBufImage = new BufferedImage(scaledWidth, scaledHeight, inputBufImage.getType());       
    // scales the input image to the output image
    Graphics2D g2d = outputBufImage.createGraphics();
    g2d.drawImage(inputBufImage, 0, 0, scaledWidth, scaledHeight, null);
    g2d.dispose();      
    return SwingFXUtils.toFXImage(outputBufImage, null);
}

Use a URL to link to a Google map with a marker on it

If working with Basic4Android and looking for an easy fix to the problem, try this it works both Google maps and Openstreet even though OSM creates a bit of a messy result and thanx to [yndolok] for the google marker

GooglemLoc="https://www.google.com/maps/place/"&[Latitude]&"+"&[Longitude]&"/@"&[Latitude]&","&[Longitude]&",15z" 

GooglemRute="https://www.google.co.ls/maps/dir/"&[FrmLatt]&","&[FrmLong]&"/"&[ToLatt]&","&[FrmLong]&"/@"&[ScreenX]&","&[ScreenY]&",14z/data=!3m1!4b1!4m2!4m1!3e0?hl=en"  'route ?hl=en

OpenStreetLoc="https://www.openstreetmap.org/#map=16/"&[Latitude]&"/"&[Longitude]&"&layers=N"

OpenStreetRute="https://www.openstreetmap.org/directions?engine=osrm_car&route="&[FrmLatt]&"%2C"&[FrmLong]&"%3B"&[ToLatt]&"%2C"&[ToLong]&"#Map=15/"&[ScreenX]&"/"&[Screeny]&"&layers=N"

YouTube iframe API: how do I control an iframe player that's already in the HTML?

Fiddle Links: Source code - Preview - Small version
Update: This small function will only execute code in a single direction. If you want full support (eg event listeners / getters), have a look at Listening for Youtube Event in jQuery

As a result of a deep code analysis, I've created a function: function callPlayer requests a function call on any framed YouTube video. See the YouTube Api reference to get a full list of possible function calls. Read the comments at the source code for an explanation.

On 17 may 2012, the code size was doubled in order to take care of the player's ready state. If you need a compact function which does not deal with the player's ready state, see http://jsfiddle.net/8R5y6/.

/**
 * @author       Rob W <[email protected]>
 * @website      https://stackoverflow.com/a/7513356/938089
 * @version      20190409
 * @description  Executes function on a framed YouTube video (see website link)
 *               For a full list of possible functions, see:
 *               https://developers.google.com/youtube/js_api_reference
 * @param String frame_id The id of (the div containing) the frame
 * @param String func     Desired function to call, eg. "playVideo"
 *        (Function)      Function to call when the player is ready.
 * @param Array  args     (optional) List of arguments to pass to function func*/
function callPlayer(frame_id, func, args) {
    if (window.jQuery && frame_id instanceof jQuery) frame_id = frame_id.get(0).id;
    var iframe = document.getElementById(frame_id);
    if (iframe && iframe.tagName.toUpperCase() != 'IFRAME') {
        iframe = iframe.getElementsByTagName('iframe')[0];
    }

    // When the player is not ready yet, add the event to a queue
    // Each frame_id is associated with an own queue.
    // Each queue has three possible states:
    //  undefined = uninitialised / array = queue / .ready=true = ready
    if (!callPlayer.queue) callPlayer.queue = {};
    var queue = callPlayer.queue[frame_id],
        domReady = document.readyState == 'complete';

    if (domReady && !iframe) {
        // DOM is ready and iframe does not exist. Log a message
        window.console && console.log('callPlayer: Frame not found; id=' + frame_id);
        if (queue) clearInterval(queue.poller);
    } else if (func === 'listening') {
        // Sending the "listener" message to the frame, to request status updates
        if (iframe && iframe.contentWindow) {
            func = '{"event":"listening","id":' + JSON.stringify(''+frame_id) + '}';
            iframe.contentWindow.postMessage(func, '*');
        }
    } else if ((!queue || !queue.ready) && (
               !domReady ||
               iframe && !iframe.contentWindow ||
               typeof func === 'function')) {
        if (!queue) queue = callPlayer.queue[frame_id] = [];
        queue.push([func, args]);
        if (!('poller' in queue)) {
            // keep polling until the document and frame is ready
            queue.poller = setInterval(function() {
                callPlayer(frame_id, 'listening');
            }, 250);
            // Add a global "message" event listener, to catch status updates:
            messageEvent(1, function runOnceReady(e) {
                if (!iframe) {
                    iframe = document.getElementById(frame_id);
                    if (!iframe) return;
                    if (iframe.tagName.toUpperCase() != 'IFRAME') {
                        iframe = iframe.getElementsByTagName('iframe')[0];
                        if (!iframe) return;
                    }
                }
                if (e.source === iframe.contentWindow) {
                    // Assume that the player is ready if we receive a
                    // message from the iframe
                    clearInterval(queue.poller);
                    queue.ready = true;
                    messageEvent(0, runOnceReady);
                    // .. and release the queue:
                    while (tmp = queue.shift()) {
                        callPlayer(frame_id, tmp[0], tmp[1]);
                    }
                }
            }, false);
        }
    } else if (iframe && iframe.contentWindow) {
        // When a function is supplied, just call it (like "onYouTubePlayerReady")
        if (func.call) return func();
        // Frame exists, send message
        iframe.contentWindow.postMessage(JSON.stringify({
            "event": "command",
            "func": func,
            "args": args || [],
            "id": frame_id
        }), "*");
    }
    /* IE8 does not support addEventListener... */
    function messageEvent(add, listener) {
        var w3 = add ? window.addEventListener : window.removeEventListener;
        w3 ?
            w3('message', listener, !1)
        :
            (add ? window.attachEvent : window.detachEvent)('onmessage', listener);
    }
}

Usage:

callPlayer("whateverID", function() {
    // This function runs once the player is ready ("onYouTubePlayerReady")
    callPlayer("whateverID", "playVideo");
});
// When the player is not ready yet, the function will be queued.
// When the iframe cannot be found, a message is logged in the console.
callPlayer("whateverID", "playVideo");

Possible questions (& answers):

Q: It doesn't work!
A: "Doesn't work" is not a clear description. Do you get any error messages? Please show the relevant code.

Q: playVideo does not play the video.
A: Playback requires user interaction, and the presence of allow="autoplay" on the iframe. See https://developers.google.com/web/updates/2017/09/autoplay-policy-changes and https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide

Q: I have embedded a YouTube video using <iframe src="http://www.youtube.com/embed/As2rZGPGKDY" />but the function doesn't execute any function!
A: You have to add ?enablejsapi=1 at the end of your URL: /embed/vid_id?enablejsapi=1.

Q: I get error message "An invalid or illegal string was specified". Why?
A: The API doesn't function properly at a local host (file://). Host your (test) page online, or use JSFiddle. Examples: See the links at the top of this answer.

Q: How did you know this?
A: I have spent some time to manually interpret the API's source. I concluded that I had to use the postMessage method. To know which arguments to pass, I created a Chrome extension which intercepts messages. The source code for the extension can be downloaded here.

Q: What browsers are supported?
A: Every browser which supports JSON and postMessage.

  • IE 8+
  • Firefox 3.6+ (actually 3.5, but document.readyState was implemented in 3.6)
  • Opera 10.50+
  • Safari 4+
  • Chrome 3+

Related answer / implementation: Fade-in a framed video using jQuery
Full API support: Listening for Youtube Event in jQuery
Official API: https://developers.google.com/youtube/iframe_api_reference

Revision history

  • 17 may 2012
    Implemented onYouTubePlayerReady: callPlayer('frame_id', function() { ... }).
    Functions are automatically queued when the player is not ready yet.
  • 24 july 2012
    Updated and successully tested in the supported browsers (look ahead).
  • 10 october 2013 When a function is passed as an argument, callPlayer forces a check of readiness. This is needed, because when callPlayer is called right after the insertion of the iframe while the document is ready, it can't know for sure that the iframe is fully ready. In Internet Explorer and Firefox, this scenario resulted in a too early invocation of postMessage, which was ignored.
  • 12 Dec 2013, recommended to add &origin=* in the URL.
  • 2 Mar 2014, retracted recommendation to remove &origin=* to the URL.
  • 9 april 2019, fix bug that resulted in infinite recursion when YouTube loads before the page was ready. Add note about autoplay.

Pointer to 2D arrays in C

int *pointer[280]; //Creates 280 pointers of type int.

In 32 bit os, 4 bytes for each pointer. so 4 * 280 = 1120 bytes.

int (*pointer)[100][280]; // Creates only one pointer which is used to point an array of [100][280] ints.

Here only 4 bytes.

Coming to your question, int (*pointer)[280]; and int (*pointer)[100][280]; are different though it points to same 2D array of [100][280].

Because if int (*pointer)[280]; is incremented, then it will points to next 1D array, but where as int (*pointer)[100][280]; crosses the whole 2D array and points to next byte. Accessing that byte may cause problem if that memory doen't belongs to your process.

SQL : BETWEEN vs <= and >=

I think the only difference is the amount of syntactical sugar on each query. BETWEEN is just a slick way of saying exactly the same as the second query.

There might be some RDBMS specific difference that I'm not aware of, but I don't really think so.

Create an Excel file using vbscripts

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = true
Set objWorkbook = objExcel.Workbooks.Add()
Set objWorksheet = objWorkbook.Worksheets(1)

intRow = 2
dim ch
objWorksheet.Cells(1,1) = "Name"
objWorksheet.Cells(1,2) = "Subject1"
objWorksheet.Cells(1,3) = "Subject2"
objWorksheet.Cells(1,4) = "Total"
for intRow = 2 to  10000 
name= InputBox("Enter your name")
sb1 = cint(InputBox("Enter your Marks in Subject 1"))
sb2 = cint(InputBox("Enter your Marks in Subject 2"))
total= sb1+sb2+sb3+sb4
objExcel.Cells(intRow, 1).Value = name
objExcel.Cells(intRow, 2).Value = sb1
objExcel.Cells(intRow, 3).Value = sb2
objExcel.Cells(intRow, 4).Value = total
ch = InputBox("Do you want continue..? if no then type no or y to continue")
    If ch = "no" Then Exit For 
Next

objExcel.Cells.EntireColumn.AutoFit

MsgBox "Done"
enter code here

Creating a new dictionary in Python

Knowing how to write a preset dictionary is useful to know as well:

cmap =  {'US':'USA','GB':'Great Britain'}

# Explicitly:
# -----------
def cxlate(country):
    try:
        ret = cmap[country]
    except KeyError:
        ret = '?'
    return ret

present = 'US' # this one is in the dict
missing = 'RU' # this one is not

print cxlate(present) # == USA
print cxlate(missing) # == ?

# or, much more simply as suggested below:

print cmap.get(present,'?') # == USA
print cmap.get(missing,'?') # == ?

# with country codes, you might prefer to return the original on failure:

print cmap.get(present,present) # == USA
print cmap.get(missing,missing) # == RU

Read a javascript cookie by name

The point of Stack Overflow is to provide a database of good quality answers, so I am going to reference some standard source code and an article that gives examples:

http://www.codelib.net/javascript/cookies.html

Note: The code is regular-expression free for greatly enhanced efficiency.

Using the source code provided, you would use cookies like this:

makeCookie('color', 'silver');

This saves a cookie indicating that the color is silver. The cookie would expire after the current session (as soon as the user quits the browser).

makeCookie('color', 'green', { domain: 'gardens.home.com' });

This saves the color green for gardens.home.com.

makeCookie('color', 'white', { domain: '.home.com', path: '/invoices' });
makeCookie('invoiceno', '0259876', { path: '/invoices', secure: true });

saves the color white for invoices viewed anywhere at home.com. The second cookie is a secure cookie, and records an invoice number. This cookie will be sent only to pages that are viewed through secure HTTPS connections, and scripts within secure pages are the only scripts allowed to access the cookie.

One HTTP host is not allowed to store or read cookies for another HTTP host. Thus, a cookie domain must be stored with at least two periods. By default, the domain is the same as the domain of the web address which created the cookie.

The path of an HTTP cookie restricts it to certain files on the HTTP host. Some browsers use a default path of /, so the cookie will be available on the whole host. Other browsers use the whole filename. In this case, if /invoices/overdue.cgi creates a cookie, only /invoices/overdue.cgi is going to get the cookie back.

When setting paths and other parameters, they are usually based on data obtained from variables like location.href, etc. These strings are already escaped, so when the cookie is created, the cookie function does not escape these values again. Only the name and value of the cookie are escaped, so we can conveniently use arbitrary names or values. Some browsers limit the total size of a cookie, or the total number of cookies which one domain is allowed to keep.

makeCookie('rememberemail', 'yes', { expires: 7 });
makeCookie('rememberlogin', 'yes', { expires: 1 });
makeCookie('allowentergrades', 'yes', { expires: 1/24 });

these cookies would remember the user's email for 7 days, the user's login for 1 day, and allow the user to enter grades without a password for 1 hour (a twenty-fourth of a day). These time limits are obeyed even if they quit the browser, and even if they don't quit the browser. Users are free to use a different browser program, or to delete cookies. If they do this, the cookies will have no effect, regardless of the expiration date.

makeCookie('rememberlogin', 'yes', { expires: -1 });

deletes the cookie. The cookie value is superfluous, and the return value false means that deletion was successful. (A expiration of -1 is used instead of 0. If we had used 0, the cookie might be undeleted until one second past the current time. In this case we would think that deletion was unsuccessful.)

Obviously, since a cookie can be deleted in this way, a new cookie will also overwrite any value of an old cookie which has the same name, including the expiration date, etc. However, cookies for completely non-overlapping paths or domains are stored separately, and the same names do not interfere with each other. But in general, any path or domain which has access to a cookie can overwrite the cookie, no matter whether or not it changes the path or domain of the new cookie.

rmCookie('rememberlogin');

also deletes the cookie, by doing makeCookie('rememberlogin', '', { expires: -1 }). This makes the cookie code longer, but saves code for people who use it, which one might think saves more code in the long run.

Autonumber value of last inserted row - MS Access / VBA

This is an adaptation from my code for you. I was inspired from developpez.com (Look in the page for : "Pour insérer des données, vaut-il mieux passer par un RecordSet ou par une requête de type INSERT ?"). They explain (with a little French). This way is much faster than the one upper. In the example, this way was 37 times faster. Try it.

Const tableName As String = "InvoiceNumbers"
Const columnIdName As String = "??"
Const columnDateName As String = "date"

Dim rsTable As DAO.recordSet
Dim recordId as long

Set rsTable = CurrentDb.OpenRecordset(tableName)
Call rsTable .AddNew
recordId = CLng(rsTable (columnIdName)) ' Save your Id in a variable
rsTable (columnDateName) = Now()        ' Store your data
rsTable .Update

recordSet.Close

LeCygne

How to resolve 'npm should be run outside of the node repl, in your normal shell'

It's simple. Press the Windows logo on your keyboard. Then, type node.js command prompt in the search bar and run it. screenshot: run npm outside node repl

Losing scope when using ng-include

Instead of using this as the accepted answer suggests, use $parent instead. So in your partial1.htmlyou'll have:

<form ng-submit="$parent.addLine()">
    <input type="text" ng-model="$parent.lineText" size="30" placeholder="Type your message here">
</form>

If you want to learn more about the scope in ng-include or other directives, check this out: https://github.com/angular/angular.js/wiki/Understanding-Scopes#ng-include

Concatenating strings doesn't work as expected

std::string a = "Hello ";
a += "World";

Check if a user has scrolled to the bottom

Let me show approch without JQuery. Simple JS function:

function isVisible(elem) {
  var coords = elem.getBoundingClientRect();
  var topVisible = coords.top > 0 && coords.top < 0;
  var bottomVisible = coords.bottom < shift && coords.bottom > 0;
  return topVisible || bottomVisible;
}

Short example how to use it:

var img = document.getElementById("pic1");
    if (isVisible(img)) { img.style.opacity = "1.00";  }

session handling in jquery

Assuming you're referring to this plugin, your code should be:

// To Store
$(function() {
    $.session.set("myVar", "value");
});


// To Read
$(function() {
    alert($.session.get("myVar"));
});

Before using a plugin, remember to read its documentation in order to learn how to use it. In this case, an usage example can be found in the README.markdown file, which is displayed on the project page.

Get current index from foreach loop

IEnumerable list = DataGridDetail.ItemsSource as IEnumerable;
List<string> lstFile = new List<string>();

int i = 0;
foreach (var row in list)
{
bool IsChecked = (bool)((CheckBox)DataGridDetail.Columns[0].GetCellContent(row)).IsChecked;
if (IsChecked)
{
  MessageBox.show(i);
--Here i want to get the index or current row from the list                   

}
 ++i;
}

Check string for palindrome

A concise version, that doesn't involve (inefficiently) initializing a bunch of objects:

boolean isPalindrome(String str) {    
    int n = str.length();
    for( int i = 0; i < n/2; i++ )
        if (str.charAt(i) != str.charAt(n-i-1)) return false;
    return true;    
}

Basic HTTP and Bearer Token Authentication

There is another solution for testing APIs on development server.

  • Set HTTP Basic Authentication only for web routes
  • Leave all API routes free from authentication

Web server configuration for nginx and Laravel would be like this:

    location /api {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location / {
        try_files $uri $uri/ /index.php?$query_string;

        auth_basic "Enter password";
        auth_basic_user_file /path/to/.htpasswd;
    }

Authorization: Bearer will do the job of defending the development server against web crawlers and other unwanted visitors.

Xcode 7 error: "Missing iOS Distribution signing identity for ..."

Make Sure that in Project Navigator > Signing > Team , A team name must need be selected.

enter image description here

.ps1 cannot be loaded because the execution of scripts is disabled on this system

You need to run Set-ExecutionPolicy:

Set-ExecutionPolicy Unrestricted <-- Will allow unsigned PowerShell scripts to run.

Set-ExecutionPolicy Restricted <-- Will not allow unsigned PowerShell scripts to run.

Set-ExecutionPolicy RemoteSigned <-- Will allow only remotely signed PowerShell scripts to run.

Replace input type=file by an image

I would use SWFUpload or Uploadify. They need Flash but do everything you want without troubles.

Any <input type="file"> based workaround that tries to trigger the "open file" dialog by means other than clicking on the actual control could be removed from browsers for security reasons at any time. (I think in the current versions of FF and IE, it is not possible any more to trigger that event programmatically.)

how to make UITextView height dynamic according to text length?

Here are two pitfalls in iOS 8.3 when coming with textView.textContainer.maximumNumberOfLines = 10

Refer to my gist, please.

textView.attributedText = originalContent

let lineLimit = 10
textView.isEditable = true
textView.isScrollEnabled = false
textView.textContainerInset = .zero // default is (8, 0, 8, 0)
textView.textContainer.maximumNumberOfLines = lineLimit // Important condition
textView.textContainer.lineBreakMode = .byTruncatingTail

// two incomplete methods, which do NOT work in iOS 8.3

// size.width???maxSize.width? ————???? iOS 8.3 ??????maximumNumberOfLines??,??????UILabel
// size.width may be less than maxSize.width, ---- Do NOT work in iOS 8.3, which disregards textView.textContainer.maximumNumberOfLines
// let size = textView.sizeThatFits(maxSize) 

// ???? iOS 8.3 ???????,????UILabel
// Does not work in iOS 8.3
// let size = textView.layoutManager.usedRectForTextContainer(textView.textContainer).size 

// Suggested method: use a temperary label to get its size
let label = UILabel(); label.attributedText = originalContent
let size = label.textRect(forBounds: CGRect(origin: .zero, size: maxSize), limitedToNumberOfLines: lineLimit).size
textView.frame.size = size

CMD command to check connected USB devices

You can use the wmic command:

wmic path CIM_LogicalDevice where "Description like 'USB%'" get /value

What is the use of the square brackets [] in sql statements?

They're handy if your columns have the same names as SQL keywords, or have spaces in them.

Example:

create table test ( id int, user varchar(20) )

Oh no! Incorrect syntax near the keyword 'user'. But this:

create table test ( id int, [user] varchar(20) )

Works fine.

How to generate a random number between 0 and 1?

Here's a general procedure for producing a random number in a specified range:

int randInRange(int min, int max)
{
  return min + (int) (rand() / (double) (RAND_MAX + 1) * (max - min + 1));
}

Depending on the PRNG algorithm being used, the % operator may result in a very non-random sequence of numbers.

MySQL, Check if a column exists in a table with SQL

DO NOT put ALTER TABLE/MODIFY COLS or any other such table mod operations inside a TRANSACTION. Transactions are for being able to roll back a QUERY failure not for ALTERations...it will error out every time in a transaction.

Just run a SELECT * query on the table and check if the column is there...

Using Regular Expressions to Extract a Value in Java

Full example:

private static final Pattern p = Pattern.compile("^([a-zA-Z]+)([0-9]+)(.*)");
public static void main(String[] args) {
    // create matcher for pattern p and given string
    Matcher m = p.matcher("Testing123Testing");

    // if an occurrence if a pattern was found in a given string...
    if (m.find()) {
        // ...then you can use group() methods.
        System.out.println(m.group(0)); // whole matched expression
        System.out.println(m.group(1)); // first expression from round brackets (Testing)
        System.out.println(m.group(2)); // second one (123)
        System.out.println(m.group(3)); // third one (Testing)
    }
}

Since you're looking for the first number, you can use such regexp:

^\D+(\d+).*

and m.group(1) will return you the first number. Note that signed numbers can contain a minus sign:

^\D+(-?\d+).*

Date formatting in WPF datagrid

Binding="{Binding YourColumn ,StringFormat='yyyy-MM-dd'}"

CSS align images and text on same line

In this case you can use display:inline or inline-block.

Example:

_x000D_
_x000D_
img.likeordisklike {display:inline;vertical-align:middle;  }_x000D_
h4.liketext { color:#F00; display:inline;vertical-align:top;padding-left:10px; }
_x000D_
<img class='likeordislike' src='design/like.png'/><h4 class='liketext'>$likes</h4>_x000D_
<img class='likeordislike' src='design/dislike.png'/><h4 class='liketext'>$dislikes</h4>
_x000D_
_x000D_
_x000D_

Don't use float:left because again need to write one more clear line and its old method also..

Correct owner/group/permissions for Apache 2 site files/folders under Mac OS X?

The user owner for me is the admin user and the group is _www and works with permissions set to 775 for dir and for files 664