# Programs & Examples On #Mac app store

For issues relating to deploying and maintaining an application in the Mac App Store.

### How to adjust the size of y axis labels only in R?

As the title suggests that we want to adjust the size of the labels and not the tick marks I figured that I actually might add something to the question, you need to use the mtext() if you want to specify one of the label sizes, or you can just use `par(cex.lab=2)` as a simple alternative. Here's a more advanced mtext() example:

``````set.seed(123)
foo <- data.frame(X = rnorm(10), Y = rnorm(10))
plot(Y ~ X, data=foo,
yaxt="n", ylab="",
xlab="Regular boring x",
pch=16,
col="darkblue")
axis(2,cex.axis=1.2)
mtext("Awesome Y variable", side=2, line=2.2, cex=2)
``````

You may need to adjust the `line=` option to get the optimal positioning of the text but apart from that it's really easy to use.

### Can (a== 1 && a ==2 && a==3) ever evaluate to true?

#### » JavaScript

_x000D_
_x000D_
``````if?=()=>!0;_x000D_
var a = 9;_x000D_
_x000D_
if?(a==1 && a== 2 && a==3)_x000D_
{_x000D_
document.write("<h1>Yes, it is possible!</h1>")_x000D_
}``````
_x000D_
_x000D_
_x000D_

The above code is a short version (thanks to @Forivin for its note in comments) and the following code is original:

_x000D_
_x000D_
``````var a = 9;_x000D_
_x000D_
if?(a==1 && a== 2 && a==3)_x000D_
{_x000D_
//console.log("Yes, it is possible!")_x000D_
document.write("<h1>Yes, it is possible!</h1>")_x000D_
}_x000D_
_x000D_
//--------------------------------------------_x000D_
_x000D_
function if?(){return true;}``````
_x000D_
_x000D_
_x000D_

If you just see top side of my code and run it you say WOW, how?

So I think it is enough to say Yes, it is possible to someone that said to you: Nothing is impossible

Trick: I used a hidden character after `if` to make a function that its name is similar to `if`. In JavaScript we can not override keywords so I forced to use this way. It is a fake `if`, but it works for you in this case!

#### » C#

Also I wrote a C# version (with increase property value technic):

``````static int _a;
public static int a => ++_a;

public static void Main()
{
if(a==1 && a==2 && a==3)
{
Console.WriteLine("Yes, it is possible!");
}
}
``````

Live Demo

### Response.Redirect to new window

I used this approach, it doesn't require you to do anything on the popup (which I didn't have access to because I was redirecting to a PDF file). It also uses classes.

``````\$(function () {
//--- setup click event for elements that use a response.redirect in code behind but should open in a new window
\$(".new-window").on("click", function () {

//--- change the form's target
\$("#aspnetForm").prop("target", "_blank");

//--- change the target back after the window has opened
setTimeout(function () {
\$("#aspnetForm").prop("target", "");
}, 1);
});
});
``````

To use, add the class "new-window" to any element. You do not need to add anything to the body tag. This function sets up the new window and fixes it in the same function.

### How to drop all tables from a database with one SQL query?

I Know this question is very old but every Time i need this code .. by the way if you have tables and views and Functions and PROCEDURES you can delete it all by this Script .. so why i post this Script ?? because if u delete all tables you will need to delete all views and if you have Functions and PROCEDURES you need to delete it too
i Hope it will help someone

``````DECLARE @sql NVARCHAR(max)=''

SELECT @sql += ' Drop table ' + QUOTENAME(TABLE_SCHEMA) + '.'+ QUOTENAME(TABLE_NAME)
+ '; '
FROM   INFORMATION_SCHEMA.TABLES
WHERE  TABLE_TYPE = 'BASE TABLE'

Exec Sp_executesql @sql

DECLARE @sql VARCHAR(MAX) = ''
, @crlf VARCHAR(2) = CHAR(13) + CHAR(10) ;

SELECT @sql = @sql + 'DROP VIEW ' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' +
QUOTENAME(v.name) +';' + @crlf
FROM   sys.views v

PRINT @sql;
EXEC(@sql);

declare @procName varchar(500)
declare cur cursor

for select [name] from sys.objects where type = 'p'
open cur
fetch next from cur into @procName
while @@fetch_status = 0
begin
exec('drop procedure [' + @procName + ']')
fetch next from cur into @procName
end
close cur
deallocate cur

Declare @sql NVARCHAR(MAX) = N'';

SELECT @sql = @sql + N' DROP FUNCTION '
+ QUOTENAME(SCHEMA_NAME(schema_id))
+ N'.' + QUOTENAME(name)
FROM sys.objects
WHERE type_desc LIKE '%FUNCTION%';

Exec sp_executesql @sql
GO
``````

### Writing a string to a cell in excel

I've had a few cranberry-vodkas tonight so I might be missing something...Is setting the range necessary? Why not use:

``````Activeworkbook.Sheets("Game").Range("A1").value = "Subtotal"
``````

Does this fail as well?

Looks like you tried something similar:

``````'Worksheets("Game").Range("A1") = "Asdf"
``````

However, Worksheets is a collection, so you can't reference "Game". I think you need to use the Sheets object instead.

Basically like this,

``````<?php
?>
``````

### Playing m3u8 Files with HTML Video Tag

In normally html5 video player will support mp4, WebM, 3gp and OGV format directly.

``````    <video controls>
<source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm>
<source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg>
<source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4>
<source src=http://techslides.com/demos/sample-videos/small.3gp type=video/3gp>
</video>
``````

We can add an external HLS js script in web application.

``````    <!DOCTYPE html>
<html>
<meta charset=utf-8 />

<script src="https://unpkg.com/video.js/dist/video.js"></script>
<script src="https://unpkg.com/videojs-contrib-hls/dist/videojs-contrib-hls.js"></script>

<body>
<video id="my_video_1" class="video-js vjs-fluid vjs-default-skin" controls preload="auto"
data-setup='{}'>
</video>

<script>
var player = videojs('my_video_1');
player.play();
</script>

</body>
</html>
``````

### Get a particular cell value from HTML table using JavaScript

I found this as an easiest way to add row . The awesome thing about this is that it doesn't change the already present table contents even if it contains input elements .

``````row = `<tr><td><input type="text"></td></tr>`
\$("#table_body tr:last").after(row) ;
``````

Here `#table_body` is the id of the table body tag .

No- you can definitely handle more than that.

Its important to remember that deep deep down, assuming you are running a single core machine, the CPU really only runs one instruction* at a time.

Namely, the CPU can only execute a very limited set of instructions, and it can't execute more than one instruction per clock tick (many instructions even take more than 1 tick).

Therefore, most concurrency we talk about in computer science is software concurrency. In other words, there are layers of software implementation that abstract the bottom level CPU from us and make us think we are running code concurrently.

These "things" can be processes, which are units of code that get run concurrently in the sense that each process thinks its running in its own world with its own, non-shared memory.

Another example is threads, which are units of code inside processes that allow concurrency as well.

The reason your 4 worker processes will be able to handle more than 4 requests is that they will fire off threads to handle more and more requests.

The actual request limit depends on HTTP server chosen, I/O, OS, hardware, network connection etc.

Good luck!

*instructions are the very basic commands the CPU can run. examples - add two numbers, jump from one instruction to another

### PHP date yesterday

How easy :)

``````date("F j, Y", strtotime( '-1 days' ) );
``````

Example:

``````echo date("Y-m-j H:i:s", strtotime( '-1 days' ) ); // 2018-07-18 07:02:43
``````

Output:

``````2018-07-17 07:02:43
``````

### How can I format decimal property to currency?

A decimal type can not contain formatting information. You can create another property, say `FormattedProperty` of a string type that does what you want.

### Lint: How to ignore "<key> is not translated in <language>" errors?

This will cause Lint to ignore the missing translation error for ALL strings in the file, yet other string resource files can be verified if needed.

``````<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools"
tools:ignore="MissingTranslation">
``````

### How to make Google Fonts work in IE?

It's all about trying all those answers, for me, nothing works except the next solution: Google font suggested

``````@import 'https://fonts.googleapis.com/css?family=Assistant';
``````

But, I'm using here foreign language fonts, and it didn't work on IE11 only. I found out this solution that worked:

``````@import 'https://fonts.googleapis.com/css?family=Assistant&subset=hebrew';
``````

Hope that save someone precious time

### Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?

another alternative, just in case you want to have a shell script which creates the database if it does not exist and otherwise just keeps it as it is:

``````psql -U postgres -tc "SELECT 1 FROM pg_database WHERE datname = 'my_db'" | grep -q 1 || psql -U postgres -c "CREATE DATABASE my_db"
``````

I found this to be helpful in devops provisioning scripts, which you might want to run multiple times over the same instance.

For those of you who would like an explanation:

``````-c = run command in database session, command is given in string
-t = skip header and footer
-q = silent mode for grep
|| = logical OR, if grep fails to find match run the subsequent command
``````

### Using an index to get an item, Python

What you show, `('A','B','C','D','E')`, is not a `list`, it's a `tuple` (the round parentheses instead of square brackets show that). Nevertheless, whether it to index a list or a tuple (for getting one item at an index), in either case you append the index in square brackets.

So:

``````thetuple = ('A','B','C','D','E')
print thetuple[0]
``````

prints `A`, and so forth.

Tuples (differently from lists) are immutable, so you couldn't assign to `thetuple[0]` etc (as you could assign to an indexing of a list). However you can definitely just access ("get") the item by indexing in either case.

### jquery: change the URL address without redirecting?

You cannot really change the whole URL in the location bar without redirecting (think of the security issues!).

However you can change the `hash` part (whats after the `#`) and read that: `location.hash`

ps. prevent the default `onclick` redirect of a link by something like:

``````\$("#link").bind("click",function(e){
doRedirectFunction();
e.preventDefault();
})
``````

### Multiple try codes in one block

You can use fuckit module.
Wrap your code in a function with `@fuckit` decorator:

``````@fuckit
def func():
code a
code b #if b fails, it should ignore, and go to c.
code c #if c fails, go to d
code d
``````

### Setting width as a percentage using jQuery

Hemnath

If your variable is the percentage:

``````var myWidth = 70;
\$('div#somediv').width(myWidth + '%');
``````

If your variable is in pixels, and you want the percentage it take up of the parent:

``````var myWidth = 140;
var myPercentage = (myWidth / \$('div#somediv').parent().width()) * 100;
\$('div#somediv').width(myPercentage + '%');
``````

### Creating a thumbnail from an uploaded image

You Can Use The Simplest Method

``````<?php
function make_thumb(\$src, \$dest, \$desired_width) {

/* read the source image */
\$source_image = imagecreatefromjpeg(\$src);
\$width = imagesx(\$source_image);
\$height = imagesy(\$source_image);

/* find the "desired height" of this thumbnail, relative to the desired width  */
\$desired_height = floor(\$height * (\$desired_width / \$width));

/* create a new, "virtual" image */
\$virtual_image = imagecreatetruecolor(\$desired_width, \$desired_height);

/* copy source image at a resized size */
imagecopyresampled(\$virtual_image, \$source_image, 0, 0, 0, 0, \$desired_width, \$desired_height, \$width, \$height);

/* create the physical thumbnail image to its destination */
imagejpeg(\$virtual_image, \$dest);
}

\$src="1494684586337H.jpg";
\$dest="new.jpg";
\$desired_width="200";
make_thumb(\$src, \$dest, \$desired_width);
?>
``````

### How to loop through a directory recursively to delete files with certain extensions

``````find /tmp \( -name "*.pdf" -o -name "*.doc" \) -type f -exec rm {} +
``````

Some versions of find (GNU, BSD) have a `-delete` action which you can use instead of calling `rm`:

``````find /tmp \( -name "*.pdf" -o -name "*.doc" \) -type f -delete
``````

### Adding text to ImageView in Android

To draw text directly on canvas do the following:

1. Create a member Paint object in `myImageView` constructor

``````Paint mTextPaint = new Paint();
``````
2. Use `canvas.drawText` in your `myImageView.onDraw()` method:

``````canvas.drawText("My fancy text", xpos, ypos, mTextPaint);
``````

Explore Paint and Canvas class documentation to add fancy effects.

### Unable to resolve host "<insert URL here>" No address associated with hostname

I got the same error and for the issue was that I was on VPN and I didn't realize that. After disconnecting the VPN and reconnecting the wifi resolved it.

### Best approach to remove time part of datetime in SQL Server

``````SELECT CAST(CAST(GETDATE() AS DATE) AS DATETIME)
``````

### Why is my Git Submodule HEAD detached from master?

As other people have said, the reason this happens is that the parent repo only contains a reference to (the SHA1 of) a specific commit in the submodule – it doesn't know anything about branches. This is how it should work: the branch that was at that commit may have moved forward (or backwards), and if the parent repo had referenced the branch then it could easily break when that happens.

However, especially if you are actively developing in both the parent repo and the submodule, `detached HEAD` state can be confusing and potentially dangerous. If you make commits in the submodule while it's in `detached HEAD` state, these become dangling and you can easily lose your work. (Dangling commits can usually be rescued using `git reflog`, but it's much better to avoid them in the first place.)

