# Programs & Examples On #Y combinator

The Y combinator is a higher-order function that allows a function that does not know its own name to call itself. It is the fundamental basis of recursion.

### What is a Y-combinator?

For programmers who haven't encountered functional programming in depth, and don't care to start now, but are mildly curious:

The Y combinator is a formula which lets you implement recursion in a situation where functions can't have names but can be passed around as arguments, used as return values, and defined within other functions.

It works by passing the function to itself as an argument, so it can call itself.

It's part of the lambda calculus, which is really maths but is effectively a programming language, and is pretty fundamental to computer science and especially to functional programming.

The day to day practical value of the Y combinator is limited, since programming languages tend to let you name functions.

In case you need to identify it in a police lineup, it looks like this:

Y = ?f.(?x.f (x x)) (?x.f (x x))

You can usually spot it because of the repeated `(?x.f (x x))`.

The `?` symbols are the Greek letter lambda, which gives the lambda calculus its name, and there's a lot of `(?x.t)` style terms because that's what the lambda calculus looks like.

### showing that a date is greater than current date

For those that want a nice conditional:

``````DECLARE @MyDate DATETIME  = 'some date in future' --example  DateAdd(day,5,GetDate())

IF @MyDate < DATEADD(DAY,1,GETDATE())
BEGIN
PRINT 'Date NOT greater than today...'
END
ELSE
BEGIN
PRINT 'Date greater than today...'
END
``````

### Updating Python on Mac

This article helped me to make the right choices eventually since mac 10.14.6 by default came with python 2.7* and I had to upgrade to 3.7.*

``````brew install python3
brew update && brew upgrade python
alias python=/usr/local/bin/python3
``````

Referred The right and wrong way to set Python 3 as default on a Mac article

### How to make a boolean variable switch between true and false every time a method is invoked?

``````value ^= true;
``````

That is value xor-equals true, which will flip it every time, and without any branching or temporary variables.

### tr:hover not working

Like @wesley says, you have not closed your first `<td>`. You opened it two times.

``````<table class="list1">
<tr>
<td>1</td><td>a</td>
</tr>
<tr>
<td>2</td><td>b</td>
</tr>
<tr>
<td>3</td><td>c</td>
</tr>
</table>
``````

CSS:

``````.list1 tr:hover{
background-color:#fefefe;
}
``````

There is no JavaScript needed, just complete your HTML code

### What is the difference between RTP or RTSP in a streaming server?

RTSP (actually RTP) can be used for streaming video, but also many other types of media including live presentations. Rtsp is just the protocol used to setup the RTP session.

For all the details you can check out my open source RTSP Server implementation on the following address: https://net7mma.codeplex.com/

It supports re-sourcing streams as well as the dynamic creation of streams, various RFC's are implemented and the library achieves better performance and less memory then FFMPEG and just about any other solutions in the transport layer and thus makes it a good candidate to use as a centralized point of access for most scenarios.

### NoSql vs Relational database

If you need to process huge amount of data with high performance

OR

If data model is not predetermined

then

NoSQL database is a better choice.

### How to get the real and total length of char * (char array)?

You can make a back-tracker character, ex, you could append any special character say "%" to the end of your string and then check the occurrence of that character.
But this is a very risky way as that character can be in other places also in the char*

``````char* stringVar = new char[4] ;
stringVar[0] = 'H' ;
stringVar[1] = 'E' ;
stringVar[2] = '\$' ; // back-tracker character.
int i = 0 ;
while(1)
{
if (stringVar[i] == '\$')
break ;
i++ ;
}
//  i is the length of the string.
// you need to make sure, that there is no other \$ in the char*
``````

Otherwise define a custom structure to keep track of length and allocate memory.

### Bootstrap Align Image with text

``````  <div class="container">
<div class="row">
<div class="pull-left ">
<img src="http://lorempixel.com/200/200" class="col-lg-3" class="img-    responsive" alt="Responsive image">
<p class="col-md-4">Lots of text here... </p>
</div>

</div>
</div>
</div>
``````

### Generating 8-character only UUIDs

First: Even the unique IDs generated by java UUID.randomUUID or .net GUID are not 100% unique. Especialy UUID.randomUUID is "only" a 128 bit (secure) random value. So if you reduce it to 64 bit, 32 bit, 16 bit (or even 1 bit) then it becomes simply less unique.

So it is at least a risk based decisions, how long your uuid must be.

Second: I assume that when you talk about "only 8 characters" you mean a String of 8 normal printable characters.

If you want a unique string with length 8 printable characters you could use a base64 encoding. This means 6bit per char, so you get 48bit in total (possible not very unique - but maybe it is ok for you application)

So the way is simple: create a 6 byte random array

`````` SecureRandom rand;
// ...
byte[] randomBytes = new byte[16];
rand.nextBytes(randomBytes);
``````

And then transform it to a Base64 String, for example by `org.apache.commons.codec.binary.Base64`

BTW: it depends on your application if there is a better way to create "uuid" then by random. (If you create a the UUIDs only once per second, then it is a good idea to add a time stamp) (By the way: if you combine (xor) two random values, the result is always at least as random as the most random of the both).

### CMake is not able to find BOOST libraries

I got the same error the first time I wanted to install LightGBM on python (GPU version).

You can simply fix it with this command line :

``````sudo apt-get install cmake libblkid-dev e2fslibs-dev libboost-all-dev libaudit-dev
``````

the boost libraries will be installed and you'll be fine to continue your installation process.

### Selector on background color of TextView

An even simpler solution to the above:

``````<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<color android:color="@color/semitransparent_white" />
</item>
<item>
<color android:color="@color/transparent" />
</item>
</selector>
``````

Save that in the drawable folder and you're good to go.

### jQuery DataTable overflow and text-wrapping issues

Just simply the css style using `white-space:nowrap` works very well to avoid text wrapping in cells. And ofcourse you can use the `text-overflow:ellipsis` and `overflow:hidden` for truncating text with ellipsis effect.

``````<td style="white-space:nowrap">Cell Value</td>
``````

### Getting a better understanding of callback functions in JavaScript

There are 3 main possibilities to execute a function:

``````var callback = function(x, y) {
// "this" may be different depending how you call the function
};
``````
1. callback(argument_1, argument_2);
2. callback.call(some_object, argument_1, argument_2);
3. callback.apply(some_object, [argument_1, argument_2]);

The method you choose depends whether:

1. You have the arguments stored in an Array or as distinct variables.
2. You want to call that function in the context of some object. In this case, using the "this" keyword in that callback would reference the object passed as argument in call() or apply(). If you don't want to pass the object context, use null or undefined. In the latter case the global object would be used for "this".

Docs for Function.call, Function.apply

### Python using enumerate inside list comprehension

Or, if you don't insist on using a list comprehension:

``````>>> mylist = ["a","b","c","d"]
>>> list(enumerate(mylist))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
``````

### How can I select multiple columns from a subquery (in SQL Server) that should have one record (select top 1) for each record in the main query?

Here's generally how to select multiple columns from a subquery:

``````SELECT
A.SalesOrderID,
A.OrderDate,
SQ.Max_Foo,
SQ.Max_Foo2
FROM
A
LEFT OUTER JOIN
(
SELECT
B.SalesOrderID,
MAX(B.Foo) AS Max_Foo,
MAX(B.Foo2) AS Max_Foo2
FROM
B
GROUP BY
B.SalesOrderID
) AS SQ ON SQ.SalesOrderID = A.SalesOrderID
``````

If what you're ultimately trying to do is get the values from the row with the highest value for Foo (rather than the max of Foo and the max of Foo2 - which is NOT the same thing) then the following will usually work better than a subquery:

``````SELECT
A.SalesOrderID,
A.OrderDate,
B1.Foo,
B1.Foo2
FROM
A
LEFT OUTER JOIN B AS B1 ON
B1.SalesOrderID = A.SalesOrderID
LEFT OUTER JOIN B AS B2 ON
B2.SalesOrderID = A.SalesOrderID AND
B2.Foo > B1.Foo
WHERE
B2.SalesOrderID IS NULL
``````

You're basically saying, give me the row from B where I can't find any other row from B with the same SalesOrderID and a greater Foo.

### How to print a stack trace in Node.js?

For what I know printing the complete stack trace in nodejs is not possible, you can just print a "partial" stack trace, you can not see from where you came from in the code, just where the Exception occur. That's what Ryan Dahl explains in this youtube video. http://youtu.be/jo_B4LTHi3I at min 56:30 for being precise. Hope this helps

### How can I get key's value from dictionary in Swift?

For finding value use below

``````if let a = companies["AAPL"] {
// a is the value
}
``````

For traversing through the dictionary

``````for (key, value) in companies {
print(key,"---", value)
}
``````

Finally for searching key by value you firstly add the extension

``````extension Dictionary where Value: Equatable {
func findKey(forValue val: Value) -> Key? {
return first(where: { \$1 == val })?.key
}
}
``````

Then just call

``````companies.findKey(val : "Apple Inc")
``````

### What is a Memory Heap?

Heap is just an area where memory is allocated or deallocated without any order. This happens when one creates an object using the `new` operator or something similar. This is opposed to stack where memory is deallocated on the first in last out basis.

### How do I get console input in javascript?

You can try something like `process.argv`, that is if you are using `node.js` to run the program.
`console.log(process.argv)` => Would print an array containing

``````[
'/usr/bin/node',
'/home/user/path/filename.js',
'your_input'
]
``````

You get the user provided input via array index, i.e., `console.log(process.argv[3])` This should provide you with the input which you can store.

Example:

``````var somevariable = process.argv[3]; // input one
var somevariable2 = process.argv[4]; // input two

console.log(somevariable);
console.log(somevariable2);
``````

If you are building a command-line program then the npm package yargs would be really helpful.

### 'typeid' versus 'typeof' in C++

my following test code for typeid does not output the correct type name. what's wrong?

There isn't anything wrong. What you see is the string representation of the type name. The standard C++ doesn't force compilers to emit the exact name of the class, it is just up to the implementer(compiler vendor) to decide what is suitable. In short, the names are up to the compiler.

These are two different tools. `typeof` returns the type of an expression, but it is not standard. In C++0x there is something called `decltype` which does the same job AFAIK.

``````decltype(0xdeedbeef) number = 0; // number is of type int!
decltype(someArray[0]) element = someArray[0];
``````

Whereas `typeid` is used with polymorphic types. For example, lets say that `cat` derives `animal`:

``````animal* a = new cat; // animal has to have at least one virtual function
...
if( typeid(*a) == typeid(cat) )
{
// the object is of type cat! but the pointer is base pointer.
}
``````

### document.getElementById().value doesn't set the value

Refer below Code Snip

In HTML Page

``````<input id="test" type="number" value="0"/>
``````

In Java Script

``````document.getElementById("test").value=request.responseText;// in case of String
document.getElementById("test").value=new Number(responseText);// in case of Number
``````

### Map with Key as String and Value as List in Groovy

``````def map = [:]
map["stringKey"] = [1, 2, 3, 4]
map["anotherKey"] = [55, 66, 77]

assert map["anotherKey"] == [55, 66, 77]
``````

### Is it possible to use std::string in a constexpr?

C++20 will add `constexpr` strings and vectors

The following proposal has been accepted apparently: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0980r0.pdf and it adds constructors such as:

``````// 20.3.2.2, construct/copy/destroy
constexpr
basic_string() noexcept(noexcept(Allocator())) : basic_string(Allocator()) { }
constexpr
explicit basic_string(const Allocator& a) noexcept;
constexpr
basic_string(const basic_string& str);
constexpr
basic_string(basic_string&& str) noexcept;
``````

in addition to constexpr versions of all / most methods.

There is no support as of GCC 9.1.0, the following fails to compile:

``````#include <string>

int main() {
constexpr std::string s("abc");
}
``````

with:

``````g++-9 -std=c++2a main.cpp
``````

with error:

``````error: the type ‘const string’ {aka ‘const std::__cxx11::basic_string<char>’} of ‘constexpr’ variable ‘s’ is not literal
``````

`std::vector` discussed at: Cannot create constexpr std::vector

Tested in Ubuntu 19.04.

### What to use instead of "addPreferencesFromResource" in a PreferenceActivity?

No alternative method is provided in the method's description because the preferred approach (as of API level 11) is to instantiate PreferenceFragment objects to load your preferences from a resource file. See the sample code here: PreferenceActivity

### How to do a join in linq to sql with method syntax?

Justin has correctly shown the expansion in the case where the join is just followed by a `select`. If you've got something else, it becomes more tricky due to transparent identifiers - the mechanism the C# compiler uses to propagate the scope of both halves of the join.

So to change Justin's example slightly:

``````var result = from sc in enumerableOfSomeClass
join soc in enumerableOfSomeOtherClass
on sc.Property1 equals soc.Property2
where sc.X + sc.Y == 10
select new { SomeClass = sc, SomeOtherClass = soc }
``````

would be converted into something like this:

``````var result = enumerableOfSomeClass
.Join(enumerableOfSomeOtherClass,
sc => sc.Property1,
soc => soc.Property2,
(sc, soc) => new { sc, soc })
.Where(z => z.sc.X + z.sc.Y == 10)
.Select(z => new { SomeClass = z.sc, SomeOtherClass = z.soc });
``````

The `z` here is the transparent identifier - but because it's transparent, you can't see it in the original query :)

### How to query DATETIME field using only date in Microsoft SQL Server?

you can try this

``````select * from test where DATEADD(dd, 0, DATEDIFF(dd, 0, date)) = '03/19/2014';
``````

### How to \$watch multiple variable change in angular

There is many way to watch multiple values :

``````//angular 1.1.4
\$scope.\$watchCollection(['foo', 'bar'], function(newValues, oldValues){
// do what you want here
});
``````

``````//angular 1.3
\$scope.\$watchGroup(['foo', 'bar'], function(newValues, oldValues, scope) {
//do what you want here
});
``````

### Python coding standards/best practices

Yes, I try to follow it as closely as possible.

I don't follow any other coding standards.

### How do I check particular attributes exist or not in XML?

You can use the GetNamedItem method to check and see if the attribute is available. If null is returned, then it isn't available. Here is your code with that check in place:

``````foreach (XmlNode xNode in nodeListName)
{
if(xNode.ParentNode.Attributes.GetNamedItem("split") != null )
{
if(xNode.ParentNode.Attributes["split"].Value != "")
{
parentSplit = xNode.ParentNode.Attributes["split"].Value;
}
}
}
``````

### How to scroll table's "tbody" independent of "thead"?

I saw this post about a month ago when I was having similar problems. I needed y-axis scrolling for a table inside of a ui dialog (yes, you heard me right). I was lucky, in that a working solution presented itself fairly quickly. However, it wasn't long before the solution took on a life of its own, but more on that later.

