# Programs & Examples On #Sparse matrix

A sparse matrix is a data structure in which not every entry is explicitly represented. Related are sparse matrix algorithms and data structures, along with questions about implementation and analyses.

### How to transform numpy.matrix or array to scipy sparse matrix

There are several sparse matrix classes in scipy.

bsr_matrix(arg1[, shape, dtype, copy, blocksize]) Block Sparse Row matrix
coo_matrix(arg1[, shape, dtype, copy]) A sparse matrix in COOrdinate format.
csc_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Column matrix
csr_matrix(arg1[, shape, dtype, copy]) Compressed Sparse Row matrix
dia_matrix(arg1[, shape, dtype, copy]) Sparse matrix with DIAgonal storage
dok_matrix(arg1[, shape, dtype, copy]) Dictionary Of Keys based sparse matrix.
lil_matrix(arg1[, shape, dtype, copy]) Row-based linked list sparse matrix

Any of them can do the conversion.

import numpy as np
from scipy import sparse
a=np.array([[1,0,1],[0,0,1]])
b=sparse.csr_matrix(a)
print(b)

(0, 0)  1
(0, 2)  1
(1, 2)  1

### pycharm running way slow

In my case, the problem was a folder in the project directory containing 300k+ files totaling 11Gb. This was just a temporary folder with images results of some computation. After moving this folder out of the project structure, the slowness disappeared. I hope this can help someone, please check your project structure to see if there is anything that is not necessary.

### Cannot ping AWS EC2 instance

If you want to enable ping (from anywhere) programmatically, via the SDK, the magic formula is:

cidrIp:     "0.0.0.0/0"
ipProtocol: "icmp"
toPort:     -1
fromPort:   8

For example, in Scala (using the AWS Java SDK v2), the following works to define an IpPermission for the authorizeSecurityGroupIngress endpoint.

val PingPermission = {
val range = IpRange.builder().cidrIp( "0.0.0.0/0" ).build()
IpPermission.builder().ipProtocol( "icmp" ).ipRanges( range ).toPort( -1 ).fromPort( 8 ).build()
}

(I've tried this is only on EC2-Classic. I don't know what egress rules might be necessary under a VPC)

### How to change the height of a div dynamically based on another div using css?

<!DOCTYPE html>
<html lang="en">
<!-- Here is the Pakka codes for making the height of a division equal to another dynamically - M C Jain, Chartered Accountant -->

<script language="javascript">
function make_equal_heights()
{

if ((document.getElementById('div_A').offsetHeight) > (document.getElementById('div_B').offsetHeight) )
{
document.getElementById('div_B').style.height = (document.getElementById('div_A').offsetHeight) + "px";
}
else
{
document.getElementById('div_A').style.height = (document.getElementById('div_B').offsetHeight) + "px"
}

}
</script>

<div  id="div_A"  style="height:200px; width:150px; margin-top:22px;
background-color:lightblue;float:left;">DIVISION A</div><br>

<div  id="div_B"  style="height:150px; width:150px; margin-left:12px;
background-color: blue; float:left; ">DIVISION B</div>

</body>
</html>

### Search a text file and print related lines in Python?

searchfile = open("file.txt", "r")
for line in searchfile:
if "searchphrase" in line: print line
searchfile.close()

To print out multiple lines (in a simple way)

f = open("file.txt", "r")
f.close()
for i, line in enumerate(searchlines):
if "searchphrase" in line:
for l in searchlines[i:i+3]: print l,
print

The comma in print l, prevents extra spaces from appearing in the output; the trailing print statement demarcates results from different lines.

Or better yet (stealing back from Mark Ransom):

with open("file.txt", "r") as f:
for i, line in enumerate(searchlines):
if "searchphrase" in line:
for l in searchlines[i:i+3]: print l,
print

### Razor view engine - How can I add Partial Views

If you don't want to duplicate code, and like me you just want to show stats, in your view model, you could just pass in the models you want to get data from like so:

public class GameViewModel
{
public virtual Ship Ship { get; set; }
public virtual GamePlayer GamePlayer { get; set; }
}

Then, in your controller just run your queries on the respective models, pass them to the view model and return it, example:

GameViewModel PlayerStats = new GameViewModel();

GamePlayer currentPlayer = (from c in db.GamePlayer [more queries]).FirstOrDefault();

[code to check if results]

//pass current player into custom view model
PlayerStats.GamePlayer = currentPlayer;

Like I said, you should only really do this if you want to display stats from the relevant tables, and there's no other part of the CRUD process happening, for security reasons other people have mentioned above.

### Regular expression - starting and ending with a character string

This should do it for you ^wp.*php\$

Matches

wp.something.php
wp.php

Doesn't match

something-wp.php
wp.php.txt

### How can I clear the Scanner buffer in Java?

Try this:

in.nextLine();

This advances the Scanner to the next line.

### How to get the date from jQuery UI datepicker

NamingException's answer worked for me. Except I used

var date = \$("#date").dtpicker({ dateFormat: 'dd,MM,yyyy' }).val()

datepicker didn't work but dtpicker did.

### Find which rows have different values for a given column in Teradata SQL

Join the table with itself and give it two different aliases (A and B in the following example). This allows to compare different rows of the same table.

SELECT DISTINCT A.Id
FROM
WHERE

The "less than" comparison < ensures that you get 2 different addresses and you don't get the same 2 address codes twice. Using "not equal" <> instead, would yield the codes as (1, 2) and (2, 1); each one of them for the A alias and the B alias in turn.

The join clause is responsible for the pairing of the rows where as the where-clause tests additional conditions.

The query above works with any address codes. If you want to compare addresses with specific address codes, you can change the query to

SELECT A.Id
FROM
ON A.Id = B.Id
WHERE

I imagine that this might be useful to find customers having a billing address (Adress Code = 1 as an example) differing from the delivery address (Adress Code = 2) .

### How do you create a Swift Date object?

Here's how I did it in Swift 4.2:

extension Date {

/// Create a date from specified parameters
///
/// - Parameters:
///   - year: The desired year
///   - month: The desired month
///   - day: The desired day
/// - Returns: A `Date` object
static func from(year: Int, month: Int, day: Int) -> Date? {
let calendar = Calendar(identifier: .gregorian)
var dateComponents = DateComponents()
dateComponents.year = year
dateComponents.month = month
dateComponents.day = day
return calendar.date(from: dateComponents) ?? nil
}
}

Usage:

let marsOpportunityLaunchDate = Date.from(year: 2003, month: 07, day: 07)

### Elegant way to check for missing packages and install them?

Almost all the answers here rely on either (1) require() or (2) installed.packages() to check if a given package is already installed or not.

• require has the side effect of loading the package's namespace, which may not always be desirable
• installed.packages is a bazooka to light a candle -- it will check the universe of installed packages first, then we check if our one (or few) package(s) are "in stock" at this library. No need to build a haystack just to find a needle.

This answer was also inspired by @ArtemKlevtsov's great answer in a similar spirit on a duplicated version of this question. He noted that system.file(package=x) can have the desired affect of returning '' if the package isn't installed, and something with nchar > 1 otherwise.

If we look under the hood of how system.file accomplishes this, we can see it uses a different base function, find.package, which we could use directly:

# a package that exists
find.package('data.table', quiet=TRUE)
# [1] "/Library/Frameworks/R.framework/Versions/4.0/Resources/library/data.table"

# a package that does not
find.package('InstantaneousWorldPeace', quiet=TRUE)
# character(0)

We can also look under the hood at find.package to see how it works, but this is mainly an instructive exercise -- the only ways to slim down the function that I see would be to skip some robustness checks. But the basic idea is: look in .libPaths() -- any installed package pkg will have a DESCRIPTION file at file.path(.libPaths(), pkg), so a quick-and-dirty check is file.exists(file.path(.libPaths(), pkg, 'DESCRIPTION').

### Create a simple 10 second countdown

JavaScript has built in to it a function called setInterval, which takes two arguments - a function, callback and an integer, timeout. When called, setInterval will call the function you give it every timeout milliseconds.

For example, if you wanted to make an alert window every 500 milliseconds, you could do something like this.

};

However, you don't have to name your function or declare it separately. Instead, you could define your function inline, like this.

Once setInterval is called, it will run until you call clearInterval on the return value. This means that the previous example would just run infinitely. We can put all of this information together to make a progress bar that will update every second and after 10 seconds, stop updating.

_x000D_
_x000D_
var timeleft = 10;_x000D_
if(timeleft <= 0){_x000D_
}_x000D_
document.getElementById("progressBar").value = 10 - timeleft;_x000D_
timeleft -= 1;_x000D_
}, 1000);
_x000D_
<progress value="0" max="10" id="progressBar"></progress>
_x000D_
_x000D_
_x000D_

Alternatively, this will create a text countdown.

_x000D_
_x000D_
var timeleft = 10;_x000D_
if(timeleft <= 0){_x000D_
document.getElementById("countdown").innerHTML = "Finished";_x000D_
} else {_x000D_
document.getElementById("countdown").innerHTML = timeleft + " seconds remaining";_x000D_
}_x000D_
timeleft -= 1;_x000D_
}, 1000);
_x000D_
<div id="countdown"></div>
_x000D_
_x000D_
_x000D_

### The database cannot be opened because it is version 782. This server supports version 706 and earlier. A downgrade path is not supported

For me using solution provided by codedom did not worked. Here we can only changed compatibility version of exiting database.

But actual problem lies that, internal database version which do not matches due to changes in there storage format.

Check out more details about SQL Server version and their internal db version & Db compatibility level here So it would be good if you create your database using SQL Server 2012 Express version or below. Or start using Visual Studio 2015 Preview.

### size of struct in C

Aligning to 6 bytes is not weird, because it is aligning to addresses multiple to 4.

So basically you have 34 bytes in your structure and the next structure should be placed on the address, that is multiple to 4. The closest value after 34 is 36. And this padding area counts into the size of the structure.

### Passing struct to function

The line function implementation should be:

}

person is not a type but a variable, you cannot use it as the type of a function parameter.

Also, make sure your struct is defined before the prototype of the function addStudent as the prototype uses it.

### Where can I get a list of Ansible pre-defined variables?

There are 3 sources of variables in Ansible:

1. Variables gathered from facts. You can get them by running command: ansible -m setup hostname

2. Built-in (pre-defined) Ansible variables (AKA 'magic' variables). They are documented in Ansible documentation: http://docs.ansible.com/playbooks_variables.html#magic-variables-and-how-to-access-information-about-other-hosts
Here is the list extracted from Ansible 1.9 documentation:

• group_names
• groups
• inventory_hostname
• ansible_hostname
• inventory_hostname_short
• play_hosts
• delegate_to
• inventory_dir
• inventory_file
3. Variables passed to ansible via command line. But obviously you know what they are

### Is it possible to get multiple values from a subquery?

you can use cross apply:

select
a.x,
bb.y,
bb.z
from
a
cross apply
(   select b.y, b.z
from b
where b.v = a.v
) bb

If there will be no row from b to mach row from a then cross apply wont return row. If you need such a rows then use outer apply

If you need to find only one specific row for each of row from a, try:

cross apply
(   select top 1 b.y, b.z
from b
where b.v = a.v
order by b.order
) bb

### typeof operator in C

It's a GNU extension. In a nutshell it's a convenient way to declare an object having the same type as another. For example:

int x;         /* Plain old int variable. */
typeof(x) y;   /* Same type as x. Plain old int variable. */

It works entirely at compile-time and it's primarily used in macros. One famous example of macro relying on typeof is container_of.

### Create a custom View by inflating a layout?

In practice, I have found that you need to be a bit careful, especially if you are using a bit of xml repeatedly. Suppose, for example, that you have a table that you wish to create a table row for each entry in a list. You've set up some xml:

In my_table_row.xml:

<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" android:id="@+id/myTableRow">
<TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="TextView" android:id="@+id/rowText"></TextView>
</TableRow>

Then you want to create it once per row with some code. It assume that you have defined a parent TableLayout myTable to attach the Rows to.