If you're like me, then most of the time if there is a branch in the submodule that points to the commit being checked out, you would rather check out that branch than be in detached HEAD state at the same commit. You can do this by adding the following alias to your `gitconfig` file:

``````[alias]
submodule-checkout-branch = "!f() { git submodule -q foreach 'branch=\$(git branch --no-column --format=\"%(refname:short)\" --points-at `git rev-parse HEAD` | grep -v \"HEAD detached\" | head -1); if [[ ! -z \$branch && -z `git symbolic-ref --short -q HEAD` ]]; then git checkout -q \"\$branch\"; fi'; }; f"
``````

Now, after doing `git submodule update` you just need to call `git submodule-checkout-branch`, and any submodule that is checked out at a commit which has a branch pointing to it will check out that branch. If you don't often have multiple local branches all pointing to the same commit, then this will usually do what you want; if not, then at least it will ensure that any commits you do make go onto an actual branch instead of being left dangling.

Furthermore, if you have set up git to automatically update submodules on checkout (using `git config --global submodule.recurse true`, see this answer), you can make a post-checkout hook that calls this alias automatically:

``````\$ cat .git/hooks/post-checkout
#!/bin/sh
git submodule-checkout-branch
``````

Then you don't need to call either `git submodule update` or `git submodule-checkout-branch`, just doing `git checkout` will update all submodules to their respective commits and check out the corresponding branches (if they exist).

### What is the default text size on Android?

Looks like someone else found it: What are the default font characteristics in Android ?

There someone discovered the default text size, for TextViews (which use TextAppearance.Small) it's 14sp.

### Ignore self-signed ssl cert using Jersey Client

I had the same problem adn did not want this to be set globally, so I used the same TrustManager and SSLContext code as above, I just changed the Client to be created with special properties

`````` ClientConfig config = new DefaultClientConfig();
config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(
new HostnameVerifier() {
@Override
public boolean verify( String s, SSLSession sslSession ) {
// whatever your matching policy states
}
}
));
Client client = Client.create(config);
``````

### Why is division in Ruby returning an integer instead of decimal value?

Change the `5` to `5.0`. You're getting integer division.

### Cannot start MongoDB as a service

Remember to create the database before starting the service