The problem with just setting the top level elements (thead, tfoot, and tbody) to display block, is that browser synchronization of the column sizes between the various components is quickly lost and everything packs to the smallest permissible size. Setting the widths of the columns seems like the best course of action, but without setting the widths of all the internal table components to match the total of these columns, even with a fixed table layout, there is a slight divergence between the headers and body when a scroll bar is present.

The solution for me was to set all the widths, check if a scroll bar was present, and then take the scaled widths the browser had actually decided on, and copy those to the header and footer adjusting the last column width for the size of the scroll bar. Doing this provides some fluidity to the column widths. If changes to the table's width occur, most major browsers will auto-scale the tbody column widths accordingly. All that's left is to set the header and footer column widths from their respective tbody sizes.

``````\$table.find("> thead,> tfoot").find("> tr:first-child")
.each(function(i,e) {
\$(e).children().each(function(i,e) {
if (i != column_scaled_widths.length - 1) {
\$(e).width(column_scaled_widths[i] - (\$(e).outerWidth() - \$(e).width()));
} else {
\$(e).width(column_scaled_widths[i] - (\$(e).outerWidth() - \$(e).width()) + \$.position.scrollbarWidth());
}
});
});
``````

This fiddle illustrates these notions: http://jsfiddle.net/borgboyone/gbkbhngq/.

Note that a table wrapper or additional tables are not needed for y-axis scrolling alone. (X-axis scrolling does require a wrapping table.) Synchronization between the column sizes for the body and header will still be lost if the minimum pack size for either the header or body columns is encountered. A mechanism for minimum widths should be provided if resizing is an option or small table widths are expected.

The ultimate culmination from this starting point is fully realized here: http://borgboyone.github.io/jquery-ui-table/

A.

### Room persistance library. Delete all

Combining what Dick Lucas says and adding a reset autoincremental from other StackOverFlow posts, i think this can work:

``````fun clearAndResetAllTables(): Boolean {
val db = db ?: return false

// reset all auto-incrementalValues
val query = SimpleSQLiteQuery("DELETE FROM sqlite_sequence")

db.beginTransaction()
return try {
db.clearAllTables()
db.query(query)
db.setTransactionSuccessful()
true
} catch (e: Exception){
false
} finally {
db.endTransaction()
}
}
``````

### Storing Images in PostgreSQL

Updating to 2012, when we see that image sizes, and number of images, are growing and growing, in all applications...

We need some distinction between "original image" and "processed image", like thumbnail.

As Jcoby's answer says, there are two options, then, I recommend:

• use blob (Binary Large OBject): for original image store, at your table. See Ivan's answer (no problem with backing up blobs!), PostgreSQL additional supplied modules, How-tos etc.

• use a separate database with DBlink: for original image store, at another (unified/specialized) database. In this case, I prefer bytea, but blob is near the same. Separating database is the best way for a "unified image webservice".

• use bytea (BYTE Array): for caching thumbnail images. Cache the little images to send it fast to the web-browser (to avoiding rendering problems) and reduce server processing. Cache also essential metadata, like width and height. Database caching is the easiest way, but check your needs and server configs (ex. Apache modules): store thumbnails at file system may be better, compare performances. Remember that it is a (unified) web-service, then can be stored at a separate database (with no backups), serving many tables. See also PostgreSQL binary data types manual, tests with bytea column, etc.

NOTE1: today the use of "dual solutions" (database+filesystem) is deprecated (!). There are many advantages to using "only database" instead dual. PostgreSQL have comparable performance and good tools for export/import/input/output.

NOTE2: remember that PostgreSQL have only bytea, not have a default Oracle's BLOB: "The SQL standard defines (...) BLOB. The input format is different from bytea, but the provided functions and operators are mostly the same",Manual.