for (int i=0; i<numRows; i++) {
/*
* 1. Make the row and attach it to myTable. For some reason this doesn't seem
* to return the TableRow as you might expect from the xml, so you need to
* receive the View it returns and then find the TableRow and other items, as
* per step 2.
*/
LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v =  inflater.inflate(R.layout.my_table_row, myTable, true);

// 2. Get all the things that we need to refer to to alter in any way.
TableRow    tr        = (TableRow)    v.findViewById(R.id.profileTableRow);
ImageButton rowButton = (ImageButton) v.findViewById(R.id.rowButton);
TextView    rowText   = (TextView)    v.findViewById(R.id.rowText);

// 3. Configure them out as you need to
rowText.setText("Text for this row");
rowButton.setId(i); // So that when it is clicked we know which one has been clicked!
rowButton.setOnClickListener(this); // See note below ...

/*
* To ensure that when finding views by id on the next time round this
* loop (or later) gie lots of spurious, unique, ids.
*/
rowText.setId(1000+i);
tr.setId(3000+i);
}

For a clear simple example on handling rowButton.setOnClickListener(this), see Onclicklistener for a programatically created button.

### Array functions in jQuery

The Visual jQuery site has some great examples of jQuery's array functionality. (Click "Utilities" on the left-hand tab, and then "Array and Object operations".)

### How to find out the number of CPUs using python

These give you the hyperthreaded CPU count

1. multiprocessing.cpu_count()
2. os.cpu_count()

These give you the virtual machine CPU count

1. psutil.cpu_count()
2. numexpr.detect_number_of_cores()

Only matters if you works on VMs.

### Where do you include the jQuery library from? Google JSAPI? CDN?

Without a doubt I choose to have JQuery served by Google API servers. I didn't go with the jsapi method since I don't leverage any other Google API's, however if that ever changed then I would consider it...

First: The Google api servers are distributed across the world instead of my single server location: Closer servers usually means faster response times for the visitor.

Second: Many people choose to have JQuery hosted on Google, so when a visitor comes to my site they may already have the JQuery script in their local cache. Pre-cached content usually means faster load times for the visitor.

Third: My web hosting company charges me for the bandwidth used. No sense consuming 18k per user session if the visitor can get the same file elsewhere.

I understand that I place a portion of trust on Google to serve the correct script file, and to be online and available. Up to this point I haven't been disappointed with using Google and will continue this configuration until it makes sense not to.

One thing worth pointing out... If you have a mixture of secure and insecure pages on your site you might want to dynamically change the Google source to avoid the usual warning you see when loading insecure content in a secure page:

Here's what I came up with:

<script type="text/javascript">
document.write([
"\<script src='",
("https:" == document.location.protocol) ? "https://" : "http://",
].join(''));
</script>

UPDATE 9/8/2010 - Some suggestions have been made to reduce the complexity of the code by removing the HTTP and HTTPS and simply use the following syntax:

<script type="text/javascript">
</script>

In addition you could also change the url to reflect the jQuery major number if you wanted to make sure that the latest Major version of the jQuery libraries were loaded:

<script type="text/javascript">
</script>

Finally, if you don't want to use Google and would prefer jQuery you could use the following source path (keep in mind that jQuery doesn't support SSL connections):

<script type="text/javascript">
document.write("\<script src='http://code.jquery.com/jquery-latest.min.js' type='text/javascript'>\<\/script>");
</script>

### Scrolling to an Anchor using Transition/CSS3

Only mozilla implements a simple property in css : http://caniuse.com/#search=scroll-behavior

you will have to use JS at least.

I personally use this because its easy to use (I use JQ but you can adapt it I guess):

/*Scroll transition to anchor*/
\$("a.toscroll").on('click',function(e) {
var url = e.target.href;
var hash = url.substring(url.indexOf("#")+1);
\$('html, body').animate({
scrollTop: \$('#'+hash).offset().top
}, 500);
return false;
});

### PHP Warning Permission denied (13) on session_start()

You don't appear to have write permission to the /tmp directory on your server. This is a bit weird, but you can work around it. Before the call to session_start() put in a call to session_save_path() and give it the name of a directory writable by the server. Details are here.

### Evaluate empty or null JSTL c tags

You can use

\${var == null}

alternatively.

### How can I call a shell command in my Perl script?

From Perl HowTo, the most common ways to execute external commands from Perl are:

• my \$files = `ls -la` — captures the output of the command in \$files
• system "touch ~/foo" — if you don't want to capture the command's output
• exec "vim ~/foo" — if you don't want to return to the script after executing the command
• open(my \$file, '|-', "grep foo"); print \$file "foo\nbar" — if you want to pipe input into the command

### Selenium and xpath: finding a div with a class/id and verifying text inside

To verify this:-

<div class="Caption">
Model saved
</div>

Write this -

//div[contains(@class, 'Caption') and text()='Model saved']

And to verify this:-

<div id="alertLabel" class="gwt-HTML sfnStandardLeftMargin sfnStandardRightMargin sfnStandardTopMargin">
Save to server successful
</div>

Write this -

//div[@id='alertLabel' and text()='Save to server successful']

### Is there an exponent operator in C#?

There is a blog post on MSDN about why an exponent operator does NOT exists from the C# team.

It would be possible to add a power operator to the language, but performing this operation is a fairly rare thing to do in most programs, and it doesn't seem justified to add an operator when calling Math.Pow() is simple.

Do I have to write a loop or include another namespace to handle exponential operations? If so, how do I handle exponential operations using non-integers?

Math.Pow supports double parameters so there is no need for you to write your own.

### oracle varchar to number

You have to use the TO_NUMBER function:

select * from exception where exception_value = to_number('105')

### How to get/generate the create statement for an existing hive table?

Steps to generate Create table DDLs for all the tables in the Hive database and export into text file to run later:

step 1)
create a .sh file with the below content, say hive_table_ddl.sh

#!/bin/bash
rm -f tableNames.txt
rm -f HiveTableDDL.txt
hive -e "use \$1; show tables;" > tableNames.txt
wait
do
hive -e "use \$1;show create table \$LINE;" >>HiveTableDDL.txt
echo  -e "\n" >> HiveTableDDL.txt
done
rm -f tableNames.txt
echo "Table DDL generated"

step 2)

Run the above shell script by passing 'db name' as paramanter

>bash hive_table_dd.sh <<databasename>>

output :

All the create table statements of your DB will be written into the HiveTableDDL.txt

### How do you reindex an array in PHP but with indexes starting from 1?

\$tmp = array();
foreach (array_values(\$array) as \$key => \$value) {
\$tmp[\$key+1] = \$value;
}
\$array = \$tmp;

### HTML: How to make a submit button with text + image in it?

Here is an other example:

<button type="submit" name="submit" style="border: none; background-color: white">

### git with IntelliJ IDEA: Could not read from remote repository

1. Go to Settings->Git->Select Native in SSH executable dropdown. (If it is not selected)
3. Go to VCS->Git->Remotes..
4. Edit the origin and Paste HTTPS link in the URL field.
5. Press Ctrl+Shift+k and push the project to repository. It works.

### Where to find the complete definition of off_t type?

As the "GNU C Library Reference Manual" says

off_t
This is a signed integer type used to represent file sizes.
In the GNU C Library, this type is no narrower than int.
If the source is compiled with _FILE_OFFSET_BITS == 64 this
type is transparently replaced by off64_t.

and

off64_t
This type is used similar to off_t. The difference is that
even on 32 bit machines, where the off_t type would have 32 bits,
off64_t has 64 bits and so is able to address files up to 2^63 bytes
in length. When compiling with _FILE_OFFSET_BITS == 64 this type
is available under the name off_t.

Thus if you want reliable way of representing file size between client and server, you can:

1. Use off64_t type and stat64() function accordingly (as it fills structure stat64, which contains off64_t type itself). Type off64_t guaranties the same size on 32 and 64 bit machines.
2. As was mentioned before compile your code with -D_FILE_OFFSET_BITS == 64 and use usual off_t and stat().
3. Convert off_t to type int64_t with fixed size (C99 standard). Note: (my book 'C in a Nutshell' says that it is C99 standard, but optional in implementation). The newest C11 standard says:
7.20.1.1 Exact-width integer types

1 The typedef name intN_t designates a signed integer type with width N ,
no padding bits, and a two’s complement representation. Thus, int8_t
denotes such a signed integer type with a width of exactly 8 bits.
without mentioning.

7.20 Integer types <stdint.h>

... An implementation shall provide those types described as ‘‘required’’,
but need not provide any of the others (described as ‘‘optional’’).
...
The following types are required:
int_least8_t  uint_least8_t
int_least16_t uint_least16_t
int_least32_t uint_least32_t
int_least64_t uint_least64_t
All other types of this form are optional.

Thus, in general, C standard can't guarantee types with fixed sizes. But most compilers (including gcc) support this feature.

### MVC 4 - how do I pass model data to a partial view?

Also, this could make it works:

@{
}

or

@{
}

### Difference between MongoDB and Mongoose

I assume you already know that MongoDB is a NoSQL database system which stores data in the form of BSON documents. Your question, however is about the packages for Node.js.

In terms of Node.js, mongodb is the native driver for interacting with a mongodb instance and mongoose is an Object modeling tool for MongoDB.

Mongoose is built on top of the MongoDB driver to provide programmers with a way to model their data.

EDIT: I do not want to comment on which is better, as this would make this answer opinionated. However I will list some advantages and disadvantages of using both approaches.

Using Mongoose, a user can define the schema for the documents in a particular collection. It provides a lot of convenience in the creation and management of data in MongoDB. On the downside, learning mongoose can take some time, and has some limitations in handling schemas that are quite complex.

However, if your collection schema is unpredictable, or you want a Mongo-shell like experience inside Node.js, then go ahead and use the MongoDB driver. It is the simplest to pick up. The downside here is that you will have to write larger amounts of code for validating the data, and the risk of errors is higher.

### PHP/MySQL insert row then get 'id'

An example.

\$query_new = "INSERT INTO students(courseid, coursename) VALUES ('', ?)";
\$query_new = \$databaseConnection->prepare(\$query_new);
\$query_new->bind_param('s', \$_POST['coursename']);
\$query_new->execute();
\$course_id = \$query_new->insert_id;
\$query_new->close();

The code line \$course_id = \$query_new->insert_id; will display the ID of the last inserted row. Hope this helps.

### iPhone SDK:How do you play video inside a view? Rather than fullscreen

NSString * pathv = [[NSBundle mainBundle] pathForResource:@"vfile" ofType:@"mov"];
playerv = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:pathv]];

[self presentMoviePlayerViewControllerAnimated:playerv];

### .Contains() on a list of custom class objects

You need to create a object from your list like:

List<CartProduct> lst = new List<CartProduct>();

CartProduct obj = lst.Find(x => (x.Name == "product name"));

That object get the looked value searching by their properties: x.name

Then you can use List methods like Contains or Remove

if (lst.Contains(obj))
{
lst.Remove(obj);
}

### How do I list the symbols in a .so file

For shared libraries libNAME.so the -D switch was necessary to see symbols in my Linux

nm -D libNAME.so

and for static library as reported by others

nm -g libNAME.a

### "Could not find a valid gem in any repository" (rubygame and others)

ruby -v
#=> ruby 1.9.3p125 (2012-02-16 revision 34643) [x86_64-linux]

gem -v
#=> 1.8.19

If your gem command is not current, you can update it like this:

gem update --system

To see if you can connect to rubygems.org using Ruby:

require 'net/http'
require 'uri'
puts Net::HTTP.get URI.parse('https://rubygems.org')

If yes, that's good.

If no, then somehow Ruby is blocked from opening a net connection. Try these and see if any of them work:

curl https://rubygems.org

curl https://rubygems.org --local-port 1080

curl https://rubygems.org --local-port 8080

env | grep -i proxy

If you're using a company machine, or within a company firewall, or running your own firewall, you may need to use a proxy.

For info on Ruby and proxies see http://www.linux-support.com/cms/http-proxies-and-ruby/

### JavaScript and getElementById for multiple elements with the same ID

The HTML spec required the ID attribute to be unique in a page:

This attribute assigns a name to an element. This name must be unique in a document.

If you have several elements with the same ID, your HTML is not valid.

So, getElementById() should only ever return one element. You can't make it return multiple elements.

There are a couple of related functions that will return an array of elements - getElementsByName, or getElementsByClassName that may be more suited to your requirements, though getElementsByClassName is new to HTML 5, which is still in draft.

### finding the type of an element using jQuery

You can use .prop() with tagName as the name of the property that you want to get:

\$("#elementId").prop('tagName');

CAUTION: This method completely removes MySQL data!

I have same problem in Ubuntu 12.10 , mysql 5.5

I have tested lots of answer related to my issue but none of theme work

at last I had to reinstall remove my mysql server completely and then I install again Mysql server

but you should be aware that you should delete all directory which related to Mysql I use this link to remove mysql completely

sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean
sudo deluser mysql
sudo rm -rf /var/lib/mysql
sudo rm -rf /etc/mysql
sudo rm -rf /var/lib/mysql
sudo rm -rf /var/run/mysqld

and then you install again LAMP by tasksel

Removing MySQL 5.5 Completely

https://serverfault.com/questions/254629/unable-to-install-mysql-server-in-ubuntu/296928#296928

### MySql export schema without data

Dumping without using output.

mysqldump --no-data <database name> --result-file=schema.sql

### Hashing a string with Sha256

Encoding.Unicode is Microsoft's misleading name for UTF-16 (a double-wide encoding, used in the Windows world for historical reasons but not used by anyone else). http://msdn.microsoft.com/en-us/library/system.text.encoding.unicode.aspx

If you inspect your bytes array, you'll see that every second byte is 0x00 (because of the double-wide encoding).

You should be using Encoding.UTF8.GetBytes instead.

But also, you will see different results depending on whether or not you consider the terminating '\0' byte to be part of the data you're hashing. Hashing the two bytes "Hi" will give a different result from hashing the three bytes "Hi". You'll have to decide which you want to do. (Presumably you want to do whichever one your friend's PHP code is doing.)

For ASCII text, Encoding.UTF8 will definitely be suitable. If you're aiming for perfect compatibility with your friend's code, even on non-ASCII inputs, you'd better try a few test cases with non-ASCII characters such as é and ? and see whether your results still match up. If not, you'll have to figure out what encoding your friend is really using; it might be one of the 8-bit "code pages" that used to be popular before the invention of Unicode. (Again, I think Windows is the main reason that anyone still needs to worry about "code pages".)

### oracle plsql: how to parse XML and insert into table

(xml IN CLOB)
AS
BEGIN
INSERT INTO EMPLOYEE (EMPID,EMPNAME,EMPDETAIL,CREATEDBY,CREATED)
SELECT
ExtractValue(column_value,'/ROOT/EMPID') AS EMPID
,ExtractValue(column_value,'/ROOT/EMPNAME') AS EMPNAME
,ExtractValue(column_value,'/ROOT/EMPDETAIL') AS EMPDETAIL
,ExtractValue(column_value,'/ROOT/CREATEDBY') AS CREATEDBY
,ExtractValue(column_value,'/ROOT/CREATEDDATE') AS CREATEDDATE
FROM   TABLE(XMLSequence( XMLType(xml))) XMLDUMMAY;

COMMIT;
END;

### Extract and delete all .gz in a directory- Linux

Extract all gz files in current directory and its subdirectories:

find . -name "*.gz" | xargs gunzip

### Using the slash character in Git branch name

I forgot that I had already an unused labs branch. Deleting it solved my problem:

git branch -d labs
git checkout -b labs/feature

Explanation:

Each name can only be a parent branch or a normal branch, not both. Thats why the branches labs and labs/feature can't exists both at the same time.

The reason: Branches are stored in the file system and there you also can't have a file labs and a directory labs at the same level.

### How do you refresh the MySQL configuration file without restarting?

You were so close! The kill -HUP method wasn't working for me either.

You were calling:

select @@global.max_connections;

All you needed was to set instead of select:

set @@global.max_connections = 400;

See:

http://www.electrictoolbox.com/update-max-connections-mysql/

### What is Dependency Injection?

Any nontrivial application is made up of two or more classes that collaborate with each other to perform some business logic. Traditionally, each object is responsible for obtaining its own references to the objects it collaborates with (its dependencies). When applying DI, the objects are given their dependencies at creation time by some external entity that coordinates each object in the system. In other words, dependencies are injected into objects.

### pandas: filter rows of DataFrame with operator chaining

The answer from @lodagro is great. I would extend it by generalizing the mask function as:

return df[f(df)]

Then you can do stuff like:

### Number of regex matches

#An example for counting matched groups
import re

pattern = re.compile(r'(\w+).(\d+).(\w+).(\w+)', re.IGNORECASE)
search_str = "My 11 Char String"

res = re.match(pattern, search_str)
print(len(res.groups())) # len = 4
print (res.group(1) ) #My
print (res.group(2) ) #11
print (res.group(3) ) #Char
print (res.group(4) ) #String

### MVC 4 Data Annotations "Display" Attribute

If two different views are sharing the same model (for instance, maybe one is for mobile output and one is regular), it could be nice to have the string reside in a single place: as metadata on the ViewModel.

Additionally, if you had an inherited version of the model that necessitated a different display, it could be useful. For instance:

public class BaseViewModel
{
[Display(Name = "Basic Name")]
public virtual string Name { get; set; }
}

public class OtherViewModel : BaseViewModel
{
[Display(Name = "Customized Inherited Name")]
public override string Name { get; set; }
}

I'll admit that that example is pretty contrived...

Those are the best arguments in favor of using the attribute that I can come up with. My personal opinion is that, for the most part, that sort of thing is best left to the markup.

### Why use Select Top 100 Percent?

I would suppose that you can use a variable in the result, but aside from getting the ORDER BY piece in a view, you will not see a benefit by implicitly stating "TOP 100 PERCENT":

declare @t int
set @t=100
select top (@t) percent * from tableOf

### Bring element to front using CSS

Another Note: z-index must be considered when looking at children objects relative to other objects.

For example

<div class="container">
<div class="branch_1">
<div class="branch_1__child"></div>
</div>
<div class="branch_2">
<div class="branch_2__child"></div>
</div>
</div>

If you gave branch_1__child a z-index of 99 and you gave branch_2__child a z-index of 1, but you also gave your branch_2 a z-index of 10 and your branch_1 a z-index of 1, your branch_1__child still will not show up in front of your branch_2__child

Anyways, what I'm trying to say is; if a parent of an element you'd like to be placed in front has a lower z-index than its relative, that element will not be placed higher.

The z-index is relative to its containers. A z-index placed on a container farther up in the hierarchy basically starts a new "layer"

Incep[inception]tion

Here's a fiddle to play around:

https://jsfiddle.net/orkLx6o8/

### How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

As for second question - you can use Fiddler filters to set response X-Frame-Options header manually to something like ALLOW-FROM *. But, of course, this trick will work only for you - other users still won't be able to see iframe content(if they not do the same).

### Convert ASCII number to ASCII Character in C

int a = 65;
char c = a;
printf("%c", c);

In fact this will also work.

printf("%c", a);  // assuming a is in valid range

### C# Passing Function as Argument

There are a couple generic types in .Net (v2 and later) that make passing functions around as delegates very easy.

For functions with return types, there is Func<> and for functions without return types there is Action<>.

Both Func and Action can be declared to take from 0 to 4 parameters. For example, Func < double, int > takes one double as a parameter and returns an int. Action < double, double, double > takes three doubles as parameters and returns nothing (void).

So you can declare your Diff function to take a Func:

public double Diff(double x, Func<double, double> f) {
double h = 0.0000001;

return (f(x + h) - f(x)) / h;
}

And then you call it as so, simply giving it the name of the function that fits the signature of your Func or Action:

double result = Diff(myValue, Function);

You can even write the function in-line with lambda syntax:

double result = Diff(myValue, d => Math.Sqrt(d * 3.14));

### How to replace a string in an existing file in Perl?

None of the existing answers here has provided a complete example of how to do this from within a script (not a one-liner). Here is what I did:

rename(\$file, \$file.'.bak');
open(IN, '<'.\$file.'.bak') or die \$!;
open(OUT, '>'.\$file) or die \$!;
while(<IN>)
{
\$_ =~ s/blue/red/g;
print OUT \$_;
}
close(IN);
close(OUT);

### Scanner is skipping nextLine() after using next() or nextFoo()?

If you want to scan input fast without getting confused into Scanner class nextLine() method , Use Custom Input Scanner for it .

#### Code :

/**
* @author Nikunj Khokhar
*/
private byte[] buf = new byte[4 * 1024];
private int index;
private BufferedInputStream in;
private int total;

in = new BufferedInputStream(inputStream);
}

private int scan() throws IOException {
if (index >= total) {
index = 0;
if (total <= 0) return -1;
}
return buf[index++];
}
public char scanChar(){
int c=scan();
while (isWhiteSpace(c))c=scan();
return (char)c;
}

public int scanInt() throws IOException {
int integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}

public String scanString() throws IOException {
int c = scan();
while (isWhiteSpace(c)) c = scan();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = scan();
} while (!isWhiteSpace(c));
return res.toString();
}

private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}

public long scanLong() throws IOException {
long integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}

public void scanLong(long[] A) throws IOException {
for (int i = 0; i < A.length; i++) A[i] = scanLong();
}

public void scanInt(int[] A) throws IOException {
for (int i = 0; i < A.length; i++) A[i] = scanInt();
}

public double scanDouble() throws IOException {
int c = scan();
while (isWhiteSpace(c)) c = scan();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = scan();
}
double res = 0;
while (!isWhiteSpace(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, scanInt());
}
res *= 10;
res += c - '0';
c = scan();
}
if (c == '.') {
c = scan();
double m = 1;
while (!isWhiteSpace(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, scanInt());
}
m /= 10;
res += (c - '0') * m;
c = scan();
}
}
return res * sgn;
}

}

• Scans Input faster than BufferReader
• Reduces Time Complexity
• Flushes Buffer for every next input

#### Methods :

• scanChar() - scan single character
• scanInt() - scan Integer value
• scanLong() - scan Long value
• scanString() - scan String value
• scanDouble() - scan Double value
• scanInt(int[] array) - scans complete Array(Integer)
• scanLong(long[] array) - scans complete Array(Long)

#### Usage :

1. Copy the Given Code below your java code.
2. Initialise Object for Given Class

import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; 4. Throw IOException from your main method to handle Exception 5. Use Provided Methods. 6. Enjoy

#### Example :

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
class Main{
public static void main(String... as) throws IOException{
int a=sc.scanInt();
System.out.println(a);
}
}

### LPCSTR, LPCTSTR and LPTSTR

Unless you are coding for Win98, there are only two of the 6+ string types you should be using in your application

• LPWSTR
• LPCWSTR

The rest are meant to support ANSI platforms or dual compilations. Those are not as relevant today as they used to be.

### Python - Extracting and Saving Video Frames

This function extracts images from video with 1 fps, IN ADDITION it identifies the last frame and stops reading also:

import cv2
import numpy as np

def extract_image_one_fps(video_source_path):

vidcap = cv2.VideoCapture(video_source_path)
count = 0
success = True
while success:
vidcap.set(cv2.CAP_PROP_POS_MSEC,(count*1000))

## Stop when last frame is identified
if np.array_equal(image,image_last):
break

cv2.imwrite("frame%d.png" % count, image)     # save frame as PNG file
print '{}.sec reading a new frame: {} '.format(count,success)
count += 1

### How to simulate "Press any key to continue?"

In windows, this short program accomplishes the goal: getch pauses the console until a key is pressed (https://www.geeksforgeeks.org/difference-getchar-getch-getc-getche/)

#include<iostream.h>
#include<conio.h>

using namespace std;

void  check()
{
char chk; int j;
cout<<"\n\nPress any key to continue...";
chk=getch();
j=chk;
for(int i=1;i<=256;i++)
if(i==j) break;
clrscr();
}

void main()
{
clrscr();
check();
cout<<"\n\nIt works!";
getch();
}

It should be noted that getch is not part of the standard library.

### How do I get LaTeX to hyphenate a word that contains a dash?

The problem (as KennyTM noted) is that LaTeX won't hyphenate words with dashes in them. Luckily, there's a standard package (part of ncctools) that addresses that very problem, called extdash. This defines new hyphen and dash commands that do not disrupt hyphenation, and which can allow or prevent line breaks at the hyphen/dash. I prefer to use it with the shortcuts option, so I can use, e.g., \-/ rather than \Hyphdash. Here's what you want:

\usepackage[shortcuts]{extdash} ... multi\-/disciplinary

To prevent breaking at that hyphen, use multi\=/disciplinary

(Aside: The Chicago Manual of Style advises dropping the hyphens attaching affixes like 'multi', unless the word is ambiguous or unintelligible without it.)

### SVN remains in conflict?

One more solution below,

If the entire folder is removed and SVNis throwing the error "admin file .svn is missing", the following will be used to resolve the conflict to working state.

svn resolve --accept working "file / directory name "

### 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"
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"
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.

### How to encode the plus (+) symbol in a URL

It's safer to always percent-encode all characters except those defined as "unreserved" in RFC-3986.

unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"

So, percent-encode the plus character and other special characters.

The problem that you are having with pluses is because, according to RFC-1866 (HTML 2.0 specification), paragraph 8.2.1. subparagraph 1., "The form field names and values are escaped: space characters are replaced by `+', and then reserved characters are escaped"). This way of encoding form data is also given in later HTML specifications, look for relevant paragraphs about application/x-www-form-urlencoded.