``````C:\>"C:\Program Files\MongoDB\Server\3.2\bin\mongod.exe" --dbpath d:\MONGODB\DB
2016-10-13T18:18:23.135+0200 I CONTROL  [main] Hotfix KB2731284 or later update is installed, no need to zero-out data files
2016-10-13T18:18:23.147+0200 I CONTROL  [initandlisten] MongoDB starting : pid=4024 port=27017 dbpath=d:\MONGODB\DB 64-bit host=mongosvr
2016-10-13T18:18:23.148+0200 I CONTROL  [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2
2016-10-13T18:18:23.149+0200 I CONTROL  [initandlisten] db version v3.2.8
2016-10-13T18:18:23.149+0200 I CONTROL  [initandlisten] git version: ed70e33130c977bda0024c125b56d159573dbaf0
2016-10-13T18:18:23.150+0200 I CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.0.1p-fips 9 Jul 2015
2016-10-13T18:18:23.151+0200 I CONTROL  [initandlisten] allocator: tcmalloc
2016-10-13T18:18:23.151+0200 I CONTROL  [initandlisten] modules: none
2016-10-13T18:18:23.152+0200 I CONTROL  [initandlisten] build environment:
2016-10-13T18:18:23.152+0200 I CONTROL  [initandlisten]     distmod: 2008plus-ssl
2016-10-13T18:18:23.153+0200 I CONTROL  [initandlisten]     distarch: x86_64
2016-10-13T18:18:23.153+0200 I CONTROL  [initandlisten]     target_arch: x86_64
2016-10-13T18:18:23.154+0200 I CONTROL  [initandlisten] options: { storage: { dbPath: "d:\MONGODB\DB" } }
2016-10-13T18:18:23.166+0200 I STORAGE  [initandlisten] wiredtiger_open config: create,cache_size=8G,session_max=20000,eviction=(threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000),checkpoint=(wait=60,log_size=2GB),statistics_log=(wait=0),
2016-10-13T18:18:23.722+0200 I NETWORK  [HostnameCanonicalizationWorker] Starting hostname canonicalization worker
2016-10-13T18:18:23.723+0200 I FTDC     [initandlisten] Initializing full-time diagnostic data capture with directory 'd:/MONGODB/DB/diagnostic.data'
2016-10-13T18:18:23.895+0200 I NETWORK  [initandlisten] waiting for connections on port 27017
``````

Then you can stop the process Control-C

``````2016-10-13T18:18:44.787+0200 I CONTROL  [thread1] Ctrl-C signal
2016-10-13T18:18:44.788+0200 I CONTROL  [consoleTerminate] got CTRL_C_EVENT, will terminate after current cmd ends
2016-10-13T18:18:44.789+0200 I FTDC     [consoleTerminate] Shutting down full-time diagnostic data capture
2016-10-13T18:18:44.792+0200 I CONTROL  [consoleTerminate] now exiting
2016-10-13T18:18:44.792+0200 I NETWORK  [consoleTerminate] shutdown: going to close listening sockets...
2016-10-13T18:18:44.793+0200 I NETWORK  [consoleTerminate] closing listening socket: 380
2016-10-13T18:18:44.793+0200 I NETWORK  [consoleTerminate] shutdown: going to flush diaglog...
2016-10-13T18:18:44.793+0200 I NETWORK  [consoleTerminate] shutdown: going to close sockets...
2016-10-13T18:18:44.795+0200 I STORAGE  [consoleTerminate] WiredTigerKVEngine shutting down
2016-10-13T18:18:45.116+0200 I STORAGE  [consoleTerminate] shutdown: removing fs lock...
2016-10-13T18:18:45.117+0200 I CONTROL  [consoleTerminate] dbexit:  rc: 12
``````

Now your database is prepared and you can start the service using

``````C:\>net start MongoDB
The MongoDB service is starting.
The MongoDB service was started successfully.
``````

### How do I get data from a table?

use Json & jQuery. It's way easier than oldschool javascript

``````function savedata1() {

var obj = \$('#myTable tbody tr').map(function() {
var \$row = \$(this);
var t1 = \$row.find(':nth-child(1)').text();
var t2 = \$row.find(':nth-child(2)').text();
var t3 = \$row.find(':nth-child(3)').text();
return {
td_1: \$row.find(':nth-child(1)').text(),
td_2: \$row.find(':nth-child(2)').text(),
td_3: \$row.find(':nth-child(3)').text()
};
}).get();
``````

### How to select a radio button by default?

XHTML solution:

``````<input type="radio" name="imgsel" value="" checked="checked" />
``````

Please note, that the actual value of `checked` attribute does not actually matter; it's just a convention to assign `"checked"`. Most importantly, strings like `"true"` or `"false"` don't have any special meaning.

If you don't aim for XHTML conformance, you can simplify the code to:

``````<input type="radio" name="imgsel" value="" checked>
``````

### How to convert decimal to hexadecimal in JavaScript

Combining some of these good ideas for an RGB-value-to-hexadecimal function (add the `#` elsewhere for HTML/CSS):

``````function rgb2hex(r,g,b) {
if (g !== undefined)
return Number(0x1000000 + r*0x10000 + g*0x100 + b).toString(16).substring(1);
else
return Number(0x1000000 + r[0]*0x10000 + r[1]*0x100 + r[2]).toString(16).substring(1);
}
``````

### initializing a boolean array in java

The array will be initialized to false when you allocate it.

All arrays in Java are initialized to the default value for the type. This means that arrays of ints are initialised to 0, arrays of booleans are initialised to false and arrays of reference types are initialised to null.

### How can I select and upload multiple files with HTML and PHP, using HTTP POST?

There are a few things you need to do to create a multiple file upload, its pretty basic actually. You don't need to use Java, Ajax, Flash. Just build a normal file upload form starting off with:

``````<form enctype="multipart/form-data" action="post_upload.php" method="POST">
``````

Then the key to success;

`<input type="file" name="file[]" multiple />`

do NOT forget those brackets! In the post_upload.php try the following:

``````<?php print_r(\$_FILES['file']['tmp_name']); ?>
``````

Notice you get an array with tmp_name data, which will mean you can access each file with an third pair of brackets with the file 'number' example:

``````\$_FILES['file']['tmp_name'][0]
``````

You can use php count() to count the number of files that was selected. Goodluck widdit!

### What's the difference between OpenID and OAuth?

I believe it makes sense revisit this question as also pointed out in the comments, the introduction of OpenID Connect may have brought more confusion.

OpenID Connect is an authentication protocol like OpenID 1.0/2.0 but it is actually built on top of OAuth 2.0, so you'll get authorization features along with authentication features. The difference between the two is pretty well explained in detail in this (relatively recent, but important) article: http://oauth.net/articles/authentication/

### If Browser is Internet Explorer: run an alternative script instead

Try this: The systemLanguage and the userLanguage is undefined in all browser.

``````if(navigator.userLanguage !== "undefined" && navigator.systemLanguage !== "undefined" && navigator.userAgent.match(/trident/i)) {
alert("hello explorer i catch U :D")
}
``````

### How can I format a String number to have commas and round?

Once you've converted your String to a number, you can use

``````// format the number for the default locale
NumberFormat.getInstance().format(num)
``````

or

``````// format the number for a particular locale
NumberFormat.getInstance(locale).format(num)
``````

### Disable text input history

``````<input type="text" autocomplete="off" />
``````

### NodeJs : TypeError: require(...) is not a function

For me, I got similar error when switched between branches - one used newer ("typescriptish") version of `@google-cloud/datastore` packages which returns object with Datastore constructor as one of properties of exported object and I switched to other branch for a task, an older datastore version was used there, which exports Datastore constructor "directly" as `module.exports` value. I got the error because node_modules still had newer modules used by branch I switched from.

### Convert varchar into datetime in SQL Server

The root cause of this issue can be in the regional settings - DB waiting for YYYY-MM-DD while an app sents, for example, DD-MM-YYYY (Russian locale format) as it was in my case. All I did - change locale format from Russian to English (United States) and voilà.

### Java program to connect to Sql Server and running the sample query From Eclipse

``````    SQL Server versions: 2005, 2008, 2008 R2, and 2012.
JDK version: 5.0 and 6.0.
``````

Run the downloaded program sqljdbc__.exe. It will extract the files into a specified directory (default is Microsoft JDBC Driver 4.0 for SQL Server). You will find two jar files sqljdbc.jar (for JDBC 3.0) and sqljdbc4.jar (for JDBC 4.0), plus some .dll files and HTML help files.

Place the sqljdbc4.jar file under your application’s classpath if you are using JDK 4.0 or sqljdbc4.1.jar file if you are using JDK 6.0 or later.

Try changing it to.

`````` Response.Clear();
Response.ClearContent();
Response.ContentType = "text/plain";
Response.Flush();
Response.TransmitFile(file.FullName);
Response.End();
``````

### How do I add the contents of an iterable to a set?

``````for item in items:
``````

For the record, I think the assertion that "There should be one-- and preferably only one --obvious way to do it." is bogus. It makes an assumption that many technical minded people make, that everyone thinks alike. What is obvious to one person is not so obvious to another.

I would argue that my proposed solution is clearly readable, and does what you ask. I don't believe there are any performance hits involved with it--though I admit I might be missing something. But despite all of that, it might not be obvious and preferable to another developer.

### Kill process by name?

If you have killall:

``````os.system("killall -9 iChat");
``````

Or:

``````os.system("ps -C iChat -o pid=|xargs kill -9")
``````

### How to set up googleTest as a shared library on Linux

Let me answer this specifically for ubuntu users. First start by installing the gtest development package.

``````sudo apt-get install libgtest-dev
``````

Note that this package only install source files. You have to compile the code yourself to create the necessary library files. These source files should be located at /usr/src/gtest. Browse to this folder and use cmake to compile the library:

``````sudo apt-get install cmake # install cmake
cd /usr/src/gtest
sudo mkdir build
cd build
sudo cmake ..
sudo make
sudo make install
``````

Now to compile your programs that uses gtest, you have to link it with:

``````-lgtest -lgtest_main -lpthread
``````

This worked perfectly for me on Ubuntu 14.04LTS.

### How to generate entire DDL of an Oracle schema (scriptable)?

``````expdp dumpfile=filename logfile=logname directory=dir_name schemas=schema_name
``````

and then import by using the `sqlfile` option (it will not import data it will just write the schema DDL to that file)

``````impdp dumpfile=filename logfile=logname directory=dir_name sqlfile=ddl.sql
``````

### Efficient way of having a function only execute once in a loop

I've thought of another—slightly unusual, but very effective—way to do this that doesn't require decorator functions or classes. Instead it just uses a mutable keyword argument, which ought to work in most versions of Python. Most of the time these are something to be avoided since normally you wouldn't want a default argument value to change from call-to-call—but that ability can be leveraged in this case and used as a cheap storage mechanism. Here's how that would work:

``````def my_function1(_has_run=[]):
if _has_run: return
print("my_function1 doing stuff")
_has_run.append(1)

def my_function2(_has_run=[]):
if _has_run: return
print("my_function2 doing some other stuff")
_has_run.append(1)

for i in range(10):
my_function1()
my_function2()

print('----')
my_function1(_has_run=[])  # Force it to run.
``````

Output:

``````my_function1 doing stuff
my_function2 doing some other stuff
----
my_function1 doing stuff
``````

This could be simplified a little further by doing what @gnibbler suggested in his answer and using an iterator (which were introduced in Python 2.2):

``````from itertools import count

def my_function3(_count=count()):
if next(_count): return
print("my_function3 doing something")

for i in range(10):
my_function3()

print('----')
my_function3(_count=count())  # Force it to run.
``````

Output:

``````my_function3 doing something
----
my_function3 doing something
``````

### Swift: Reload a View Controller

View Life Cycle

it will load `ViewWillAppear` everytime you open the view. above is the link to the picture View Controller Lifecycle.

viewWillAppear()—Called just before the view controller’s content view is added to the app’s view hierarchy. Use this method to trigger any operations that need to occur before the content view is presented onscreen. Despite the name, just because the system calls this method, it does not guarantee that the content view will become visible. The view may be obscured by other views or hidden. This method simply indicates that the content view is about to be added to the app’s view hierarchy.

https://developer.apple.com/library/archive/referencelibrary/GettingStarted/DevelopiOSAppsSwift/WorkWithViewControllers.html

### Android API 21 Toolbar Padding

A combination of

`android:padding="0dp"` In the xml for the Toolbar

and

`mToolbar.setContentInsetsAbsolute(0, 0)` In the code

This worked for me.

### How to push a new folder (containing other folders and files) to an existing git repo?

You need to `git add my_project` to stage your new folder. Then `git add my_project/*` to stage its contents. Then commit what you've staged using `git commit` and finally push your changes back to the source using `git push origin master` (I'm assuming you wish to push to the master branch).

### How to resolve the C:\fakepath?

If you go to Internet Explorer, Tools, Internet Option, Security, Custom, find the "Include local directory path When uploading files to a server" (it is quite a ways down) and click on "Enable" . This will work

### Django 1.7 - makemigrations not detecting changes

Added this answer because none of other available above worked for me.

In my case something even more weird was happening (Django 1.7 Version), In my models.py I had an "extra" line at the end of my file (it was a blank line) and when I executed the `python manage.py makemigrations` command the result was: "no changes detected".

To fix this I deleted this "blank line" that was at the end of my models.py file and I did run the command again, everything was fixed and all the changes made to models.py were detected!

### Peak memory usage of a linux/unix process

Perhaps (gnu) time(1) already does what you want. For instance:

``````\$ /usr/bin/time -f "%P %M" command
43% 821248
``````

But other profiling tools may give more accurate results depending on what you are looking for.

### How to open google chrome from terminal?

From the macOS Terminal, use `open` with the `-a` flag and give the name of the app you want to open. In this case "Google Chrome". You may pass it a file or URL you want it to open with.

``````open -a "Google Chrome" index.html
``````

### fitting data with numpy

Note that you can use the Polynomial class directly to do the fitting and return a Polynomial instance.

``````from numpy.polynomial import Polynomial

p = Polynomial.fit(x, y, 4)
plt.plot(*p.linspace())
``````

`p` uses scaled and shifted x values for numerical stability. If you need the usual form of the coefficients, you will need to follow with

``````pnormal = p.convert(domain=(-1, 1))
``````

### How can I use async/await at the top level?

i like this clever syntax to do async work from an entrypoint

``````void async function main() {
await doSomeWork()
await doMoreWork()
}()
``````

### Plotting categorical data with pandas and matplotlib

You can simply use `value_counts` with `sort` option set to `False`. This will preserve ordering of the categories

``````df['colour'].value_counts(sort=False).plot.bar(rot=0)
``````

### How do you convert an entire directory with ffmpeg?

Only this one Worked for me, pls notice that you have to create "newfiles" folder manually where the ffmpeg.exe file is located.

Convert . files to .wav audio Code:

``````for %%a in ("*.*") do ffmpeg.exe -i "%%a" "newfiles\%%~na.wav"
pause
``````

i.e if you want to convert all .mp3 files to .wav change `("*.*")` to `("*.mp3")`.

The author of this script is :

hope it helped .

### Unable to connect to SQL Server instance remotely

I know this is almost 1.5 years old, but I hope I can help someone with what I found.

I had built both a console app and a UWP app and my console connnected fine, but not my UWP. After hours of banging my head against the desk - if it's a intranet server hosting the SQL database you must enable "Private Networks (Client & Server)". It's under Package.appxmanifest and the Capabilities tab.Screenshot

### RichTextBox (WPF) does not have string property "Text"

Using two extension methods, this becomes very easy:

``````public static class Ext
{
public static void SetText(this RichTextBox richTextBox, string text)
{
richTextBox.Document.Blocks.Clear();
}

public static string GetText(this RichTextBox richTextBox)
{
return new TextRange(richTextBox.Document.ContentStart,
richTextBox.Document.ContentEnd).Text;
}
}
``````

### Rethrowing exceptions in Java without losing the stack trace

In Java is almost the same:

``````try
{
...
}
catch (Exception e)
{
if (e instanceof FooException)
throw e;
}
``````

### How to express a One-To-Many relationship in Django

To be more clear - there's no OneToMany in Django, only ManyToOne - which is Foreignkey described above. You can describe OneToMany relation using Foreignkey but that is very inexpressively.

A good article about it: https://amir.rachum.com/blog/2013/06/15/a-case-for-a-onetomany-relationship-in-django/

### Returning a stream from File.OpenRead()

You need

``````    str.CopyTo(data);
data.Position = 0; // reset to beginning
byte[] buf = new byte[data.Length];
``````

And since your `Test()` method is imitating the client it ought to `Close()` or `Dispose()` the `str` Stream. And the memoryStream too, just out of principal.

### Linq Select Group By

``````    from p in PriceLog
group p by p.LogDateTime.ToString("MMM") into g
select new
{
LogDate = g.Key.ToString("MMM yyyy"),
GoldPrice = (int)dateGroup.Average(p => p.GoldPrice),
SilverPrice = (int)dateGroup.Average(p => p.SilverPrice)
}
``````

### How to completely uninstall Android Studio on Mac?

I was also facing same kind of problem on my Macbook Pro. I took these very simple steps and freshly installed Android Studio.

** Link Contains Images, look if facing any problem.

These Very Simple Steps Can Solve Your Problem.

1. Type "Command+option+Space Bar"
2. Type "Android Studio"
3. Click '+' button just below search box.
4. A new bar will come up "Kind" is "any" click on "kind" --> Others --> search for "system file" and select that by putting a tick mark.! And click on Ok.
5. Then select "are included" from the drop down menu !
6. Then you get a lot of system file that need to be deleted to complete the fully un-installation of any app.
7. Click "command+A" to select all files and take a look on the file remove is some video files are also included. And click "command + Delete"

### How to overlay density plots in R?

Adding base graphics version that takes care of y-axis limits, add colors and works for any number of columns:

If we have a data set:

``````myData <- data.frame(std.nromal=rnorm(1000, m=0, sd=1),
wide.normal=rnorm(1000, m=0, sd=2),
exponent=rexp(1000, rate=1),
uniform=runif(1000, min=-3, max=3)
)
``````

Then to plot the densities:

``````dens <- apply(myData, 2, density)

plot(NA, xlim=range(sapply(dens, "[", "x")), ylim=range(sapply(dens, "[", "y")))
mapply(lines, dens, col=1:length(dens))

legend("topright", legend=names(dens), fill=1:length(dens))
``````

Which gives:

### Hide element by class in pure Javascript

`document.getElementsByClassName` returns an `HTMLCollection`(an array-like object) of all elements matching the class name. The `style` property is defined for `Element` not for `HTMLCollection`. You should access the first element using the bracket(subscript) notation.

``````document.getElementsByClassName('appBanner')[0].style.visibility = 'hidden';
``````

Updated jsFiddle

To change the style rules of all elements matching the class, using the Selectors API:

``````[].forEach.call(document.querySelectorAll('.appBanner'), function (el) {
el.style.visibility = 'hidden';
});
``````

If `for...of` is available:

``````for (let el of document.querySelectorAll('.appBanner')) el.style.visibility = 'hidden';
``````

### gcc makefile error: "No rule to make target ..."

In my experience, this error is frequently caused by a spelling error.

I got this error today.

make[1]: *** No rule to make target `maintenaceDialog.cpp', needed by`maintenaceDialog.o'. Stop.

In my case the error was simply a spelling error. The word MAINTENANCE was missing it's third N.

Also check the spelling on your filenames.

### How to activate JMX on my JVM for access with jconsole?

Note, Java 6 in the latest incarnation allows for jconsole to attach itself to a running process even after it has been started without JMX incantations.

If that is available to you, also consider jvisualvm as it provides a wealth of information on running processes, including a profiler.

### Post order traversal of binary tree without recursion

Here is a Python version too ::

``````class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None

def postOrderIterative(root):

if root is None :
return

s1 = []
s2 = []
s1.append(root)

while(len(s1)>0):
node = s1.pop()
s2.append(node)

if(node.left!=None):
s1.append(node.left)

if(node.right!=None):
s1.append(node.right)

while(len(s2)>0):
node = s2.pop()
print(node.data)

root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
postOrderIterative(root)
``````

Here is the output ::

### Create a new txt file using VB.NET

Here is a single line that will create (or overwrite) the file:

``````File.Create("C:\my files\2010\SomeFileName.txt").Dispose()
``````

Note: calling Dispose() ensures that the reference to the file is closed.

### Single Result from Database by using mySQLi

Use `mysqli_fetch_row()`. Try this,

``````\$query = "SELECT ssfullname, ssemail FROM userss WHERE user_id = ".\$user_id;
\$result = mysqli_query(\$conn, \$query);
\$row   = mysqli_fetch_row(\$result);

\$ssfullname = \$row['ssfullname'];
\$ssemail    = \$row['ssemail'];
``````

### How do CSS triangles work?

clip-path has the best result for me - works great for divs/containers with and without fixed dimensions:

``````.triangleContainer{
position: relative;
width: 500px;
height: 500px;
}

.triangleContainer::before{
content: "";
position: absolute;
background:blue;
top: 0;
left: 0;
width: 100%;
height: 100%;
clip-path: polygon(50% 0, 0 100%, 100% 100%);
}
``````

### Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

Do make sure that you haven't written your unit tests in a .NET Standard 2.0 Class Library. The visualstudio runner does not support running tests in netstandard2.0 class libraries at the time of this writing.

Check here for the Test Runner Compatibility matrix:

https://xunit.github.io/#runners

### How to split a number into individual digits in c#?

Here is some code that might help you out. Strings can be treated as an array of characters

``````string numbers = "12345";
int[] intArray = new int[numbers.Length];
for (int i=0; i < numbers.Length; i++)
{
intArray[i] = int.Parse(numbers[i]);
}
``````

### How to close a web page on a button click, a hyperlink or a link button click?

Assuming you're using WinForms, as it was the first thing I did when I was starting C# you need to create an event to close this form.

Lets say you've got a button called myNewButton. If you double click it on WinForms designer you will create an event. After that you just have to use `this.Close`

``````    private void myNewButton_Click(object sender, EventArgs e) {
this.Close();
}
``````

And that should be it.

The only reason for this not working is that your Event is detached from button. But it should create new event if old one is no longer attached when you double click on the button in WinForms designer.

### CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

``````Access-Control-Allow-Origin:*
``````

or

``````Access-Control-Allow-Origin:your domain
``````

In Apache config files, the code is like this:

``````Header set Access-Control-Allow-Origin "*"
``````

In nodejs,the code is like this:

``````res.setHeader('Access-Control-Allow-Origin','*');
``````

### Gaussian filter in MATLAB

You first create the filter with fspecial and then convolve the image with the filter using imfilter (which works on multidimensional images as in the example).

You specify `sigma` and `hsize` in `fspecial`.

#### Code:

``````%%# Read an image
%# Create the gaussian filter with hsize = [5 5] and sigma = 2
G = fspecial('gaussian',[5 5],2);
%# Filter it
Ig = imfilter(I,G,'same');
%# Display
imshow(Ig)
``````

### How would you make two <div>s overlap?

I might approach it like so (CSS and HTML):

_x000D_
_x000D_
``````html,_x000D_
body {_x000D_
margin: 0px;_x000D_
}_x000D_
#logo {_x000D_
position: absolute; /* Reposition logo from the natural layout */_x000D_
left: 75px;_x000D_
top: 0px;_x000D_
width: 300px;_x000D_
height: 200px;_x000D_
z-index: 2;_x000D_
}_x000D_
#content {_x000D_
margin-top: 100px; /* Provide buffer for logo */_x000D_
}_x000D_
height: 75px;_x000D_
margin-left: 400px; /* Flush links (with a 25px "padding") right of logo */_x000D_
}``````
_x000D_
``````<div id="logo">_x000D_
<img src="https://via.placeholder.com/200x100" />_x000D_
</div>_x000D_
<div id="content">_x000D_
_x000D_
</div>``````
_x000D_
_x000D_
_x000D_

### C++ Error 'nullptr was not declared in this scope' in Eclipse IDE

You are using g++ 4.6 version you must invoke the flag -std=c++0x to compile

g++ -std=c++0x *.cpp -o output