EDIT 2014: I have not changed the original text above today (my answer was Apr 22 '12, now with 14 votes), I am opening the answer for your changes (see "Wiki mode", you can edit!), for proofreading and for updates.
The question is stable (@Ivans's '08 answer with 19 votes), please, help to improve this text.

### Could not resolve Spring property placeholder

make sure your properties file exist in classpath directory but not in sub folder of your classpath directory. if it is exist in sub folder then write as below classpath:subfolder/idm.properties

### Target class controller does not exist - Laravel 8

Happened to me when I passing null to the `middleware` function

``````Route::middleware(null)->group(function () {
Route::get('/some-path', [SomeController::class, 'search']);
});
``````

Passing `[]` for no middleware works or probably just remove the `middleware` call if not using middleware :D

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

On linux ubuntu 20.04 I needed few steps,downgrade node first to apropriate version,remove node_modules,run yarn install and finally run `sudo yarn add [email protected] --force`.Node version 10.0.0. Only working way for me.

### Get original URL referer with PHP?

Using Cookie as a repository of reference page is much better in most cases, as cookies will keep referrer until the browser is closed (and will keep it even if browser tab is closed), so in case if user left the page open, let's say before weekends, and returned to it after a couple of days, your session will probably be expired, but cookies are still will be there.

Put that code at the begin of a page (before any html output, as cookies will be properly set only before any echo/print):

``````if(!isset(\$_COOKIE['origin_ref']))
{
}
``````

Then you can access it later:

``````\$var = \$_COOKIE['origin_ref'];
``````

And to addition to what @pcp suggested about escaping \$_SERVER['HTTP_REFERER'], when using cookie, you may also want to escape \$_COOKIE['origin_ref'] on each request.

### What does template <unsigned int N> mean?

It's perfectly possible to template a class on an integer rather than a type. We can assign the templated value to a variable, or otherwise manipulate it in a way we might with any other integer literal:

``````unsigned int x = N;
``````

In fact, we can create algorithms which evaluate at compile time (from Wikipedia):

``````template <int N>
struct Factorial
{
enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0>
{
enum { value = 1 };
};

// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
int x = Factorial<4>::value; // == 24
int y = Factorial<0>::value; // == 1
}
``````

### TypeScript and field initializers

Updated 07/12/2016: Typescript 2.1 introduces Mapped Types and provides `Partial<T>`, which allows you to do this....

``````class Person {
public name: string = "default"
public address: string = "default"
public age: number = 0;

public constructor(init?:Partial<Person>) {
Object.assign(this, init);
}
}

let persons = [
new Person(),
new Person({}),
new Person({name:"John"}),
new Person({age:20, address:"Earth", name:"John"}),
];
``````

My approach is to define a separate `fields` variable that you pass to the constructor. The trick is to redefine all the class fields for this initialiser as optional. When the object is created (with its defaults) you simply assign the initialiser object onto `this`;

``````export class Person {
public name: string = "default"
public address: string = "default"
public age: number = 0;

public constructor(
fields?: {
name?: string,
age?: number
}) {
if (fields) Object.assign(this, fields);
}
}
``````

or do it manually (bit more safe):

``````if (fields) {
this.name = fields.name || this.name;
this.age = fields.age || this.age;
}
``````

usage:

``````let persons = [
new Person(),
new Person({name:"Joe"}),
new Person({
name:"Joe",
}),
new Person({
age:5,
name:"Joe"
}),
new Person(new Person({name:"Joe"})) //shallow clone
];
``````

and console output:

``````Person { name: 'default', address: 'default', age: 0 }
Person { name: 'Joe', address: 'default', age: 0 }
Person { name: 'Joe', address: 'planet Earth', age: 0 }
Person { name: 'Joe', address: 'planet Earth', age: 5 }
Person { name: 'Joe', address: 'default', age: 0 }
``````

This gives you basic safety and property initialization, but its all optional and can be out-of-order. You get the class's defaults left alone if you don't pass a field.

You can also mix it with required constructor parameters too -- stick `fields` on the end.

About as close to C# style as you're going to get I think (actual field-init syntax was rejected). I'd much prefer proper field initialiser, but doesn't look like it will happen yet.

For comparison, If you use the casting approach, your initialiser object must have ALL the fields for the type you are casting to, plus don't get any class specific functions (or derivations) created by the class itself.

### Please initialize the log4j system properly warning

``````BasicConfigurator.configure();
``````

in your static main class as below..

``````import org.apache.log4j.BasicConfigurator;

public class ViewCountDriver extends Configured implements Tool{

public static void main(String[]args) throws Exception{

BasicConfigurator.configure();

int exitcode = ToolRunner.run(new ViewCountDriver(), args);
System.exit(exitcode);
}
}
``````

### MongoDB "root" user

Mongodb user management:

roles list:

``````read
``````

create user:

``````db.createUser(user, writeConcern)

db.createUser({ user: "user",
pwd: "pass",
roles: [
{ role: "read", db: "database" }
]
})
``````

update user:

``````db.updateUser("user",{
roles: [
{ role: "readWrite", db: "database" }
]
})
``````

drop user:

``````db.removeUser("user")
``````

or

``````db.dropUser("user")
``````

view users:

``````db.getUsers();
``````

### Make EditText ReadOnly

Try overriding the onLongClick listener of the edit text to remove context menu:

``````EditText myTextField = (EditText)findViewById(R.id.my_edit_text_id);
myTextField.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
``````

### How to use SVG markers in Google Maps API v3

You need to pass `optimized: false`.

E.g.

``````var img = { url: 'img/puff.svg', scaledSide: new google.maps.Size(5, 5) };
new google.maps.Marker({position: this.mapOptions.center, map: this.map, icon: img, optimized: false,});
``````

Without passing `optimized: false`, my svg appeared as a static image.

### In bootstrap how to add borders to rows without adding up?

On my projects i give all rows the class "borders" which I want it to display more like a table with even borders. Giving each child element a border on the bottom and right and the first element of each row a left border will make all of your boxes have an even border:

First give all of the rows children a border on the right and bottom

``````.borders div{
border-right:1px solid #999;
border-bottom:1px solid #999;
}
``````

Next give the first child of each or a left border

``````.borders div:first-child{
border-left:
1px solid #999;
}
``````

Last make sure to clear the borders for their child elements

``````.borders div > div{
border:0;
}
``````

HTML:

``````<div class="row borders">
<div class="col-xs-5 col-md-2">Email</div>
<div class="col-xs-7 col-md-4">[email protected]</div>
<div class="col-xs-5 col-md-2">Phone</div>
<div class="col-xs-7 col-md-4">555-123-4567</div>
</div>
``````

### Change collations of all columns of all tables in SQL Server

Sorry late to the party, but here is mine - cater for table with a schema and funny column and table names. Yes I had some of them.

``````SELECT
'ALTER TABLE [' +  TABLE_SCHEMA + '].[' + TABLE_NAME
+ '] ALTER COLUMN [' + COLUMN_NAME + '] ' + DATA_TYPE
+ '(' + CAST(CHARACTER_MAXIMUM_LENGTH AS nvarchar(100))
+ ') COLLATE ' + 'Latin1_General_CI_AS'
+ CASE WHEN IS_NULLABLE = 'YES' THEN ' NULL' ELSE ' NOT NULL' END
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
DATA_TYPE like '%char'
``````

### Warning: Cannot modify header information - headers already sent by ERROR

You are trying to send headers information after outputing content.

If you want to do this, look for output buffering.

Therefore, look to use `ob_start();`

### Convert ascii value to char

``````for (int i = 0; i < 5; i++){
int asciiVal = rand()%26 + 97;
char asciiChar = asciiVal;
cout << asciiChar << " and ";
}
``````

### How to check if a windows form is already open, and close it if it is?

I'm not sure that I understand the statement. Hope this helps. If you want to operate with only one instance of this form you should prevent Form.Dispose call on user close. In order to do this, you can handle child form's Closing event.

``````private void ChildForm_FormClosing(object sender, FormClosingEventArgs e)
{
this.Hide();
e.Cancel = true;
}
``````

And then you don't need to create new instances of `frm`. Just call Show method on the instance.

You can check Form.Visible property to check if the form open at the moment.

``````private ChildForm form = new ChildForm();

private void ReopenChildForm()
{
if(form.Visible)
{
form.Hide();
}
//Update form information
form.Show();
}
``````

Actually, I still don't understand why don't you just update the data on the form.

### Convert a row of a data frame to vector

Columns of data frames are already vectors, you just have to pull them out. Note that you place the column you want after the comma, not before it:

``````> newV <- df[,1]
> newV
[1] 1 2 4 2
``````

If you actually want a row, then do what Ben said and please use words correctly in the future.

### SQL update statement in C#

``````private void button4_Click(object sender, EventArgs e)
{
String st = "DELETE FROM supplier WHERE supplier_id =" + textBox1.Text;

SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
MessageBox.Show("????");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}

private void button6_Click(object sender, EventArgs e)
{
String st = "SELECT * FROM suppliers";

SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
DataTable datatable = new DataTable();
dataGridView1.DataSource = datatable;
//MessageBox.Show("LEFT OUTER??");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
``````

### Graph visualization library in JavaScript

I've just put together what you may be looking for: http://www.graphdracula.net

It's JavaScript with directed graph layouting, SVG and you can even drag the nodes around. Still needs some tweaking, but is totally usable. You create nodes and edges easily with JavaScript code like this:

``````var g = new Graph();
``````

I used the previously mentioned Raphael JS library (the graffle example) plus some code for a force based graph layout algorithm I found on the net (everything open source, MIT license). If you have any remarks or need a certain feature, I may implement it, just ask!

You may want to have a look at other projects, too! Below are two meta-comparisons:

• SocialCompare has an extensive list of libraries, and the "Node / edge graph" line will filter for graph visualization ones.

• DataVisualization.ch has evaluated many libraries, including node/graph ones. Unfortunately there's no direct link so you'll have to filter for "graph":

Here's a list of similar projects (some have been already mentioned here):

#### Pure JavaScript Libraries

• vis.js supports many types of network/edge graphs, plus timelines and 2D/3D charts. Auto-layout, auto-clustering, springy physics engine, mobile-friendly, keyboard navigation, hierarchical layout, animation etc. MIT licensed and developed by a Dutch firm specializing in research on self-organizing networks.

• Cytoscape.js - interactive graph analysis and visualization with mobile support, following jQuery conventions. Funded via NIH grants and developed by by @maxkfranz (see his answer below) with help from several universities and other organizations.

• The JavaScript InfoVis Toolkit - Jit, an interactive, multi-purpose graph drawing and layout framework. See for example the Hyperbolic Tree. Built by Twitter dataviz architect Nicolas Garcia Belmonte and bought by Sencha in 2010.

• D3.js Powerful multi-purpose JS visualization library, the successor of Protovis. See the force-directed graph example, and other graph examples in the gallery.

• Plotly's JS visualization library uses D3.js with JS, Python, R, and MATLAB bindings. See a nexworkx example in IPython here, human interaction example here, and JS Embed API.

• sigma.js Lightweight but powerful library for drawing graphs

• jsPlumb jQuery plug-in for creating interactive connected graphs

• Springy - a force-directed graph layout algorithm

• Processing.js Javascript port of the Processing library by John Resig

• JS Graph It - drag'n'drop boxes connected by straight lines. Minimal auto-layout of the lines.

• RaphaelJS's Graffle - interactive graph example of a generic multi-purpose vector drawing library. RaphaelJS can't layout nodes automatically; you'll need another library for that.

• JointJS Core - David Durman's MPL-licensed open source diagramming library. It can be used to create either static diagrams or fully interactive diagramming tools and application builders. Works in browsers supporting SVG. Layout algorithms not-included in the core package

• mxGraph Previously commercial HTML 5 diagramming library, now available under Apache v2.0. mxGraph is the base library used in draw.io.

#### Abandoned libraries

• Cytoscape Web Embeddable JS Network viewer (no new features planned; succeeded by Cytoscape.js)

• Canviz JS renderer for Graphviz graphs. Abandoned in Sep 2013.

• arbor.js Sophisticated graphing with nice physics and eye-candy. Abandoned in May 2012. Several semi-maintained forks exist.

• jssvggraph "The simplest possible force directed graph layout algorithm implemented as a Javascript library that uses SVG objects". Abandoned in 2012.

• jsdot Client side graph drawing application. Abandoned in 2011.

• Protovis Graphical Toolkit for Visualization (JavaScript). Replaced by d3.

• Moo Wheel Interactive JS representation for connections and relations (2008)

• JSViz 2007-era graph visualization script

• dagre Graph layout for JavaScript

### "Register" an .exe so you can run it from any command line in Windows

This worked for me:

• put a .bat file with the commands you need (I use to run .py script into this) into a FOLDER,
• go in the variable environment setting (type var in the search bar and it will show up)
• in the global settings
• choose path,
• then modify,
• then add the path to your .bat file (without the .bat file)
• close everything: done.

Open the cmd, write the name of the .bat file and it will work

### SQL Server Service not available in service list after installation of SQL Server Management Studio

downloaded Sql server management 2008 r2 and got it installed. Its getting installed but when I try to connect it via .\SQLEXPRESS it shows error. DO I need to install any SQL service on my system?

You installed management studio which is just a management interface to SQL Server. If you didn't (which is what it seems like) already have SQL Server installed, you'll need to install it in order to have it on your system and use it.

### How to redirect a url in NGINX

First make sure you have installed Nginx with the HTTP rewrite module. To install this we need to have pcre-library

How to install pcre library

If the above mentioned are done or if you already have them, then just add the below code in your nginx server block

``````  if (\$host !~* ^www\.) {
rewrite ^(.*)\$ http://www.\$host\$1 permanent;
}
``````

To remove www from every request you can use

``````  if (\$host = 'www.your_domain.com' ) {
rewrite  ^/(.*)\$  http://your_domain.com/\$1  permanent;
}
``````

so your server block will look like

``````  server {
listen       80;
server_name  test.com;
if (\$host !~* ^www\.) {
rewrite ^(.*)\$ http://www.\$host\$1 permanent;
}
client_max_body_size   10M;
client_body_buffer_size   128k;

root       /home/test/test/public;
passenger_enabled on;
rails_env production;

error_page   500 502 503 504  /50x.html;
location = /50x.html {
root   html;
}
}
``````

### jQuery UI themes and HTML tables

I've got a one liner to make HTML Tables look BootStrapped:

``````<table class="table table-striped table-bordered table-hover">
``````

The theme suits other controls and it supports alternate row highlighting.

### jQuery - add additional parameters on submit (NOT ajax)

You could write a jQuery function which allowed you to add hidden fields to a form:

``````// This must be applied to a form (or an object inside a form).
jQuery.fn.addHidden = function (name, value) {
return this.each(function () {
var input = \$("<input>").attr("type", "hidden").attr("name", name).val(value);
\$(this).append(\$(input));
});
};
``````

And then add the hidden field before you submit:

``````var frm = \$("#form").addHidden('SaveAndReturn', 'Save and Return')
.submit();
``````

### How can I search for a commit message on GitHub?

The short answer is, you cannot search commit messages directly on github.com the website. For the time being we recommend the local `git grep` solution others on this thread have proposed.

At one point in time GitHub did offer a `git grep` style search over commit messages for a single repository. Unfortunately, this approach exposed a denial of service that could render a file server inaccessible. For this reason, we removed `git grep` searching.

Current back-of-the envelope estimates puts the number of commits in GitHub somewhere around the 80 billion mark. Although Google engineers laugh behind our backs, this is a rather large number of documents to store in ElasticSearch. We'd love to make this dataset searchable, but it is not a trivial project.

### How to compare data between two table in different databases using Sql Server 2008?

If both database on same server. You can check similar tables by using following query :

``````select
fdb.name, sdb.name
from
FIRSTDBNAME.sys.tables fdb
join SECONDDBNAME.sys.tables sdb
on fdb.name = sdb.name -- compare same name tables
order by
1
``````

By listing out similar table you can compare columns schema using `sys.columns` view.

Hope this helps you.

### Visual Studio Code pylint: Unable to import 'protorpc'

I've not played around with all possibilities, but at least I had the impression that this could be a python version related issue. No idea why, I just trusted my gut.

Thus I just changed the pythonPath to python3 (default: python):

``````"python.pythonPath": "python3"
``````

I reinstalled the dependencies (including pylint!!!) with

``````pip3 install <package> --user
``````

... and after restarting vs code, everything looked fine.

HTH Kai

### DataGridView AutoFit and Fill

``````public static void Fill(DataGridView dgv2)
{
try
{
dgv = dgv2;
foreach (DataGridViewColumn GridCol in dgv.Columns)
{
for (int j = 0; j < GridCol.DataGridView.ColumnCount; j++)
{
GridCol.DataGridView.Columns[j].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
GridCol.DataGridView.Columns[j].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
GridCol.DataGridView.Columns[j].FillWeight = 1;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
``````

### How do I parse a HTML page with Node.js

#### November 2020 Update

I searched for the top NodeJS html parser libraries.

Because my use cases didn't require a library with many features, I could focus on stability and performance.

By stability I mean that I want the library to be used long enough by the community in order to find bugs and that it will be still maintained and that open issues will be closed.

Its hard to understand the future of an open source library, but I did a small summary based on the top 10 libraries in openbase.

I divided into 2 groups according to the last commit (and on each group the order is according to Github starts):

Last commit is in the last 6 months:

jsdom - ` Last commit: 3 Months, Open issues: 331, Github stars: 14.9K`.

htmlparser2 - ` Last commit: 8 days, Open issues: 2, Github stars: 2.7K`.

parse5 - ` Last commit: 2 Months, Open issues: 21, Github stars: 2.5K`.

swagger-parser - ` Last commit: 2 Months, Open issues: 48, Github stars: 663`.

html-parse-stringify - `Last commit: 4 Months, Open issues: 3, Github stars: 215`.

node-html-parser - ` Last commit: 7 days, Open issues: 15, Github stars: 205`.

Last commit is 6 months and above:

cheerio - ` Last commit: 1 year, Open issues: 174, Github stars: 22.9K`.

koa-bodyparser - ` Last commit: 6 months, Open issues: 9, Github stars: 1.1K`.

sax-js - ` Last commit: 3 Years, Open issues: 65, Github stars: 941`.

draftjs-to-html - ` Last commit: 1 Year, Open issues: 27, Github stars: 233`.

I picked Node-html-parser because it seems quiet fast and very active at this moment.

(*) Openbase adds much more information regarding each library like the number of contributors (with +3 commits), weekly downloads, Monthly commits, Version etc'.

(**) The table above is a snapshot according to the specific time and date - I would check the reference again and as a first step check the level of recent activity and then dive into the smaller details.

### How can I get stock quotes using Google Finance API?

Perhaps of interest, the Google Finance API documentaton includes a section detailing how to access different parameters via JavaScript.

I suppose the JavaScript API might be a wrapper to the JSON request you mention above... perhaps you could check which HTTP requests are being sent.

### how to fetch data from database in Hibernate

Hibernate has its own sql features that is known as hibernate query language. for retriving data from database using hibernate.

``````String sql_query = "from employee"//user table name which is in database.
Query query = session.createQuery(sql_query);
//for fetch we need iterator
Iterator it=query.iterator();
while(it.hasNext())
{
s=(employee) it.next();
System.out.println("Id :"+s.getId()+"FirstName"+s.getFirstName+"LastName"+s.getLastName);

}
``````

for fetch we need Iterator for that define and import package.

### How can I find the location of origin/master in git, and how do I change it?

sometimes there's a difference between the local cached version of origin master (origin/master) and the true origin master.

If you run `git remote update` this will resynch origin master with origin/master

see the accepted answer to this question

Differences between git pull origin master & git pull origin/master

### Failed to instantiate module error in Angular js

You need to include `angular-route.js` in your HTML:

``````<script src="angular-route.js">
``````

http://docs.angularjs.org/api/ngRoute

### Suppress/ print without b' prefix for bytes in Python 3

Use `decode`:

``````print(curses.version.decode())
# 2.2
``````

### C# find biggest number

If your numbers are a, b and c then:

``````    int a = 1;
int b = 2;
int c = 3;

int d =  a > b ? a : b;
return c > d ? c : d;
``````

This could turn into one of those "how many different ways can we do this" type questions!

### Concatenating strings in Razor

Use the parentesis syntax of Razor:

``````@(Model.address + " " + Model.city)
``````

or

``````@(String.Format("{0} {1}", Model.address, Model.city))
``````

Update: With C# 6 you can also use the \$-Notation (officially interpolated strings):

``````@(\$"{Model.address} {Model.city}")
``````

### PHP & MySQL: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given

The query either returned no rows or is erroneus, thus `FALSE` is returned. Change it to

``````if (!\$dbc || mysqli_num_rows(\$dbc) == 0)
``````

`mysqli_num_rows`:

Return Values

Returns TRUE on success or FALSE on failure. For SELECT, SHOW, DESCRIBE or EXPLAIN mysqli_query() will return a result object.

### Scale image to fit a bounding box

This example to stretch the image proportionally to fit the entire window. An improvisation to the above correct code is to add `\$( window ).resize(function(){});`

``````function stretchImg(){
\$('div').each(function() {
(\$(this).height() > \$(this).find('img').height())
: '';
(\$(this).width() > \$(this).find('img').width())
: '';
});
}
stretchImg();

\$( window ).resize(function() {
strechImg();
});
``````

There are two if conditions. The first one keeps checking if the image height is less than the div and applies `.fillheight` class while the next checks for width and applies `.fillwidth` class. In both cases the other class is removed using `.removeClass()`

Here is the CSS

``````.fillwidth {
width: 100%;
max-width: none;
height: auto;
}
.fillheight {
height: 100vh;
max-width: none;
width: auto;
}
``````

You can replace `100vh` by `100%` if you want to stretch the image with in a div. This example to stretch the image proportionally to fit the entire window.

### Service has zero application (non-infrastructure) endpoints

I just worked through this issue on my service. Here is the error I was receiving:

Service 'EmailSender.Wcf.EmailService' has zero application (non-infrastructure) endpoints. This might be because no configuration file was found for your application, or because no service element matching the service name could be found in the configuration file, or because no endpoints were defined in the service element.

Here are the two steps I used to fix it:

1. Use the correct fully-qualified class name:

``````<service behaviorConfiguration="DefaultBehavior" name="EmailSender.Wcf.EmailService">
``````
2. Enable an endpoint with mexHttpBinding, and most importantly, use the IMetadataExchange contract:

``````<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
``````

### PHP import Excel into database (xls & xlsx)

If you save the excel file as a CSV file then you can import it into a mysql database using tools such as PHPMyAdmin

Im not sure if this would help in your situation, but a csv file either manually or programatically would be a lot easier to parse into a database than an excel file I would have thought.

EDIT: I would however suggest looking at the other answers rather than mine since @diEcho answer seems more appropriate.

### How to use paginator from material angular?

The issue in the original question is that you are not capturing "page" event, to resolve this you need to add `(page)='yourEventHandler(\$event)`' as an attribute in the md-paginator tag.

check a working example here

You can also check the API docs here

### Add SUM of values of two LISTS into new LIST

Here is another way to do it. We make use of the internal __add__ function of python:

``````class SumList(object):
def __init__(self, this_list):
self.mylist = this_list

new_list = []
zipped_list = zip(self.mylist, other.mylist)
for item in zipped_list:
new_list.append(item[0] + item[1])
return SumList(new_list)

def __repr__(self):
return str(self.mylist)

list1 = SumList([1,2,3,4,5])
list2 = SumList([10,20,30,40,50])
sum_list1_list2 = list1 + list2
print(sum_list1_list2)
``````

Output

``````[11, 22, 33, 44, 55]
``````

### docker-compose up for only certain containers

To start a particular service defined in your docker-compose file. for example if your have a docker-compose.yml

``````docker-compose start db
``````

given a compose file like as:

``````version: '3.3'

services:
db:
image: mysql:5.7
ports:
- "3306:3306"
volumes:
- ./db_data:/var/lib/mysql
restart: always
environment:
MYSQL_DATABASE: wordpress
MYSQL_USER: wordpress

wordpress:
depends_on:
- db
image: wordpress:latest
ports:
- "80:80"
volumes:
- ./l3html:/var/www/html
restart: always
environment:
WORDPRESS_DB_HOST: db:3306
WORDPRESS_DB_USER: wordpress
volumes:
db_data:
l3html:
``````

Some times you want to start mySQL only (sometimes you just want to populate a database) before you start your entire suite.

### IIS7: Setup Integrated Windows Authentication like in IIS6

So do you want them to get the IE password-challenge box, or should they be directed to your login page and enter their information there? If it's the second option, then you should at least enable Anonymous access to your login page, since the site won't know who they are yet.

If you want the first option, then the login page they're getting forwarded to will need to read the currently logged-in user and act based on that, since they would have had to correctly authenticate to get this far.

### Twitter Bootstrap vs jQuery UI?

You can use both with relatively few issues. Twitter Bootstrap uses jQuery 1.7.1 (as of this writing), and I can't think of any reasons why you cannot integrate additional Jquery UI components into your HTML templates.

I've been using a combination of HTML5 Boilerplate & Twitter Bootstrap built at Initializr.com. This combines two awesome starter templates into one great starter project. Check out the details at http://html5boilerplate.com/ and http://www.initializr.com/ Or to get started right away, go to http://www.initializr.com/, click the "Bootstrap 2" button, and click "Download It". This will give you all the js and css you need to get started.

And don't be scared off by HTML5 and CSS3. Initializr and HTML5 Boilerplate include polyfills and IE specific code that will allow all features to work in IE 6, 7 8, and 9.

The use of LESS in Twitter Bootstrap is also optional. They use LESS to compile all the CSS that is used by Bootstrap, but if you just want to override or add your own styles, they provide an empty css file for that purpose.

There is also a blank js file (script.js) for you to add custom code. This is where you would add your handlers or selectors for additional jQueryUI components.

### How to change Maven local repository in eclipse

I found that even after following all the steps above, I was still getting errors saying that my Maven dependencies (i.e. pom.xml) were pointing to jar files that didn't exist.

Viewing the errors in the Problems tab, for some reason these were still pointing to the old location of my repository. This was probably because I'd changed the location of my Maven repository since creating the workspace and project.

This can be easily solved by deleting the project from the Eclipse workspace, and re-adding it again through Package Explorer -> R/Click -> Import... -> Existing Projects.

### In bash, how to store a return value in a variable?

It is easy you need to echo the value you need to return and then capture it like below

``````demofunc(){
local variable="hellow"
echo \$variable
}

val=\$(demofunc)
echo \$val
``````

### What is an ORM, how does it work, and how should I use one?

Can anyone give me a brief explanation...

Sure.

ORM stands for "Object to Relational Mapping" where

• The Object part is the one you use with your programming language ( python in this case )

• The Relational part is a Relational Database Manager System ( A database that is ) there are other types of databases but the most popular is relational ( you know tables, columns, pk fk etc eg Oracle MySQL, MS-SQL )

• And finally the Mapping part is where you do a bridge between your objects and your tables.

In applications where you don't use a ORM framework you do this by hand. Using an ORM framework would allow you do reduce the boilerplate needed to create the solution.

So let's say you have this object.

`````` class Employee:
def __init__( self, name ):
self.__name = name

def getName( self ):
return self.__name

#etc.
``````

and the table

``````   create table employee(
name varcar(10),
-- etc
)
``````

Using an ORM framework would allow you to map that object with a db record automagically and write something like:

``````   emp = Employee("Ryan")

orm.save( emp )
``````

And have the employee inserted into the DB.

Oops it was not that brief but I hope it is simple enough to catch other articles you read.

### Convert text into number in MySQL query

``````SELECT *, CAST(SUBSTRING_INDEX(field, '-', -1) AS UNSIGNED) as num FROM tableName ORDER BY num;
``````

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

the fancy answer. Use std::vector and search with std::find

use a for loop

### Html- how to disable <a href>?

``````<script>
\$('#connectBtn').click(function(e){
e.preventDefault();
})
});
</script>
``````

This will prevent the default action.

### Which command in VBA can count the number of characters in a string variable?

``````Len(word)
``````

Although that's not what your question title asks =)

### How do I make an attributed string using Swift?

`````` let attrString = NSAttributedString (
string: "title-title-title",
attributes: [NSAttributedStringKey.foregroundColor: UIColor.black])
``````

### Command line to remove an environment variable from the OS level configuration

To remove the variable from the current environment (not permanently):

``````set FOOBAR=
``````

To permanently remove the variable from the user environment (which is the default place `setx` puts it):

``````REG delete HKCU\Environment /F /V FOOBAR
``````

If the variable is set in the system environment (e.g. if you originally set it with `setx /M`), as an administrator run:

``````REG delete "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /F /V FOOBAR
``````

Note: The `REG` commands above won't affect any existing processes (and some new processes that are forked from existing processes), so if it's important for the change to take effect immediately, the easiest and surest thing to do is log out and back in or reboot. If this isn't an option or you want to dig deeper, some of the other answers here have some great suggestions that may suit your use case.

### Using Java generics for JPA findAll() query with WHERE clause

This will work, and if you need where statement you can add it as parameter.

``````class GenericDAOWithJPA<T, ID extends Serializable> {
``````

.......

``````public List<T> findAll() {
return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
}
}
``````

### Move the mouse pointer to a specific position?

You could detect position of the mouse pointer and then move the web page (with body position relative) so they hover over what you want them to click.

For an example you can paste this code on the current page in your browser console (and refresh afterwards)

``````var upvote_position = \$('#answer-12878316').position();
\$('body').mousemove(function (event) {
\$(this).css({
position: 'relative',
left: (event.pageX - upvote_position.left - 22) + 'px',
top: (event.pageY - upvote_position.top - 35) + 'px'
});
});
``````

### Unable to set variables in bash script

Five problems:

1. Don't put a space before or after the equal sign.
2. Use `"\$(...)"` to get the output of a command as text.
3. `[` is a command. Put a space between it and the arguments.
4. Commands are case-sensitive. You want `echo`.
5. Use double quotes around variables. `rm "\$folderToBeMoved"`

### How to upgrade pip3?

#### The Problem

You use `pip` (the Python 2 one). Now you want to upgrade `pip` (the Python 3 one). After that, `pip` is the Python 3 one.

#### The solution

Use `pip2` and `pip3`. This way it is explicit.

If you want to use `pip`, just check where it is (`which pip`) and change the link. For example:

``````\$ which pip
/usr/local/bin/pip

\$ pip --version
pip 9.0.1 from /usr/local/lib/python3.5/dist-packages (python 3.5)

\$ which pip2
/usr/local/bin/pip2

\$ sudo rm /usr/local/bin/pip
\$ sudo ln -s /usr/local/bin/pip2 /usr/local/bin/pip

\$ pip --version
pip 9.0.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)
``````

### How to get a List<string> collection of values from app.config in WPF?

In App.config:

``````<add key="YOURKEY" value="a,b,c"/>
``````

In C#:

``````string[] InFormOfStringArray = ConfigurationManager.AppSettings["YOURKEY"].Split(',').Select(s => s.Trim()).ToArray();
List<string> list = new List<string>(InFormOfStringArray);
``````

### Making sure at least one checkbox is checked

You should avoid having two checkboxes with the same name if you plan to reference them like `document.FC.c1`. If you have multiple checkboxes named `c1` how will the browser know which you are referring to?

Here's a non-jQuery solution to check if any checkboxes on the page are checked.

``````var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);
``````

You need the `Array.prototype.slice.call` part to convert the `NodeList` returned by `document.querySelectorAll` into an array that you can call `some` on.

### Converting EditText to int? (Android)

I'm very sleepy and tired right now but wouldn't this work?:

``````EditText et = (EditText)findViewById(R.id.editText1);
String sTextFromET = et.getText().toString();
int nIntFromET = new Integer(sTextFromET).intValue();
``````

OR

``````try
{
int nIntFromET = Integer.parseInt(sTextFromET);
}
catch (NumberFormatException e)
{
// handle the exception
}
``````

### Comparing two arrays & get the values which are not common

Look at `Compare-Object`

``````Compare-Object \$a1 \$b1 | ForEach-Object { \$_.InputObject }
``````

Or if you would like to know where the object belongs to, then look at SideIndicator:

``````\$a1=@(1,2,3,4,5,8)
\$b1=@(1,2,3,4,5,6)
Compare-Object \$a1 \$b1
``````

### Extracting Path from OpenFileDialog path/filename

``````string fullPath = ofd.FileName;
string fileName = ofd.SafeFileName;
string path = fullPath.Replace(fileName, "");
``````

### How to use index in select statement?

In general, the index will be used if the assumed cost of using the index, and then possibly having to perform further bookmark lookups is lower than the cost of just scanning the entire table.

If your query is of the form:

``````SELECT Name from Table where Name = 'Boris'
``````

And 1 row out of 1000 has the name Boris, it will almost certainly be used. If everyone's name is Boris, it will probably resort to a table scan, since the index is unlikely to be a more efficient strategy to access the data.

If it's a wide table (lot's of columns) and you do:

``````SELECT * from Table where Name = 'Boris'
``````

Then it may still choose to perform the table scan, if it's a reasonable assumption that it's going to take more time retrieving the other columns from the table than it will to just look up the name, or again, if it's likely to be retrieving a lot of rows anyway.

### Add / Change parameter of URL and redirect to the new URL

I need help to adjust my script below or to find a script that could be used on my wordpress site to grab the url suffix parameters from a forward url, then to be added at the button click url for tracking the proper forward ads id.

REASON: parameters are used for advertisement tracking to find out from which ad the user has been forward, even if the user hops from optin page to the sales page by using button click.

Here the goal to reach: 1. An FB ad points to an optin page with tracking code: https://ownsite.com/optin-page/?tid=fbad1 2. At the optin-page there is a button with a setup URL to forward to the sales page, but if clicked then only the URL is forward, but the parameter "?tid=fbad1" is missing. 3. The auto-forward script below (which is working properly) can be used to change for button click forward, but has a limitation as it grab only "tid" parameters instead also utm parameters.

Therefore a script code shall be implemented to establish click buttons (also to style them or use images instead) and while clicking the button to forward to a different sales page with grabbing the suffix parameter form the current optin-page to forward then to sales-page https://ownsite.com/sales-page/?tid=fbad1 also including UTM parameters

Currently, I could have solved this by using an auto-redirect script, but A.) I do not want to use an autoredirect at this page. Better is an event click button used to let the user himself click to forward with the URL parameter included. B.) The tracking ID parameter in this script is limited to "?tid=..." instead I do also want to track the UTM code on button click also i.e. Grab from current page the paramater of URL https://www.optin-page.com/?tid=facebookad1?utm_campaign=blogpost then on button click grab parameters and add to button set URL https://www.sales-page.com/?tid=facebookad1?utm_campaign=blogpost