### Using Gulp to Concatenate and Uglify files

we are using below configuration to do something similar

var gulp = require('gulp'),
async = require("async"),
less = require('gulp-less'),
minifyCSS = require('gulp-minify-css'),
uglify = require('gulp-uglify'),
concat = require('gulp-concat'),
gulpDS = require("./gulpDS"),
del = require('del');

// CSS & Less
var jsarr = [gulpDS.jsbundle.mobile, gulpDS.jsbundle.desktop, gulpDS.jsbundle.common];
var cssarr = [gulpDS.cssbundle];

var generateJS = function() {

jsarr.forEach(function(gulpDSObject) {
async.map(Object.keys(gulpDSObject), function(key) {
var val = gulpDSObject[key]
execGulp(val, key);
});

})
}

var generateCSS = function() {
cssarr.forEach(function(gulpDSObject) {
async.map(Object.keys(gulpDSObject), function(key) {
var val = gulpDSObject[key];
execCSSGulp(val, key);
})
})
}

var execGulp = function(arrayOfItems, dest) {
var destSplit = dest.split("/");
var file = destSplit.pop();
del.sync([dest])
gulp.src(arrayOfItems)
.pipe(concat(file))
.pipe(uglify())
.pipe(gulp.dest(destSplit.join("/")));
}

var execCSSGulp = function(arrayOfItems, dest) {
var destSplit = dest.split("/");
var file = destSplit.pop();
del.sync([dest])
gulp.src(arrayOfItems)
.pipe(less())
.pipe(concat(file))
.pipe(minifyCSS())
.pipe(gulp.dest(destSplit.join("/")));
}

sample GulpDS file is below:

{

jsbundle: {
"mobile": {
"public/javascripts/sample.min.js": ["public/javascripts/a.js", "public/javascripts/mobile/b.js"]
},
"desktop": {
'public/javascripts/sample1.js': ["public/javascripts/c.js", "public/javascripts/d.js"]},
"common": {
'public/javascripts/responsive/sample2.js': ['public/javascripts/n.js']
}
},
cssbundle: {
"public/stylesheets/a.css": "public/stylesheets/less/a.less",
}
}

### How to convert enum value to int?

A somewhat different approach (at least on Android) is to use the IntDef annotation to combine a set of int constants

@IntDef({NOTAX, SALESTAX, IMPORTEDTAX})
@interface TAX {}
int NOTAX = 0;
int SALESTAX = 10;
int IMPORTEDTAX = 5;

Use as function parameter:

void computeTax(@TAX int taxPercentage){...}

or in a variable declaration:

@TAX int currentTax = IMPORTEDTAX;

### Arithmetic overflow error converting numeric to data type numeric

check your value which you want to store in integer column. I think this is greater then range of integer. if you want to store value greater then integer range. you should use bigint datatype

### Render HTML to PDF in Django site

If you have context data along with css and js in your html template. Than you have good option to use pdfjs.

In your code you can use like this.

import pdfkit
from django.conf import settings

context={....}
template = get_template('reports/products.html')
html_string = template.render(context)
pdfkit.from_string(html_string, os.path.join(settings.BASE_DIR, "media", 'products_report-%s.pdf'%(id)))

In your HTML you can link extranal or internal css and js, it will generate best quality of pdf.

### Angular 2 Hover event

If the mouse over for all over the component is your option, you can directly is @hostListener to handle the events to perform the mouse over al below.

import {HostListener} from '@angular/core';

@HostListener('mouseenter') onMouseEnter() {
this.hover = true;
}

@HostListener('mouseleave') onMouseLeave() {
this.hover = false;
}

Its available in @angular/core. I tested it in angular 4.x.x

### Height equal to dynamic width (CSS fluid layout)

There is a way using CSS!

If you set your width depending on the parent container you can set the height to 0 and set padding-bottom to the percentage which will be calculated depending on the current width:

.some_element {
position: relative;
width: 20%;
height: 0;
}

This works well in all major browsers.

# JSFiddle: https://jsfiddle.net/ayb9nzj3/

### How do I do word Stemming or Lemmatization?

.Net lucene has an inbuilt porter stemmer. You can try that. But note that porter stemming does not consider word context when deriving the lemma. (Go through the algorithm and its implementation and you will see how it works)

### How to avoid HTTP error 429 (Too Many Requests) python

In many cases, continuing to scrape data from a website even when the server is requesting you not to is unethical. However, in the cases where it isn't, you can utilize a list of public proxies in order to scrape a website with many different IP addresses.

### How to convert HTML file to word?

just past this on head of your php page. before any code on this should be the top code.

<?php

?>

this will convert all html to MSWORD, now you can customize it according to your client requirement.

### How do I make a text input non-editable?

<input type="text" value="3" class="field left" readonly>

No styling necessary.

### <SELECT multiple> - how to allow only one item selected?

I am coming here after searching google and change thing at my-end.

So I just change this sample and it will work with jquery at run-time.

\$('select[name*="homepage_select"]').removeAttr('multiple')

http://jsfiddle.net/ajayendra2707/ejkxgy1p/5/

### Detect element content changes with jQuery

We can achieve this by using Mutation Events. According to www.w3.org, The mutation event module is designed to allow notification of any changes to the structure of a document, including attr and text modifications. For more detail MUTATION EVENTS

For Example :

\$("body").on('DOMSubtreeModified', "#content", function() {
});

### Android saving file to external storage

since android 4.4 file saving has been changed. there is

ContextCompat.getExternalFilesDirs(context, name);

it retuns an array.

when name is null

the first value is like /storage/emulated/0/Android/com.my.package/files

the second value is like /storage/extSdCard/Android/com.my.package/files

android 4.3 and less it retuns a single item array

parts of little messy code but it demonstrates how it works:

/** Create a File for saving an image or video
* @throws Exception */
private File getOutputMediaFile(int type) throws Exception{

// Check that the SDCard is mounted
File mediaStorageDir;
if(internalstorage.isChecked())
{
mediaStorageDir = new File(getFilesDir().getAbsolutePath() );
}
else
{
File[] dirs=ContextCompat.getExternalFilesDirs(this, null);
mediaStorageDir = new File(dirs[dirs.length>1?1:0].getAbsolutePath() );
}

// Create the storage directory(MyCameraVideo) if it does not exist
if (! mediaStorageDir.exists()){

if (! mediaStorageDir.mkdirs()){

output.setText("Failed to create directory.");

Toast.makeText(this, "Failed to create directory.", Toast.LENGTH_LONG).show();

Log.d("myapp", "Failed to create directory");
return null;
}
}

// Create a media file name

// For unique file name appending current timeStamp with file name
java.util.Date date= new java.util.Date();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.ENGLISH)  .format(date.getTime());

File mediaFile;

if(type == MEDIA_TYPE_VIDEO) {

// For unique video file name appending current timeStamp with file name
mediaFile = new File(mediaStorageDir.getPath() + File.separator + slpid + "_" + pwsid + "_" + timeStamp + ".mp4");

}
else if(type == MEDIA_TYPE_AUDIO) {

// For unique video file name appending current timeStamp with file name
mediaFile = new File(mediaStorageDir.getPath() + File.separator + slpid + "_" + pwsid + "_" + timeStamp + ".3gp");

} else {
return null;
}

return mediaFile;
}

/** Create a file Uri for saving an image or video
* @throws Exception */
private  Uri getOutputMediaFileUri(int type) throws Exception{

return Uri.fromFile(getOutputMediaFile(type));
}

//usage:
try {
file=getOutputMediaFileUri(MEDIA_TYPE_AUDIO).getPath();
} catch (Exception e1) {
e1.printStackTrace();
return;
}

### How to execute logic on Optional if not present?

I don't think you can do it in a single statement. Better do:

if (!obj.isPresent()) {
logger.fatal(...);
} else {
obj.get().setAvailable(true);
}
return obj;

### How to enable ASP classic in IIS7.5

I found some detailed instructions here: http://digitallibraryworld.com/?p=6

The key piece of advice seems to be, don't use the 64-bit ASP.DLL (found in system32) if you've configured the app pool to run 32-bit applications (instead, use the 32-bit ASP.DLL).

Add a script map using the following setting:

Request Path: *.asp
Executable: C:\Windows\system32\inetsrv\asp.dll
Name: whatever you want. I named my Classic ASP

The executable above is 64 BIT ASP handler for your asp script. If you want your ASP script to be handled in 32 bit environment, you need to use executable from this location: C:\Windows\SysWOW64\inetsrv\asp.dll.

Of course, if you don't need to load any 32-bit libraries (or data providers, etc.), just make your life easier by running the 64-bit ASP.DLL!

### Trigger a Travis-CI rebuild without pushing a commit?

Please make sure to Log In to Travis first. The rebuild button doesn't appear until you're logged in. I know this is obvious, but someone just tripped on it as well ;-)

### How to get the bluetooth devices as a list?

In this code you just need to call this in your button click.

private void list_paired_Devices() {
ArrayList<String> devices = new ArrayList<>();
for (BluetoothDevice bt : pairedDevices) {
}
}

### How to remove "disabled" attribute using jQuery?

This question specifically mentions jQuery, but if you are looking to accomplish this without jQuery, the equivalent in vanilla JavaScript is:

elem.removeAttribute('disabled');

### How do I correctly setup and teardown for my pytest class with tests?

import pytest
class Test:
@pytest.fixture()
def setUp(self):
print("setup")
yield "resource"
print("teardown")

def test_that_depends_on_resource(self, setUp):
print("testing {}".format(setUp))

In order to run:

pytest nam_of_the_module.py -v

### How to set image button backgroundimage for different state?

Create an xml file in your drawable like this :

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_enabled="false"
android:drawable="@drawable/btn_sendemail_disable" />
<item
android:state_pressed="true"
android:state_enabled="true"
android:drawable="@drawable/btn_send_email_click" />
<item
android:state_focused="true"
android:state_enabled="true"
android:drawable="@drawable/btn_sendemail_roll" />
<item
android:state_enabled="true"
android:drawable="@drawable/btn_sendemail" />
</selector>

And set images accordingly and then set this xml as background of your imageButton.

### How do I get a list of locked users in an Oracle database?

This suits the requirement:

select username, account_status, EXPIRY_DATE from dba_users where

Output:

--------------------------------------------------------------------------------
SYSTEM          EXPIRED                          13-NOV-17

</form>

Result html

<form>

### "RangeError: Maximum call stack size exceeded" Why?

You first need to understand Call Stack. Understanding Call stack will also give you clarity to how "function hierarchy and execution order" works in JavaScript Engine.

The call stack is primarily used for function invocation (call). Since there is only one call stack. Hence, all function(s) execution get pushed and popped one at a time, from top to bottom.

It means the call stack is synchronous. When you enter a function, an entry for that function is pushed onto the Call stack and when you exit from the function, that same entry is popped from the Call Stack. So, basically if everything is running smooth, then at the very beginning and at the end, Call Stack will be found empty.

Here is the illustration of Call Stack:

Now, if you provide too many arguments or caught inside any unhandled recursive call. You will encounter

RangeError: Maximum call stack size exceeded

which is quite obvious as explained by others.

Hope this helps !

### C++ String array sorting

Your loop does not do anything because your counter z is 0 (and 0 < 0 evaluates to false, so the loop never starts).

Instead, if you have access to C++11 (and you really should aim for that!) try to use iterators, e.g. by using the non-member function std::begin() and std::end(), and a range-for loop to display the result:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
int z = 0;
string name[] = {"john", "bobby", "dear", "test1", "catherine", "nomi", "shinta", "martin", "abe", "may", "zeno", "zack", "angeal", "gabby"};

sort(begin(name),end(name));

for(auto n: name){
cout << n << endl;
}
return 0;
}

### ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value

Interestingly:

Or if you still is not generic:

seems to solved my problem smoothly.

### Linq : select value in a datatable column

var name = from r in MyTable
where r.ID == 0
select r.Name;

If the row is unique then you could even just do:

var row = DataContext.MyTable.SingleOrDefault(r => r.ID == 0);
var name = row != null ? row.Name : String.Empty;

### iOS for VirtualBox

VirtualBox is a virtualizer, not an emulator. (The name kinda gives it away.) I.e. it can only virtualize a CPU that is actually there, not emulate one that isn't. In particular, VirtualBox can only virtualize x86 and AMD64 CPUs. iOS only runs on ARM CPUs.