### How to install Maven 3 on Ubuntu 18.04/17.04/16.10/16.04 LTS/15.10/15.04/14.10/14.04 LTS/13.10/13.04 by using apt-get?

Here's an easier way:

``````sudo apt-get install maven
``````

More details are here.

### Open a local HTML file using window.open in Chrome

First, make sure that the source page and the target page are both served through the `file` URI scheme. You can't force an `http` page to open a `file` page (but it works the other way around).

Next, your script that calls `window.open()` should be invoked by a user-initiated event, such as clicks, keypresses and the like. Simply calling `window.open()` won't work.

You can test this right here in this question page. Run these in Chrome's JavaScript console:

``````// Does nothing

// This will open a new window, but it would be blank
\$(document.body).unbind('click').click(function() { window.open('file:///path/to/a/local/html/file.html'); });
``````

You can also test if this works with a local file. Here's a sample HTML file that simply loads jQuery:

``````<html>
<body>
<h5>Feel the presha</h5>
<h3>Come play my game, I'll test ya</h3>
</body>
</html>
``````

Then open Chrome's JavaScript console and run the statements above. The 3rd one will now work.

### How to Exit a Method without Exiting the Program?

If the function is a void, ending the function will `return`. Otherwise, you need to do an explicit `return someValue`. As Mark mentioned, you can also `throw` an exception. What's the context of your question? Do you have a larger code sample with which to show you some ways to exit the function?

### Show/Hide Table Rows using Javascript classes

Well one way to do it would be to just put a class on the "parent" rows and remove all the ids and inline `onclick` attributes:

``````<table id="products">
<tr>
<th>Product</th>
<th>Price</th>
<th>Destination</th>
<th>Updated on</th>
</tr>
<tbody>
<tr class="parent">
<td>Oranges</td>
<td>100</td>
<td><a href="#">+ On Store</a></td>
<td>22/10</td>
</tr>
<tr>
<td></td>
<td>120</td>
<td>City 1</td>
<td>22/10</td>
</tr>
<tr>
<td></td>
<td>140</td>
<td>City 2</td>
<td>22/10</td>
</tr>
...etc.
</tbody>
</table>
``````

And then have some CSS that hides all non-parents:

``````tbody tr {
display : none;          // default is hidden
}
tr.parent {
display : table-row;     // parents are shown
}
tr.open {
display : table-row;     // class to be given to "open" child rows
}
``````

That greatly simplifies your html. Note that I've added `<thead>` and `<tbody>` to your markup to make it easy to hide data rows and ignore heading rows.

With jQuery you can then simply do this:

``````// when an anchor in the table is clicked
\$("#products").on("click","a",function(e) {
// prevent default behaviour
e.preventDefault();
// find all the following TR elements up to the next "parent"
// and toggle their "open" class
\$(this).closest("tr").nextUntil(".parent").toggleClass("open");
});
``````

Or, to implement something like that in plain JavaScript, perhaps something like the following:

``````document.getElementById("products").addEventListener("click", function(e) {
// if clicked item is an anchor
if (e.target.tagName === "A") {
e.preventDefault();
// get reference to anchor's parent TR
var row = e.target.parentNode.parentNode;
// loop through all of the following TRs until the next parent is found
while ((row = nextTr(row)) && !/\bparent\b/.test(row.className))
toggle_it(row);
}
});

function nextTr(row) {
// find next sibling that is an element (skip text nodes, etc.)
while ((row = row.nextSibling) && row.nodeType != 1);
return row;
}

function toggle_it(item){
if (/\bopen\b/.test(item.className))       // if item already has the class
item.className = item.className.replace(/\bopen\b/," "); // remove it
else                                       // otherwise
item.className += " open";             // add it
}
``````

Either way, put the JavaScript in a `<script>` element that is at the end of the body, so that it runs after the table has been parsed.

### How to open a link in new tab (chrome) using Selenium WebDriver?

Selenium can only automate on the WebElements of the browser. Opening a new tab is an operation performed on the webBrowser which is a stand alone application. For doing this you can make use of the Robot class from the java.util.* package which can perform operations using the keyboard regardless of what type of application it is. So here's the code for your operation. Note that you cannot automate stand alone applications using the Robot class but you can perform keyboard or mouse operations

``````System.setProperty("webdriver.chrome.driver","softwares\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
driver.manage().window().maximize();
Robot rob = new Robot();
rob.keyPress(keyEvent.VK_CONTROL);
rob.keyPress(keyEvent.VK_T);
rob.keyRelease(keyEvent.VK_CONTROL);
rob.keyRelease(keyEvent.VK_T);
``````

After this step you will need a window iterator to switch to the new tab:

``````Set <String> ids = driver.getWindowHandles();
Iterator <String> it = ids.iterator();
String currentWindow = it.next();
String newWindow = it.next();
driver.switchTo().window(newWindow);
``````

### XmlSerializer giving FileNotFoundException at constructor

This exception can also be trapped by a managed debugging assistant (MDA) called BindingFailure.

This MDA is useful if your application is designed to ship with pre-build serialization assemblies. We do this to increase performance for our application. It allows us to make sure that the pre-built serialization assemblies are being properly built by our build process, and loaded by the application without being re-built on the fly.

It's really not useful except in this scenario, because as other posters have said, when a binding error is trapped by the Serializer constructor, the serialization assembly is re-built at runtime. So you can usually turn it off.

### How to compute precision, recall, accuracy and f1-score for the multiclass case with scikit learn?

Lot of very detailed answers here but I don't think you are answering the right questions. As I understand the question, there are two concerns:

1. How to I score a multiclass problem?
2. How do I deal with unbalanced data?

#### 1.

You can use most of the scoring functions in scikit-learn with both multiclass problem as with single class problems. Ex.:

``````from sklearn.metrics import precision_recall_fscore_support as score

predicted = [1,2,3,4,5,1,2,1,1,4,5]
y_test = [1,2,3,4,5,1,2,1,1,4,1]

precision, recall, fscore, support = score(y_test, predicted)

print('precision: {}'.format(precision))
print('recall: {}'.format(recall))
print('fscore: {}'.format(fscore))
print('support: {}'.format(support))
``````

This way you end up with tangible and interpretable numbers for each of the classes.

``````| Label | Precision | Recall | FScore | Support |
|-------|-----------|--------|--------|---------|
| 1     | 94%       | 83%    | 0.88   | 204     |
| 2     | 71%       | 50%    | 0.54   | 127     |
| ...   | ...       | ...    | ...    | ...     |
| 4     | 80%       | 98%    | 0.89   | 838     |
| 5     | 93%       | 81%    | 0.91   | 1190    |
``````

Then...

#### 2.

... you can tell if the unbalanced data is even a problem. If the scoring for the less represented classes (class 1 and 2) are lower than for the classes with more training samples (class 4 and 5) then you know that the unbalanced data is in fact a problem, and you can act accordingly, as described in some of the other answers in this thread. However, if the same class distribution is present in the data you want to predict on, your unbalanced training data is a good representative of the data, and hence, the unbalance is a good thing.

### Viewing PDF in Windows forms using C#

``````private void btnopen_Click(object sender, EventArgs e){
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK){
axAcroPDF1.src = openFileDialog1.FileName;
}
}
``````

### Convert java.util.Date to java.time.LocalDate

``````Date input = new Date();
LocalDateTime  conv=LocalDateTime.ofInstant(input.toInstant(), ZoneId.systemDefault());
LocalDate convDate=conv.toLocalDate();
``````

The `Date` instance does contain time too along with the date while `LocalDate` doesn't. So you can firstly convert it into `LocalDateTime` using its method `ofInstant()` then if you want it without time then convert the instance into `LocalDate`.

### Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel

I have Windows 8 installed on my machine, and the aspnet_regiis.exe tool did not worked for me either.

The solution that worked for me is posted on this link, on the answer by Neha: System.ServiceModel.Activation.HttpModule error

Everywhere the problem to this solution was mentioned as re-registering aspNet by using aspnet_regiis.exe. But this did not work for me.

Though this is a valid solution (as explained beautifully here)

but it did not work with Windows 8.

For Windows 8 you need to Windows features and enable everything under ".Net Framework 3.5" and ".Net Framework 4.5 Advanced Services".

Thanks Neha

### Add a list item through javascript

The above answer was helpful for me, but it might be useful (or best practice) to add the name on submit, as I wound up doing. Hopefully this will be helpful to someone. CodePen Sample

``````    <form id="formAddName">
<fieldset>
<label for="firstName">First Name</label>
<input type="text" id="firstName" name="firstName" />

</fieldset>
</form>

<ol id="demo"></ol>

<script>
var list = document.getElementById('demo');
entry.onsubmit = function(evt) {
evt.preventDefault();
var firstName = document.getElementById('firstName').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(firstName));
list.appendChild(entry);
}
</script>
``````

### Parse JSON object with string and value only

You need to get a list of all the keys, loop over them and add them to your map as shown in the example below:

``````    String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
JSONObject jObject  = new JSONObject(s);

Map<String,String> map = new HashMap<String,String>();
while(iter.hasNext()){
String key = (String)iter.next();
map.put(key,value);
}
``````

### How to extract base URL from a string in JavaScript?

You can do it using a regex :

``````/(http:\/\/)?(www)[^\/]+\//i
``````

does it fit ?

### Best way to compare 2 XML documents in Java

The following will check if the documents are equal using standard JDK libraries.

```DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setCoalescing(true);
dbf.setIgnoringElementContentWhitespace(true);
DocumentBuilder db = dbf.newDocumentBuilder();

Document doc1 = db.parse(new File("file1.xml"));
doc1.normalizeDocument();

Document doc2 = db.parse(new File("file2.xml"));
doc2.normalizeDocument();

Assert.assertTrue(doc1.isEqualNode(doc2));
```