Please now find here the Code below in use for auto-redirect and grabbing the URL parameters. This code shall be changed now to be able to create a button with a click-event to be redirect then to the forward URL with parameter grabbing of current URL if the button is clicked (as stated above).

``````    <p><!-- Modify this according to your requirement - core script from https://gist.github.com/Joel-James/62d98e8cb3a1b6b05102 and suffix grabbing </p>
<h3 style="text-align: center;"><span style="color: #ffffff; background-color: #039e00;">?Auto-redirecting after <span id="countdown">35</span> seconds?</span></h3>
<p><!-- JavaScript part --><br /><script type="text/javascript">

function findGetParameter(parameterName) {
var result = null,
tmp = [];
location.search
.substr(1)
.split("&")
.forEach(function (item) {
tmp = item.split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
});
return result;
}

// Total seconds to wait
var seconds = 45;

function countdown() {
seconds = seconds - 1;
if (seconds < 0) {
var tid = findGetParameter('tid');
window.location = "https://www.2share.info/ql-cb2/" + '?tid='+tid;
} else {
// Update remaining seconds
document.getElementById("countdown").innerHTML = seconds;
// Count down using javascript
window.setTimeout("countdown()", 1000);
}
}

// Run countdown function
countdown();

</script></p>
``````

### Show DataFrame as table in iPython Notebook

You'll need to use the `HTML()` or `display()` functions from IPython's display module:

``````from IPython.display import display, HTML

# Assuming that dataframes df1 and df2 are already defined:
print "Dataframe 1:"
display(df1)
print "Dataframe 2:"
display(HTML(df2.to_html()))
``````

Note that if you just `print df1.to_html()` you'll get the raw, unrendered HTML.

You can also import from `IPython.core.display` with the same effect

### Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

We've just come across a very similar issue and I'm now very much a +1 for never using Money except in top level presentation. We have multiple tables (effectively a sales voucher and sales invoice) each of which contains one or more Money fields for historical reasons, and we need to perform a pro-rata calculation to work out how much of the total invoice Tax is relevant to each line on the sales voucher. Our calculation is

``````vat proportion = total invoice vat x (voucher line value / total invoice value)
``````