### Under which circumstances textAlign property works in Flutter?

textAlign property only works when there is a more space left for the Text's content. Below are 2 examples which shows when textAlign has impact and when not.

#### No impact

For instance, in this example, it won't have any impact because there is no extra space for the content of the Text.

Text(
"Hello",
textAlign: TextAlign.end, // no impact
),

#### Has impact

If you wrap it in a Container and provide extra width such that it has more extra space.

Container(
width: 200,
color: Colors.orange,
child: Text(
"Hello",
textAlign: TextAlign.end, // has impact
),
)

### Test credit card numbers for use with PayPal sandbox

In case anyone else comes across this in a search for an answer...

The test numbers listed in various places no longer work in the Sandbox. PayPal have the same checks in place now so that a card cannot be linked to more than one account.

Go here and get a number generated. Use any expiry date and CVV

It's worked every time for me so far...

### recursively use scp but excluding some folders

Although scp supports recursive directory copying with the -r option, it does not support filtering of the files. There are several ways to accomplish your task, but I would probably rely on find, xargs, tar, and ssh instead of scp.

find . -type d -wholename '*bench*/image' \
| xargs tar cf - \
| ssh user@remote tar xf - -C /my/dir

The rsync solution can be made to work, but you are missing some arguments. rsync also needs the r switch to recurse into subdirectories. Also, if you want the same security of scp, you need to do the transfer under ssh. Something like:

rsync -avr -e "ssh -l user" --exclude 'fl_*' ./bench* remote:/my/dir

### CS1617: Invalid option ‘6’ for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default

This happened to me when I pulled down my repo after moving it to a new location. The solution was to unload and then reload each project that was showing this error.

I tried a few other options but nothing worked for me. Also in this situation my config files were set to use languageversion 6, so setting them to default did not fix the issue.

### How to send an email with Gmail as provider using Python?

Enable less secure apps on your gmail account and use (Python>=3.6):

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

gmailUser = '[email protected]'
recipient = '[email protected]'

message = f"""
"""

msg = MIMEMultipart()
msg['To'] = recipient
msg['Subject'] = "Subject here..."
msg.attach(MIMEText(message))

try:
mailServer = smtplib.SMTP('smtp.gmail.com', 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.sendmail(gmailUser, recipient, msg.as_string())
mailServer.close()
print ('Email sent!')
except:
print ('Something went wrong...')

### How to force input to only allow Alpha Letters?

If your form is PHP based, it would work this way within your " <?php \$data = array(" code:

'onkeypress' => 'return /[a-z 0-9]/i.test(event.key)',

### How to check if an object is an array?

Since I don't like any Object.prototype-calls, I searched for another solution. Especially because the solutions of ChaosPandion won't always work, and the solution of MidnightTortoise with isArray() doesn't work with arrays coming from the DOM (like getElementsByTagName). And finally I found an easy and cross-browser solution, which probably also would have worked with Netscape 4. ;)

It's just these 4 lines (checking any object h):

function isArray(h){
if((h.length!=undefined&&h[0]!=undefined)||(h.length===0&&h[0]===undefined)){
return true;
}
else{ return false; }
}

I already tested these arrays (all return true):

1) array=d.getElementsByName('some_element'); //'some_element' can be a real or unreal element
2) array=[];
3) array=[10];
4) array=new Array();
5) array=new Array();
array.push("whatever");

Can anybody confirm that this works for all cases? Or does anybody find a case where my solution don't work?

### Why are there two ways to unstage a file in Git?

git rm --cached is used to remove a file from the index. In the case where the file is already in the repo, git rm --cached will remove the file from the index, leaving it in the working directory and a commit will now remove it from the repo as well. Basically, after the commit, you would have unversioned the file and kept a local copy.

git reset HEAD file ( which by default is using the --mixed flag) is different in that in the case where the file is already in the repo, it replaces the index version of the file with the one from repo (HEAD), effectively unstaging the modifications to it.

In the case of unversioned file, it is going to unstage the entire file as the file was not there in the HEAD. In this aspect git reset HEAD file and git rm --cached are same, but they are not same ( as explained in the case of files already in the repo)

To the question of Why are there 2 ways to unstage a file in git? - there is never really only one way to do anything in git. that is the beauty of it :)

### How to debug Apache mod_rewrite

Based on Ben's answer you you could do the following when running apache on Linux (Debian in my case).

RewriteLog "/var/log/apache2/rewrite.log"
RewriteLogLevel 3

Then enter

\$ a2enmod rewrite-log

followed by

\$ service apache2 restart

And when you finished with debuging your rewrite rules

\$ a2dismod rewrite-log && service apache2 restart

### Using media breakpoints in Bootstrap 4-alpha

I answered a similar question here

As @Syden said, the mixins will work. Another option is using SASS map-get like this..

@media (min-width: map-get(\$grid-breakpoints, sm)){
.something {
}
}

@media (min-width: map-get(\$grid-breakpoints, md)){
.something {
}
}

http://www.codeply.com/go/0TU586QNlV

Bootstrap 4 Breakpoints demo

### no debugging symbols found when using gdb

The most frequent cause of "no debugging symbols found" when -g is present is that there is some "stray" -s or -S argument somewhere on the link line.

From man ld:

-s
--strip-all
Omit all symbol information from the output file.

-S
--strip-debug
Omit debugger symbol information (but not all symbols) from the output file.

### How do I convert special UTF-8 chars to their iso-8859-1 equivalent using javascript?

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

### Getting Serial Port Information

EDIT: Sorry, I zipped past your question too quick. I realize now that you're looking for a list with the port name + port description. I've updated the code accordingly...

Using System.Management, you can query for all the ports, and all the information for each port (just like Device Manager...)

Sample code (make sure to add reference to System.Management):

using System;
using System.Management;
using System.Collections.Generic;
using System.Linq;
using System.IO.Ports;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
using (var searcher = new ManagementObjectSearcher
("SELECT * FROM WIN32_SerialPort"))
{
string[] portnames = SerialPort.GetPortNames();
var ports = searcher.Get().Cast<ManagementBaseObject>().ToList();
var tList = (from n in portnames
join p in ports on n equals p["DeviceID"].ToString()
select n + " - " + p["Caption"]).ToList();

tList.ForEach(Console.WriteLine);
}

// pause program execution to review results...
Console.WriteLine("Press enter to exit");
}
}
}

### blur() vs. onblur()

I guess it's just because the onblur event is called as a result of the input losing focus, there isn't a blur action associated with an input, like there is a click action associated with a button

### %i or %d to print integer in C using printf()?

They are completely equivalent when used with printf(). Personally, I prefer %d, it's used more often (should I say "it's the idiomatic conversion specifier for int"?).

(One difference between %i and %d is that when used with scanf(), then %d always expects a decimal integer, whereas %i recognizes the 0 and 0x prefixes as octal and hexadecimal, but no sane programmer uses scanf() anyway so this should not be a concern.)

### Foreach loop in C++ equivalent of C#

Using boost is the best option as it helps you to provide a neat and concise code, but if you want to stick to STL

void listbox_add(const char* item, ListBox &lb)
{
}