normalize() is there to make sure there are no cycles (there technically wouldn't be any)

The above code will require the white spaces to be the same within the elements though, because it preserves and evaluates it. The standard XML parser that comes with Java does not allow you to set a feature to provide a canonical version or understand `xml:space` if that is going to be a problem then you may need a replacement XML parser such as xerces or use JDOM.

### How do I set browser width and height in Selenium WebDriver?

Try something like this:

``````IWebDriver _driver = new FirefoxDriver();
_driver.Manage().Window.Position = new Point(0, 0);
_driver.Manage().Window.Size = new Size(1024, 768);
``````

Not sure if it'll resize after being launched though, so maybe it's not what you want

### UILabel Align Text to center

From iOS 6 and later `UITextAlignment` is deprecated. use `NSTextAlignment`

``````myLabel.textAlignment = NSTextAlignmentCenter;
``````

Swift Version from iOS 6 and later

``````myLabel.textAlignment = .center
``````

### Python 3 Float Decimal Points/Precision

In a word, you can't.

`3.65` cannot be represented exactly as a `float`. The number that you're getting is the nearest number to `3.65` that has an exact `float` representation.

The difference between (older?) Python 2 and 3 is purely due to the default formatting.

I am seeing the following both in Python 2.7.3 and 3.3.0:

``````In [1]: 3.65
Out[1]: 3.65

In [2]: '%.20f' % 3.65
Out[2]: '3.64999999999999991118'
``````

For an exact decimal datatype, see `decimal.Decimal`.

### Bash Templating: How to build configuration files from templates with Bash?

Instead of reinventing the wheel go with envsubst Can be used in almost any scenario, for instance building configuration files from environment variables in docker containers.

If on mac make sure you have homebrew then link it from gettext:

``````brew install gettext
``````

./template.cfg

``````# We put env variables into placeholders here
this_variable_1 = \${SOME_VARIABLE_1}
this_variable_2 = \${SOME_VARIABLE_2}
``````

./.env:

``````SOME_VARIABLE_1=value_1
SOME_VARIABLE_2=value_2
``````

./configure.sh

``````#!/bin/bash
cat template.cfg | envsubst > whatever.cfg
``````

Now just use it:

``````# make script executable
chmod +x ./configure.sh
. .env
# In practice you may not have to manually export variables
# if your solution depends on tools that utilise .env file
# automatically like pipenv etc.
export SOME_VARIABLE_1 SOME_VARIABLE_2
./configure.sh
``````

### Find an element in a list of tuples

If you just want the first number to match you can do it like this:

``````[item for item in a if item[0] == 1]
``````

If you are just searching for tuples with 1 in them:

``````[item for item in a if 1 in item]
``````

### What are the alternatives now that the Google web search API has been deprecated?

Yes, Google Custom Search has now replaced the old Search API, but you can still use Google Custom Search to search the entire web, although the steps are not obvious from the Custom Search setup.

To create a Google Custom Search engine that searches the entire web:

1. From the Google Custom Search homepage ( http://www.google.com/cse/ ), click Create a Custom Search Engine.
2. Type a name and description for your search engine.
3. Under Define your search engine, in the Sites to Search box, enter at least one valid URL (For now, just put www.anyurl.com to get past this screen. More on this later ).
4. Select the CSE edition you want and accept the Terms of Service, then click Next. Select the layout option you want, and then click Next.
5. Click any of the links under the Next steps section to navigate to your Control panel.
6. In the left-hand menu, under Control Panel, click Basics.
7. In the Search Preferences section, select Search the entire web but emphasize included sites.
8. Click Save Changes.
9. In the left-hand menu, under Control Panel, click Sites.
10. Delete the site you entered during the initial setup process.

Now your custom search engine will search the entire web.

Pricing

• After that you pay \$5 per 1000 queries.
• There is a maximum of 10,000 queries per day.

• The search quality is much lower than normal Google search (no synonyms, "intelligence" etc.)
• It seems that Google is even planning to shut down this service completely.

### Dictionary of dictionaries in Python?

dictionary's setdefault is a good way to update an existing dict entry if it's there, or create a new one if it's not all in one go:

Looping style:

``````# This is our sample data
data = [("Milter", "Miller", 4), ("Milter", "Miler", 4), ("Milter", "Malter", 2)]

# dictionary we want for the result
dictionary = {}

# loop that makes it work
for realName, falseName, position in data:
dictionary.setdefault(realName, {})[falseName] = position
``````

dictionary now equals:

``````{'Milter': {'Malter': 2, 'Miler': 4, 'Miller': 4}}
``````

# Generate change SQL queries (FAST)

mysql -e "SELECT CONCAT( 'update ', table_name , ' set ', column_name, ' = replace(', column_name,', ''www.oldsite.com'', ''www.newsite.com'');' ) AS statement FROM information_schema.columns WHERE table_name LIKE 'wp_%'" -u root -p your_db_name_here > upgrade_script.sql

# Run generated script with --force options to skip errors. (SLOW - grab a coffee if big DB)

mysql -u root -p your_db_name_here --force < upgrade_script.sql

### Specifying java version in maven - differences between properties and compiler plugin

Consider the alternative:

``````<properties>
<javac.src.version>1.8</javac.src.version>
<javac.target.version>1.8</javac.target.version>
</properties>
``````

It should be the same thing of `maven.compiler.source/maven.compiler.target` but the above solution works for me, otherwise the second one gets the parent specification (I have a matrioska of .pom)

### How to verify a method is called two times with mockito verify()

``````testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"
``````

code:

``````interface MyCallback {
fun someMethod(value: String)
}

class MyTestableManager(private val callback: MyCallback){
fun perform(){
callback.someMethod("first")
callback.someMethod("second")
callback.someMethod("third")
}
}
``````

test:

``````import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.mock
...
val callback: MyCallback = mock()
val manager = MyTestableManager(callback)
manager.perform()

val captor: KArgumentCaptor<String> = com.nhaarman.mockitokotlin2.argumentCaptor<String>()

verify(callback, times(3)).someMethod(captor.capture())

assertTrue(captor.allValues[0] == "first")
assertTrue(captor.allValues[1] == "second")
assertTrue(captor.allValues[2] == "third")
``````

### Set HTML element's style property in javascript

I'd like to note that it's usually preferable to change the class of the node instead of it's style and let CSS handle what that means.

### Hook up Raspberry Pi via Ethernet to laptop without router?

configure static ip on the raspberry pi:

``````sudo nano /etc/network/interfaces
``````

``````iface eth0 inet static
``````

then you can acces your raspberry via ssh

``````ssh [email protected]
``````

### How does spring.jpa.hibernate.ddl-auto property exactly work in Spring?

For the record, the `spring.jpa.hibernate.ddl-auto` property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, `hibernate.hbm2ddl.auto`.

The values `create`, `create-drop`, `validate`, and `update` basically influence how the schema tool management will manipulate the database schema at startup.

For example, the `update` operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.

The `update` operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.

Typically in test case scenarios, you'll likely use `create-drop` so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.

In development, it's often common to see developers use `update` to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.

In production, it's often highly recommended you use `none` or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.

### Logarithmic returns in pandas dataframe

Here is one way to calculate log return using `.shift()`. And the result is similar to but not the same as the gross return calculated by `pct_change()`. Can you upload a copy of your sample data (dropbox share link) to reproduce the inconsistency you saw?

``````import pandas as pd
import numpy as np

np.random.seed(0)
df = pd.DataFrame(100 + np.random.randn(100).cumsum(), columns=['price'])
df['pct_change'] = df.price.pct_change()
df['log_ret'] = np.log(df.price) - np.log(df.price.shift(1))

Out[56]:
price  pct_change  log_ret
0   101.7641         NaN      NaN
1   102.1642      0.0039   0.0039
2   103.1429      0.0096   0.0095
3   105.3838      0.0217   0.0215
4   107.2514      0.0177   0.0176
5   106.2741     -0.0091  -0.0092
6   107.2242      0.0089   0.0089
7   107.0729     -0.0014  -0.0014
..       ...         ...      ...
92  101.6160      0.0021   0.0021
93  102.5926      0.0096   0.0096
94  102.9490      0.0035   0.0035
95  103.6555      0.0069   0.0068
96  103.6660      0.0001   0.0001
97  105.4519      0.0172   0.0171
98  105.5788      0.0012   0.0012
99  105.9808      0.0038   0.0038

[100 rows x 3 columns]
``````

### printing a two dimensional array in python

``````for i in A:
print('\t'.join(map(str, i)))
``````

### Warning: date_format() expects parameter 1 to be DateTime

You need to pass DateTime object to this func. See manual: php

``````string date_format ( DateTime \$object , string \$format )
``````

You can try using:

``````date_format (new DateTime(\$time), 'd-m-Y');
``````

Or you can also use:

``````\$date = date_create('2000-01-01');
echo date_format(\$date, 'Y-m-d H:i:s');
``````

### How to ignore conflicts in rpm installs

From the context, the conflict was caused by the version of the package.
Let's take a look the manual about `rpm`:

``````--force
Same as using --replacepkgs, --replacefiles, and --oldpackage.

--oldpackage
Allow an upgrade to replace a newer package with an older one.
``````

So, you can execute the command `rpm -Uvh info-4.13a-2.rpm --force` to solve your issue.

### How to lazy load images in ListView in Android

I can recommend a different way that works like a charm: Android Query.

``````AQuery androidAQuery = new AQuery(this);
``````

As an example:

``````androidAQuery.id(YOUR IMAGEVIEW).image(YOUR IMAGE TO LOAD, true, true, getDeviceWidth(), ANY DEFAULT IMAGE YOU WANT TO SHOW);
``````

It's very fast and accurate, and using this you can find many more features like animation when loading, getting a bitmap (if needed), etc.

### How can I change IIS Express port for a site

If we are talking about a WebSite, not web app, my issue was that the actual .sln folder was somewhere else than the website, and I had not noticed. Look for the .sln path and then for the .vs (hidden) folder there.

### How can I get new selection in "select" in Angular 2?

In Angular 5 I did with the following way. get the object \$event.value instead of \$event.target.value

``````<mat-form-field color="warn">
<mat-select (ngModelChange)="onChangeTown(\$event)" class="form-width" formControlName="branch" [(ngModel)]="branch" placeholder="Enter branch">
<mat-option *ngFor="let branch of branchs" [value]="branch.value">
{{ branch.name }}
</mat-option>
</mat-select>
</mat-form-field>

onChangeTown(event): void {
const selectedTown = event;
console.log('selectedTown: ', selectedTown);
}
``````

### How to scanf only integer and repeat reading if the user enters non-numeric characters?

You could create a function that reads an integer between 1 and 23 or returns 0 if non-int

e.g.

``````int getInt()
{
int n = 0;
char buffer[128];
fgets(buffer,sizeof(buffer),stdin);
n = atoi(buffer);
return ( n > 23 || n < 1 ) ? 0 : n;
}
``````

### rails + MySQL on OSX: Library not loaded: libmysqlclient.18.dylib

In El Capitan I got `ln: /usr/lib/libmysqlclient.18.dylib: Operation not permitted`

In El Capitan `/usr/lib/` now has a restricted flag and can't be written to without disabling security so I just put the link in `/usr/local/lib` instead.

``````sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.18.dylib
``````

Rails server is running fine again.

### How can I autoplay a video using the new embed code style for Youtube?

Just put "?autoplay=1" in the url the video will autoload.

So your url would be: `http://www.youtube.com/embed/JW5meKfy3fY?autoplay=1`

In case you wanna disable autoplay, just make `1` to `0` as `?autoplay=0`

### Change action bar color in android

onclick buttons `c2` to fetch and change the color of action bar and notification bar according to button's background, hope this helps

``````int color = c2.getBackground()).getColor();
int colorlighter = -color * 40 / 100 + color;
getWindow().setStatusBarColor(colorlighter);
ActionBar bar = getSupportActionBar();
bar.setBackgroundDrawable(new ColorDrawable(color));
``````

`colorlighter` is used to set color of notification bar a little lighter than action bar
`color` is the background color of button `c2`, according to which we change our color.

### Java socket API: How to tell if a connection has been closed?

I faced similar problem. In my case client must send data periodically. I hope you have same requirement. Then I set SO_TIMEOUT `socket.setSoTimeout(1000 * 60 * 5);` which is throw `java.net.SocketTimeoutException` when specified time is expired. Then I can detect dead client easily.

### Why does .NET foreach loop throw NullRefException when collection is null?

Because behind the scenes the `foreach` acquires an enumerator, equivalent to this:

``````using (IEnumerator<int> enumerator = returnArray.getEnumerator()) {
while (enumerator.MoveNext()) {
int i = enumerator.Current;
// do some more stuff
}
}
``````

### Selecting data from two different servers in SQL Server

I had same issue to connect an SQL_server 2008 to an SQL_server 2016 hosted in a remote server. Other answers didn't worked for me straightforward. I write my tweaked solution here as I think it may be useful for someone else.

An extended answer for remote IP db connections:

``````EXEC sp_addlinkedserver @server='SRV_NAME',
@srvproduct=N'',
@provider=N'SQLNCLI',
@datasrc=N'aaa.bbb.ccc.ddd';

``````

...where `SRV_NAME` is an invented name. We will use it to refer to the remote server from our queries. `aaa.bbb.ccc.ddd` is the ip address of the remote server hosting your SQLserver DB.

Step 2: Run your queries For instance:

``````SELECT * FROM [SRV_NAME].your_remote_db_name.dbo.your_table
``````

...and that's it!

### Format specifier %02x

Your string is wider than your format width of 2. So there's no padding to be done.

### UIButton title text color

I created a custom class MyButton extended from `UIButton`. Then added this inside the `Identity Inspector`:

After this, change the button type to Custom:

Then you can set attributes like `textColor` and `UIFont` for your `UIButton` for the different states:

Then I also created two methods inside `MyButton` class which I have to call inside my code when I want a `UIButton` to be displayed as highlighted:

``````- (void)changeColorAsUnselection{
[self setTitleColor:[UIColor colorFromHexString:acColorGreyDark]
forState:UIControlStateNormal &
UIControlStateSelected &
UIControlStateHighlighted];
}

- (void)changeColorAsSelection{
[self setTitleColor:[UIColor colorFromHexString:acColorYellow]
forState:UIControlStateNormal &
UIControlStateHighlighted &
UIControlStateSelected];
}
``````

You have to set the `titleColor` for normal, highlight and selected `UIControlState` because there can be more than one state at a time according to the documentation of `UIControlState`. If you don't create these methods, the `UIButton` will display selection or highlighting but they won't stay in the `UIColor` you setup inside the `UIInterface Builder` because they are just available for a short display of a selection, not for displaying selection itself.

### Parse v. TryParse

`Parse` throws an exception if it cannot parse the value, whereas `TryParse` returns a `bool` indicating whether it succeeded.

`TryParse` does not just `try`/`catch` internally - the whole point of it is that it is implemented without exceptions so that it is fast. In fact the way it is most likely implemented is that internally the `Parse` method will call `TryParse` and then throw an exception if it returns `false`.

In a nutshell, use `Parse` if you are sure the value will be valid; otherwise use `TryParse`.

### How do I open port 22 in OS X 10.6.7

I couldn't solve the problem; Then I did the following and the issue was resolved: Refer here:

``````sudo launchctl unload -w /System/Library/LaunchDaemons/ssh.plist
ssh -v localhost
sudo launchctl list | grep "sshd"
46427   -   com.openssh.sshd
``````

### forcing web-site to show in landscape mode only

While I myself would be waiting here for an answer, I wonder if it can be done via CSS:

``````@media only screen and (orientation:portrait){
#wrapper {width:1024px}
}

@media only screen and (orientation:landscape){
#wrapper {width:1024px}
}
``````

### How to Multi-thread an Operation Within a Loop in Python

Edit 2018-02-06: revision based on this comment

Edit: forgot to mention that this works on Python 2.7.x

There's multiprocesing.pool, and the following sample illustrates how to use one of them:

``````from multiprocessing.pool import ThreadPool as Pool
# from multiprocessing import Pool

pool_size = 5  # your "parallelness"

# define worker function before a Pool is instantiated
def worker(item):
try:
api.my_operation(item)
except:
print('error with item')

pool = Pool(pool_size)

for item in items:
pool.apply_async(worker, (item,))

pool.close()
pool.join()
``````

Now if you indeed identify that your process is CPU bound as @abarnert mentioned, change ThreadPool to the process pool implementation (commented under ThreadPool import). You can find more details here: http://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers

### Cannot connect to local SQL Server with Management Studio

Check the sql log in the LOG directory of your instance - see if anything is going on there. You'll need to stop the service to open the log - or restart and you can read the old one - named with .1 on the end.

With the error you're getting, you need to enable TCP/IP or Named pipes for named connections. Shared memory connection should work, but you seem to not be using that. Are you trying to connect through SSMS?

In my log I see entries like this...

``````Server local connection provider is ready to accept connection on [\\.\pipe\mssql\$sqlexpress\sql\query ]
``````

As the comments said, .\SQLEXPRESS should work. Also worstationName\SQLEXPRESS will work.

### Angular cli generate a service and include the provider in one step

#### Angular 6+ Singleton Services

The recommended approach for a singleton service for Angular 6 and beyond is :

``````import { Injectable } from '@angular/core';

@Injectable({
providedIn: 'root',
})
export class UserService {
}
``````

In fact the CLI `--module` switch doesn't even exist any more for registering a service at the `app` level because it doesn't need to modify `app.module.ts` anymore.

This will create the above code, without needing to specify a module.

``````ng g s services/user
``````

So if you don't want your service to be a singleton you must remove the `providedIn` code yourself - and then add it manually to `providers` for a component or lazy loaded module. Doesn't look like there is currently a switch to not generate the `providedIn: 'root'` part so you need to manually remove it.

### How to delete duplicate rows in SQL Server?

should work equally as in other SQL servers, like Postgres:

``````DELETE FROM table
WHERE id NOT IN (
select min(id) from table
group by col1, col2, col3, col4, col5, col6, col7
)
``````

### Java FileOutputStream Create File if not exists

Just Giving an alternative way to create the file only if doesn't exists using Path and Files.

``````Path path = Paths.get("Some/path/filename.txt");
Files.createDirectories(path.getParent());
if( !Files.exists(path))
Files.createFile(path);
Files.write(path, ("").getBytes());
``````

### What exactly is Python's file.flush() doing?

Because the operating system may not do so. The flush operation forces the file data into the file cache in RAM, and from there it's the OS's job to actually send it to the disk.

### How to find time complexity of an algorithm

Although there are some good answers for this question. I would like to give another answer here with several examples of `loop`.

• O(n): Time Complexity of a loop is considered as O(n) if the loop variables is incremented / decremented by a constant amount. For example following functions have O(n) time complexity.

``````// Here c is a positive integer constant
for (int i = 1; i <= n; i += c) {
// some O(1) expressions
}

for (int i = n; i > 0; i -= c) {
// some O(1) expressions
}
``````
• O(n^c): Time complexity of nested loops is equal to the number of times the innermost statement is executed. For example the following sample loops have O(n^2) time complexity

``````for (int i = 1; i <=n; i += c) {
for (int j = 1; j <=n; j += c) {
// some O(1) expressions
}
}

for (int i = n; i > 0; i += c) {
for (int j = i+1; j <=n; j += c) {
// some O(1) expressions
}
``````

For example Selection sort and Insertion Sort have O(n^2) time complexity.

• O(Logn) Time Complexity of a loop is considered as O(Logn) if the loop variables is divided / multiplied by a constant amount.

``````for (int i = 1; i <=n; i *= c) {
// some O(1) expressions
}
for (int i = n; i > 0; i /= c) {
// some O(1) expressions
}
``````

For example Binary Search has O(Logn) time complexity.

• O(LogLogn) Time Complexity of a loop is considered as O(LogLogn) if the loop variables is reduced / increased exponentially by a constant amount.

``````// Here c is a constant greater than 1
for (int i = 2; i <=n; i = pow(i, c)) {
// some O(1) expressions
}
//Here fun is sqrt or cuberoot or any other constant root
for (int i = n; i > 0; i = fun(i)) {
// some O(1) expressions
}
``````

One example of time complexity analysis

``````int fun(int n)
{
for (int i = 1; i <= n; i++)
{
for (int j = 1; j < n; j += i)
{
}
}
}
``````

Analysis:

``` For i = 1, the inner loop is executed n times. For i = 2, the inner loop is executed approximately n/2 times. For i = 3, the inner loop is executed approximately n/3 times. For i = 4, the inner loop is executed approximately n/4 times. ……………………………………………………. For i = n, the inner loop is executed approximately n/n times. ```

So the total time complexity of the above algorithm is `(n + n/2 + n/3 + … + n/n)`, Which becomes `n * (1/1 + 1/2 + 1/3 + … + 1/n)`

The important thing about series `(1/1 + 1/2 + 1/3 + … + 1/n)` is equal to O(Logn). So the time complexity of the above code is O(nLogn).

Ref: 1 2 3

### Changing cell color using apache poi

Short version: Create styles only once, use them everywhere.

Long version: use a method to create the styles you need (beware of the limit on the amount of styles).

``````private static Map<String, CellStyle> styles;

private static Map<String, CellStyle> createStyles(Workbook wb){
Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
DataFormat df = wb.createDataFormat();

CellStyle style;
style = createBorderedStyle(wb);
style.setAlignment(CellStyle.ALIGN_CENTER);
styles.put("style1", style);

style = createBorderedStyle(wb);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setDataFormat(df.getFormat("d-mmm"));
styles.put("date_style", style);
...
return styles;
}
``````

you can also use methods to do repetitive tasks while creating styles hashmap

``````private static CellStyle createBorderedStyle(Workbook wb) {
CellStyle style = wb.createCellStyle();
style.setBorderRight(CellStyle.BORDER_THIN);
style.setRightBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderBottom(CellStyle.BORDER_THIN);
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderLeft(CellStyle.BORDER_THIN);
style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderTop(CellStyle.BORDER_THIN);
style.setTopBorderColor(IndexedColors.BLACK.getIndex());
return style;
}
``````

then, in your "main" code, set the style from the styles map you have.

``````Cell cell = xssfCurrentRow.createCell( intCellPosition );
cell.setCellValue( blah );
cell.setCellStyle( (CellStyle) styles.get("style1") );
``````

### Flexbox: center horizontally and vertically

1 - Set CSS on parent div to `display: flex;`

2 - Set CSS on parent div to `flex-direction: column;`
Note that this will make all content within that div line up top to bottom. This will work best if the parent div only contains the child and nothing else.

3 - Set CSS on parent div to `justify-content: center;`

Here is an example of what the CSS will look like:

_x000D_
_x000D_
``````.parentDivClass {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
justify-content: center;_x000D_
}``````
_x000D_
_x000D_
_x000D_

### Join two sql queries

You can use CTE also like below.

``````With cte as
(select Activity, SUM(Amount) as "Total Amount 2009"
from Activities, Incomes
where Activities.UnitName = ? AND
Incomes.ActivityId = Activities.ActivityID
GROUP BY Activity
),
cte1 as
(select Activity, SUM(Amount) as "Total Amount 2008"
from Activities, Incomes2008
where Activities.UnitName = ? AND
Incomes2008.ActivityId = Activities.ActivityID
GROUP BY Activity
)
Select cte.Activity, cte.[Total Amount 2009] ,cte1.[Total Amount 2008]
from cte join cte1 ON cte.ActivityId = cte1.ActivityID
WHERE a.UnitName = ?
ORDER BY cte.Activity
``````

### Convert JSON array to Python list

`data` will return you a string representation of a list, but it is actually still a string. Just check the type of `data` with `type(data)`. That means if you try using indexing on this string representation of a list as such `data['fruits'][0]`, it will return you "[" as it is the first character of `data['fruits']`

You can do `json.loads(data['fruits'])` to convert it back to a Python list so that you can interact with regular list indexing. There are 2 other ways you can convert it back to a Python list suggested here

### Could not load file or assembly CrystalDecisions.ReportAppServer.ClientDoc

Regarding the 64-bit system wanting 32-bit support. I don't find it so bizarre:

Although deployed to a 64-bit system, this doesn't mean all the referenced assemblies are necessarily 64-bit Crystal Reports assemblies. Further to that, the Crystal Reports assemblies are largely just wrappers to a collection of legacy DLLs upon which they are based. Many 32-bit DLLs are required by the primarily referenced assembly. The error message "can not load the assembly" involves these DLLs as well. To see visually what those are, go to www.dependencywalker.com and run 'Depends' on the assembly in question, directly on that IIS server.

### Using Mockito, how do I verify a method was a called with a certain argument?

First you need to create a mock m_contractsDao and set it up. Assuming that the class is ContractsDao:

``````ContractsDao mock_contractsDao = mock(ContractsDao.class);
when(mock_contractsDao.save(any(String.class))).thenReturn("Some result");
``````

Then inject the mock into m_orderSvc and call your method.

``````m_orderSvc.m_contractsDao = mock_contractsDao;
m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc);
m_prog.work();
``````

Finally, verify that the mock was called properly:

``````verify(mock_contractsDao, times(1)).save("Parameter I'm expecting");
``````

### How do I remove ï»¿ from the beginning of a file?

I had the same problem with the BOM appearing in some of my PHP files (ï»¿ï»¿).

If you use PhpStorm you can set at hotkey to remove it in Settings -> IDE Settings -> Keymap -> Main Menu - > File -> Remove BOM.

### Linq on DataTable: select specific column into datatable, not whole table

Your select statement is returning a sequence of anonymous type , not a sequence of DataRows. CopyToDataTable() is only available on `IEnumerable<T>` where `T` is or derives from `DataRow`. You can select `r` the row object to call CopyToDataTable on it.

``````var query = from r in matrix.AsEnumerable()
where r.Field<string>("c_to") == c_to &&
r.Field<string>("p_to") == p_to
select r;

DataTable conversions = query.CopyToDataTable();
``````

You can also implement CopyToDataTable Where the Generic Type T Is Not a DataRow.

### In Python, how do I loop through the dictionary and change the value if it equals something?

You could create a dict comprehension of just the elements whose values are None, and then update back into the original:

``````tmp = dict((k,"") for k,v in mydict.iteritems() if v is None)
mydict.update(tmp)
``````

Update - did some performance tests

Well, after trying dicts of from 100 to 10,000 items, with varying percentage of None values, the performance of Alex's solution is across-the-board about twice as fast as this solution.

### How to extract public key using OpenSSL?

``````openssl rsa -in privkey.pem -pubout > key.pub
``````

That writes the public key to `key.pub`

### How do I invoke a Java method when given the method name as a string?

``````public static Method method[];
public static MethodClass obj;
public static String testMethod="A";

public static void main(String args[])
{
obj=new MethodClass();
method=obj.getClass().getMethods();
try
{
for(int i=0;i<method.length;i++)
{
String name=method[i].getName();
if(name==testMethod)
{
method[i].invoke(name,"Test Parameters of A");
}
}
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
``````

Thanks....

### Is it possible to create static classes in PHP (like in C#)?

object cannot be defined staticly but this works

``````final Class B{
static \$var;
static function init(){
self::\$var = new A();
}
B::init();
``````

### Show all current locks from get_lock

Starting with MySQL 5.7, the performance schema exposes all metadata locks, including locks related to the `GET_LOCK()` function.

### How to use JavaScript variables in jQuery selectors?

``````\$("input").click(function(){
var name = \$(this).attr("name");
\$('input[name="' + name + '"]').hide();
});
``````

Also works with ID:

``````var id = \$(this).attr("id");
\$('input[id="' + id + '"]').hide();
``````

when, (sometimes)

``````\$('input#' + id).hide();
``````

does not work, as it should.

You can even do both:

``````\$('input[name="' + name + '"][id="' + id + '"]').hide();
``````

### How to set enum to null

You can either use the "?" operator for a nullable type.

``````public Color? myColor = null;
``````

Or use the standard practice for enums that cannot be null by having the FIRST value in the enum (aka 0) be the default value. For example in a case of color None.

``````public Color myColor = Color.None;
``````

### How to start an application using android ADB tools?

open ~/.bash_profile and add these bash functions to the end of the file

``````function androidinstall(){
}
function androidrun(){
ant clean debug
adb shell am start -n \$1/\$1.\$2
}
``````

then open the Android project folder

``````androidinstall app-debug && androidrun com.example.app MainActivity
``````

### Why does NULL = NULL evaluate to false in SQL server

Maybe it depends, but I thought `NULL=NULL` evaluates to `NULL` like most operations with NULL as an operand.

### How to increase scrollback buffer size in tmux?

Open tmux configuration file with the following command:

``````vim ~/.tmux.conf
``````

In the configuration file add the following line:

``````set -g history-limit 5000
``````

Log out and log in again, start a new tmux windows and your limit is 5000 now.

### ASP.Net which user account running Web Service on IIS 7?

Server 2008

Start Task Manager Find w3wp.exe process (description IIS Worker Process) Check User Name column to find who you're IIS process is running as.

In the IIS GUI you can configure your application pool to run as a specific user: Application Pool default Advanced Settings Identity

Here's the info from Microsoft on setting up Application Pool Identites:

http://learn.iis.net/page.aspx/624/application-pool-identities/

### How to find a text inside SQL Server procedures / triggers?

Any searching with select statement yield you only object name, where search keyword contains. Easiest and efficient way is get script of procedure/function and then search in generated text file, I also follows this technique :) So you are exact pinpoint.

### Put search icon near textbox using bootstrap

``````<input type="text" name="whatever" id="funkystyling" />
``````

Here's the CSS for the image on the left:

``````#funkystyling {
background: white url(/path/to/icon.png) left no-repeat;
}
``````

And here's the CSS for the image on the right:

``````#funkystyling {
background: white url(/path/to/icon.png) right no-repeat;
}
``````

### Find and replace words/lines in a file

This is the sort of thing I'd normally use a scripting language for. It's very useful to have the ability to perform these sorts of transformations very simply using something like Ruby/Perl/Python (insert your favorite scripting language here).

I wouldn't normally use Java for this since it's too heavyweight in terms of development cycle/typing etc.

Note that if you want to be particular in manipulating XML, it's advisable to read the file as XML and manipulate it as such (the above scripting languages have very useful and simple APIs for doing this sort of work). A simple text search/replace can invalidate your file in terms of character encoding etc. As always, it depends on the complexity of your search/replace requirements.

### Data binding in React

I think @Richard Garside is correct.

I suggest some changes to clear even more the code.

Change this

``````onChange={(e) => this.update("field2", e)}
``````

To this

``````onChange={this.handleOnChange}
``````

And also, change this

``````this.setState({ [name]: e.target.value });
``````

To this

``````this.setState({ [e.target.name]: e.target.value})
``````

Besides, you have to add the "name" attribute to the field with a value that relates with the key on the state object.

### How to set the range of y-axis for a seaborn boxplot?

It is standard matplotlib.pyplot:

``````...
import matplotlib.pyplot as plt
plt.ylim(10, 40)
``````

``````ax.set(ylim=(10, 40))
``````

### Push item to associative array in PHP

Curtis's answer was very close to what I needed, but I changed it up a little.

Where he used:

``````\$options['inputs']['name'][] = \$new_input['name'];
``````

I used:

``````\$options[]['inputs']['name'] = \$new_input['name'];
``````

Here's my actual code using a query from a DB:

``````while(\$row=mysql_fetch_array(\$result)){
\$dtlg_array[]['dt'] = \$row['dt'];
\$dtlg_array[]['lat'] = \$row['lat'];
\$dtlg_array[]['lng'] = \$row['lng'];
}
``````

Thanks!

### Convert date from 'Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)' to 'YYYY-MM-DD' in javascript

`````` function convertDatePickerTimeToMySQLTime(str) {
var month, day, year, hours, minutes, seconds;
var date = new Date(str),
month = ("0" + (date.getMonth() + 1)).slice(-2),
day = ("0" + date.getDate()).slice(-2);
hours = ("0" + date.getHours()).slice(-2);
minutes = ("0" + date.getMinutes()).slice(-2);
seconds = ("0" + date.getSeconds()).slice(-2);

var mySQLDate = [date.getFullYear(), month, day].join("-");
var mySQLTime = [hours, minutes, seconds].join(":");
return [mySQLDate, mySQLTime].join(" ");
}
``````

### Compile error: "g++: error trying to exec 'cc1plus': execvp: No such file or directory"

This problem can happen if different versions of g++ and gcc are installed.

``````   g++ --version
gcc --version
``````

If these don't give the result, you probably have multiple versions of gcc installed. You can check by using:

``````    dpkg -l | grep gcc | awk '{print \$2}'
``````

Usually, /usr/bin/gcc will be sym-linked to /etc/alternatives/gcc which is again sym-linked to say /usr/bin/gcc-4.6 or /usr/bin/gcc-4.8 (In case you have gcc-4.6, gcc-4.8 installed.)

By changing this link you can make gcc and g++ run in the same version and this may resolve your issue!

### Set NOW() as Default Value for datetime datatype?

This worked for me - just changed INSERT to UPDATE for my table.

``````INSERT INTO Yourtable (Field1, YourDateField) VALUES('val1', (select now()))
``````

### How to get JSON response from http.Get

The ideal way is not to use `ioutil.ReadAll`, but rather use a decoder on the reader directly. Here's a nice function that gets a url and decodes its response onto a `target` structure.

``````var myClient = &http.Client{Timeout: 10 * time.Second}

func getJson(url string, target interface{}) error {
r, err := myClient.Get(url)
if err != nil {
return err
}
defer r.Body.Close()

return json.NewDecoder(r.Body).Decode(target)
}
``````

Example use:

``````type Foo struct {
Bar string
}

func main() {
foo1 := new(Foo) // or &Foo{}
getJson("http://example.com", foo1)
println(foo1.Bar)

// alternately:

foo2 := Foo{}
getJson("http://example.com", &foo2)
println(foo2.Bar)
}
``````

You should not be using the default `*http.Client` structure in production as this answer originally demonstrated! (Which is what `http.Get`/etc call to). The reason is that the default client has no timeout set; if the remote server is unresponsive, you're going to have a bad day.

### Comparing two strings in C?

You are currently comparing the addresses of the two strings.

Use strcmp to compare the values of two char arrays

`````` if (strcmp(namet2, nameIt2) != 0)
``````

### Undefined symbols for architecture arm64

This issue occurred for me after installing a pod via Podfile and `pod install`. After trying a bunch of different fixes I finally just imported the Pod manually (dragging the necessary files into my project) and that solved the problem.

### Numpy - add row to array

You can use `numpy.append()` to append a row to numpty array and reshape to a matrix later on.

``````import numpy as np
a = np.array([1,2])
a = np.append(a, [3,4])
print a
# [1,2,3,4]
A = [1,2]
for row in X:
A = np.append(A, row)
``````

### What is a simple command line program or script to backup SQL server databases?

You can use the backup application by ApexSQL. Although it’s a GUI application, it has all its features supported in CLI. It is possible to either perform one-time backup operations, or to create a job that would back up specified databases on the regular basis. You can check the switch rules and exampled in the articles:

### SELECT * FROM multiple tables. MySQL

You will have the duplicate values for name and price here. And ids are duplicate in the drinks_photos table.There is no way you can avoid them.Also what exactly you want the output ?

### Date only from TextBoxFor()

``````[DataType(DataType.Date)]
public string dtArrivalDate { get; set; }
``````

### Find first and last day for previous calendar month in SQL Server Reporting Services (VB.Net)

``````Dim thisMonth As New DateTime(DateTime.Today.Year, DateTime.Today.Month, 1)
Dim firstDayLastMonth As DateTime
Dim lastDayLastMonth As DateTime

``````

### What's the difference between ".equals" and "=="?

== operator compares two object references to check whether they refer to same instance. This also, will return true on successful match.for example

``````public class Example{
public static void main(String[] args){
String s1 = "Java";
String s2 = "Java";
String s3 = new string ("Java");
test(Sl == s2)     //true
test(s1 == s3)      //false
}}
``````

above example == is a reference comparison i.e. both objects point to the same memory location

String equals() is evaluates to the comparison of values in the objects.

``````   public class EqualsExample1{
public static void main(String args[]){
String s = "Hell";
String s1 =new string( "Hello");
String s2 =new string( "Hello");
s1.equals(s2);    //true
s.equals(s1) ;   //false
}}
``````

above example It compares the content of the strings. It will return true if string matches, else returns false.

### After updating Entity Framework model, Visual Studio does not see changes

Are you working in an N-Tiered project? If so, try rebuilding your Data Layer (or wherever your EDMX file is stored) before using it.

### C#: How would I get the current time into a string?

You can use format strings as well.

``````string time = DateTime.Now.ToString("hh:mm:ss"); // includes leading zeros
string date = DateTime.Now.ToString("dd/MM/yy"); // includes leading zeros
``````

or some shortcuts if the format works for you

``````string time = DateTime.Now.ToShortTimeString();
string date = DateTime.Now.ToShortDateString();
``````

Either should work.

### Bootstrap 3 Gutter Size

Facing this problem, I made the following addition to my css stylesheet:

``````#mainContent .container {
}
#mainContent .row {
margin-left: -8px;
margin-right: -8px;
}