This results in a real world money / money calculation which causes scale errors on the division part, which then multiplies up into an incorrect vat proportion. When these values are subsequently added, we end up with a sum of the vat proportions which do not add up to the total invoice value. Had either of the values in the brackets been a decimal (I'm about to cast one of them as such) the vat proportion would be correct.

When the brackets weren't there originally this used to work, I guess because of the larger values involved, it was effectively simulating a higher scale. We added the brackets because it was doing the multiplication first, which was in some rare cases blowing the precision available for the calculation, but this has now caused this much more common error.

### Start a fragment via Intent within a Fragment

You cannot open new fragments. Fragments need to be always hosted by an activity. If the fragment is in the same activity (eg tabs) then the back key navigation is going to be tricky I am assuming that you want to open a new screen with that fragment.

So you would simply create a new activity and put the new fragment in there. That activity would then react to the intent either explicitly via the activity class or implicitly via `intent filter`s.

### Find IP address of directly connected device

Mmh ... there are many ways. I answer another network discovery question, and I write a little getting started.

Some tcpip stacks reply to icmp broadcasts. So you can try a PING to your network broadcast address.

For example, you have ip 192.168.1.1 and subnet 255.255.255.0

1. ping 192.168.1.255
2. stop the ping after 5 seconds
3. watch the devices replies : arp -a

Note : on step 3. you get the lists of the MAC-to-IP cached entries, so there are also the hosts in your subnet you exchange data to in the last minutes, even if they don't reply to icmp_get.

Note (2) : now I am on linux. I am not sure, but it can be windows doesn't reply to icm_get via broadcast.

Is it the only one device attached to your pc ? Is it a router or another simple pc ?

### PHP : send mail in localhost

It is possible to send Emails without using any heavy libraries I have included my example here.

lightweight SMTP Email sender for PHP

https://github.com/jerryurenaa/EZMAIL

Tested in both environments production and development.

and most importantly emails will not go to spam unless your IP is blacklisted by the server.

cheers.

### ASP.Net Download file to client browser

Just a slight addition to the above solution if you are having problem with downloaded file's name...

``````Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");
``````

This will return the exact file name even if it contains spaces or other characters.

### Check if ADODB connection is open

This is an old topic, but in case anyone else is still looking...

I was having trouble after an undock event. An open db connection saved in a global object would error, even after reconnecting to the network. This was due to the TCP connection being forcibly terminated by remote host. (Error -2147467259: TCP Provider: An existing connection was forcibly closed by the remote host.)

However, the error would only show up after the first transaction was attempted. Up to that point, neither Connection.State nor Connection.Version (per solutions above) would reveal any error.

So I wrote the small sub below to force the error - hope it's useful.

Performance testing on my setup (Access 2016, SQL Svr 2008R2) was approx 0.5ms per call.

``````Function adoIsConnected(adoCn As ADODB.Connection) As Boolean

'----------------------------------------------------------------
'#PURPOSE: Checks whether the supplied db connection is alive and
'          hasn't had it's TCP connection forcibly closed by remote
'          host, for example, as happens during an undock event
'#RETURNS: True if the supplied db is connected and error-free,
'          False otherwise
'----------------------------------------------------------------

Dim i As Long
Dim cmd As New ADODB.Command

'Set up SQL command to return 1
cmd.CommandText = "SELECT 1"

'Run a simple query, to test the connection
On Error Resume Next
i = cmd.Execute.Fields(0)
On Error GoTo 0

'Tidy up
Set cmd = Nothing

'If i is 1, connection is open
If i = 1 Then
Else
End If

End Function
``````

### Jquery UI Datepicker not displaying

Ok, I finally found my solution.

If you are using templates on your view (using Moustache.js, or others...), you must take into account that some of your classes can be loaded twice, or will be created later. So, you must apply this function `\$(".datepicker" ).datepicker();` once the instance has been created.

### Using multiple arguments for string formatting in Python (e.g., '%s ... %s')

If you're using more than one argument it has to be in a tuple (note the extra parentheses):

``````'%s in %s' % (unicode(self.author),  unicode(self.publication))
``````

As EOL points out, the `unicode()` function usually assumes ascii encoding as a default, so if you have non-ASCII characters, it's safer to explicitly pass the encoding:

``````'%s in %s' % (unicode(self.author,'utf-8'),  unicode(self.publication('utf-8')))
``````

And as of Python 3.0, it's preferred to use the `str.format()` syntax instead:

``````'{0} in {1}'.format(unicode(self.author,'utf-8'),unicode(self.publication,'utf-8'))
``````

### Can I prevent text in a div block from overflowing?

It's now the css property:

`word-break: break-all`

### Best way to compare two complex objects

Serialize both objects, then calculate Hash Code, then compare.

### How to edit Docker container files from the host?

Whilst it is possible, and the other answers explain how, you should avoid editing files in the Union File System if you can.

Your definition of volumes isn't quite right - it's more about bypassing the Union File System than exposing files on the host. For example, if I do:

``````\$ docker run --name="test" -v /volume-test debian echo "test"
``````

The directory `/volume-test` inside the container will not be part of the Union File System and instead will exist somewhere on the host. I haven't specified where on the host, as I may not care - I'm not exposing host files, just creating a directory that is shareable between containers and the host. You can find out exactly where it is on the host with:

``````\$ docker inspect -f "{{.Volumes}}" test
map[/volume_test:/var/lib/docker/vfs/dir/b7fff1922e25f0df949e650dfa885dbc304d9d213f703250cf5857446d104895]
``````

If you really need to just make a quick edit to a file to test something, either use `docker exec` to get a shell in the container and edit directly, or use `docker cp` to copy the file out, edit on the host and copy back in.

### How to Populate a DataTable from a Stored Procedure

You can use a `SqlDataAdapter`:

``````    SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("usp_GetABCD", sqlcon);
cmd.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable();
``````

### Find when a file was deleted in Git

``````git log --full-history -- your_file
``````

will show you all commits in your repo's history, including merge commits, that touched `your_file`. The last (top) one is the one that deleted the file.

#### Some explanation:

The `--full-history` flag here is important. Without it, Git performs "history simplification" when you ask it for the log of a file. The docs are light on details about exactly how this works and I lack the grit and courage required to try to figure it out from the source code, but the git-log docs have this much to say:

#### Default mode

Simplifies the history to the simplest history explaining the final state of the tree. Simplest because it prunes some side branches if the end result is the same (i.e. merging branches with the same content)

This is obviously concerning when the file whose history we want is deleted, since the simplest history explaining the final state of a deleted file is no history. Is there a risk that `git log` without `--full-history` will simply claim that the file was never created? Unfortunately, yes. Here's a demonstration:

``````mark@lunchbox:~/example\$ git init
Initialised empty Git repository in /home/mark/example/.git/
mark@lunchbox:~/example\$ touch foo && git add foo && git commit -m "Added foo"
[master (root-commit) ddff7a7] Added foo
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 foo
mark@lunchbox:~/example\$ git checkout -b newbranch
Switched to a new branch 'newbranch'
mark@lunchbox:~/example\$ touch bar && git add bar && git commit -m "Added bar"
[newbranch 7f9299a] Added bar
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 bar
mark@lunchbox:~/example\$ git checkout master
Switched to branch 'master'
mark@lunchbox:~/example\$ git rm foo && git commit -m "Deleted foo"
rm 'foo'
[master 7740344] Deleted foo
1 file changed, 0 insertions(+), 0 deletions(-)
delete mode 100644 foo
mark@lunchbox:~/example\$ git checkout newbranch
Switched to branch 'newbranch'
mark@lunchbox:~/example\$ git rm bar && git commit -m "Deleted bar"
rm 'bar'
[newbranch 873ed35] Deleted bar
1 file changed, 0 insertions(+), 0 deletions(-)
delete mode 100644 bar
mark@lunchbox:~/example\$ git checkout master
Switched to branch 'master'
mark@lunchbox:~/example\$ git merge newbranch
Merge made by the 'recursive' strategy.
mark@lunchbox:~/example\$ git log -- foo
commit 77403443a13a93073289f95a782307b1ebc21162
Author: Mark Amery
Date:   Tue Jan 12 22:50:50 2016 +0000

Deleted foo

commit ddff7a78068aefb7a4d19c82e718099cf57be694
Author: Mark Amery
Date:   Tue Jan 12 22:50:19 2016 +0000

mark@lunchbox:~/example\$ git log -- bar
mark@lunchbox:~/example\$ git log --full-history -- foo
commit 2463e56a21e8ee529a59b63f2c6fcc9914a2b37c
Merge: 7740344 873ed35
Author: Mark Amery
Date:   Tue Jan 12 22:51:36 2016 +0000

Merge branch 'newbranch'

commit 77403443a13a93073289f95a782307b1ebc21162
Author: Mark Amery
Date:   Tue Jan 12 22:50:50 2016 +0000

Deleted foo

commit ddff7a78068aefb7a4d19c82e718099cf57be694
Author: Mark Amery
Date:   Tue Jan 12 22:50:19 2016 +0000

mark@lunchbox:~/example\$ git log --full-history -- bar
commit 873ed352c5e0f296b26d1582b3b0b2d99e40d37c
Author: Mark Amery
Date:   Tue Jan 12 22:51:29 2016 +0000

Deleted bar

commit 7f9299a80cc9114bf9f415e1e9a849f5d02f94ec
Author: Mark Amery
Date:   Tue Jan 12 22:50:38 2016 +0000

``````

Notice how `git log -- bar` in the terminal dump above resulted in literally no output; Git is "simplifying" history down into a fiction where `bar` never existed. `git log --full-history -- bar`, on the other hand, gives us the commit that created `bar` and the commit that deleted it.

To be clear: this issue isn't merely theoretical. I only looked into the docs and discovered the `--full-history` flag because `git log -- some_file` was failing for me in a real repository where I was trying to track a deleted file down. History simplification might sometimes be helpful when you're trying to understand how a currently-existing file came to be in its current state, but when trying to track down a file deletion it's more likely to screw you over by hiding the commit you care about. Always use the `--full-history` flag for this use case.

### converting CSV/XLS to JSON?

This worked perfectly for me and does NOT require a file upload:

https://github.com/cparker15/csv-to-json?files=1

### How to make two plots side-by-side using Python?

You can use - matplotlib.gridspec.GridSpec

The below code displays a heatmap on right and an Image on left.

``````#Creating 1 row and 2 columns grid
gs = gridspec.GridSpec(1, 2)
fig = plt.figure(figsize=(25,3))

#Using the 1st row and 1st column for plotting heatmap
ax=plt.subplot(gs[0,0])
ax=sns.heatmap([[1,23,5,8,5]],annot=True)

#Using the 1st row and 2nd column to show the image
ax1=plt.subplot(gs[0,1])
ax1.grid(False)
ax1.set_yticklabels([])
ax1.set_xticklabels([])

#The below lines are used to display the image on ax1
image = io.imread("https://images-na.ssl-images- amazon.com/images/I/51MvhqY1qdL._SL160_.jpg")

plt.imshow(image)
plt.show()
``````

Output image

### Correct use for angular-translate in controllers

#### Recommended: don't translate in the controller, translate in your view

I'd recommend to keep your controller free from translation logic and translate your strings directly inside your view like this:

``````<h1>{{ 'TITLE.HELLO_WORLD' | translate }}</h1>
``````

#### Using the provided service

Angular Translate provides the `\$translate` service which you can use in your Controllers.

An example usage of the `\$translate` service can be:

``````.controller('TranslateMe', ['\$scope', '\$translate', function (\$scope, \$translate) {
\$translate('PAGE.TITLE')
.then(function (translatedValue) {
\$scope.pageTitle = translatedValue;
});
});
``````

The translate service also has a method for directly translating strings without the need to handle a promise, using `\$translate.instant()`:

``````.controller('TranslateMe', ['\$scope', '\$translate', function (\$scope, \$translate) {
\$scope.pageTitle = \$translate.instant('TITLE.DASHBOARD'); // Assuming TITLE.DASHBOARD is defined
});
``````

The downside with using `\$translate.instant()` could be that the language file isn't loaded yet if you are loading it async.

#### Using the provided filter

This is my preferred way since I don't have to handle promises this way. The output of the filter can be directly set to a scope variable.

``````.controller('TranslateMe', ['\$scope', '\$filter', function (\$scope, \$filter) {
var \$translate = \$filter('translate');

\$scope.pageTitle = \$translate('TITLE.DASHBOARD'); // Assuming TITLE.DASHBOARD is defined
});
``````

#### Using the provided directive

Since @PascalPrecht is the creator of this awesome library, I'd recommend going with his advise (see his answer below) and use the provided directive which seems to handle translations very intelligent.

The directive takes care of asynchronous execution and is also clever enough to unwatch translation ids on the scope if the translation has no dynamic values.

### Sorting an ArrayList of objects using a custom sorting order

Here's a tutorial about ordering objects:

Although I will give some examples, I would recommend to read it anyway.

There are various way to sort an `ArrayList`. If you want to define a natural (default) ordering, then you need to let `Contact` implement `Comparable`. Assuming that you want to sort by default on `name`, then do (nullchecks omitted for simplicity):

``````public class Contact implements Comparable<Contact> {

private String name;
private String phone;

@Override
public int compareTo(Contact other) {
return name.compareTo(other.name);
}

// Add/generate getters/setters and other boilerplate.
}
``````

so that you can just do

``````List<Contact> contacts = new ArrayList<Contact>();
// Fill it.

Collections.sort(contacts);
``````

If you want to define an external controllable ordering (which overrides the natural ordering), then you need to create a `Comparator`:

``````List<Contact> contacts = new ArrayList<Contact>();
// Fill it.

// Now sort by address instead of name (default).
Collections.sort(contacts, new Comparator<Contact>() {
public int compare(Contact one, Contact other) {
}
});
``````

You can even define the `Comparator`s in the `Contact` itself so that you can reuse them instead of recreating them everytime:

``````public class Contact {

private String name;
private String phone;

// ...

public static Comparator<Contact> COMPARE_BY_PHONE = new Comparator<Contact>() {
public int compare(Contact one, Contact other) {
return one.phone.compareTo(other.phone);
}
};

public static Comparator<Contact> COMPARE_BY_ADDRESS = new Comparator<Contact>() {
public int compare(Contact one, Contact other) {
}
};

}
``````

which can be used as follows:

``````List<Contact> contacts = new ArrayList<Contact>();
// Fill it.

// Sort by address.

// Sort later by phone.
Collections.sort(contacts, Contact.COMPARE_BY_PHONE);
``````

And to cream the top off, you could consider to use a generic javabean comparator:

``````public class BeanComparator implements Comparator<Object> {

private String getter;

public BeanComparator(String field) {
this.getter = "get" + field.substring(0, 1).toUpperCase() + field.substring(1);
}

public int compare(Object o1, Object o2) {
try {
if (o1 != null && o2 != null) {
o1 = o1.getClass().getMethod(getter, new Class[0]).invoke(o1, new Object[0]);
o2 = o2.getClass().getMethod(getter, new Class[0]).invoke(o2, new Object[0]);
}
} catch (Exception e) {
// If this exception occurs, then it is usually a fault of the developer.
throw new RuntimeException("Cannot compare " + o1 + " with " + o2 + " on " + getter, e);
}

return (o1 == null) ? -1 : ((o2 == null) ? 1 : ((Comparable<Object>) o1).compareTo(o2));
}

}
``````

which you can use as follows:

``````// Sort on "phone" field of the Contact bean.
Collections.sort(contacts, new BeanComparator("phone"));
``````

(as you see in the code, possibly null fields are already covered to avoid NPE's during sort)

### Converting string "true" / "false" to boolean value

``````var val = (string === "true");
``````

### How do I make a Windows batch script completely silent?

To suppress output, use redirection to `NUL`.

There are two kinds of output that console commands use:

• standard output, or `stdout`,

• standard error, or `stderr`.

Of the two, `stdout` is used more often, both by internal commands, like `copy`, and by console utilities, or external commands, like `find` and others, as well as by third-party console programs.

`>NUL` suppresses the standard output and works fine e.g. for suppressing the `1 file(s) copied.` message of the `copy` command. An alternative syntax is `1>NUL`. So,

``````COPY file1 file2 >NUL
``````

or

``````COPY file1 file2 1>NUL
``````

or

``````>NUL COPY file1 file2
``````

or

``````1>NUL COPY file1 file2
``````

suppresses all of `COPY`'s standard output.

To suppress error messages, which are typically printed to `stderr`, use `2>NUL` instead. So, to suppress a `File Not Found` message that `DEL` prints when, well, the specified file is not found, just add `2>NUL` either at the beginning or at the end of the command line:

``````DEL file 2>NUL
``````

or

``````2>NUL DEL file
``````

Although sometimes it may be a better idea to actually verify whether the file exists before trying to delete it, like you are doing in your own solution. Note, however, that you don't need to delete the files one by one, using a loop. You can use a single command to delete the lot:

``````IF EXIST "%scriptDirectory%*.noext" DEL "%scriptDirectory%*.noext"
``````

### Can't install APK from browser downloads

I had this problem. Couldn't install apk via the Downloads app. However opening the apk in a file manager app allowed me to install it fine. Using OI File Manager on stock Nexus 7 4.2.1

### How to install Java 8 on Mac

Run these commands on mac High Sierra

``````brew update
brew cask install java8
``````

and check with command

``````java -version
``````

### How can I add a table of contents to a Jupyter / JupyterLab notebook?

How about using a Browser plugin that gives you an overview of ANY html page. I have tried the following:

They both work pretty well for IPython Notebooks. I was reluctant to use the previous solutions as they seem a bit unstable and ended up using these extensions.

### Proxy Error 502 : The proxy server received an invalid response from an upstream server

I had this issue once. It turned out to be database query issue. After re-create tables and index it has been fixed.

Although it says proxy error, when you look at server log, it shows execute query timeout. This is what I had before and how I solved it.

### Extending from two classes

As everyone else has said. No, you can't. However even though people have said many times over the years that you should use multiple interfaces they haven't really gone into how. Hopefully this will help.

Say you have `class Foo` and `class Bar` that you both want to try extending into a `class FooBar`. Of course, as you said, you can't do:

``````public class FooBar extends Foo, Bar
``````

People have gone into the reasons for this to some extent already. Instead, write `interfaces` for both `Foo` and `Bar` covering all of their public methods. E.g.

``````public interface FooInterface {

public void methodA();

public int methodB();

//...
}

public interface BarInterface {

public int methodC(int i);

//...
}
``````

And now make `Foo` and `Bar` implement the relative interfaces:

``````public class Foo implements FooInterface { /*...*/ }

public class Bar implements BarInterface { /*...*/ }
``````

Now, with `class FooBar`, you can implement both `FooInterface` and `BarInterface` while keeping a `Foo` and `Bar` object and just passing the methods straight through:

``````public class FooBar implements FooInterface, BarInterface {

Foo myFoo;
Bar myBar;

// You can have the FooBar constructor require the arguments for both
//  the Foo and the Bar constructors
public FooBar(int x, int y, int z){
myFoo = new Foo(x);
myBar = new Bar(y, z);
}

// Or have the Foo and Bar objects passed right in
public FooBar(Foo newFoo, Bar newBar){
myFoo = newFoo;
myBar = newBar;
}

public void methodA(){
myFoo.methodA();
}

public int methodB(){
return myFoo.methodB();
}

public int methodC(int i){
return myBar.methodC(i);
}

//...

}
``````

The bonus for this method, is that the `FooBar` object fits the moulds of both `FooInterface` and `BarInterface`. That means this is perfectly fine:

``````FooInterface testFoo;
testFoo = new FooBar(a, b, c);
testFoo = new Foo(a);

BarInterface testBar;
testBar = new FooBar(a, b, c);
testBar = new Bar(b, c);
``````

Hope this clarifies how to use interfaces instead of multiple extensions. Even if I am a few years late.

### How to find all positions of the maximum value in a list?

The chosen answer (and most others) require at least two passes through the list.
Here's a one pass solution which might be a better choice for longer lists.

Edited: To address the two deficiencies pointed out by @John Machin. For (2) I attempted to optimize the tests based on guesstimated probability of occurrence of each condition and inferences allowed from predecessors. It was a little tricky figuring out the proper initialization values for `max_val` and `max_indices` which worked for all possible cases, especially if the max happened to be the first value in the list — but I believe it now does.

``````def maxelements(seq):
''' Return list of position(s) of largest element '''
max_indices = []
if seq:
max_val = seq[0]
for i,val in ((i,val) for i,val in enumerate(seq) if val >= max_val):
if val == max_val:
max_indices.append(i)
else:
max_val = val
max_indices = [i]

return max_indices
``````

### Checking cin input stream produces an integer

Heh, this is an old question that could use a better answer.

User input should be obtained as a string and then attempt-converted to the data type you desire. Conveniently, this also allows you to answer questions like “what type of data is my input?”

Here is a function I use a lot. Other options exist, such as in Boost, but the basic premise is the same: attempt to perform the string?type conversion and observe the success or failure:

``````template <typename T>
std::optional <T> string_to( const std::string& s )
{
std::istringstream ss( s );
T result;
ss >> result >> std::ws;      // attempt the conversion
if (ss.eof()) return result;  // success
return {};                    // failure
}
``````

Using the `optional` type is just one way. You could also throw an exception or return a default value on failure. Whatever works for your situation.

Here is an example of using it:

``````int n;
std::cout << "n? ";
{
std::string s;
getline( std::cin, s );
auto x = string_to <int> ( s );
if (!x) return complain();
n = *x;
}
std::cout << "Multiply that by seven to get " << (7 * n) << ".\n";
``````

limitations and type identification

In order for this to work, of course, there must exist a method to unambiguously extract your data type from a stream. This is the natural order of things in C++ — that is, business as usual. So no surprises here.

The next caveat is that some types subsume others. For example, if you are trying to distinguish between `int` and `double`, check for `int` first, since anything that converts to an `int` is also a `double`.

### "Instantiating" a List in Java?

Use `List<Integer> list = new ArrayList<Integer>();`

### Angular 4 img src is not found

Copy your images into the assets folder. Angular can only access static files like images and config files from assets folder.

Try like this: `<img src="assets/img/myimage.png">`

### Send request to curl with post data sourced from a file

If you are using form data to upload file,in which a parameter name must be specified , you can use:

`curl -X POST -i -F "parametername=@filename" -F "additional_parm=param2" host:port/xxx`

### SimpleDateFormat parse loses timezone

``````SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));

SimpleDateFormat sdfLocal = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");

try {
String d = sdf.format(new Date());
System.out.println(d);
System.out.println(sdfLocal.parse(d));
} catch (Exception e) {
e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
}
``````

Output : slightly dubious, but I want only the date to be consistent

``````2013.08.08 11:01:08
Thu Aug 08 11:01:08 GMT+08:00 2013
``````

### invalid operands of types int and double to binary 'operator%'

Because `%` is only defined for integer types. That's the modulus operator.

5.6.2 of the standard:

The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]

As Oli pointed out, you can use `fmod()`. Don't forget to include `math.h`.

### Appending a list to a list of lists in R

The `purrr` package has a lot of handy functions for working on lists. The `flatten` command can clean up unwanted nesting.

``````resultsa <- list(1,2,3,4,5)
resultsb <- list(6,7,8,9,10)
resultsc <- list(11,12,13,14,15)

nested_outlist <- list(resultsa, resultsb, resultsc)
outlist <- purrr::flatten(nested_outlist)
``````

### C# Set collection?

Have a look at PowerCollections over at CodePlex. Apart from Set and OrderedSet it has a few other usefull collection types such as Deque, MultiDictionary, Bag, OrderedBag, OrderedDictionary and OrderedMultiDictionary.

For more collections, there is also the C5 Generic Collection Library.

### A simple explanation of Naive Bayes Classification

Your question as I understand it is divided in two parts, part one being you need a better understanding of the Naive Bayes classifier & part two being the confusion surrounding Training set.

In general all of Machine Learning Algorithms need to be trained for supervised learning tasks like classification, prediction etc. or for unsupervised learning tasks like clustering.

During the training step, the algorithms are taught with a particular input dataset (training set) so that later on we may test them for unknown inputs (which they have never seen before) for which they may classify or predict etc (in case of supervised learning) based on their learning. This is what most of the Machine Learning techniques like Neural Networks, SVM, Bayesian etc. are based upon.

So in a general Machine Learning project basically you have to divide your input set to a Development Set (Training Set + Dev-Test Set) & a Test Set (or Evaluation set). Remember your basic objective would be that your system learns and classifies new inputs which they have never seen before in either Dev set or test set.

The test set typically has the same format as the training set. However, it is very important that the test set be distinct from the training corpus: if we simply reused the training set as the test set, then a model that simply memorized its input, without learning how to generalize to new examples, would receive misleadingly high scores.

In general, for an example, 70% of our data can be used as training set cases. Also remember to partition the original set into the training and test sets randomly.

Now I come to your other question about Naive Bayes.

To demonstrate the concept of Naïve Bayes Classification, consider the example given below:

As indicated, the objects can be classified as either `GREEN` or `RED`. Our task is to classify new cases as they arrive, i.e., decide to which class label they belong, based on the currently existing objects.

Since there are twice as many `GREEN` objects as `RED`, it is reasonable to believe that a new case (which hasn't been observed yet) is twice as likely to have membership `GREEN` rather than `RED`. In the Bayesian analysis, this belief is known as the prior probability. Prior probabilities are based on previous experience, in this case the percentage of `GREEN` and `RED` objects, and often used to predict outcomes before they actually happen.

Thus, we can write:

Prior Probability of `GREEN`: `number of GREEN objects / total number of objects`

Prior Probability of `RED`: `number of RED objects / total number of objects`

Since there is a total of `60` objects, `40` of which are `GREEN` and 20 `RED`, our prior probabilities for class membership are:

Prior Probability for `GREEN`: `40 / 60`

Prior Probability for `RED`: `20 / 60`

Having formulated our prior probability, we are now ready to classify a new object (`WHITE` circle in the diagram below). Since the objects are well clustered, it is reasonable to assume that the more `GREEN` (or `RED`) objects in the vicinity of X, the more likely that the new cases belong to that particular color. To measure this likelihood, we draw a circle around X which encompasses a number (to be chosen a priori) of points irrespective of their class labels. Then we calculate the number of points in the circle belonging to each class label. From this we calculate the likelihood:

From the illustration above, it is clear that Likelihood of `X` given `GREEN` is smaller than Likelihood of `X` given `RED`, since the circle encompasses `1` `GREEN` object and `3` `RED` ones. Thus:

Although the prior probabilities indicate that `X` may belong to `GREEN` (given that there are twice as many `GREEN` compared to `RED`) the likelihood indicates otherwise; that the class membership of `X` is `RED` (given that there are more `RED` objects in the vicinity of `X` than `GREEN`). In the Bayesian analysis, the final classification is produced by combining both sources of information, i.e., the prior and the likelihood, to form a posterior probability using the so-called Bayes' rule (named after Rev. Thomas Bayes 1702-1761).

Finally, we classify X as `RED` since its class membership achieves the largest posterior probability.

### How do I implement IEnumerable<T>

make mylist into a `List<MyObject>`, is one option

### Newline in markdown table?

Use an HTML line break (`<br />`) to force a line break within a table cell:

``````|Something|Something else<br />that's rather long|Something else|
``````

### How to Find And Replace Text In A File With C#

This code Worked for me

``````- //-------------------------------------------------------------------
// Create an instance of the Printer
IPrinter printer = new Printer();

//----------------------------------------------------------------------------
String path = @"" + file_browse_path.Text;
//  using (StreamReader sr = File.OpenText(path))

{

string fileLocMove="";
string newpath = Path.GetDirectoryName(path);
fileLocMove = newpath + "\\" + "new.prn";

string text = File.ReadAllText(path);
text= text.Replace("<REF>", reference_code.Text);
text=   text.Replace("<ORANGE>", orange_name.Text);
text=   text.Replace("<SIZE>", size_name.Text);
text=   text.Replace("<INVOICE>", invoiceName.Text);
text=   text.Replace("<BINQTY>", binQty.Text);
text = text.Replace("<DATED>", dateName.Text);

File.WriteAllText(fileLocMove, text);

// Print the file
printer.PrintRawFile("Godex G500", fileLocMove, "n");
// File.WriteAllText("C:\\Users\\Gunjan\\Desktop\\new.prn", s);
}
``````

### Running a cron job on Linux every six hours

You need to use *

``````0 */6 * * * /path/to/mycommand
``````

Also you can refer to https://crontab.guru/ which will help you in scheduling better...

### How to calculate md5 hash of a file using javascript

I don't believe there is a way in javascript to access the contents of a file upload. So you therefore cannot look at the file contents to generate an MD5 sum.

You can however send the file to the server, which can then send an MD5 sum back or send the file contents back .. but that's a lot of work and probably not worthwhile for your purposes.

### Getting each individual digit from a whole integer

This solution gives correct results over the entire range [0,UINT_MAX] without requiring digits to be buffered.

It also works for wider types or signed types (with positive values) with appropriate type changes.

This kind of approach is particularly useful on tiny environments (e.g. Arduino bootloader) because it doesn't end up pulling in all the printf() bloat (when printf() isn't used for demo output) and uses very little RAM. You can get a look at value just by blinking a single led :)

``````#include <limits.h>
#include <stdio.h>

int
main (void)
{
unsigned int score = 42;   // Works for score in [0, UINT_MAX]

printf ("score via printf:     %u\n", score);   // For validation

printf ("score digit by digit: ");
unsigned int div = 1;
unsigned int digit_count = 1;
while ( div <= score / 10 ) {
digit_count++;
div *= 10;
}
while ( digit_count > 0 ) {
printf ("%d", score / div);
score %= div;
div /= 10;
digit_count--;
}
printf ("\n");

return 0;
}
``````

### Display an image into windows forms

There could be many reasons for this. A few that come up quickly to my mind:

1. Did you call this routine AFTER `InitializeComponent()`?
2. Is the path syntax you are using correct? Does it work if you try it in the debugger? Try using backslash (\) instead of Slash (/) and see.
3. This may be due to side-effects of some other code in your form. Try using the same code in a blank Form (with just the constructor and this function) and check.

### How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?

Adam Luter gave me the idea for this, but it actually turned out to be really simple:

``````img {
width:  75px;
height: auto;
}
``````

IE6 now scales the image fine and this seems to be what all the other browsers use by default.

Thanks for both the answers though!

### Warning: Permanently added the RSA host key for IP address

I had similar problem. In git site after user clicking on clone or download button, while copying the cloned url there are 2 options to select ssh and https. I selected https url to clone and it worked.

### Transpose/Unzip Function (inverse of zip)?

None of the previous answers efficiently provide the required output, which is a tuple of lists, rather than a list of tuples. For the former, you can use `tuple` with `map`. Here's the difference:

``````res1 = list(zip(*original))              # [('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
res2 = tuple(map(list, zip(*original)))  # (['a', 'b', 'c', 'd'], [1, 2, 3, 4])
``````

In addition, most of the previous solutions assume Python 2.7, where `zip` returns a list rather than an iterator.

For Python 3.x, you will need to pass the result to a function such as `list` or `tuple` to exhaust the iterator. For memory-efficient iterators, you can omit the outer `list` and `tuple` calls for the respective solutions.

### SFTP in Python? (platform independent)

fsspec is a great option for this, it offers a filesystem like implementation of sftp.

``````from fsspec.implementations.sftp import SFTPFileSystem

# list a directory
fs.ls("/")

# open a file
with fs.open(file_name) as file:
``````

Also worth noting that fsspec uses paramiko in the implementation.

### How to align a div inside td element using CSS class

I cannot help you much without a small (possibly reduced) snippit of the problem. If the problem is what I think it is then it's because a div by default takes up 100% width, and as such cannot be aligned.

What you may be after is to align the inline elements inside the div (such as text) with text-align:center; otherwise you may consider setting the div to display:inline-block;

If you do go down the inline-block route then you may have to consider my favorite IE hack.

``````width:100px;
display:inline-block;
zoom:1; //IE only
*display:inline; //IE only
``````

Happy Coding :)