int foo()
{
const char* starr[] = {"ram", "mohan", "sita"};
ListBox listBox;
std::for_each(starr,
starr + sizeof(starr)/sizeof(char*),

}

### how to find host name from IP with out login to the host

• For Windows, try:

NBTSTAT -A 10.100.3.104

or

ping -a 10.100.3.104

• For Linux, try:

nmblookup -A 10.100.3.104

They are almost same.

### Executing Shell Scripts from the OS X Dock?

As long as your script is executable and doesn't have any extension you can drag it as-is to the right side (Document side) of the Dock and it will run in a terminal window when clicked instead of opening an editor.

If you want to have an extension (like foo.sh), you can go to the file info window in Finder and change the default application for that particular script from whatever it is (TextEdit, TextMate, whatever default is set on your computer for .sh files) to Terminal. It will then just execute instead of opening in a text editor. Again, you will have to drag it to the right side of the Dock.

### Combining C++ and C - how does #ifdef __cplusplus work?

1. extern "C" doesn't change the presence or absence of the __cplusplus macro. It just changes the linkage and name-mangling of the wrapped declarations.

2. You can nest extern "C" blocks quite happily.

3. If you compile your .c files as C++ then anything not in an extern "C" block, and without an extern "C" prototype will be treated as a C++ function. If you compile them as C then of course everything will be a C function.

4. Yes

5. You can safely mix C and C++ in this way.

### How to receive JSON as an MVC 5 action method parameter

fwiw, this didn't work for me until I had this in the ajax call:

contentType: "application/json; charset=utf-8",

using Asp.Net MVC 4.

### How can I specify a [DllImport] path at runtime?

As long as you know the directory where your C++ libraries could be found at run time, this should be simple. I can clearly see that this is the case in your code. Your myDll.dll would be present inside myLibFolder directory inside temporary folder of the current user.

string str = Path.GetTempPath() + "..\\myLibFolder\\myDLL.dll";

Now you can continue using the DllImport statement using a const string as shown below:

[DllImport("myDLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int DLLFunction(int Number1, int Number2);

Just at run time before you call the DLLFunction function (present in C++ library) add this line of code in C# code:

string assemblyProbeDirectory = Path.GetTempPath() + "..\\myLibFolder\\myDLL.dll";
Directory.SetCurrentDirectory(assemblyProbeDirectory);

This simply instructs the CLR to look for the unmanaged C++ libraries at the directory path which you obtained at run time of your program. Directory.SetCurrentDirectory call sets the application's current working directory to the specified directory. If your myDLL.dll is present at path represented by assemblyProbeDirectory path then it will get loaded and the desired function will get called through p/invoke.

### PHP array value passes to next row

Change the checkboxes so that the name includes the index inside the brackets:

<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo \$i; ?>" <?php if (\$vehicle_feature[\$i]->check) echo "checked"; ?> name="feature[<?php echo \$i; ?>]" value="<?php echo \$vehicle_feature[\$i]->id; ?>">

The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.

### PostgreSQL how to see which queries have run

You can see in pg_log folder if the log configuration is enabled in postgresql.conf with this log directory name.

### How to get char from string by index?

Another recommended exersice for understanding lists and indexes:

L = ['a', 'b', 'c']
for index, item in enumerate(L):
print index + '\n' + item

0
a
1
b
2
c

### Logout button php

When you want to destroy a session completely, you need to do more then just

session_destroy();

First, you should unset any session variables. Then you should destroy the session followed by closing the write of the session. This can be done by the following:

<?php
session_start();
unset(\$_SESSION);
session_destroy();
session_write_close();
die;
?>

The reason you want have a separate script for a logout is so that you do not accidently execute it on the page. So make a link to your logout script, then the header will redirect to the root of your site.

Edit:

You need to remove the () from your exit code near the top of your script. it should just be

exit;

### How to clear browsing history using JavaScript?

It's not possible to clear user history without plugins. And also it's not an issue at developer's perspective, it's the burden of the user to clear his history.

### Finding common rows (intersection) in two Pandas dataframes

In SQL, this problem could be solved by several methods:

select * from df1 where exists (select * from df2 where df2.user_id = df1.user_id)
union all
select * from df2 where exists (select * from df1 where df1.user_id = df2.user_id)

or join and then unpivot (possible in SQL server)

select
df1.user_id,
c.rating
from df1
inner join df2 on df2.user_i = df1.user_id
outer apply (
select df1.rating union all
select df2.rating
) as c

Second one could be written in pandas with something like:

>>> df1 = pd.DataFrame({"user_id":[1,2,3], "rating":[10, 15, 20]})
>>> df2 = pd.DataFrame({"user_id":[3,4,5], "rating":[30, 35, 40]})
>>>
>>> df4 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df = pd.merge(df1, df2, on='user_id', suffixes=['_1', '_2'])
>>> df3 = df[['user_id', 'rating_1']].rename(columns={'rating_1':'rating'})
>>> df4 = df[['user_id', 'rating_2']].rename(columns={'rating_2':'rating'})
>>> pd.concat([df3, df4], axis=0)
user_id  rating
0        3      20
0        3      30

### Code coverage with Mocha

Now (2021) the preferred way to use istanbul is via its "state of the art command line interface" nyc.

# Setup

First, install it in your project with

npm i nyc --save-dev

Then, if you have a npm based project, just change the test script inside the scripts object of your package.json file to execute code coverage of your mocha tests:

{
"scripts": {
"test": "nyc --reporter=text mocha"
}
}

# Run

npm test

and you will see a table like this in your console, just after your tests output:

# Customization

#### Html report

Just use

nyc --reporter=html

instead of text. Now it will produce a report inside ./coverage/index.html.

#### Report formats

Istanbul supports a wide range of report formats. Just look at its reports library to find the most useful for you. Just add a --reporter=REPORTER_NAME option for each format you want. For example, with

nyc --reporter=html --reporter=text

you will have both the console and the html report.

#### Don't run coverage with npm test

Just add another script in your package.json and leave the test script with only your test runner (e.g. mocha):

{
"scripts": {
"test": "mocha",
"test-with-coverage": "nyc --reporter=text mocha"
}
}

Now run this custom script

npm run test-with-coverage

to run tests with code coverage.

#### Force test failing if code coverage is low

Fail if the total code coverage is below 90%:

nyc --check-coverage --lines 90

Fail if the code coverage of at least one file is below 90%:

nyc --check-coverage --lines 90 --per-file

### IOError: [Errno 2] No such file or directory trying to open a file

Hmm, there are a few things going wrong here.

for f in os.listdir(src_dir):
os.path.join(src_dir, f)

You're not storing the result of join. This should be something like:

for f in os.listdir(src_dir):
f = os.path.join(src_dir, f)

This open call is is the cause of your IOError. (Because without storing the result of the join above, f was still just 'file.csv', not 'src_dir/file.csv'.)

Also, the syntax:

with open(f):

is close, but the syntax isn't quite right. It should be with open(file_name) as file_object:. Then, you use to the file_object to perform read or write operations.

And finally:

write(line)

You told python what you wanted to write, but not where to write it. Write is a method on the file object. Try file_object.write(line).

Edit: You're also clobbering your input file. You probably want to open the output file and write lines to it as you're reading them in from the input file.

### Select all 'tr' except the first one

Another option:

tr:nth-child(n + 2) {
/* properties */
}

### C++ compile error: has initializer but incomplete type

` Please include either of these:

`#include<sstream>`

using std::istringstream;

### Export data to Excel file with ASP.NET MVC 4 C# is rendering into view

I have tried your code and it works just fine. The file is being created without any problem, this is the code I used (it's your code, I just changed the datasource for testing):

public ActionResult ExportToExcel()
{
var products = new System.Data.DataTable("teste");

var grid = new GridView();
grid.DataSource = products;
grid.DataBind();

Response.ClearContent();
Response.Buffer = true;
Response.ContentType = "application/ms-excel";

Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);

grid.RenderControl(htw);

Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();

return View("MyView");
}

### Ruby: How to turn a hash into HTTP parameters?

No need to load up the bloated ActiveSupport or roll your own, you can use Rack::Utils.build_query and Rack::Utils.build_nested_query. Here's a blog post that gives a good example:

require 'rack'

Rack::Utils.build_query(
authorization_token: "foo",
access_level: "moderator",
previous: "index"
)

# => "authorization_token=foo&access_level=moderator&previous=index"

It even handles arrays:

Rack::Utils.build_query( {:a => "a", :b => ["c", "d", "e"]} )
# => "a=a&b=c&b=d&b=e"
Rack::Utils.parse_query _
# => {"a"=>"a", "b"=>["c", "d", "e"]}

Or the more difficult nested stuff:

Rack::Utils.build_nested_query( {:a => "a", :b => [{:c => "c", :d => "d"}, {:e => "e", :f => "f"}] } )
# => "a=a&b[][c]=c&b[][d]=d&b[][e]=e&b[][f]=f"
Rack::Utils.parse_nested_query _
# => {"a"=>"a", "b"=>[{"c"=>"c", "d"=>"d", "e"=>"e", "f"=>"f"}]}

### How to hide image broken Icon using only CSS/HTML?

The same idea as described by others works in React as follow:

<img src='YOUR-URL' onError={(e) => e.target.style.display='none' }/>

### How can I align YouTube embedded video in the center in bootstrap

<iframe style="display: block; margin: auto;" width="560" height="315" src="https://www.youtube.com/embed/ig3qHRVZRvM" frameborder="0" allowfullscreen></iframe>

### Set a border around a StackPanel.

<Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="160" Margin="10,55,0,0" VerticalAlignment="Top" Width="492"/>

### Python map object is not subscriptable

In Python 3, map returns an iterable object of type map, and not a subscriptible list, which would allow you to write map[i]. To force a list result, write

payIntList = list(map(int,payList))

However, in many cases, you can write out your code way nicer by not using indices. For example, with list comprehensions:

payIntList = [pi + 1000 for pi in payList]
for pi in payIntList:
print(pi)

### Android Studio - Auto complete and other features not working

Close Android Studio Go to C:\Users\UserName.android and rename the folder:

• build-cache to build-cache_old

• caches to caches_old

• compiler to compiler_old

• compile-server to compile-server_old

• conversion to conversion_old

• external_build_system to external_build_system_old

• frameworks to frameworks_old

• resource_folder_cache to resource_folder_cache_old

Open the Android Studio and open your project again.

### How to remove single character from a String

public static String removechar(String fromString, Character character) {
int indexOf = fromString.indexOf(character);
if(indexOf==-1)
return fromString;
String front = fromString.substring(0, indexOf);
String back = fromString.substring(indexOf+1, fromString.length());
return front+back;
}

### List of all index & index columns in SQL Server DB

Following gives what is similar as sp_helpindex tablename

select T.name as TableName, I.name as IndexName, AC.Name as ColumnName, I.type_desc as IndexType
from sys.tables as T inner join sys.indexes as I on T.[object_id] = I.[object_id]
inner join sys.index_columns as IC on IC.[object_id] = I.[object_id] and IC.[index_id] = I.[index_id]
inner join sys.all_columns as AC on IC.[object_id] = AC.[object_id] and IC.[column_id] = AC.[column_id]
order by T.name, I.name

### js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check

You must use a .ts file - e.g. test.ts to get Typescript validation, intellisense typing of vars, return types, as well as "typed" error checking (e.g. passing a string to a method that expects an number param will error out).

It will be transpiled into (standard) .js via tsc.

#### Update (11/2018):

types

• Yes, you can do type checking in VS Code in .js files with @ts-check - as shown in the animation

• What I originally was referring to for Typescript types is something like this in .ts which isn't quite the same thing:

hello-world.ts

function hello(str: string): string {
return 1;
}

function foo(str:string):void{
console.log(str);
}

This will not compile. Error: Type "1" is not assignable to String

• if you tried this syntax in a Javascript hello-world.js file:

//@ts-check

function hello(str: string): string {
return 1;
}

function foo(str:string):void{
console.log(str);
}

The error message referenced by OP is shown: [js] 'types' can only be used in a .ts file

If there's something I missed that covers this as well as the OP's context, please add. Let's all learn.

### How to concat a string to xsl:value-of select="...?

You can use the rather sensibly named xpath function called concat here

<a>
<xsl:attribute name="href">
<xsl:value-of select="concat('myText:', /*/properties/property[@name='report']/@value)" />
</xsl:attribute>
</a>

Of course, it doesn't have to be text here, it can be another xpath expression to select an element or attribute. And you can have any number of arguments in the concat expression.

Do note, you can make use of Attribute Value Templates (represented by the curly braces) here to simplify your expression

<a href="{concat('myText:', /*/properties/property[@name='report']/@value)}"></a>

### Using Caps Lock as Esc in Mac OS X

Having tried several of these solutions, I have some notes:

DoubleCommand will not allow you to swap esc and caps-lock.

PCKeyboardHack will allow you to map capslock to escape, but does not have the capability to map escape to capslock. Recent versions will allow you to perform a complete swap by editing both keys.

This may or may not be sufficient for your needs (I know it is for mine).

### Delete all local git branches

If you want to keep master, develop and all remote branches. Delete all local branches which are not present on Github anymore.

\$ git fetch --prune

\$ git branch | grep -v "origin" | grep -v "develop" | grep -v "master" | xargs git branch -D

1] It will delete remote refs that are no longer in use on the remote repository.

2] This will get list of all your branches. Remove branch containing master, develop or origin (remote branches) from the list. Delete all branches in list.

Warning - This deletes your own local branches as well. So do this when you have merged your branch and doing a cleanup after merge, delete.

### How to initialize a list of strings (List<string>) with many string values

Move round brackets like this:

### What is a callback function?

A callback is an idea of passing a function as a parameter to another function and have this one invoked once the process has completed.

If you get the concept of callback through awesome answers above, I recommend you should learn the background of its idea.

"What made them(Computer-Scientists) develop callback?" You might learn a problem, which is blocking.(especially blocking UI) And callback is not the only solution to it. There are a lot of other solutions(ex: Thread, Futures, Promises...).

### Div show/hide media query

It sounds like you may be wanting to access the viewport of the device. You can do this by inserting this meta tag in your header.

<meta name="viewport" content="width=device-width, initial-scale=1.0">

http://www.w3schools.com/css/css_rwd_viewport.asp

### how does int main() and void main() work

Neither main() or void main() are standard C. The former is allowed as it has an implicit int return value, making it the same as int main(). The purpose of main's return value is to return an exit status to the operating system.

In standard C, the only valid signatures for main are:

int main(void)

and

int main(int argc, char **argv)

The form you're using: int main() is an old style declaration that indicates main takes an unspecified number of arguments. Don't use it - choose one of those above.

### Query-string encoding of a Javascript Object

With Ramda:

R.pipe(R.toPairs, R.map(R.join('=')), R.join('&'))({a: 'b', b: 'a'})

### rails 3 validation on uniqueness on multiple attributes

#### Multiple Scope Parameters:

class TeacherSchedule < ActiveRecord::Base
validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
end

http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_uniqueness_of

### Converting java.util.Properties to HashMap<String,String>

The efficient way to do that is just to cast to a generic Map as follows:

Properties props = new Properties();

Map<String, String> map = (Map)props;

This will convert a Map<Object, Object> to a raw Map, which is "ok" for the compiler (only warning). Once we have a raw Map it will cast to Map<String, String> which it also will be "ok" (another warning). You can ignore them with annotation @SuppressWarnings({ "unchecked", "rawtypes" })

This will work because in the JVM the object doesn't really have a generic type. Generic types are just a trick that verifies things at compile time.

If some key or value is not a String it will produce a ClassCastException error. With current Properties implementation this is very unlikely to happen, as long as you don't use the mutable call methods from the super Hashtable<Object,Object> of Properties.

So, if don't do nasty things with your Properties instance this is the way to go.

### Make flex items take content width, not width of parent container

In addtion to align-self you can also consider auto margin which will do almost the same thing

_x000D_
_x000D_
.container {_x000D_
background: red;_x000D_
height: 200px;_x000D_
flex-direction: column;_x000D_
display: flex;_x000D_
}_x000D_
a {_x000D_
margin-right:auto;_x000D_
background: pink;_x000D_
}
_x000D_
<div class="container">_x000D_
<a href="#">Test</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

### Getting SyntaxError for print with keyword argument end=' '

Try this one if you are working with python 2.7:

from __future__ import print_function

### React - How to pass HTML tags in props?

You can successfully utilize React fragments for this task. Depending on the React version you use, you can use short syntax: <> or the full tag: <React.Fragment>. Works especially well if you don't want to wrap entire string within HTML tags.

<MyComponent text={<>Hello World. <u>Don't be so ruthless</u>.</>} />

### What is the difference between CHARACTER VARYING and VARCHAR in PostgreSQL?

Varying is an alias for varchar, so no difference, see documentation :)

The notations varchar(n) and char(n) are aliases for character varying(n) and character(n), respectively. character without length specifier is equivalent to character(1). If character varying is used without length specifier, the type accepts strings of any size. The latter is a PostgreSQL extension.

### Writing new lines to a text file in PowerShell

You can use the Environment class's static NewLine property to get the proper newline:

\$errorMsg =  "{0} Error {1}{2} key {3} expected: {4}{5} local value is: {6}" -f `
(Get-Date),\$keyPath,\$value,\$key,\$policyValue,([Environment]::NewLine),\$localValue

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

Just an addition to the previous answers. Let's not forget that when dealing with real data there might be null values, so it's useful to also include those in the counting by using the option dropna=False (default is True)

An example:

>>> df['Embarked'].value_counts(dropna=False)
S      644
C      168
Q       77
NaN      2

### SQL Server stored procedure creating temp table and inserting value

A SELECT INTO statement creates the table for you. There is no need for the CREATE TABLE statement before hand.

What is happening is that you create #ivmy_cash_temp1 in your CREATE statement, then the DB tries to create it for you when you do a SELECT INTO. This causes an error as it is trying to create a table that you have already created.

Either eliminate the CREATE TABLE statement or alter your query that fills it to use INSERT INTO SELECT format.

If you need a unique ID added to your new row then it's best to use SELECT INTO... since IDENTITY() only works with this syntax.

### Drop all data in a pandas dataframe

You need to pass the labels to be dropped.

df.drop(df.index, inplace=True)

By default, it operates on axis=0.

You can achieve the same with

df.iloc[0:0]

which is much more efficient.

### How can I adjust DIV width to contents

One way you can achieve this is setting display: inline-block; on the div. It is by default a block element, which will always fill the width it can fill (unless specifying width of course).

inline-block's only downside is that IE only supports it correctly from version 8. IE 6-7 only allows setting it on naturally inline elements, but there are hacks to solve this problem.

There are other options you have, you can either float it, or set position: absolute on it, but these also have other effects on layout, you need to decide which one fits your situation better.

### Radio buttons not checked in jQuery

if ( ! \$("input").is(':checked') )

Doesn't work?

You might also try iterating over the elements like so:

var iz_checked = true;
\$('input').each(function(){
iz_checked = iz_checked && \$(this).is(':checked');
});
if ( ! iz_checked )

### Using multiple case statements in select query

There are two ways to write case statements, you seem to be using a combination of the two

case a.updatedDate
when 1760 then 'Entered on' + a.updatedDate
when 1710 then 'Viewed on' + a.updatedDate
else 'Last Updated on' + a.updateDate
end

or

case
when a.updatedDate = 1760 then 'Entered on' + a.updatedDate
when a.updatedDate = 1710 then 'Viewed on' + a.updatedDate
else 'Last Updated on' + a.updateDate
end

are equivalent. They may not work because you may need to convert date types to varchars to append them to other varchars.

### How to create custom button in Android using XML Styles

Have you ever tried to create the background shape for any buttons?

Check this out below:

Below is the separated image from your image of a button.

Now, put that in your ImageButton for android:src "source" like so:

Now, just create shape of the ImageButton to have a black shader background.

android:background="@drawable/button_shape"

and the button_shape is the xml file in drawable resource:

<?xml version="1.0" encoding="UTF-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android">
<stroke
android:width="1dp"
android:color="#505050"/>
<corners

android:left="1dp"
android:right="1dp"
android:top="1dp"
android:bottom="1dp"/>

<solid android:color="#505050"/>

</shape>

Just try to implement it with this. You might need to change the color value as per your requirement.

Let me know if it doesn't work.

### Spring Boot @autowired does not work, classes in different package

I had the same problem. It worked for me when i removed the private modifier from the Autowired objects.

When running Wget with -r or -p, but without -N, -nd, or -nc, re-downloading a file will result in the new copy simply overwriting the old.

So adding -nc will prevent this behavior, instead causing the original version to be preserved and any newer copies on the server to be ignored.

### Python 3 TypeError: must be str, not bytes with sys.stdout.write()

While the accepted answer will work fine if the bytes you have from your subprocess are encoded using sys.stdout.encoding (or a compatible encoding, like reading from a tool that outputs ASCII and your stdout uses UTF-8), the correct way to write arbitrary bytes to stdout is:

sys.stdout.buffer.write(some_bytes_object)

This will just output the bytes as-is, without trying to treat them as text-in-some-encoding.

### How to cast or convert an unsigned int to int in C?

IMHO this question is an evergreen. As stated in various answers, the assignment of an unsigned value that is not in the range [0,INT_MAX] is implementation defined and might even raise a signal. If the unsigned value is considered to be a two's complement representation of a signed number, the probably most portable way is IMHO the way shown in the following code snippet:

#include <limits.h>
unsigned int u;
int i;

if (u <= (unsigned int)INT_MAX)
i = (int)u; /*(1)*/
else if (u >= (unsigned int)INT_MIN)
i = -(int)~u - 1; /*(2)*/
else
i = INT_MIN; /*(3)*/
• Branch (1) is obvious and cannot invoke overflow or traps, since it is value-preserving.

• Branch (2) goes through some pains to avoid signed integer overflow by taking the one's complement of the value by bit-wise NOT, casts it to 'int' (which cannot overflow now), negates the value and subtracts one, which can also not overflow here.

• Branch (3) provides the poison we have to take on one's complement or sign/magnitude targets, because the signed integer representation range is smaller than the two's complement representation range.

This is likely to boil down to a simple move on a two's complement target; at least I've observed such with GCC and CLANG. Also branch (3) is unreachable on such a target -- if one wants to limit the execution to two's complement targets, the code could be condensed to

#include <limits.h>
unsigned int u;
int i;

if (u <= (unsigned int)INT_MAX)
i = (int)u; /*(1)*/
else
i = -(int)~u - 1; /*(2)*/

The recipe works with any signed/unsigned type pair, and the code is best put into a macro or inline function so the compiler/optimizer can sort it out. (In which case rewriting the recipe with a ternary operator is helpful. But it's less readable and therefore not a good way to explain the strategy.)

And yes, some of the casts to 'unsigned int' are redundant, but

• they might help the casual reader

• some compilers issue warnings on signed/unsigned compares, because the implicit cast causes some non-intuitive behavior by language design

### How to set width of mat-table column in angular?

Just need to update the width of the th tag.

th {
width: 100px;
}

### Index (zero based) must be greater than or equal to zero

Your second String.Format uses {2} as a placeholder but you're only passing in one argument, so you should use {0} instead.

Change this:

To this:

### Before and After Suite execution hook in jUnit 4.x

Since maven-surefire-plugin does not run Suite class first but treats suite and test classes same, so we can configure plugin as below to enable only suite classes and disable all the tests. Suite will run all the tests.

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.5</version>
<configuration>
<includes>
<include>**/*Suite.java</include>
</includes>
<excludes>
<exclude>**/*Test.java</exclude>
<exclude>**/*Tests.java</exclude>
</excludes>
</configuration>
</plugin>

### Hidden Features of Java

Use StringBuilder instead of StringBuffer when you don't need synchronized management included in StringBuilder. It will increase the performance of your application.

Improvements for Java 7 would be even better than any hidden Java features:

Don't use those infinite <> syntax at instanciation:

Map<String, List<String>> anagrams = new HashMap<String, List<String>>();

// Can now be replaced with this:

Map<String, List<String>> anagrams = new HashMap<>();

Use String in switch, instead of old-C int:

String s = "something";
switch(s) {
case "quux":
processQuux(s);
// fall-through

case "foo":
case "bar":
processFooOrBar(s);
break;

case "baz":
processBaz(s);
// fall-through

default:
processDefault(s);
break;
}

This old code:

static void copy(String src, String dest) throws IOException {
InputStream in = new FileInputStream(src);
try {
OutputStream out = new FileOutputStream(dest);
try {
byte[] buf = new byte[8 * 1024];
int n;
while ((n = in.read(buf)) >= 0)
out.write(buf, 0, n);
} finally {
out.close();
}
} finally {
in.close();
}
}

can now be replaced by this much simpler code:

static void copy(String src, String dest) throws IOException {
try (InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest)) {
byte[] buf = new byte[8192];
int n;
while ((n = in.read(buf)) >= 0)
out.write(buf, 0, n);
}
}

### Printing all global variables/local variables?

Type info variables to list "All global and static variable names".

Type info locals to list "Local variables of current stack frame" (names and values), including static variables in that function.

Type info args to list "Arguments of the current stack frame" (names and values).

### npm global path prefix

Spent a while on this issue, and the PATH switch wasn't helping. My problem was the Homebrew/node/npm bug found here - https://github.com/npm/npm/issues/3794

If you've already installed node using Homebrew, try ****Note per comments that this might not be safe. It worked for me but could have unintended consequences. It also appears that latest version of Homebrew properly installs npm. So likely I would try brew update, brew doctor, brew upgrade node etc before trying****:

npm update -gf

Or, if you want to install node with Homebrew and have npm work, use:

brew install node --without-npm
curl -L https://npmjs.org/install.sh | sh

### Get a file name from a path

Function:

#include <string>

std::string
basename(const std::string &filename)
{
if (filename.empty()) {
return {};
}

auto len = filename.length();
auto index = filename.find_last_of("/\\");

if (index == std::string::npos) {
return filename;
}

if (index + 1 >= len) {

len--;
index = filename.substr(0, len).find_last_of("/\\");

if (len == 0) {
return filename;
}

if (index == 0) {
return filename.substr(1, len - 1);
}

if (index == std::string::npos) {
return filename.substr(0, len);
}

return filename.substr(index + 1, len - index - 1);
}

return filename.substr(index + 1, len - index);
}

Tests:

#define CATCH_CONFIG_MAIN
#include <catch/catch.hpp>

TEST_CASE("basename")
{
CHECK(basename("") == "");
CHECK(basename("no_path") == "no_path");
CHECK(basename("with.ext") == "with.ext");
CHECK(basename("/no_filename/") == "no_filename");
CHECK(basename("no_filename/") == "no_filename");
CHECK(basename("/no/filename/") == "filename");
CHECK(basename("/absolute/file.ext") == "file.ext");
CHECK(basename("../relative/file.ext") == "file.ext");
CHECK(basename("/") == "/");
CHECK(basename("c:\\windows\\path.ext") == "path.ext");
CHECK(basename("c:\\windows\\no_filename\\") == "no_filename");
}

### Difference between MEAN.js and MEAN.io

First of all, MEAN is an acronym for MongoDB, Express, Angular and Node.js.

It generically identifies the combined used of these technologies in a "stack". There is no such a thing as "The MEAN framework".

Lior Kesos at Linnovate took advantage of this confusion. He bought the domain MEAN.io and put some code at https://github.com/linnovate/mean

They luckily received a lot of publicity, and theree are more and more articles and video about MEAN. When you Google "mean framework", mean.io is the first in the list.

Unfortunately the code at https://github.com/linnovate/mean seems poorly engineered.

In February I fell in the trap myself. The site mean.io had a catchy design and the Github repo had 1000+ stars. The idea of questioning the quality did not even pass through my mind. I started experimenting with it but it did not take too long to stumble upon things that were not working, and puzzling pieces of code.

The commit history was also pretty concerning. They re-engineered the code and directory structure multiple times, and merging the new changes is too time consuming.

The nice things about both mean.io and mean.js code is that they come with Bootstrap integration. They also come with Facebook, Github, Linkedin etc authentication through PassportJs and an example of a model (Article) on the backend on MongoDB that sync with the frontend model with AngularJS.

According to Linnovate's website:

Linnovate is the leading Open Source company in Israel, with the most experienced team in the country, dedicated to the creation of high-end open source solutions. Linnovate is the only company in Israel which gives an A-Z services for enterprises for building and maintaining their next web project.

From the website it looks like that their core skill set is Drupal (a PHP content management system) and only lately they started using Node.js and AngularJS.

Lately I was reading the Mean.js Blog and things became clearer. My understanding is that the main Javascript developer (Amos Haviv) left Linnovate to work on Mean.js leaving MEAN.io project with people that are novice Node.js developers that are slowing understanding how things are supposed to work.

In the future things may change but for now I would avoid to use mean.io. If you are looking for a boilerplate for a quickstart Mean.js seems a better option than mean.io.

### What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?

If you're getting this error in the build somewhere else, while your IDE says everything is perfectly fine, then check that you are using the same Java versions in both places.

For example, Java 7 and Java 8 have different APIs, so calling a non-existent API in an older Java version would cause this error.

### Can I have an IF block in DOS batch file?

Instead of this goto mess, try using the ampersand & or double ampersand && (conditional to errorlevel 0) as command separators.

I fixed a script snippet with this trick, to summarize, I have three batch files, one which calls the other two after having found which letters the external backup drives have been assigned. I leave the first file on the primary external drive so the calls to its backup routine worked fine, but the calls to the second one required an active drive change. The code below shows how I fixed it:

for %%b in (d e f g h i j k l m n o p q r s t u v w x y z) DO (
if exist "%%b:\Backup.cmd" %%b: & CALL "%%b:\Backup.cmd"
)

### Remove the complete styling of an HTML button/submit

I'm assuming that when you say 'click the button, it moves to the top a little' you're talking about the mouse down click state for the button, and that when you release the mouse click, it returns to its normal state? And that you're disabling the default rendering of the button by using:

input, button, submit { border:none; }

If so..

Personally, I've found that you can't actually stop/override/disable this IE native action, which led me to change my markup a little to allow for this movement and not affect the overall look of the button for the various states.

This is my final mark-up:

_x000D_
_x000D_
<span class="your-button-class">_x000D_
<span>_x000D_
<input type="Submit" value="View Person">_x000D_
</span>_x000D_
</span>
_x000D_
_x000D_
_x000D_

### Cross field validation with Hibernate Validator (JSR 303)

With Hibernate Validator 4.1.0.Final I recommend using @ScriptAssert. Exceprt from its JavaDoc:

Script expressions can be written in any scripting or expression language, for which a JSR 223 ("Scripting for the JavaTM Platform") compatible engine can be found on the classpath.

Note: the evaluation is being performed by a scripting "engine" running in the Java VM, therefore on Java "server side", not on "client side" as stated in some comments.

Example:

@ScriptAssert(lang = "javascript", script = "_this.passVerify.equals(_this.pass)")
public class MyBean {
@Size(min=6, max=50)
private String pass;

private String passVerify;
}

or with shorter alias and null-safe:

@ScriptAssert(lang = "javascript", alias = "_",
script = "_.passVerify != null && _.passVerify.equals(_.pass)")
public class MyBean {
@Size(min=6, max=50)
private String pass;

private String passVerify;
}

or with Java 7+ null-safe Objects.equals():

@ScriptAssert(lang = "javascript", script = "Objects.equals(_this.passVerify, _this.pass)")
public class MyBean {
@Size(min=6, max=50)
private String pass;

private String passVerify;
}

Nevertheless, there is nothing wrong with a custom class level validator @Matches solution.

### What does "static" mean in C?

static means different things in different contexts.

1. You can declare a static variable in a C function. This variable is only visible in the function however it behaves like a global in that it is only initialized once and it retains its value. In this example, everytime you call foo() it will print an increasing number. The static variable is initialized only once.

void foo ()
{
static int i = 0;
printf("%d", i); i++
}

2. Another use of static is when you implement a function or global variable in a .c file but don't want its symbol to be visible outside of the .obj generated by the file. e.g.

static void foo() { ... }

### spring PropertyPlaceholderConfigurer and context:property-placeholder

Following worked for me:
<context:property-placeholder location="file:src/resources/spring/AppController.properties"/>

Somehow "classpath:xxx" is not picking the file.

### .htaccess redirect all pages to new domain

My solution as SymLinks did not work on my server so I used an If in my PHP.

function curPageURL() {
\$pageURL = 'http';
if (\$_SERVER["HTTPS"] == "on") {\$pageURL .= "s";}
\$pageURL .= "://";
if (\$_SERVER["SERVER_PORT"] != "80") {
\$pageURL .= \$_SERVER["SERVER_NAME"] . ":" . \$_SERVER["SERVER_PORT"] . \$_SERVER["REQUEST_URI"];
} else {
\$pageURL .= \$_SERVER["SERVER_NAME"] . \$_SERVER["REQUEST_URI"];
}
return \$pageURL;
}
\$redirect = str_replace("www.", "", curPageURL());
\$remove_http_root    = str_replace('http://', '', \$redirect);
\$split_url_array     = explode('/', \$remove_http_root );

if(\$split_url_array[0] == "olddomain.com"){
die();
}

### How to make a rest post call from ReactJS code?

As of 2018 and beyond, you have a more modern option which is to incorporate async/await in your ReactJS application. A promise-based HTTP client library such as axios can be used. The sample code is given below:

import axios from 'axios';
...
constructor(props, context) {
super(props, context);
...
}
const { email, password } = this.state;
try {
console.log(response);
} catch (err) {
...
}
}
...
}

### Are the shift operators (<<, >>) arithmetic or logical in C?

GCC does

1. for -ve - > Arithmetic Shift

2. For +ve -> Logical Shift

### What is the format specifier for unsigned short int?

Here is a good table for printf specifiers. So it should be %hu for unsigned short int.

### Perl: function to trim string leading and trailing whitespace

Here's one approach using a regular expression:

\$string =~ s/^\s+|\s+\$//g ;     # remove both leading and trailing whitespace

Perl 6 will include a trim function:

\$string .= trim;

Source: Wikipedia

### how to fix the issue "Command /bin/sh failed with exit code 1" in iphone

I had this issue because i denied keychain access and in order to solve it you need to open keychain, Then click on the lock on top right of the screen to lock it again, after that you can archive and it will work

Just use

File.Copy(filepath, "\\\\192.168.1.28\\Files");

A windows fileshare exposed via a UNC path is treated as part of the file system, and has nothing to do with the web.

The credentials used will be that of the ASP.NET worker process, or any impersonation you've enabled. If you can tweak those to get it right, this can be done.

You may run into problems because you are using the IP address instead of the server name (windows trust settings prevent leaving the domain - by using IP you are hiding any domain details). If at all possible, use the server name!

If this is not on the same windows domain, and you are trying to use a different domain account, you will need to specify the username as "[domain_or_machine]\[username]"

If you need to specify explicit credentials, you'll need to look into coding an impersonation solution.

### When to use virtual destructors?

If you use shared_ptr(only shared_ptr, not unique_ptr), you don't have to have the base class destructor virtual:

#include <iostream>
#include <memory>

using namespace std;

class Base
{
public:
Base(){
cout << "Base Constructor Called\n";
}
~Base(){ // not virtual
cout << "Base Destructor called\n";
}
};

class Derived: public Base
{
public:
Derived(){
cout << "Derived constructor called\n";
}
~Derived(){
cout << "Derived destructor called\n";
}
};

int main()
{
shared_ptr<Base> b(new Derived());
}

output:

Base Constructor Called
Derived constructor called
Derived destructor called
Base Destructor called

### Running ASP.Net on a Linux based server

So I know this is an older question but I think it could stand an updated answer.

Microsoft has officially released asp.net vnext and its open source and deploy-able to both Linux and Mac. Its all still pretty new but does rely on the latest builds of mono and thus currently needs you to compile the mono-framework but in time I suspect that it will be easier to access as various linux distros release updated versions of mono. This is a how to setup guide

This information may be somewhat volatile and with updates is due to change.

# Update ASP.NET CORE 11/10/2017

### Selecting a Linux I/O Scheduler

You can set this at boot by adding the "elevator" parameter to the kernel cmdline (such as in grub.cfg)

Example:

This will make "deadline" the default I/O scheduler for all block devices.

If you'd like to query or change the scheduler after the system has booted, or would like to use a different scheduler for a specific block device, I recommend installing and use the tool ioschedset to make this easy.

https://github.com/kata198/ioschedset

If you're on Archlinux it's available in aur:

https://aur.archlinux.org/packages/ioschedset

Some example usage:

# Get i/o scheduler for all block devices
sda:    bfq
sr0:    bfq

# Query available I/O schedulers

# Set sda to use "kyber"
Must be root to set IO Scheduler. Rerunning under sudo...

+ Successfully set sda to 'kyber'!

# Get i/o scheduler for all block devices to assert change
sda:    kyber
sr0:    bfq

# Set all block devices to use 'deadline' i/o scheduler
Must be root to set IO Scheduler. Rerunning under sudo...

+ Successfully set sda to 'deadline'!
+ Successfully set sr0 to 'deadline'!

# Get the current block scheduler just for sda

Usage should be self-explanatory. The tools are standalone and only require bash.

Hope this helps!

EDIT: Disclaimer, these are scripts I wrote.

### How can I "disable" zoom on a mobile web page?

There are a number of approaches here- and though the position is that typically users should not be restricted when it comes to zooming for accessibility purposes, there may be incidences where is it required:

Render the page at the width of the device, dont scale:

<meta name="viewport" content="width=device-width, initial-scale=1.0">

Prevent scaling- and prevent the user from being able to zoom:

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

Removing all zooming, all scaling

<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />

### Init method in Spring Controller (annotation version)

There are several ways to intercept the initialization process in Spring. If you have to initialize all beans and autowire/inject them there are at least two ways that I know of that will ensure this. I have only testet the second one but I belive both work the same.

If you are using @Bean you can reference by initMethod, like this.

@Configuration
public class BeanConfiguration {

@Bean(initMethod="init")
public BeanA beanA() {
return new BeanA();
}
}

public class BeanA {

// method to be initialized after context is ready
public void init() {
}

}

If you are using @Component you can annotate with @EventListener like this.

@Component
public class BeanB {

@EventListener
public void onApplicationEvent(ContextRefreshedEvent event) {
}
}

In my case I have a legacy system where I am now taking use of IoC/DI where Spring Boot is the choosen framework. The old system brings many circular dependencies to the table and I therefore must use setter-dependency a lot. That gave me some headaches since I could not trust @PostConstruct since autowiring/injection by setter was not yet done. The order is constructor, @PostConstruct then autowired setters. I solved it with @EventListener annotation which wil run last and at the "same" time for all beans. The example shows implementation of InitializingBean aswell.

I have two classes (@Component) with dependency to each other. The classes looks the same for the purpose of this example displaying only one of them.

@Component
public class BeanA implements InitializingBean {
private BeanB beanB;

public BeanA() {
log.debug("Created...");
}

@PostConstruct
private void postConstruct() {
log.debug("@PostConstruct");
}

@Autowired
public void setBeanB(BeanB beanB) {
log.debug("@Autowired beanB");
this.beanB = beanB;
}

@Override
public void afterPropertiesSet() throws Exception {
log.debug("afterPropertiesSet()");
}

@EventListener
public void onApplicationEvent(ContextRefreshedEvent event) {
log.debug("@EventListener");
}
}

This is the log output showing the order of the calls when the container starts.

2018-11-30 18:29:30.504 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : Created...
2018-11-30 18:29:30.509 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : Created...
2018-11-30 18:29:30.517 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : @Autowired beanA
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : @PostConstruct
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : afterPropertiesSet()
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : @Autowired beanB
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : @PostConstruct
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : afterPropertiesSet()
2018-11-30 18:29:30.607 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : @EventListener
2018-11-30 18:29:30.607 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : @EventListener

As you can see @EventListener is run last after everything is ready and configured.

### How to commit my current changes to a different branch in Git

1. git checkout my_other_branch
3. git commit -m

### How to implement 2D vector array?

I use this piece of code . works fine for me .copy it and run on your computer. you'll understand by yourself .

#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector <vector <int> > matrix;
size_t row=3 , col=3 ;
for(int i=0,cnt=1 ; i<row ; i++)
{
for(int j=0 ; j<col ; j++)
{
vector <int> colVector ;
matrix.push_back(colVector) ;
matrix.at(i).push_back(cnt++) ;
}
}
matrix.at(1).at(1) = 0;     //matrix.at(columns).at(rows) = intValue
//printing all elements
for(int i=0,cnt=1 ; i<row ; i++)
{
for(int j=0 ; j<col ; j++)
{
cout<<matrix[i][j] <<" " ;
}
cout<<endl ;
}
}

### What is the difference between primary, unique and foreign key constraints, and indexes?

Here are some reference for you:

Primary & foreign key Constraint.

Primary Key: A primary key is a field or combination of fields that uniquely identify a record in a table, so that an individual record can be located without confusion.

Foreign Key: A foreign key (sometimes called a referencing key) is a key used to link two tables together. Typically you take the primary key field from one table and insert it into the other table where it becomes a foreign key (it remains a primary key in the original table).

Index, on the other hand, is an attribute that you can apply on some columns so that the data retrieval done on those columns can be speed up.

Keep in mind this overwrites any ID that the element already has:

\$(".element").attr("id","SomeID");

The reason why addClass exists is because an element can have multiple classes, so you wouldn't want to necessarily overwrite the classes already set. But with most attributes, there is only one value allowed at any given time.

### How to make a function wait until a callback has been called using node.js

Note: This answer should probably not be used in production code. It's a hack and you should know about the implications.

There is the uvrun module (updated for newer Nodejs versions here) where you can execute a single loop round of the libuv main event loop (which is the Nodejs main loop).

Your code would look like this:

function(query) {
var r;
myApi.exec('SomeCommand', function(response) {
r = response;
});
var uvrun = require("uvrun");
while (!r)
uvrun.runOnce();
return r;
}

(You might alternative use uvrun.runNoWait(). That could avoid some problems with blocking, but takes 100% CPU.)

Note that this approach kind of invalidates the whole purpose of Nodejs, i.e. to have everything async and non-blocking. Also, it could increase your callstack depth a lot, so you might end up with stack overflows. If you run such function recursively, you definitely will run into troubles.