#mainContent .col-xs-1, #mainContent .col-sm-1, #mainContent .col-md-1, #mainContent .col-lg-1, #mainContent .col-xs-2, #mainContent .col-sm-2, #mainContent .col-md-2, #mainContent .col-lg-2, #mainContent .col-xs-3, #mainContent .col-sm-3, #mainContent .col-md-3, #mainContent .col-lg-3, #mainContent .col-xs-4, #mainContent .col-sm-4, #mainContent .col-md-4, #mainContent .col-lg-4, #mainContent .col-xs-5, #mainContent .col-sm-5, #mainContent .col-md-5, #mainContent .col-lg-5, #mainContent .col-xs-6, #mainContent .col-sm-6, #mainContent .col-md-6, #mainContent .col-lg-6, #mainContent .col-xs-7, #mainContent .col-sm-7, #mainContent .col-md-7, #mainContent .col-lg-7, #mainContent .col-xs-8, #mainContent .col-sm-8, #mainContent .col-md-8, #mainContent .col-lg-8, #mainContent .col-xs-9, #mainContent .col-sm-9, #mainContent .col-md-9, #mainContent .col-lg-9, #mainContent .col-xs-10, #mainContent .col-sm-10, #mainContent .col-md-10, #mainContent .col-lg-10, #mainContent .col-xs-11, #mainContent .col-sm-11, #mainContent .col-md-11, #mainContent .col-lg-11, #mainContent .col-xs-12, #mainContent .col-sm-12, #mainContent .col-md-12, #mainContent .col-lg-12
{
}
``````