### Get selected item value from Bootstrap DropDown with specific ID

The selector would be `#demolist.dropdown-menu li a` note no space between id and class. However i would suggest a more generic approach:

``````<div class="input-group">
<input type="TextBox" Class="form-control datebox"></input>
<div class="input-group-btn">
<button type="button" class="btn dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
</button>
<li><a href="#">A</a></li>
<li><a href="#">B</a></li>
<li><a href="#">C</a></li>
</ul>
</div>

\$(document).on('click', '.dropdown-menu li a', function() {
\$(this).parent().parent().parent().find('.datebox').val(\$(this).html());
});
``````

by using a class rather than id, and using `parent().find()`, you can have as many of these on a page as you like, with no duplicated js

### Video auto play is not working in Safari and Chrome desktop browser

On safari iPhone when battery is low and iPhone is on Low Power Mode it won`t autoplay, even if you have the following attributes: autoplay, loop, muted, playsinline set on your video html tag.

Walk around I found working is to have user gesture event to trigger video play:

``````document.body.addEventListener("touchstart", function () {
var allVideos = document.querySelectorAll('video');
for (var i = 0; i < allVideos.length; i++) {
allVideos[i].play();
}
},{ once: true });
``````

You can read more about user gesture and Video Policies for iOS in webkit site:

https://webkit.org/blog/6784/new-video-policies-for-ios/

### 'was not declared in this scope' error

Here's a simplified example based on of your problem:

``````if (test)
{//begin scope 1
int y = 1;
}//end scope 1
else
{//begin scope 2
int y = 2;//error, y is not in scope
}//end scope 2
int x = y;//error, y is not in scope
``````

In the above version you have a variable called `y` that is confined to scope 1, and another different variable called `y` that is confined to scope 2. You then try to refer to a variable named `y` after the end of the `if`, and not such variable `y` can be seen because no such variable exists in that scope.

You solve the problem by placing `y` in the outermost scope which contains all references to it:

``````int y;
if (test)
{
y = 1;
}
else
{
y = 2;
}
int x = y;
``````

I've written the example with simplified made up code to make it clearer for you to understand the issue. You should now be able to apply the principle to your code.

### BackgroundWorker vs background Thread

I want to point out one behavior of BackgroundWorker class that wasn't mentioned yet. You can make a normal Thread to run in background by setting the Thread.IsBackground property.

Background threads are identical to foreground threads, except that background threads do not prevent a process from terminating. [1]

You can test this behavoir by calling the following method in the constructor of your form window.

``````void TestBackgroundThread()
{
{
long count = 0;
while (true)
{
count++;
Debug.WriteLine("Thread loop count: " + count);
}
});

// Choose one option:
thread.IsBackground = true; // <--- This will make the thread run in background
thread.IsBackground = false; // <--- This will delay program termination

}
``````

When the IsBackground property is set to true and you close the window, then your application will terminate normaly.

But when the IsBackground property is set to false (by default) and you close the window, then just the window will disapear but the process will still keep running.

The BackgroundWorker class utilize a Thread that runs in the background.

### Detect backspace and del on "input" event?

``````\$('div[contenteditable]').keydown(function(e) {
// trap the return key being pressed
if (e.keyCode === 13 || e.keyCode === 8)
{
return false;
}
});
``````

### Why call super() in a constructor?

We can Access SuperClass members using super keyword

If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword `super`. You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass:

``````public class Superclass {

public void printMethod() {
System.out.println("Printed in Superclass.");
}
}
``````

// Here is a subclass, called Subclass, that overrides `printMethod()`:

``````public class Subclass extends Superclass {

// overrides printMethod in Superclass
public void printMethod() {
super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.printMethod();
}
}
``````

Within Subclass, the simple name `printMethod()` refers to the one declared in Subclass, which overrides the one in Superclass. So, to refer to `printMethod()` inherited from Superclass, Subclass must use a qualified name, using super as shown. Compiling and executing Subclass prints the following:

``````Printed in Superclass.
Printed in Subclass
``````

### What is the difference between atomic / volatile / synchronized?

A volatile + synchronization is a fool proof solution for an operation(statement) to be fully atomic which includes multiple instructions to the CPU.

Say for eg:volatile int i = 2; i++, which is nothing but i = i + 1; which makes i as the value 3 in the memory after the execution of this statement. This includes reading the existing value from memory for i(which is 2), load into the CPU accumulator register and do with the calculation by increment the existing value with one(2 + 1 = 3 in accumulator) and then write back that incremented value back to the memory. These operations are not atomic enough though the value is of i is volatile. i being volatile guarantees only that a SINGLE read/write from memory is atomic and not with MULTIPLE. Hence, we need to have synchronized also around i++ to keep it to be fool proof atomic statement. Remember the fact that a statement includes multiple statements.

Hope the explanation is clear enough.

### Load an image from a url into a PictureBox

The PictureBox.Load(string url) method "sets the ImageLocation to the specified URL and displays the image indicated."

### javascript: calculate x% of a number

``````var number = 10000;
var result = .358 * number;
``````

### Cast int to varchar

I solved a problem to comparing a integer Column x a `varchar` column with

`where CAST(Column_name AS CHAR CHARACTER SET latin1 ) collate latin1_general_ci = varchar_column_name`

### Illegal Escape Character "\"

do two \'s

"\\"

it's because it's an escape character

### Oracle - How to create a materialized view with FAST REFRESH and JOINS

Have you tried it without the ANSI join ?

``````CREATE MATERIALIZED VIEW MV_Test
NOLOGGING
CACHE
BUILD IMMEDIATE
REFRESH FAST ON COMMIT
AS
SELECT V.*, P.* FROM TPM_PROJECTVERSION V,TPM_PROJECT P
WHERE  P.PROJECTID = V.PROJECTID
``````

### Adding placeholder text to textbox

Let's extend the TextBox with PlcaeHoldText and PlaceHoldBackround. I stripped some code form my project.

say goodbye to Grid or Canvas!

``````<TextBox x:Class="VcpkgGui.View.PlaceHoldedTextBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:VcpkgGui.View"
mc:Ignorable="d"
Name="placeHoldTextBox"
TextAlignment="Left"
>
<TextBox.Resources>
<local:FrameworkWidthConverter x:Key="getElemWidth"/>
<local:FrameworkHeightConverter x:Key="getElemHeight"/>
<VisualBrush x:Key="PlaceHoldTextBrush" TileMode="None" Stretch="None" AlignmentX="Left" AlignmentY="Center" Opacity="1">
<VisualBrush.Visual>
<Border Background="{Binding ElementName=placeHoldTextBox, Path=PlaceHoldBackground}"
BorderThickness="0"
Margin="0,0,0,0"
Width="{Binding Mode=OneWay, ElementName=placeHoldTextBox, Converter={StaticResource getElemWidth}}"
Height="{Binding Mode=OneWay, ElementName=placeHoldTextBox, Converter={StaticResource getElemHeight}}"
>
<Label Content="{Binding ElementName=placeHoldTextBox, Path=PlaceHoldText}"
Background="Transparent"
Foreground="#88000000"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
HorizontalContentAlignment="Left"
VerticalContentAlignment="Center"
ClipToBounds="True"
FontSize="14"
FontStyle="Normal"
Opacity="1"/>
</Border>
</VisualBrush.Visual>
</VisualBrush>
</TextBox.Resources>
<TextBox.Style>
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Text" Value="{x:Null}">
<Setter Property="Background"  Value="{StaticResource PlaceHoldTextBrush}"/>
</Trigger>
<Trigger Property="Text" Value="">
<Setter Property="Background"  Value="{StaticResource PlaceHoldTextBrush}"/>
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
``````
``````using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace VcpkgGui.View
{
/// <summary>
/// PlaceHoldedTextBox.xaml ?????
/// </summary>
public partial class PlaceHoldedTextBox : TextBox
{

public string PlaceHoldText
{
get { return (string)GetValue(PlaceHoldTextProperty); }
set { SetValue(PlaceHoldTextProperty, value); }
}

// Using a DependencyProperty as the backing store for PlaceHolderText.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty PlaceHoldTextProperty =
DependencyProperty.Register("PlaceHoldText", typeof(string), typeof(PlaceHoldedTextBox), new PropertyMetadata(string.Empty));

public Brush PlaceHoldBackground
{
get { return (Brush)GetValue(PlaceHoldBackgroundProperty); }
set { SetValue(PlaceHoldBackgroundProperty, value); }
}

public static readonly DependencyProperty PlaceHoldBackgroundProperty =
DependencyProperty.Register(nameof(PlaceHoldBackground), typeof(Brush), typeof(PlaceHoldedTextBox), new PropertyMetadata(Brushes.White));

public PlaceHoldedTextBox() :base()
{
InitializeComponent();
}
}

[ValueConversion(typeof(FrameworkElement), typeof(double))]
internal class FrameworkWidthConverter : System.Windows.Data.IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if(value is FrameworkElement elem)
return double.IsNaN(elem.Width) ? elem.ActualWidth : elem.Width;
else
return DependencyProperty.UnsetValue;
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}

[ValueConversion(typeof(FrameworkElement), typeof(double))]
internal class FrameworkHeightConverter : System.Windows.Data.IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is FrameworkElement elem)
return double.IsNaN(elem.Height) ? elem.ActualHeight : elem.Height;
else
return DependencyProperty.UnsetValue;
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}

}
``````

### ZIP file content type for HTTP request

``````[request setValue:@"application/zip" forHTTPHeaderField:@"Content-Type"];
``````

### How to select element using XPATH syntax on Selenium for Python?

HTML

``````<div id='a'>
<div>
<a class='click'>abc</a>
</div>
</div>
``````

You could use the XPATH as :

``````//div[@id='a']//a[@class='click']
``````

output

``````<a class="click">abc</a>
``````

That said your Python code should be as :

``````driver.find_element_by_xpath("//div[@id='a']//a[@class='click']")
``````

### Regex: Remove lines containing "help", etc

If you're on Windows, try `findstr`. Third-party tools are not needed:

``````findstr /V /L "searchstring" inputfile.txt > outputfile.txt
``````

It supports regex's too! Just read the tool's help `findstr /?`.

P.S. If you want to work with big, huge files (like 400 MB log files) a text editor is not very memory-efficient, so, as someone already pointed out, command-line tools are the way to go. But there's no grep on Windows, so...

I just ran this on a 1 GB log file, and it literally took 3 seconds.

### Best way to split string into lines

``````string[] lines = input.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
``````

### Windows batch script to unhide files hidden by virus

Try this one. Hope this is working fine.. :)

``````@ECHO off

cls

ECHO.

set drvltr=

set /p drvltr=Enter Drive letter:

attrib -s -h -a /s /d  %drvltr%:\*.*

ECHO Unhide Completed

pause
``````

### How to insert data into SQL Server

You have to set Connection property of Command object and use parametersized query instead of hardcoded SQL to avoid SQL Injection.

`````` using(SqlConnection openCon=new SqlConnection("your_connection_String"))
{
string saveStaff = "INSERT into tbl_staff (staffName,userID,idDepartment) VALUES (@staffName,@userID,@idDepartment)";

using(SqlCommand querySaveStaff = new SqlCommand(saveStaff))
{
querySaveStaff.Connection=openCon;
.....
openCon.Open();

querySaveStaff.ExecuteNonQuery();
}
}
``````

### Is it possible to insert multiple rows at a time in an SQLite database?

Sqlite3 can't do that directly in SQL except via a SELECT, and while SELECT can return a "row" of expressions, I know of no way to make it return a phony column.

However, the CLI can do it:

``````.import FILE TABLE     Import data from FILE into TABLE
.separator STRING      Change separator used by output mode and .import

\$ sqlite3 /tmp/test.db
SQLite version 3.5.9
Enter ".help" for instructions
sqlite> create table abc (a);
sqlite> .import /dev/tty abc
1
2
3
99
^D
sqlite> select * from abc;
1
2
3
99
sqlite>
``````

If you do put a loop around an INSERT, rather than using the CLI `.import` command, then be sure to follow the advice in the sqlite FAQ for INSERT speed:

By default, each INSERT statement is its own transaction. But if you surround multiple INSERT statements with BEGIN...COMMIT then all the inserts are grouped into a single transaction. The time needed to commit the transaction is amortized over all the enclosed insert statements and so the time per insert statement is greatly reduced.

Another option is to run PRAGMA synchronous=OFF. This command will cause SQLite to not wait on data to reach the disk surface, which will make write operations appear to be much faster. But if you lose power in the middle of a transaction, your database file might go corrupt.

### Make multiple-select to adjust its height to fit options without scroll bar

I know the question is old, but how the topic is not closed I'll give my help.

The attribute "size" will resolve your problem.

Example:

``````<select name="courses" multiple="multiple" size="30">
``````

### DateTimeFormat in TypeScript

This should work...

``````var displayDate = new Date().toLocaleDateString();

``````

But I suspect you are trying it on something else, for example:

``````var displayDate = Date.now.toLocaleDateString(); // No!

``````

### plotting different colors in matplotlib

``````for color in ['r', 'b', 'g', 'k', 'm']:
plot(x, y, color=color)
``````

### 'node' is not recognized as an internal or an external command, operable program or batch file while using phonegap/cordova

In Windows, you need to set node.js folder path into system variables or user variables.

1) open Control Panel -> System and Security -> System -> Advanced System Settings -> Environment Variables

2) in "User variables" or "System variables" find variable `PATH` and add node.js folder path as value. Usually it is `C:\Program Files\nodejs;`. If variable doesn't exists, create it.

3) Restart your IDE or computer.

It is useful add also "npm" and "Git" paths as variable, separated by semicolon.

### How to create PDF files in Python

I use rst2pdf to create a pdf file, since I am more familiar with RST than with HTML. It supports embedding almost any kind of raster or vector images.

It requires reportlab, but I found reportlab is not so straight forward to use (at least for me).

### Openstreetmap: embedding map in webpage (like Google Maps)

I would also take a look at CloudMade's developer tools. They offer a beautifully styled OSM base map service, an OpenLayers plugin, and even their own light-weight, very fast JavaScript mapping client. They also host their own routing service, which you mentioned as a possible requirement. They have great documentation and examples.

### How do I skip a header from CSV files in Spark?

Use the `filter()` method in PySpark by filtering out the first column name to remove the header:

``````# Read file (change format for other file formats)
contentRDD = sc.textfile(<filepath>)

# Filter out first column of the header
filterDD = contentRDD.filter(lambda l: not l.startswith(<first column name>)

# Check your result
for i in filterDD.take(5) : print (i)
``````

### Getting the screen resolution using PHP

I found using CSS inside my html inside my php did the trick for me.

``````<?php
echo '<h2 media="screen and (max-width: 480px)">';
echo '</h2>';

echo '<h1 media="screen and (min-width: 481px)">';
echo '</h1>';

?>
``````

This will output a smaller sized headline if the screen is 480px or less. So no need to pass any vars using JS or similar.

### jQuery show/hide options from one select drop down, when option on other select dropdown is slected

``````// find the first select and bind a click handler
\$('#column_select').bind('click', function(){
// retrieve the selected value
var value = \$(this).val(),
// build a regular expression that does a head-match
expression = new RegExp('^' + value),
// find the second select
\$select = \$('#layout_select);

// hide all children (<option>s) of the second select,
// check each element's value agains the regular expression built from the first select's value
// show elements that match the expression
\$select.children().hide().filter(function(){
return !!\$(this).val().match(expression);
}).show();
});
``````

(this is far from perfect, but should get you there…)

### Concatenation of strings in Lua

Strings can be joined together using the concatenation operator ".."

this is the same for variables I think

### What is ADT? (Abstract Data Type)

The term data type is as the type of data which a particular variable can hold - it may be an integer, a character, a float, or any range of simple data storage representation. However, when we build an object oriented system, we use other data types, known as abstract data type, which represents more realistic entities.

E.g.: We might be interested in representing a 'bank account' data type, which describe how all bank account are handled in a program. Abstraction is about reducing complexity, ignoring unnecessary details.

### How to include "zero" / "0" results in COUNT aggregate?

You must use `LEFT JOIN` instead of `INNER JOIN`

``````SELECT person.person_id, COUNT(appointment.person_id) AS "number_of_appointments"
FROM person
LEFT JOIN appointment ON person.person_id = appointment.person_id
GROUP BY person.person_id;
``````

### Change background color of iframe issue

You can do it using javascript

• Change iframe background color
• Change background color of the loaded page (same domain)

Plain javascript

``````var iframe = document.getElementsByTagName('iframe')[0];
iframe.style.background = 'white';
iframe.contentWindow.document.body.style.backgroundColor = 'white';
``````

jQuery

``````\$('iframe').css('background', 'white');
\$('iframe').contents().find('body').css('backgroundColor', 'white');
``````

### Use JavaScript to place cursor at end of text in text input element

I also faced same problem. Finally this gonna work for me:

``````jQuery.fn.putCursorAtEnd =  = function() {

return this.each(function() {

// Cache references
var \$el = \$(this),
el = this;

// Only focus if input isn't already
if (!\$el.is(":focus")) {
\$el.focus();
}

// If this function exists... (IE 9+)
if (el.setSelectionRange) {

// Double the length because Opera is inconsistent about whether a carriage return is one character or two.
var len = \$el.val().length * 2;

// Timeout seems to be required for Blink
setTimeout(function() {
el.setSelectionRange(len, len);
}, 1);

} else {

// As a fallback, replace the contents with itself
// Doesn't work in Chrome, but Chrome supports setSelectionRange
\$el.val(\$el.val());

}

// Scroll to the bottom, in case we're in a tall textarea
// (Necessary for Firefox and Chrome)
this.scrollTop = 999999;

});

};
``````

This is how we can call this:

``````var searchInput = \$("#searchInputOrTextarea");

searchInput
.putCursorAtEnd() // should be chainable
.on("focus", function() { // could be on any event
searchInput.putCursorAtEnd()
});
``````

It's works for me in safari, IE, Chrome, Mozilla. On mobile devices I didn't tried this.

### How to set JAVA_HOME path on Ubuntu?

I normally set paths in

``````~/.bashrc
``````

However for Java, I followed instructions at https://askubuntu.com/questions/55848/how-do-i-install-oracle-java-jdk-7

and it was sufficient for me.

you can also define multiple java_home's and have only one of them active (rest commented).

suppose in your bashrc file, you have

`export JAVA_HOME=......jdk1.7`

`#export JAVA_HOME=......jdk1.8`