This overrides the default bootstrap styling and makes the left and right sides and the gutter equal width.

### get selected value in datePicker and format it

Use jquery-dateFormat. It will solve your problem.

You need to include the jquery.dateFormat in your html file.

``````<script>
var date = \$('#scheduleDate').val();
document.write(\$.format.date(date, "dd,MM,yyyy"));

var dateTypeVar = \$('#scheduleDate').datepicker('getDate');
document.write(\$.format.date(dateTypeVar, "dd-MM-yy"));
</script>
``````

### When use ResponseEntity<T> and @RestController for Spring RESTful applications

According to official documentation: Creating REST Controllers with the @RestController annotation

@RestController is a stereotype annotation that combines @ResponseBody and @Controller. More than that, it gives more meaning to your Controller and also may carry additional semantics in future releases of the framework.

It seems that it's best to use `@RestController` for clarity, but you can also combine it with `ResponseEntity` for flexibility when needed (According to official tutorial and the code here and my question to confirm that).

For example:

``````@RestController
public class MyController {

@GetMapping(path = "/test")
@ResponseStatus(HttpStatus.OK)
public User test() {
User user = new User();
user.setName("Name 1");

return user;
}

}
``````

is the same as:

``````@RestController
public class MyController {

@GetMapping(path = "/test")
public ResponseEntity<User> test() {
User user = new User();
user.setName("Name 1");

// ...
}

}
``````

This way, you can define `ResponseEntity` only when needed.

Update

You can use this:

``````    return ResponseEntity.ok().headers(responseHeaders).body(user);
``````

### Bootstrap 4 - Responsive cards in card-columns

Another late answer, but I was playing with this and came up with a general purpose Sass solution that I found useful and many others might as well. To give an overview, this introduces new classes that can modify the column count of a `.card-columns` element in very similar ways to columns with `.col-4` or `.col-lg-3`:

``````@import "bootstrap";

\$card-column-counts: 1, 2, 3, 4, 5;

.card-columns {
@each \$column-count in \$card-column-counts {
&.card-columns-#{\$column-count} {
column-count: \$column-count;
}
}

@each \$breakpoint in map-keys(\$grid-breakpoints) {
@include media-breakpoint-up(\$breakpoint) {
\$infix: breakpoint-infix(\$breakpoint, \$grid-breakpoints);
@each \$column-count in \$card-column-counts {
&.card-columns#{\$infix}-#{\$column-count} {
column-count: \$column-count;
}
}
}
}
}
``````

The end result of this is if you have the following:

``````<div class="card-columns card-columns-2 card-columns-md-3 card-columns-xl-4">
...
</div>
``````

Then you would have 2 columns by default, 3 for medium devices and up and 4 for xl devices and up. Additionally if you change your grid breakpoints this will automatically support those, and the `\$card-column-counts` can be overridden to change the allowed numbers of columns.

### Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

If like me you recently moved certain classes to different packages ect. and you use android navigation. Make sure to change the argType to you match you new package address. from:

``````app:argType="com.example.app.old.Item"
``````

to:

``````app:argType="com.example.app.new.Item"
``````

### Tkinter example code for multiple windows, why won't buttons load correctly?

I tried to use more than two windows using the Rushy Panchal example above. The intent was to have the change to call more windows with different widgets in them. The butnew function creates different buttons to open different windows. You pass as argument the name of the class containing the window (the second argument is nt necessary, I put it there just to test a possible use. It could be interesting to inherit from another window the widgets in common.

``````import tkinter as tk

class Demo1:
def __init__(self, master):
self.master = master
self.master.geometry("400x400")
self.frame = tk.Frame(self.master)
self.butnew("Window 1", "ONE", Demo2)
self.butnew("Window 2", "TWO", Demo3)
self.frame.pack()

def butnew(self, text, number, _class):
tk.Button(self.frame, text = text, width = 25, command = lambda: self.new_window(number, _class)).pack()

def new_window(self, number, _class):
self.newWindow = tk.Toplevel(self.master)
_class(self.newWindow, number)

class Demo2:
def __init__(self, master, number):
self.master = master
self.master.geometry("400x400+400+400")
self.frame = tk.Frame(self.master)
self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
self.label = tk.Label(master, text=f"this is window number {number}")
self.label.pack()
self.quitButton.pack()
self.frame.pack()

def close_windows(self):
self.master.destroy()

class Demo3:
def __init__(self, master, number):
self.master = master
self.master.geometry("400x400+400+400")
self.frame = tk.Frame(self.master)
self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
self.label = tk.Label(master, text=f"this is window number {number}")
self.label.pack()
self.label2 = tk.Label(master, text="THIS IS HERE TO DIFFERENTIATE THIS WINDOW")
self.label2.pack()
self.quitButton.pack()
self.frame.pack()

def close_windows(self):
self.master.destroy()

def main():
root = tk.Tk()
app = Demo1(root)
root.mainloop()

if __name__ == '__main__':
main()
``````

#### Open the new window only once

To avoid having the chance to press multiple times the button having multiple windows... that are the same window, I made this script (take a look at this page too)

``````import tkinter as tk

def new_window1():
global win1
try:
if win1.state() == "normal": win1.focus()
except:
win1 = tk.Toplevel()
win1.geometry("300x300+500+200")
win1["bg"] = "navy"
lb = tk.Label(win1, text="Hello")
lb.pack()

win = tk.Tk()
win.geometry("200x200+200+100")
button = tk.Button(win, text="Open new Window")
button['command'] = new_window1
button.pack()
win.mainloop()
``````

### Correct file permissions for WordPress

For those who have their wordpress root folder under their home folder:

** Ubuntu/apache

You want to call `usermod` on your user. So that would be:

``````sudo usermod -aG www-data yourUserName
``````

** Assuming `www-data` group exists

1. Check your user is in `www-data` group:

`groups yourUserName`

You should get something like:

``````youUserName : youUserGroupName www-data
``````

** youUserGroupName is usually similar to you user name

1. Recursively change group ownership of the wp-content folder keeping your user ownership

`chown yourUserName:www-data -R youWebSiteFolder/wp-content/*`

2. Change directory to youWebSiteFolder/wp-content/

`cd youWebSiteFolder/wp-content`

3. Recursively change group permissions of the folders and sub-folders to enable write permissions:

`find . -type d -exec chmod -R 775 {} \;`

** mode of `/home/yourUserName/youWebSiteFolder/wp-content/' changed from 0755 (rwxr-xr-x) to 0775 (rwxrwxr-x)

1. Recursively change group permissions of the files and sub-files to enable write permissions:

`find . -type f -exec chmod -R 664 {} \;`

The result should look something like:

``````WAS:
-rw-r--r--  1 yourUserName www-data  7192 Oct  4 00:03 filename.html
CHANGED TO:
-rw-rw-r--  1 yourUserName www-data  7192 Oct  4 00:03 filename.html
``````

Equivalent to:

chmod -R ug+rw foldername

Permissions will be like 664 for files or 775 for directories.

P.s. if anyone encounters error `'could not create directory'` when updating a plugin, do:
`server@user:~/domainame.com\$ sudo chown username:www-data -R wp-content`
when you are at the root of your domain.
Assuming: `wp-config.php` has
FTP credentials on LocalHost
`define('FS_METHOD','direct');`

### CSS performance relative to translateZ(0)

CSS transformations create a new stacking context and containing block, as described in the spec. In plain English, this means that fixed position elements with a transformation applied to them will act more like absolutely positioned elements, and `z-index` values are likely to get screwed with.

If you take a look at this demo, you'll see what I mean. The second div has a transformation applied to it, meaning that it creates a new stacking context, and the pseudo elements are stacked on top rather than below.

So basically, don't do that. Apply a 3D transformation only when you need the optimization. `-webkit-font-smoothing: antialiased;` is another way to tap into 3D acceleration without creating these problems, but it only works in Safari.

### Check if a path represents a file or a folder

To check if a string represents a path or a file programatically, you should use API methods such as `isFile(), isDirectory().`

How does system understand whether there's a file or a folder?

I guess, the file and folder entries are kept in a data structure and it's managed by the file system.

### How do I make my ArrayList Thread-Safe? Another approach to problem in Java?

You can change from ArrayList to Vector type, in which every method is synchronized.

``````private Vector finishingOrder;
//Make a Vector to hold RaceCar objects to determine winners
finishingOrder = new Vector(numberOfRaceCars);
``````

### sqlalchemy IS NOT NULL select

Starting in version 0.7.9 you can use the filter operator `.isnot` instead of comparing constraints, like this:

`query.filter(User.name.isnot(None))`

This method is only necessary if pep8 is a concern.

source: sqlalchemy documentation

### How to smooth a curve in the right way?

If you are plotting time series graph and if you have used mtplotlib for drawing graphs then use median method to smooth-en the graph

``````smotDeriv = timeseries.rolling(window=20, min_periods=5, center=True).median()
``````

where `timeseries` is your set of data passed you can alter `windowsize` for more smoothining.

### How to make 'submit' button disabled?

It is important that you include the "required" keyword inside each one of your mandatory input tags for it to work.

`````` <form (ngSubmit)="login(loginForm.value)" #loginForm="ngForm">
...
``````

### Folder is locked and I can't unlock it

To unlock a file in your working copy from command prompt that is currently locked by another user, use `--force` option.

`\$ svn unlock --force tree.jpg`

### get name of a variable or parameter

Alternatively,

1) Without touching `System.Reflection` namespace,

``````GETNAME(new { myInput });

public static string GETNAME<T>(T myInput) where T : class
{
if (myInput == null)
return string.Empty;

return myInput.ToString().TrimStart('{').TrimEnd('}').Split('=')[0].Trim();
}
``````

2) The below one can be faster though (from my tests)

``````GETNAME(new { variable });
public static string GETNAME<T>(T myInput) where T : class
{
if (myInput == null)
return string.Empty;

return typeof(T).GetProperties()[0].Name;
}
``````

You can also extend this for properties of objects (may be with extension methods):

``````new { myClass.MyProperty1 }.GETNAME();
``````

You can cache property values to improve performance further as property names don't change during runtime.

The Expression approach is going to be slower for my taste. To get parameter name and value together in one go see this answer of mine

### Convert JSON String to Pretty Print JSON output using Jackson

The simplest and also the most compact solution (for v2.3.3):

``````ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.writeValueAsString(obj)
``````

### PHP header() redirect with POST variables

Use a smarty template for your stuff then just set the POST array as a smarty array and open the template. In the template just echo out the array so if it passes:

``````if(correct){
} else {
\$smarty->assign("variables", \$_POST);
\$smarty->display("register_error.php");
exit;
}
``````

I have not tried this yet but I am going to try it as a solution and will let you know what I find. But of course this method assumes that you are using smarty.

If not you can just recreate your form there on the error page and echo info into the form or you could send back non important data in a get from and get it

ex.

``````register.php?name=mr_jones&address==......
echo \$_GET[name];
``````

### Using Mockito's generic "any()" method

Since Java 8 you can use the argument-less `any` method and the type argument will get inferred by the compiler:

``````verify(bar).doStuff(any());
``````

#### Explanation

The new thing in Java 8 is that the target type of an expression will be used to infer type parameters of its sub-expressions. Before Java 8 only arguments to methods where used for type parameter inference (most of the time).

In this case the parameter type of `doStuff` will be the target type for `any()`, and the return value type of `any()` will get chosen to match that argument type.

This mechanism was added in Java 8 mainly to be able to compile lambda expressions, but it improves type inferences generally.

#### Primitive types

This doesn't work with primitive types, unfortunately:

``````public interface IBar {
void doPrimitiveStuff(int i);
}

verify(bar).doPrimitiveStuff(any()); // Compiles but throws NullPointerException
verify(bar).doPrimitiveStuff(anyInt()); // This is what you have to do instead
``````

The problem is that the compiler will infer `Integer` as the return value type of `any()`. Mockito will not be aware of this (due to type erasure) and return the default value for reference types, which is `null`. The runtime will try to unbox the return value by calling the `intValue` method on it before passing it to `doStuff`, and the exception gets thrown.

### Convert data file to blob

As pointed in the comments, `file` is a `blob`:

``````file instanceof Blob; // true
``````

And you can get its content with the file reader API https://developer.mozilla.org/en/docs/Web/API/FileReader

_x000D_
_x000D_
``````var input = document.querySelector('input[type=file]');
var textarea = document.querySelector('textarea');

textarea.textContent = event.target.result;
console.log(event.target.result);
}

function changeFile() {
var file = input.files[0];
}

_x000D_
``````<input type="file">
<textarea rows="10" cols="50"></textarea>``````
_x000D_
_x000D_
_x000D_

### TypeLoadException says 'no implementation', but it is implemented

I encountered this error in a context where I was using Autofac and a lot of dynamic assembly loading.

While performing an Autofac resolution operation, the runtime would fail to load one of the assemblies. The error message complained that `Method 'MyMethod' in type 'MyType' from assembly 'ImplementationAssembly' does not have an implementation`. The symptoms occurred when running on a Windows Server 2012 R2 VM, but did not occur on Windows 10 or Windows Server 2016 VMs.

`ImplementationAssembly` referenced `System.Collections.Immutable` 1.1.37, and contained implementations of a `IMyInterface<T1,T2>` interface, which was defined in a separate `DefinitionAssembly`. `DefinitionAssembly` referenced `System.Collections.Immutable` 1.1.36.

The methods from `IMyInterface<T1,T2>` which were "not implemented" had parameters of type `IImmutableDictionary<TKey, TRow>`, which is defined in `System.Collections.Immutable`.

The actual copy of `System.Collections.Immutable` found in the program directory was version 1.1.37. On my Windows Server 2012 R2 VM, the GAC contained a copy of `System.Collections.Immutable` 1.1.36. On Windows 10 and Windows Server 2016, the GAC contained a copy of `System.Collections.Immutable` 1.1.37. The loading error only occurred when the GAC contained the older version of the DLL.

So, the root cause of the assembly load failure was the mismatching references to `System.Collections.Immutable`. The interface definition and implementation had identical-looking method signatures, but actually depended on different versions of `System.Collections.Immutable`, which meant that the runtime did not consider the implementation class to match the interface definition.

Adding the following binding redirect to my application config file fixed the issue:

``````<dependentAssembly>
<assemblyIdentity name="System.Collections.Immutable" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.1.37.0" newVersion="1.1.37.0" />
</dependentAssembly>
``````

### When to use Common Table Expression (CTE)

`````` ;with cte as
(
Select Department, Max(salary) as MaxSalary
from test
group by department
)
select t.* from test t join cte c on c.department=t.department
where t.salary=c.MaxSalary;
``````

try this

### ASP.NET MVC 5 - Identity. How to get current ApplicationUser

#### You should not need to query the database directly for the current ApplicationUser.

That introduces a new dependency of having an extra context for starters, but going forward the user database tables change (3 times in the past 2 years) but the API is consistent. For example the `users` table is now called `AspNetUsers` in Identity Framework, and the names of several primary key fields kept changing, so the code in several answers will no longer work as-is.

Another problem is that the underlying OWIN access to the database will use a separate context, so changes from separate SQL access can produce invalid results (e.g. not seeing changes made to the database). Again the solution is to work with the supplied API and not try to work-around it.

The correct way to access the current user object in ASP.Net identity (as at this date) is:

``````var user = UserManager.FindById(User.Identity.GetUserId());
``````

or, if you have an async action, something like:

``````var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
``````

`FindById` requires you have the following using statement so that the non-async `UserManager` methods are available (they are extension methods for UserManager, so if you do not include this you will only see `FindByIdAsync`):

``````using Microsoft.AspNet.Identity;
``````

If you are not in a controller at all (e.g. you are using IOC injection), then the user id is retrieved in full from:

``````System.Web.HttpContext.Current.User.Identity.GetUserId();
``````

If you are not in the standard Account controller you will need to add the following (as an example) to your controller:

#### 1. Add these two properties:

``````    /// <summary>
/// Application DB context
/// </summary>
protected ApplicationDbContext ApplicationDbContext { get; set; }

/// <summary>
/// User manager - attached to application DB context
/// </summary>
protected UserManager<ApplicationUser> UserManager { get; set; }
``````

#### 2. Add this in the Controller's constructor:

``````    this.ApplicationDbContext = new ApplicationDbContext();
this.UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.ApplicationDbContext));
``````

Update March 2015

Note: The most recent update to Identity framework changes one of the underlying classes used for authentication. You can now access it from the Owin Context of the current HttpContent.

``````ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
``````

When using EF and Identity Framework with Azure, over a remote database connection (e.g. local host testing to Azure database), you can randomly hit the dreaded “error: 19 - Physical connection is not usable”. As the cause is buried away inside Identity Framework, where you cannot add retries (or what appears to be a missing `.Include(x->someTable)`), you need to implement a custom `SqlAzureExecutionStrategy` in your project.

### How to select a single child element using jQuery?

No. Every jQuery function returns a jQuery object, and that is how it works. This is a crucial part of jQuery's magic.

If you want to access the underlying element, you have three options...

1. Do not use jQuery
2. Use `[0]` to reference it
3. Extend jQuery to do what you want...

``````\$.fn.child = function(s) {
return \$(this).children(s)[0];
}
``````