notice 1.8 is commented. Once you do

`source ~/.bashrc`

jdk1.7 will be in path.

you can switch them fairly easily this way. There are other more permanent solutions too. The link I posted has that info.

### Angular + Material - How to refresh a data source (mat-table)

``````this.dataSource = new MatTableDataSource<Element>(this.elements);
``````

Add this line below your action of add or delete the particular row.

``````refresh() {
this.authService.getAuthenticatedUser().subscribe((res) => {
this.user = new MatTableDataSource<Element>(res);
});
}
``````

### Get selected value of a dropdown's item using jQuery

HTML:

``````<select class="form-control" id="SecondSelect">
<option>5<option>
<option>10<option>
<option>20<option>
<option>30<option>
</select>
``````

JavaScript:

``````var value = \$('#SecondSelect')[0].value;
``````

### In a simple to understand explanation, what is Runnable in Java?

A Runnable is basically a type of class (Runnable is an Interface) that can be put into a thread, describing what the thread is supposed to do.

The Runnable Interface requires of the class to implement the method `run()` like so:

``````public class MyRunnableTask implements Runnable {
public void run() {
// do stuff here
}
}
``````

And then use it like this:

``````Thread t = new Thread(new MyRunnableTask());
t.start();
``````

If you did not have the `Runnable` interface, the Thread class, which is responsible to execute your stuff in the other thread, would not have the promise to find a `run()` method in your class, so you could get errors. That is why you need to implement the interface.

#### Advanced: Anonymous Type

Note that you do not need to define a class as usual, you can do all of that inline:

``````Thread t = new Thread(new Runnable() {
public void run() {
// stuff here
}
});
t.start();
``````

This is similar to the above, only you don't create another named class.

### Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio

The bitmap constructor has resizing built in.

``````Bitmap original = (Bitmap)Image.FromFile("DSC_0002.jpg");
Bitmap resized = new Bitmap(original,new Size(original.Width/4,original.Height/4));
resized.Save("DSC_0002_thumb.jpg");
``````

http://msdn.microsoft.com/en-us/library/0wh0045z.aspx

If you want control over interpolation modes see this post.

### What are the Differences Between "php artisan dump-autoload" and "composer dump-autoload"?

Laravel's Autoload is a bit different:

1) It will in fact use Composer for some stuff

2) It will call Composer with the optimize flag

3) It will 'recompile' loads of files creating the huge bootstrap/compiled.php

4) And also will find all of your Workbench packages and composer dump-autoload them, one by one.

### Throughput and bandwidth difference?

Bandwidth is the maximum amount of data that can travel through a 'channel'.

Throughput is how much data actually does travel through the 'channel' successfully. This can be limited by a ton of different things including latency, and what protocol you are using.

### How to make primary key as autoincrement for Room Persistence lib

You can add `@PrimaryKey(autoGenerate = true)` like this:

``````@Entity
data class Food(
var foodName: String,
var foodDesc: String,
var protein: Double,
var carbs: Double,
var fat: Double
){
@PrimaryKey(autoGenerate = true)
var foodId: Int = 0 // or foodId: Int? = null
var calories: Double = 0.toDouble()
}
``````

### What does --net=host option in Docker command really do?

1. you can create your own new network like --net="anyname"
2. this is done to isolate the services from different container.
3. suppose the same service are running in different containers, but the port mapping remains same, the first container starts well , but the same service from second container will fail. so to avoid this, either change the port mappings or create a network.

### Best practices for Storyboard login screen, handling clearing of data upon logout

To update @iAleksandr answer for Xcode 11, which causes problems due to Scene kit.

1. Replace
``````let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = rootViewController
``````

With

guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,let sceneDelegate = windowScene.delegate as? SceneDelegate else { return
} sceneDelegate.window?.rootViewController = rootViewController

1. call the Switcher.updateRootViewcontroller in Scene delegate rather than App delegate like this:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

``````Switcher.updateRootViewController()
``````

guard let _ = (scene as? UIWindowScene) else { return }
}

### How can I generate an ObjectId with mongoose?

You can create a new MongoDB `ObjectId` like this using mongoose:

``````var mongoose = require('mongoose');
var newId = new mongoose.mongo.ObjectId('56cb91bdc3464f14678934ca');
// or leave the id string blank to generate an id with a new hex identifier
var newId2 = new mongoose.mongo.ObjectId();
``````

### document.getElementById().value and document.getElementById().checked not working for IE

Have a look at jQuery, a cross-browser library that will make your life a lot easier.

``````var msg = 'abc';
\$('#msg').val(msg);
\$('#sp_100').attr('checked', 'checked');
``````

### How to fix: "No suitable driver found for jdbc:mysql://localhost/dbname" error when using pools?

I had the same problem using Tomcat7 with mysql-connector-java-5.1.26 that I put in both my \$CATALINA_HOME/lib and WEB-INF/lib, just in case. But it wouldn't find it until I used either one of these two statements before getting the connection:

`DriverManager.registerDriver(new com.mysql.jdbc.Driver ());`

OR

`Class.forName("com.mysql.jdbc.Driver");`

I then followed up with removing mysql-connector-java-5.1.26 from \$CATALINA_HOME/lib and the connection still works.

### Android EditText Max Length

If you used `maxLength = 6` , some times what you are entering those characters are added in top of the keyboard called suggestions. So when you deleting entered letters that time it will delete suggestions first and then actual text inside `EditText`. For that you need to remove the suggestions.just add

``````android:inputType="textNoSuggestions"`
``````

or

``````android:inputType="textFilter"
``````

It will remove those suggestions.

### Rollback one specific migration in Laravel

#### Laravel 5.3+

Rollback one step. Natively.

``````php artisan migrate:rollback --step=1
``````

And here's the manual page: docs.

#### Laravel 5.2 and before

No way to do without some hassle. For details, check Martin Bean's answer.

### How can I extract substrings from a string in Perl?

This just requires a small change to my last answer:

``````my (\$guid, \$scheme, \$star) = \$line =~ m{
The [ ] Scheme [ ] GUID: [ ]
([a-zA-Z0-9-]+)          #capture the guid
[ ]
\(  (.+)  \)             #capture the scheme
(?:
[ ]
([*])                #capture the star
)?                       #if it exists
}x;
``````

### Take a char input from the Scanner

There are three ways to approach this problem:

• Call `next()` on the Scanner, and extract the first character of the String (e.g. `charAt(0)`) If you want to read the rest of the line as characters, iterate over the remaining characters in the String. Other answers have this code.

• Use `setDelimiter("")` to set the delimiter to an empty string. This will cause `next()` to tokenize into strings that are exactly one character long. So then you can repeatedly call `next().charAt(0)` to iterate the characters. You can then set the delimiter to its original value and resume scanning in the normal way!

• Use the Reader API instead of the Scanner API. The `Reader.read()` method delivers a single character read from the input stream. For example:

``````Reader reader = new InputStreamReader(System.in);
if (ch != -1) {  // check for EOF
// we have a character ...
}
``````

When you read from the console via `System.in`, the input is typically buffered by the operating system, and only "released" to the application when the user types ENTER. So if you intend your application to respond to individual keyboard strokes, this is not going to work. You would need to do some OS-specific native code stuff to turn off or work around line-buffering for console at the OS level.

Reference:

### WooCommerce: Finding the products in database

The following tables are store WooCommerce products database :

• wp_posts -

The core of the WordPress data is the posts. It is stored a `post_type` like product or `variable_product`.

• wp_postmeta-

Each post features information called the meta data and it is stored in the wp_postmeta. Some plugins may add their own information to this table like WooCommerce plugin store `product_id` of product in wp_postmeta table.

Product categories, subcategories stored in this table :

• wp_terms
• wp_termmeta
• wp_term_taxonomy
• wp_term_relationships
• wp_woocommerce_termmeta

following Query Return a list of product categories

``````SELECT wp_terms.*
FROM wp_terms
LEFT JOIN wp_term_taxonomy ON wp_terms.term_id = wp_term_taxonomy.term_id
WHERE wp_term_taxonomy.taxonomy = 'product_cat';
``````

for more reference -

### Creating multiple log files of different content with log4j

I had this question, but with a twist - I was trying to log different content to different files. I had information for a LowLevel debug log, and a HighLevel user log. I wanted the LowLevel to go to only one file, and the HighLevel to go to both a file, and a syslogd.

My solution was to configure the 3 appenders, and then setup the logging like this:

``````log4j.threshold=ALL
log4j.rootLogger=,LowLogger

log4j.logger.HighLevel=ALL,Syslog,HighLogger
``````

The part that was difficult for me to figure out was that the 'log4j.logger' could have multiple appenders listed. I was trying to do it one line at a time.

Hope this helps someone at some point!

### What is the correct way to read a serial port using .NET framework?

``````    using System;
using System.IO.Ports;

{
{
static void Main(string[] args)
{
SerialPort port = new SerialPort("COM6", 115200, Parity.None, 8, StopBits.One);
port.Open();
while(true){
}

}
}
}
``````

### jQuery’s .bind() vs. .on()

Internally, `.bind` maps directly to `.on` in the current version of jQuery. (The same goes for `.live`.) So there is a tiny but practically insignificant performance hit if you use `.bind` instead.

However, `.bind` may be removed from future versions at any time. There is no reason to keep using `.bind` and every reason to prefer `.on` instead.

### Pointers in Python?

``````>> id(1)
1923344848  # identity of the location in memory where 1 is stored
>> id(1)
1923344848  # always the same
>> a = 1
>> b = a  # or equivalently b = 1, because 1 is immutable
>> id(a)
1923344848
>> id(b)  # equal to id(a)
1923344848
``````

As you can see `a` and `b` are just two different names that reference to the same immutable object (int) `1`. If later you write `a = 2`, you reassign the name `a` to a different object (int) `2`, but the `b` continues referencing to `1`:

``````>> id(2)
1923344880
>> a = 2
>> id(a)
1923344880  # equal to id(2)
>> b
1           # b hasn't changed
>> id(b)
1923344848  # equal to id(1)
``````

What would happen if you had a mutable object instead, such as a list `[1]`?

``````>> id([1])
328817608
>> id([1])
328664968  # different from the previous id, because each time a new list is created
>> a = [1]
>> id(a)
328817800
>> id(a)
328817800 # now same as before
>> b = a
>> id(b)
328817800  # same as id(a)
``````

Again, we are referencing to the same object (list) `[1]` by two different names `a` and `b`. However now we can mutate this list while it remains the same object, and `a`, `b` will both continue referencing to it

``````>> a[0] = 2
>> a
[2]
>> b
[2]
>> id(a)
328817800  # same as before
>> id(b)
328817800  # same as before
``````