# Programs & Examples On #Geography

Geography is the science that deals with the study of the Earth and its lands, features, inhabitants, and phenomena.

### Calculate distance between 2 GPS coordinates

you can find a implementation of this (with some good explanation) in F# on fssnip

here are the important parts:

``````
let GreatCircleDistance<[<Measure>] 'u> (R : float<'u>) (p1 : Location) (p2 : Location) =

let sq x = x * x
// take the sin of the half and square the result
let sinSqHf (a : float<rad>) = (System.Math.Sin >> sq) (a / 2.0<rad>)

let dLat = (p2.Latitude - p1.Latitude) |> degToRad
let dLon = (p2.Longitude - p1.Longitude) |> degToRad

let a = sinSqHf dLat + cos p1.Latitude * cos p2.Latitude * sinSqHf dLon
let c = 2.0 * System.Math.Atan2(System.Math.Sqrt(a), System.Math.Sqrt(1.0-a))

R * c
``````

### Getting distance between two points based on latitude/longitude

Edit: Just as a note, if you just need a quick and easy way of finding the distance between two points, I strongly recommend using the approach described in Kurt's answer below instead of re-implementing Haversine -- see his post for rationale.

This answer focuses just on answering the specific bug OP ran into.

It's because in Python, all the trig functions use radians, not degrees.

You can either convert the numbers manually to radians, or use the `radians` function from the math module:

``````from math import sin, cos, sqrt, atan2, radians

# approximate radius of earth in km
R = 6373.0

dlon = lon2 - lon1
dlat = lat2 - lat1

a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))

distance = R * c

print("Result:", distance)
print("Should be:", 278.546, "km")
``````

The distance is now returning the correct value of `278.545589351` km.

### How to display with n decimal places in Matlab

You can convert a number to a string with n decimal places using the SPRINTF command:

```>> x = 1.23;
>> sprintf('%0.6f', x)

ans =

1.230000

>> x = 1.23456789;
>> sprintf('%0.6f', x)

ans =

1.234568
```

### How do I view / replay a chrome network debugger har file saved with content?

Drag and drop is best solution. I am just showing another way to import by clicking the HAR import icon:

### Remove all HTMLtags in a string (with the jquery text() function)

I created this test case: http://jsfiddle.net/ccQnK/1/ , I used the Javascript replace function with regular expressions to get the results that you want.

``````\$(document).ready(function() {
var myContent = '<div id="test">Hello <span>world!</span></div>';
});
``````

### How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?

If you have an `Order` class, adding a property that references another class in your model, for instance `Customer` should be enough to let EF know there's a relationship in there:

``````public class Order
{
public int ID { get; set; }

// Some other properties

// Foreign key to customer
public virtual Customer Customer { get; set; }
}
``````

You can always set the `FK` relation explicitly:

``````public class Order
{
public int ID { get; set; }

// Some other properties

// Foreign key to customer
[ForeignKey("Customer")]
public string CustomerID { get; set; }
public virtual Customer Customer { get; set; }
}
``````

The `ForeignKeyAttribute` constructor takes a string as a parameter: if you place it on a foreign key property it represents the name of the associated navigation property. If you place it on the navigation property it represents the name of the associated foreign key.

What this means is, if you where to place the `ForeignKeyAttribute` on the `Customer` property, the attribute would take `CustomerID` in the constructor:

``````public string CustomerID { get; set; }
[ForeignKey("CustomerID")]
public virtual Customer Customer { get; set; }
``````

EDIT based on Latest Code You get that error because of this line:

``````[ForeignKey("Parent")]
public Patient Patient { get; set; }
``````

EF will look for a property called `Parent` to use it as the Foreign Key enforcer. You can do 2 things:

1) Remove the `ForeignKeyAttribute` and replace it with the `RequiredAttribute` to mark the relation as required:

``````[Required]
public virtual Patient Patient { get; set; }
``````

Decorating a property with the `RequiredAttribute` also has a nice side effect: The relation in the database is created with `ON DELETE CASCADE`.

I would also recommend making the property `virtual` to enable Lazy Loading.

2) Create a property called `Parent` that will serve as a Foreign Key. In that case it probably makes more sense to call it for instance `ParentID` (you'll need to change the name in the `ForeignKeyAttribute` as well):

``````public int ParentID { get; set; }
``````

In my experience in this case though it works better to have it the other way around:

``````[ForeignKey("Patient")]
public int ParentID { get; set; }

public virtual Patient Patient { get; set; }
``````

### Using iFrames In ASP.NET

``````<asp:HtmlIframe ID="yourIframe" runat="server" />
``````

Is supported since .Net Framework 4.5

If you have Problems using this control, you might take a look here.

Try:

``````    fs.readFile("test.txt", "utf8", function(err, data) {...});
``````

Basically, you need to specify the encoding.

### NLTK and Stopwords Fail #lookuperror

``````import nltk
``````

Click on download button when gui prompted. It worked for me.(`nltk.download('stopwords')` doesn't work for me)

### Parsing JSON from URL

A simple alternative solution:

• Paste the URL into a json to csv converter

• Open the CSV file in either Excel or Open Office

• Use the spreadsheet tools to parse the data

### Code snippet or shortcut to create a constructor in Visual Studio

I have created some handy code snippets that'll create overloaded constructors as well. You're welcome to use them: https://github.com/ejbeaty/Power-Snippets

For example: 'ctor2' would create a constructor with two arguments and allow you to tab through them one by one like this:

``````public MyClass(ArgType argName, ArgType argName)
{

}
``````

### scrollable div inside container

i have just added (overflow:scroll;) in (div3) with fixed height.

see the fiddle:- http://jsfiddle.net/fMs67/10/

### Oracle SQL Developer spool output?

I was trying things to duplicate the spools you get from sqlplus. I found the following and hope it helps:

Create your sql script file ie:

Please note the echo and serveroutput.

Test_Spool.SQL

``````Spool 'c:\temp\Test1.txt';
set echo on;
set serveroutput on;
declare
sqlresult varchar2(60);

begin
select to_char(sysdate,'YYYY-MM-DD HH24:MI:SS') into sqlresult from dual;
dbms_output.put_line('The date is ' || sqlresult);
end;

/

Spool off;
set serveroutput off;
set echo off;
``````

Run the script from another worksheet:

``````@TEST_Spool.SQL
``````

My output from the Test1.txt

``````set serveroutput on
declare
sqlresult varchar2(60);

begin
select to_char(sysdate,'YYYY-MM-DD HH24:MI:SS') into sqlresult from dual;
dbms_output.put_line('The date is ' || sqlresult);
end;
``````

anonymous block completed

The date is 2016-04-07 09:21:32

Spool of

### What is boilerplate code?

In a nutshell, boilerplate codes are repetitive codes required to be included in the application with little to no change by the program/framework, and contribute nothing to the logic of the application. When you write pseudo codes you can remove boilerplate codes. The recommendation is to use a proper Editor that generates boilerplate codes.

in HTML, the boilerplate codes in the interface.

``````<!DOCTYPE html>
<html>
<title></title>
<body> </body>
</html>
``````

in C#, The boilerplate codes of properties.

``````class Price
{
private string _price;
public string Price
{
get {return _price;}
set {_price= value;}
}
}
``````

### How to convert currentTimeMillis to a date in Java?

If the millis value is number of millis since Jan 1, 1970 GMT, as is standard for the JVM, then that is independent of time zone. If you want to format it with a specific time zone, you can simply convert it to a GregorianCalendar object and set the timezone. After that there are numerous ways to format it.

### How do I change a single value in a data.frame?

To change a cell value using a column name, one can use

``````iris\$Sepal.Length[3]=999
``````

### Regarding Java switch statements - using return and omitting breaks in each case

I think that what you have written is perfectly fine. I also don't see any readability issue with having multiple return statements.

I would always prefer to return from the point in the code when I know to return and this will avoid running logic below the return.

There can be an argument for having a single return point for debugging and logging. But, in your code, there is no issue of debugging and logging if we use it. It is very simple and readable the way you wrote.

### SQL Query to find the last day of the month

select DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-0, -1) LastDate

### VB.NET Switch Statement GoTo Case

Why don't you just refactor the default case as a method and call it from both places? This should be more readable and will allow you to change the code later in a more efficient manner.

### How to run Python script on terminal?

First of all, you need to move to the location of the file you are trying to execute, so in a Terminal:

``````cd ~/Documents/python
``````

Now, you should be able to execute your file:

``````python gameover.py
``````

### How do you check if a certain index exists in a table?

Problem: Process runs once a quarter taking an hour due to missing index.

Correction: Alter query process or Procedure to check for index and create it if missing... Same code is placed at the end of the query and procedure to remove index since it is not needed but quarterly. Showing Only drop syntax here

``````-- drop the index
begin

IF EXISTS (SELECT *  FROM sys.indexes  WHERE name='Index_Name'
AND object_id = OBJECT_ID('[SchmaName].[TableName]'))
begin
DROP INDEX [Index_Name] ON [SchmaName].[TableName];
end

end
``````

### Can't subtract offset-naive and offset-aware datetimes

have you tried to remove the timezone awareness?

``````naive = dt.replace(tzinfo=None)
``````

may have to add time zone conversion as well.

### How to do 3 table JOIN in UPDATE query?

For PostgreSQL example:

``````UPDATE TableA AS a
SET param_from_table_a=FALSE -- param FROM TableA
FROM TableB AS b
WHERE b.id=a.param_id AND a.amount <> 0;
``````

### How to convert text to binary code in JavaScript?

Try this:

``````String.prototype.toBinaryString = function(spaces = 0) {
return this.split("").map(function(character) {
return character.charCodeAt(0).toString(2);
}).join(" ".repeat(spaces));
}
``````

And use it like this:

``````"test string".toBinaryString(1); // with spaces
"test string".toBinaryString(); // without spaces
"test string".toBinaryString(2); // with 2 spaces
``````

### Relative path in HTML

The easiest way to solve this in pure HTML is to use the `<base href="…">` element like so:

``````<base href="http://localhost/mywebsite/" />
``````

Then all of the URLs in your HTML can just be this:

``````<a href="images/example.png">Link To Image</a>
``````

Just change the `<base href="…">` to match your server. The rest of the HTML paths will just fall in line and will be appended to that.

### What does it mean: The serializable class does not declare a static final serialVersionUID field?

The reasons for warning are documented here, and the simple fixes are to turn off the warning or put the following declaration in your code to supply the version UID. The actual value is not relevant, start with 999 if you like, but changing it when you make incompatible changes to the class is.

``````public class HelloWorldSwing extends JFrame {

JTextArea m_resultArea = new JTextArea(6, 30);
private static final long serialVersionUID = 1L;
``````

### android ellipsize multiline textview

You need to include this in your textview:

``````android:singleLine="false"
``````

by default its true. You need to explicitly set it false.

### How can I exclude directories from grep -R?

SOLUTION 1 (combine `find` and `grep`)

The purpose of this solution is not to deal with `grep` performance but to show a portable solution : should also work with busybox or GNU version older than 2.5.

Use `find`, for excluding directories foo and bar :

``````find /dir \( -name foo -prune \) -o \( -name bar -prune \) -o -name "*.sh" -print
``````

Then combine `find` and the non-recursive use of `grep`, as a portable solution :

``````find /dir \( -name node_modules -prune \) -o -name "*.sh" -exec grep --color -Hn "your text to find" {} 2>/dev/null \;
``````

SOLUTION 2 (using the `--exclude-dir` option of `grep`):

You know this solution already, but I add it since it's the most recent and efficient solution. Note this is a less portable solution but more human-readable.

``````grep -R --exclude-dir=node_modules 'some pattern' /path/to/search
``````

To exclude multiple directories, use `--exclude-dir` as:

`--exclude-dir={node_modules,dir1,dir2,dir3}`

SOLUTION 3 (Ag)

If you frequently search through code, Ag (The Silver Searcher) is a much faster alternative to grep, that's customized for searching code. For instance, it automatically ignores files and directories listed in `.gitignore`, so you don't have to keep passing the same cumbersome exclude options to `grep` or `find`.

### How can I convert a VBScript to an executable (EXE) file?

You can try VbsEdit. Get the latest version from Adersoft's VbsEdit http://www.vbsedit.com its a small download but it is a powerful tool to create and edit vbs files and convert them into executables without unpacking to temporary folder. (unless you get an old version like version 4.x.x.x) I've been using this program since 2008, and it's free to evaluate forever but comes with a reminder to activate and each time you Start your script from the vbsedit window you will have to wait a few seconds, Or you could purchase it for \$60 to remove those minor annoyances.
Unlike ScriptCryptor, the converted exe won't have any limitations if you are still evaluating, it will run without any unwanted additional windows.

### How to replace all double quotes to single quotes using jquery?

Use double quote to enclose the quote or escape it.

``````newTemp = mystring.replace(/"/g, "'");
``````

or

``````newTemp = mystring.replace(/"/g, '\'');
``````

### How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

If you want to use the Jupyter Notebook API (and not the IPython one anymore), I find the ipywidgets Jupyter's sub-project. You have an `Image` widget. Docstring specifies that you have a `value` parameter which is a bytes. So you can do:

``````import requests
from ipywidgets import Image

Image(value=requests.get('https://octodex.github.com/images/yaktocat.png').content)
``````

I agree, it's simpler to use the Markdown style. But it shows you the Image display Notebook API. You can also resize the image with the `width` and `height` parameters.

### Eclipse memory settings when getting "Java Heap Space" and "Out of Memory"

There's a couple of different memory settings for good reason.

The eclipse memory setting is because Eclipse is a large java program. if you are going to have a huge amount of files open in a couple of projects, then you're going to want to give Eclipse more ram. This is an issue only on "enterprise" systems normally personal projects wont use that many file handles or interfaces.

The JRE setting is how much ram to allow the java runtime when you run your project. This is probably the one you want when you are running some memory hogging application. I've run mathematical projects that needed a few gigs of ram and had to really tell the JRE it was okay, the JVM kept assuming my program was in some leaky runaway state, but I was doing it on purpose, and had to tell JVM specifically what it was allowed to use.

Then Catalina's memory setting is for the application server Tomcat. That server needs memory for each application and concurrent users. This blends with the JRE number because your project might be a web application and I'm not sure which one needs the memory.

### How to force a line break on a Javascript concatenated string?

``````document.getElementById("address_box").value =
``````

### Can I write native iPhone apps using Python?

Yes you can. You write your code in tinypy (which is restricted Python), then use tinypy to convert it to C++, and finally compile this with XCode into a native iPhone app. Phil Hassey has published a game called Elephants! using this approach. Here are more details,

http://www.philhassey.com/blog/2009/12/23/elephants-is-free-on-the-app-store/

### How can foreign key constraints be temporarily disabled using T-SQL?

You can temporarily disable constraints on your tables, do work, then rebuild them.

Here is an easy way to do it...

Disable all indexes, including the primary keys, which will disable all foreign keys, then re-enable just the primary keys so you can work with them...

``````DECLARE @sql AS NVARCHAR(max)=''
select @sql = @sql +
'ALTER INDEX ALL ON [' + t.[name] + '] DISABLE;'+CHAR(13)
from
sys.tables t
where type='u'

select @sql = @sql +
'ALTER INDEX ' + i.[name] + ' ON [' + t.[name] + '] REBUILD;'+CHAR(13)
from
sys.key_constraints i
join
sys.tables t on i.parent_object_id=t.object_id
where
i.type='PK'

exec dbo.sp_executesql @sql;
go
``````

Then re-enable and rebuild the indexes...

``````DECLARE @sql AS NVARCHAR(max)=''
select @sql = @sql +
'ALTER INDEX ALL ON [' + t.[name] + '] REBUILD;'+CHAR(13)
from
sys.tables t
where type='u'

exec dbo.sp_executesql @sql;
go
``````

### How to see log files in MySQL?

You have to activate the query logging in mysql.

1. edit /etc/my.cnf

```[mysqld]
log=/tmp/mysql.log
```
2. restart the computer or the mysqld service

```service mysqld restart
```
3. open phpmyadmin/any application that uses mysql/mysql console and run a query

4. `cat /tmp/mysql.log` ( you should see the query )

### Why is my Button text forced to ALL CAPS on Lollipop?

Using the android.support.v7.widget.AppCompatButton in the XML layout will allow you to avoid having to have a layout-21 or programmatically changing anything. Naturally this will also work with AppCompat v7 library.

``````<android.support.v7.widget.AppCompatButton
android:id="@+id/btnOpenMainDemo"
android:textAllCaps="false"
style="@style/HGButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/btn_main_demo"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
``````

Hope this helps.

### How to free memory in Java?

To extend upon the answer and comment by Yiannis Xanthopoulos and Hot Licks (sorry, I cannot comment yet!), you can set VM options like this example:

``````-XX:+UseG1GC -XX:MinHeapFreeRatio=15 -XX:MaxHeapFreeRatio=30
``````

In my jdk 7 this will then release unused VM memory if more than 30% of the heap becomes free after GC when the VM is idle. You will probably need to tune these parameters.

While I didn't see it emphasized in the link below, note that some garbage collectors may not obey these parameters and by default java may pick one of these for you, should you happen to have more than one core (hence the UseG1GC argument above).

VM arguments

Update: For java 1.8.0_73 I have seen the JVM occasionally release small amounts with the default settings. Appears to only do it if ~70% of the heap is unused though.. don't know if it would be more aggressive releasing if the OS was low on physical memory.

### What is the difference between JAX-RS and JAX-WS?

JAX-WS - is Java API for the XML-Based Web Services - a standard way to develop a Web- Services in SOAP notation (Simple Object Access Protocol).

Calling of the Web Services is performed via remote procedure calls. For the exchange of information between the client and the Web Service is used SOAP protocol. Message exchange between the client and the server performed through XML- based SOAP messages.

Clients of the JAX-WS Web- Service need a WSDL file to generate executable code that the clients can use to call Web- Service.

JAX-RS - Java API for RESTful Web Services. RESTful Web Services are represented as resources and can be identified by Uniform Resource Identifiers (URI). Remote procedure call in this case is represented a HTTP- request and the necessary data is passed as parameters of the query. Web Services RESTful - more flexible, can use several different MIME- types. Typically used for XML data exchange or JSON (JavaScript Object Notation) data exchange...

### How to change font in ipython notebook

You can hover to `.ipython` folder (i.e. you can type `\$ ipython locate` in your terminal/bash OR `CMD.exe Prompt` from your Anaconda Navigator to see where is your ipython is located)

Then, in `.ipython`, you will see `profile_default` directory which is the default one. This directory will have `static/custom/custom.css` file located.

You can now apply change to this `custom.css` file. There are a lot of styles in the `custom.css` file that you can use or search for. For example, you can see this link (which is my own customize `custom.css` file)

Basically, this `custom.css` file apply changes to your browser. You can use inspect elements in your ipython notebook to see which elements you want to change. Then, you can changes to the `custom.css` file. For example, you can add these chunk to change font in `.CodeMirror pre` to type `Monaco`

``````.CodeMirror pre {font-family: Monaco; font-size: 9pt;}
``````

Note that now for Jupyter notebook version >= 4.1, the custom css file is moved to `~/.jupyter/custom/custom.css` instead.

### How to convert a String to JsonObject using gson library

To do it in a simpler way, consider below:

``````JsonObject jsonObject = (new JsonParser()).parse(json).getAsJsonObject();
``````

### Tomcat manager/html is not available?

I couldn't log in to the manager app, even though my tomcat-users.xml file was set up correctly. The problem was that tomcat was configured to get users from a database. An employee who knew how this all worked left the company so I had to track this all down.

If you have a web application with something like this in the projects web.xml:

``````<security-role>
<role-name>manager</role-name>
</security-role>
``````

You should be aware that this is using the same system for log ins as tomcat! So where ever your manager role user(s) are defined, that is where you should define your manager-gui role and user. In server.xml I found this:

`````` <Realm className="org.apache.catalina.realm.JDBCRealm"
driverName="org.gjt.mm.mysql.Driver"
userRoleTable="user_roles" roleNameCol="role_name" />
``````

That tells me there is a database storing all the users and roles. This overrides the tomcat-users.xml file. Nothing in that file works unless this Realm is commented out. The solution is to add your tomcat user to the users table and your manager-gui role to the user_roles table:

``````insert into users (user_name, user_pass) values ('tomcat', '<changeMe>');
insert into user_roles (user_name, role_name) values ('tomcat', 'manager-gui');
``````

You should also have a "manager-gui" rolename in the roles table. Add that if it doesn't exist. Hope this helps someone.

### StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First

Some quick but extremely useful additional information that I just learned from another post, but can't seem to find the documentation for (if anyone can share a link to it on MSDN that would be amazing):

The validation messages associated with these attributes will actually replace placeholders associated with the attributes. For example:

``````[MaxLength(100, "{0} can have a max of {1} characters")]
public string Address { get; set; }
``````

Will output the following if it is over the character limit: "Address can have a max of 100 characters"

The placeholders I am aware of are:

• {0} = Property Name
• {1} = Max Length
• {2} = Min Length

Much thanks to bloudraak for initially pointing this out.

### matplotlib get ylim values

`````` ymin, ymax = axes.get_ylim()
``````

If you are using the `plt` api directly, you can avoid calls to `axes` altogether:

``````def myplotfunction(title, values, errors, plot_file_name):

# plot errorbars
indices = range(0, len(values))
fig = plt.figure()
plt.errorbar(tuple(indices), tuple(values), tuple(errors), marker='.')

plt.ylim([-0.5, len(values) - 0.5])
plt.xlabel('My x-axis title')
plt.ylabel('My y-axis title')

# title
plt.title(title)

# save as file
plt.savefig(plot_file_name)

# close figure
plt.close(fig)
``````

### Dynamic Web Module 3.0 -- 3.1

1) Go to your project and find ".settings" directory this one
2) Open file xml named:
org.eclipse.wst.common.project.facet.core.xml
3)

``````<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<fixed facet="wst.jsdt.web"/>
<installed facet="java" version="1.5"/>
<installed facet="jst.web" version="2.3"/>
<installed facet="wst.jsdt.web" version="1.0"/>
</faceted-project>
``````

Change jst.web version to 3.0 and java version to 1.7 or 1.8 (base on your current using jdk version)

4) Change your `web.xml` file under `WEB-INF` directory , please refer to this article:
https://www.mkyong.com/web-development/the-web-xml-deployment-descriptor-examples/
5) Go to `pom.xml` file and paste these lines:

``````<build>
<finalName>YOUR_PROJECT_NAME</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source> THIS IS YOUR USING JDK's VERSION
<target>1.8</target> SAME AS ABOVE
</configuration>
</plugin>
</plugins>
</build>
``````

Without code in iframe + animate:

``````<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script language="javascript" type="text/javascript">

function resizeIframe(obj) {

\$(obj).animate({height: obj.contentWindow.document.body.scrollHeight + 'px'}, 500)

});

}
</script>
<iframe width="100%" src="iframe.html" height="0" frameborder="0" scrolling="no" onload="resizeIframe(this)" >
``````

### ImageView in circular through xml

Actually, you can use what Google provides via the support library RoundedBitmapDrawableFactory class (here and here), instead of using a third party library :

``````implementation 'androidx.appcompat:appcompat:1.0.0-beta01'
``````

MainActivity.kt

``````class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val originalDrawable = ContextCompat.getDrawable(this, R.drawable.avatar_1)!!
val bitmap = convertDrawableToBitmap(originalDrawable)
val drawable = RoundedBitmapDrawableFactory.create(resources, bitmap)
drawable.setAntiAlias(true)
drawable.cornerRadius = Math.max(bitmap.width, bitmap.height) / 2.0f
avatarImageView.setImageDrawable(drawable)
}

companion object {
@JvmStatic
fun convertDrawableToBitmap(drawable: Drawable): Bitmap {
if (drawable is BitmapDrawable)
return drawable.bitmap
// We ask for the bounds if they have been set as they would be most
// correct, then we check we are  > 0
val bounds = drawable.bounds
val width = if (!bounds.isEmpty) bounds.width() else drawable.intrinsicWidth
val height = if (!bounds.isEmpty) bounds.height() else drawable.intrinsicHeight
// Now we check we are > 0
val bitmap = Bitmap.createBitmap(if (width <= 0) 1 else width, if (height <= 0) 1 else height,
Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
return bitmap
}
}
}
``````

res/layout/activity_main.xml

``````<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".MainActivity">

<androidx.appcompat.widget.AppCompatImageView
android:id="@+id/avatarImageView" android:layout_width="100dp" android:layout_height="100dp"
android:layout_gravity="center"/>

</FrameLayout>
``````

res/drawable/avatar_1.xml

``````<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="128dp" android:height="128dp"
android:viewportHeight="128.0" android:viewportWidth="128.0">
<path
android:fillColor="#FF8A80" android:pathData="M0 0h128v128h-128z"/>
<path
android:fillColor="#FFE0B2"
android:pathData="M36.3 94.8c6.4 7.3 16.2 12.1 27.3 12.4 10.7,-.3 20.3,-4.7 26.7,-11.6l.2.1c-17,-13.3,-12.9,-23.4,-8.5,-28.6 1.3,-1.2 2.8,-2.5 4.4,-3.9l13.1,-11c1.5,-1.2 2.6,-3 2.9,-5.1.6,-4.4,-2.5,-8.4,-6.9,-9.1,-1.5,-.2,-3 0,-4.3.6,-.3,-1.3,-.4,-2.7,-1.6,-3.5,-1.4,-.9,-2.8,-1.7,-4.2,-2.5,-7.1,-3.9,-14.9,-6.6,-23,-7.9,-5.4,-.9,-11,-1.2,-16.1.7,-3.3 1.2,-6.1 3.2,-8.7 5.6,-1.3 1.2,-2.5 2.4,-3.7 3.7l-1.8 1.9c-.3.3,-.5.6,-.8.8,-.1.1,-.2 0,-.4.2.1.2.1.5.1.6,-1,-.3,-2.1,-.4,-3.2,-.2,-4.4.6,-7.5 4.7,-6.9 9.1.3 2.1 1.3 3.8 2.8 5.1l11 9.3c1.8 1.5 3.3 3.8 4.6 5.7 1.5 2.3 2.8 4.9 3.5 7.6 1.7 6.8,-.8 13.4,-5.4 18.4,-.5.6,-1.1 1,-1.4 1.7,-.2.6,-.4 1.3,-.6 2,-.4 1.5,-.5 3.1,-.3 4.6.4 3.1 1.8 6.1 4.1 8.2 3.3 3 8 4 12.4 4.5 5.2.6 10.5.7 15.7.2 4.5,-.4 9.1,-1.2 13,-3.4 5.6,-3.1 9.6,-8.9 10.5,-15.2m-14.4,-49.8c.9 0 1.6.7 1.6 1.6 0 .9,-.7 1.6,-1.6 1.6,-.9 0,-1.6,-.7,-1.6,-1.6,-.1,-.9.7,-1.6 1.6,-1.6zm-25.7 0c.9 0 1.6.7 1.6 1.6 0 .9,-.7 1.6,-1.6 1.6,-.9 0,-1.6,-.7,-1.6,-1.6,-.1,-.9.7,-1.6 1.6,-1.6z"/>
<path
android:fillColor="#E0F7FA"
android:pathData="M105.3 106.1c-.9,-1.3,-1.3,-1.9,-1.3,-1.9l-.2,-.3c-.6,-.9,-1.2,-1.7,-1.9,-2.4,-3.2,-3.5,-7.3,-5.4,-11.4,-5.7 0 0 .1 0 .1.1l-.2,-.1c-6.4 6.9,-16 11.3,-26.7 11.6,-11.2,-.3,-21.1,-5.1,-27.5,-12.6,-.1.2,-.2.4,-.2.5,-3.1.9,-6 2.7,-8.4 5.4l-.2.2s-.5.6,-1.5 1.7c-.9 1.1,-2.2 2.6,-3.7 4.5,-3.1 3.9,-7.2 9.5,-11.7 16.6,-.9 1.4,-1.7 2.8,-2.6 4.3h109.6c-3.4,-7.1,-6.5,-12.8,-8.9,-16.9,-1.5,-2.2,-2.6,-3.8,-3.3,-5z"/>
<path
android:fillColor="#444" android:pathData="M76.3,47.5 m-2.0, 0 a 2.0,2.0 0 1,1 4.0,0 a2.0,2.0 0 1,1 -4.0,0"/>
<path
android:fillColor="#444" android:pathData="M50.7,47.6 m-2.0, 0 a 2.0,2.0 0 1,1 4.0,0 a2.0,2.0 0 1,1 -4.0,0"/>
<path
android:fillColor="#444"
android:pathData="M48.1 27.4c4.5 5.9 15.5 12.1 42.4 8.4,-2.2,-6.9,-6.8,-12.6,-12.6,-16.4 17.2 1.5 14.1,-9.4 14.1,-9.4,-1.4 5.5,-11.1 4.4,-11.1 4.4h-18.8c-1.7,-.1,-3.4 0,-5.2.3,-12.8 1.8,-22.6 11.1,-25.7 22.9 10.6,-1.9 15.3,-7.6 16.9,-10.2z"/>
</vector>
``````

The result:

And, suppose you want to add a border on top of it, you can use this for example:

stroke_drawable.xml

``````<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<stroke
android:width="4dp" android:color="@android:color/black"/>
</shape>
``````

And add `android:foreground="@drawable/stroke_drawable"` to the ImageView in the layout XML file, and you get this :

I'm not sure how to add shadow (that will work on older Android versions), though. Using FloatingActionButton (from the "com.google.android.material:material" dependency), I failed to make the bitmap fill the FAB itself. Using it instead could be even better if it worked.

EDIT: if you wish to add shadow of elevation (available from API 21), you can change a bit what I wrote:

Inside the layout XML file:

``````<androidx.appcompat.widget.AppCompatImageView android:padding="4dp"
android:id="@+id/avatarImageView" android:layout_width="100dp" android:layout_height="100dp" android:elevation="8dp"
android:layout_gravity="center" android:background="@drawable/stroke_drawable" tools:srcCompat="@drawable/avatar_1"/>
``````

``````@TargetApi(Build.VERSION_CODES.LOLLIPOP)
override fun getOutline(view: View, outline: Outline) {
val size = Math.max(view.width, view.height)
outline.setRoundRect(0, 0, size, size, size / 2f)
}
}
``````

In code:

``````    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
``````

Result:

I'm pretty late to the party, but here is another implementation using : https://stackblitz.com/edit/angular-confirmation-dialog

confirmation-dialog.service.ts

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

import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

import { ConfirmationDialogComponent } from './confirmation-dialog.component';

@Injectable()
export class ConfirmationDialogService {

constructor(private modalService: NgbModal) { }

public confirm(
title: string,
message: string,
btnOkText: string = 'OK',
btnCancelText: string = 'Cancel',
dialogSize: 'sm'|'lg' = 'sm'): Promise<boolean> {
const modalRef = this.modalService.open(ConfirmationDialogComponent, { size: dialogSize });
modalRef.componentInstance.title = title;
modalRef.componentInstance.message = message;
modalRef.componentInstance.btnOkText = btnOkText;
modalRef.componentInstance.btnCancelText = btnCancelText;

return modalRef.result;
}

}
``````

confirmation-dialog.component.ts

``````import { Component, Input, OnInit } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
selector: 'app-confirmation-dialog',
templateUrl: './confirmation-dialog.component.html',
styleUrls: ['./confirmation-dialog.component.scss'],
})
export class ConfirmationDialogComponent implements OnInit {

@Input() title: string;
@Input() message: string;
@Input() btnOkText: string;
@Input() btnCancelText: string;

constructor(private activeModal: NgbActiveModal) { }

ngOnInit() {
}

public decline() {
this.activeModal.close(false);
}

public accept() {
this.activeModal.close(true);
}

public dismiss() {
this.activeModal.dismiss();
}

}
``````

confirmation-dialog.component.html

``````<div class="modal-header">
<h4 class="modal-title">{{ title }}</h4>
<button type="button" class="close" aria-label="Close" (click)="dismiss()">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
{{ message }}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" (click)="decline()">{{ btnCancelText }}</button>
<button type="button" class="btn btn-primary" (click)="accept()">{{ btnOkText }}</button>
</div>
``````

Use the dialog like this:

``````public openConfirmationDialog() {
this.confirmationDialogService.confirm('Please confirm..', 'Do you really want to ... ?')
.then((confirmed) => console.log('User confirmed:', confirmed))
.catch(() => console.log('User dismissed the dialog (e.g., by using ESC, clicking the cross icon, or clicking outside the dialog)'));
}
``````

### How do I create a message box with "Yes", "No" choices and a DialogResult?

This should do it:

``````DialogResult dialogResult = MessageBox.Show("Sure", "Some Title", MessageBoxButtons.YesNo);
if(dialogResult == DialogResult.Yes)
{
//do something
}
else if (dialogResult == DialogResult.No)
{
//do something else
}
``````

### In a Bash script, how can I exit the entire script if a certain condition occurs?

I often include a function called run() to handle errors. Every call I want to make is passed to this function so the entire script exits when a failure is hit. The advantage of this over the set -e solution is that the script doesn't exit silently when a line fails, and can tell you what the problem is. In the following example, the 3rd line is not executed because the script exits at the call to false.

``````function run() {
cmd_output=\$(eval \$1)
return_value=\$?
if [ \$return_value != 0 ]; then
echo "Command \$1 failed"
exit -1
else
echo "output: \$cmd_output"
echo "Command succeeded."
fi
return \$return_value
}
run "date"
run "false"
run "date"
``````

### Datetime current year and month in Python

Use:

``````from datetime import datetime
today = datetime.today()
datem = datetime(today.year, today.month, 1)
``````

I assume you want the first of the month.

### Linker error: "linker input file unused because linking not done", undefined reference to a function in that file

I think you are confused about how the compiler puts things together. When you use `-c` flag, i.e. no linking is done, the input is C++ code, and the output is object code. The `.o` files thus don't mix with `-c`, and compiler warns you about that. Symbols from object file are not moved to other object files like that.

All object files should be on the final linker invocation, which is not the case here, so linker (called via `g++` front-end) complains about missing symbols.

Here's a small example (calling `g++` explicitly for clarity):

``````PROG ?= myprog
OBJS = worker.o main.o

all: \$(PROG)

.cpp.o:
g++ -Wall -pedantic -ggdb -O2 -c -o \$@ \$<

\$(PROG): \$(OBJS)
g++ -Wall -pedantic -ggdb -O2 -o \$@ \$(OBJS)
``````

There's also `makedepend` utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the `-M` `gcc` option for building `make` rules.

### SQL query to find record with ID not in another table

#### Fast Alternative

I ran some tests (on postgres 9.5) using two tables with ~2M rows each. This query below performed at least 5* better than the other queries proposed:

``````-- Count
SELECT count(*) FROM (
(SELECT id FROM table1) EXCEPT (SELECT id FROM table2)
) t1_not_in_t2;

-- Get full row
SELECT table1.* FROM (
(SELECT id FROM table1) EXCEPT (SELECT id FROM table2)
) t1_not_in_t2 JOIN table1 ON t1_not_in_t2.id=table1.id;
``````

### Why is there no Constant feature in Java?

You can use static final to create something that works similar to Const, I have used this in the past.

``````protected static final int cOTHER = 0;
protected static final int cRPM = 1;
protected static final int cSPEED = 2;
protected static final int cTPS = 3;

public static final int INVALID_PIN = -1;
public static final int LED_PIN = 0;
``````

### How to use global variable in node.js?

I would suggest everytime when using global check if the variable is already define by simply check

``````if (!global.logger){
global.logger = require('my_logger');
}
``````

I've found it to have better performance

### Random number c++ in some range

Use the `rand` function:

http://www.cplusplus.com/reference/clibrary/cstdlib/rand/

Quote:

``````A typical way to generate pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range:

( value % 100 ) is in the range 0 to 99
( value % 100 + 1 ) is in the range 1 to 100
( value % 30 + 1985 ) is in the range 1985 to 2014
``````

### How can I prevent a window from being resized with tkinter?

You can use the `minsize` and `maxsize` to set a minimum & maximum size, for example:

``````def __init__(self,master):
master.minsize(width=666, height=666)
master.maxsize(width=666, height=666)
``````

Will give your window a fixed width & height of 666 pixels.

Or, just using `minsize`

``````def __init__(self,master):
master.minsize(width=666, height=666)
``````

Will make sure your window is always at least 666 pixels large, but the user can still expand the window.

### Load local HTML file in a C# WebBrowser

for me it worked as the following lines in `VS2017`

``````string curDir = Directory.GetCurrentDirectory();
this.webBrowser1.Navigate(new Uri(String.Format("file:///{0}/my_html.html", curDir)));
``````

### What does "res.render" do, and what does the html file look like?

Renders a view and sends the rendered HTML string to the client.

``````res.render('index');
``````

Or

``````res.render('index', function(err, html) {
if(err) {...}
res.send(html);
});
``````

### Get loop count inside a Python FOR loop

Agree with Nick. Here is more elaborated code.

``````#count=0
for idx, item in enumerate(list):
print item
#count +=1
#if count % 10 == 0:
if (idx+1) % 10 == 0:
print 'did ten'
``````

I have commented out the count variable in your code.

### How would I get a cron job to run every 30 minutes?

You mention you are using OS X- I have used cronnix in the past. It's not as geeky as editing it yourself, but it helped me learn what the columns are in a jiffy. Just a thought.

### How to conditionally take action if FINDSTR fails to find a string

In DOS/Windows Batch most commands return an exitCode, called "errorlevel", that is a value that customarily is equal to zero if the command ends correctly, or a number greater than zero if ends because an error, with greater numbers for greater errors (hence the name).

There are a couple methods to check that value, but the original one is:

``````IF ERRORLEVEL value command
``````

Previous IF test if the errorlevel returned by the previous command was GREATER THAN OR EQUAL the given value and, if this is true, execute the command. For example:

``````verify bad-param
if errorlevel 1 echo Errorlevel is greater than or equal 1
echo The value of errorlevel is: %ERRORLEVEL%
``````

Findstr command return 0 if the string was found and 1 if not:

``````CD C:\MyFolder
findstr /c:"stringToCheck" fileToCheck.bat
IF ERRORLEVEL 1 XCOPY "C:\OtherFolder\fileToCheck.bat" "C:\MyFolder" /s /y
``````

Previous code will copy the file if the string was NOT found in the file.

``````CD C:\MyFolder
findstr /c:"stringToCheck" fileToCheck.bat
IF NOT ERRORLEVEL 1 XCOPY "C:\OtherFolder\fileToCheck.bat" "C:\MyFolder" /s /y
``````

Previous code copy the file if the string was found. Try this:

``````findstr "string" file
if errorlevel 1 (
) else (
echo String found
)
``````

### Extract values in Pandas value_counts()

First you have to `sort` the `dataframe` by the `count` column `max` to `min` if it's not sorted that way already. In your post, it is in the right order already but I will `sort` it anyways:

``````dataframe.sort_index(by='count', ascending=[False])
col     count
0   apple   5
1   sausage 2
2   banana  2
3   cheese  1
``````

Then you can output the `col` column to a list:

``````dataframe['col'].tolist()
['apple', 'sausage', 'banana', 'cheese']
``````

### Loop Through All Subfolders Using VBA

Just a simple folder drill down.

``````sub sample()
Dim FileSystem As Object
Dim HostFolder As String

HostFolder = "C:\"

Set FileSystem = CreateObject("Scripting.FileSystemObject")
DoFolder FileSystem.GetFolder(HostFolder)
end  sub

Sub DoFolder(Folder)
Dim SubFolder
For Each SubFolder In Folder.SubFolders
DoFolder SubFolder
Next
Dim File
For Each File In Folder.Files
' Operate on each file
Next
End Sub
``````

### Reset auto increment counter in postgres

if you want to Reset auto increment from GUI, then follow this steps.

2. Click on Public
3. in the tables Listing page you can see TABS like 'Tables', 'Views', 'Sequences' like that.
4. Click on Sequences
5. when you click on 'Sequences' you can see all the Sequences Listing, click on any that you want to Reset
6. After that you can see multiple choice like 'Alter', 'Set Value', 'Restart', 'Reset' etc...
7. then click on Reset, then add one New Row.

### How to check if an element of a list is a list (in Python)?

you can simply write:

``````for item,i in zip(your_list, range(len(your_list)):

if type(item) == list:
print(f"{item} at index {i} is a list")
``````

### Regular expression for URL validation (in JavaScript)

try with this:

`````` var RegExp =/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?\$/i;
``````

### What is ":-!!" in C code?

Some people seem to be confusing these macros with `assert()`.

These macros implement a compile-time test, while `assert()` is a runtime test.

### Password Protect a SQLite DB. Is it possible?

I know this is an old question but wouldn't the simple solution be to just protect the file at the OS level? Just prevent the users from accessing the file and then they shouldn't be able to touch it. This is just a guess and I'm not sure if this is an ideal solution.

### Convert a list of characters into a string

If your Python interpreter is old (1.5.2, for example, which is common on some older Linux distributions), you may not have `join()` available as a method on any old string object, and you will instead need to use the string module. Example:

``````a = ['a', 'b', 'c', 'd']

try:
b = ''.join(a)

except AttributeError:
import string
b = string.join(a, '')
``````

The string `b` will be `'abcd'`.

### How to remove a virtualenv created by "pipenv run"

You can run the `pipenv` command with the `--rm` option as in:

``````pipenv --rm
``````

This will remove the virtualenv created for you under ~/.virtualenvs

### How do I install the OpenSSL libraries on Ubuntu?

How could I have figured that out for myself (other than asking this question here)? Can I somehow tell apt-get to list all packages, and grep for ssl? Or do I need to know the "lib*-dev" naming convention?

If you're linking with `-lfoo` then the library is likely `libfoo.so`. The library itself is probably part of the `libfoo` package, and the headers are in the `libfoo-dev` package as you've discovered.

Some people use the GUI "synaptic" app (`sudo synaptic`) to (locate and) install packages, but I prefer to use the command line. One thing that makes it easier to find the right package from the command line is the fact that `apt-get` supports bash completion.

Try typing `sudo apt-get install libssl` and then hit tab to see a list of matching package names (which can help when you need to select the correct version of a package that has multiple versions or other variations available).

Bash completion is actually very useful... for example, you can also get a list of commands that `apt-get` supports by typing `sudo apt-get` and then hitting tab.

### How do I tell matplotlib that I am done with a plot?

If none of them are working then check this.. say if you have x and y arrays of data along respective axis. Then check in which cell(jupyter) you have initialized x and y to empty. This is because , maybe you are appending data to x and y without re-initializing them. So plot has old data too. So check that..

### How to specify new GCC path for CMake

This not only works with `cmake`, but also with `./configure` and `make`:

``````./configure CC=/usr/local/bin/gcc CXX=/usr/local/bin/g++
``````

Which is resulting in:

``````checking for gcc... /usr/local/bin/gcc
checking whether the C compiler works... yes
``````

### Redirect using AngularJS

Assuming you're not using html5 routing, try `\$location.path("route")`. This will redirect your browser to `#/route` which might be what you want.

### How can I render repeating React elements?

This is, imo, the most elegant way to do it (with ES6). Instantiate you empty array with 7 indexes and map in one line:

``````Array.apply(null, Array(7)).map((i)=>
<Somecomponent/>
)
``````

### <!--[if !IE]> not working

Conditional comment is a comment starts with `<!--[if IE]>` which couldn't be read by any browser except IE.

from 2011 Conditional comment isn't supported starting form IE 10 as announced by Microsoft in that time https://msdn.microsoft.com/en-us/library/hh801214(v=vs.85).aspx

The only option to use the Conditional comments is to request IE to run your site as IE 9 which supports the Conditional comments.

you can write your own css and/or js files for ie only and other browsers won't load or execute it.

this code snippet shows how to make IE 10 or 11 run ie-only.css and ie-only.js which contains custom codes to solve IE compatibility issues.

``````    <html>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9">
<!--[if IE]>
<meta http-equiv="Content-Type" content="text/html; charset=Unicode">
<script src="/js/ie-only.js"></script>
<![endif]-->
</html>
``````

### How to list the certificates stored in a PKCS12 keystore with keytool?

You can also use `openssl` to accomplish the same thing:

``````\$ openssl pkcs12 -nokeys -info \
-in </path/to/file.pfx> \

MAC Iteration 2048
MAC verified OK
PKCS7 Encrypted data: pbeWithSHA1And40BitRC2-CBC, Iteration 2048
Certificate bag
Bag Attributes
localKeyID: XX XX XX XX XX XX XX XX XX XX XX XX XX 48 54 A0 47 88 1D 90
friendlyName: jedis-server
subject=/C=US/ST=NC/L=Raleigh/O=XXX Security/OU=XXX/CN=something1
issuer=/C=US/ST=NC/L=Raleigh/O=XXX Security/OU=XXXX/CN=something1
-----BEGIN CERTIFICATE-----
...
...
...
-----END CERTIFICATE-----
PKCS7 Data
Shrouded Keybag: pbeWithSHA1And3-KeyTripleDES-CBC, Iteration 2048
``````

For me the following explanatory snippet worked. Perhaps you shouldn't use `'` for header name?

``````{
Authorization: "Basic " + getAuthDigest(),
Accept: "text/plain"
}
}
``````

I'm using `\$http.ajax()`, though I wouldn't expect that to be a game changer.

Here you can find some useful info about cURL & cookies http://docstore.mik.ua/orelly/webprog/pcook/ch11_04.htm .

You can also use this well done method https://github.com/alixaxel/phunction/blob/master/phunction/Net.php#L89 like a function:

``````function CURL(\$url, \$data = null, \$method = 'GET', \$cookie = null, \$options = null, \$retries = 3)
{
\$result = false;

if ((extension_loaded('curl') === true) && (is_resource(\$curl = curl_init()) === true))
{
curl_setopt(\$curl, CURLOPT_URL, \$url);
curl_setopt(\$curl, CURLOPT_FAILONERROR, true);
curl_setopt(\$curl, CURLOPT_AUTOREFERER, true);
curl_setopt(\$curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt(\$curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt(\$curl, CURLOPT_SSL_VERIFYPEER, false);

{
{
curl_setopt_array(\$curl, array(CURLOPT_HEADER => true, CURLOPT_NOBODY => true));
}

else if (preg_match('~^(?:POST|PUT)\$~i', \$method) > 0)
{
if (is_array(\$data) === true)
{
foreach (preg_grep('~^@~', \$data) as \$key => \$value)
{
\$data[\$key] = sprintf('@%s', rtrim(str_replace('\\', '/', realpath(ltrim(\$value, '@'))), '/') . (is_dir(ltrim(\$value, '@')) ? '/' : ''));
}

if (count(\$data) != count(\$data, COUNT_RECURSIVE))
{
\$data = http_build_query(\$data, '', '&');
}
}

curl_setopt(\$curl, CURLOPT_POSTFIELDS, \$data);
}

curl_setopt(\$curl, CURLOPT_CUSTOMREQUEST, strtoupper(\$method));

{
}

if ((intval(ini_get('safe_mode')) == 0) && (ini_set('open_basedir', null) !== false))
{
curl_setopt_array(\$curl, array(CURLOPT_MAXREDIRS => 5, CURLOPT_FOLLOWLOCATION => true));
}

if (is_array(\$options) === true)
{
curl_setopt_array(\$curl, \$options);
}

for (\$i = 1; \$i <= \$retries; ++\$i)
{
\$result = curl_exec(\$curl);

if ((\$i == \$retries) || (\$result !== false))
{
break;
}

usleep(pow(2, \$i - 2) * 1000000);
}
}

curl_close(\$curl);
}

return \$result;
}
``````

And pass this as `\$cookie` parameter:

``````\$cookie_jar = tempnam('/tmp','cookie');
``````

### How to emulate a BEFORE INSERT trigger in T-SQL / SQL Server for super/subtype (Inheritance) entities?

While Andriy's proposal will work well for INSERTs of a small number of records, full table scans will be done on the final join as both 'enumerated' and '@new_super' are not indexed, resulting in poor performance for large inserts.

This can be resolved by specifying a primary key on the @new_super table, as follows:

``````DECLARE @new_super TABLE (
row_num INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
super_id   int
);
``````

This will result in the SQL optimizer scanning through the 'enumerated' table but doing an indexed join on @new_super to get the new key.

### Disable elastic scrolling in Safari

I had solved it on iPad. Try, if it works also on OSX.

`body, html { position: fixed; }`

Works only if you have content smaller then screen or you are using some layout framework (Angular Material in my case).

In Angular Material it is great, that you will disable over-scroll effect of whole page, but inner sections `<md-content>` can be still scrollable.

### How do I center content in a div using CSS?

By using transform: works like a charm!

``````<div class="parent">
<span>center content using transform</span>
</div>

//CSS
.parent {
position: relative;
height: 200px;
border: 1px solid;
}
.parent span {
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
``````

### List of IP Space used by Facebook

Updated list as of 6/11/2013

204.15.20.0/22
69.63.176.0/20

66.220.144.0/20
66.220.144.0/21
69.63.184.0/21
69.63.176.0/21
74.119.76.0/22
69.171.255.0/24
173.252.64.0/18
69.171.224.0/19
69.171.224.0/20
103.4.96.0/22
69.63.176.0/24
173.252.64.0/19
173.252.70.0/24
31.13.64.0/18
31.13.24.0/21
66.220.152.0/21
66.220.159.0/24
69.171.239.0/24
69.171.240.0/20
31.13.64.0/19
31.13.64.0/24
31.13.65.0/24
31.13.67.0/24
31.13.68.0/24
31.13.69.0/24
31.13.70.0/24
31.13.71.0/24
31.13.72.0/24
31.13.73.0/24
31.13.74.0/24
31.13.75.0/24
31.13.76.0/24
31.13.77.0/24
31.13.96.0/19
31.13.66.0/24
173.252.96.0/19
69.63.178.0/24
31.13.78.0/24
31.13.79.0/24
31.13.80.0/24
31.13.82.0/24
31.13.83.0/24
31.13.84.0/24
31.13.85.0/24
31.13.87.0/24
31.13.88.0/24
31.13.89.0/24
31.13.90.0/24
31.13.91.0/24
31.13.92.0/24
31.13.93.0/24
31.13.94.0/24
31.13.95.0/24
69.171.253.0/24
69.63.186.0/24
204.15.20.0/22
69.63.176.0/20
69.63.176.0/21
69.63.184.0/21
66.220.144.0/20
69.63.176.0/20

### How to sort an array of associative arrays by value of a given key in PHP?

by using usort (http://php.net/usort) , we can sort an array in ascending and descending order. just we need to create a function and pass it as parameter in usort. As per below example used greater than for ascending order if we passed less than condition then it's sort in descending order. Example :

``````\$array = array(
array('price'=>'1000.50','product'=>'test1'),
array('price'=>'8800.50','product'=>'test2'),
array('price'=>'200.0','product'=>'test3')
);

function cmp(\$a, \$b) {
return \$a['price'] > \$b['price'];
}

usort(\$array, "cmp");
print_r(\$array);
``````

Output:

``````Array
(
[0] => Array
(
[price] => 200.0
[product] => test3
)

[1] => Array
(
[price] => 1000.50
[product] => test1
)

[2] => Array
(
[price] => 8800.50
[product] => test2
)
)
``````

### Parsing arguments to a Java command line program

I realize that the question mentions a preference for Commons CLI, but I guess that when this question was asked, there was not much choice in terms of Java command line parsing libraries. But nine years later, in 2020, would you not rather write code like the below?

``````import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;
import java.io.File;
import java.util.List;
import java.util.concurrent.Callable;

@Command(name = "myprogram", mixinStandardHelpOptions = true,
description = "Does something useful.", version = "1.0")
public class MyProgram implements Callable<Integer> {

@Option(names = "-r", description = "The r option") String rValue;
@Option(names = "-S", description = "The S option") String sValue;
@Option(names = "-A", description = "The A file") File aFile;
@Option(names = "--test", description = "The test option") boolean test;
@Parameters(description = "Positional params") List<String> positional;

@Override
public Integer call() {
System.out.printf("-r=%s%n", rValue);
System.out.printf("-S=%s%n", sValue);
System.out.printf("-A=%s%n", aFile);
System.out.printf("--test=%s%n", test);
System.out.printf("positionals=%s%n", positional);
return 0;
}

public static void main(String... args) {
System.exit(new CommandLine(new MyProgram()).execute(args));
}
}
``````

Execute by running the command in the question:

``````java MyProgram -r opt1 -S opt2 arg1 arg2 arg3 arg4 --test -A opt3
``````

• compact - no boilerplate
• declarative - using annotations instead of a builder API
• strongly typed - annotated fields can be any type, not just String
• no duplication - option declaration and getting parse result are together in the annotated field
• clear - the annotations express the intention better than imperative code
• separation of concerns - the business logic in the `call` method is free of parsing-related logic
• convenient - one line of code in main wires up the parser and runs the business logic in the Callable
• powerful - automatic usage and version help with the built-in `--help` and `--version` options
• user-friendly - usage help message uses colors to contrast important elements like option names from the rest of the usage help to reduce the cognitive load on the user

The above functionality is only part of what you get when you use the picocli (https://picocli.info) library.

Now, bear in mind that I am totally, completely, and utterly biased, being the author of picocli. :-) But I do believe that in 2020 we have better alternatives for building a command line apps than Commons CLI.

### How to add elements of a string array to a string array list?

``````ArrayList<String> arraylist= new ArrayList<String>();

arraylist.addAll( Arrays.asList("mp3 radio", "presvlake", "dizalica", "sijelice", "brisaci farova", "neonke", "ratkape", "kuka", "trokut"));
``````

### 500 internal server error at GetResponse()

For me this error occurred because I had 2 web API actions that had the exact same signatures and both had the same verbs, `HttpPost`, what I did was change one of the verbs (the one used for updating) to PUT and the error was removed. The following in my catch statement helped in getting to the root of the problem:

``````catch (WebException webex)
{
WebResponse errResp = webex.Response;
using (Stream respStream = errResp.GetResponseStream())
{
}
}
``````

### Bootstrap DatePicker, how to set the start date for tomorrow?

``````this.\$('#datepicker').datepicker({minDate: 1});
``````

`minDate:0` - Enable dates in the calender from the current date. `MinDate:1` enable dates in the calender `currentDate+1`

To Restrict date between from tomorrow and the same day next month u need to give something like

``````\$( "#datepicker" ).datepicker({ minDate: 1, maxDate: "+1M" });
``````

### Initialize Array of Objects using NSArray

There is also a shorthand of doing this:

``````NSArray *persons = @[person1, person2, person3];
``````

It's equivalent to

``````NSArray *persons = [NSArray arrayWithObjects:person1, person2, person3, nil];
``````

As iiFreeman said, you still need to do proper memory management if you're not using ARC.

### How do I remove the top margin in a web page?

You can prevent the effects of margin collapsing with:

``````body { overflow: hidden }
``````

That will make the `body` margins remain accurate.

### How to use shared memory with Linux in C

Here is an example for shared memory :

``````#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define SHM_SIZE 1024  /* make it a 1K shared memory segment */

int main(int argc, char *argv[])
{
key_t key;
int shmid;
char *data;
int mode;

if (argc > 2) {
fprintf(stderr, "usage: shmdemo [data_to_write]\n");
exit(1);
}

/* make the key: */
if ((key = ftok("hello.txt", 'R')) == -1) /*Here the file must exist */
{
perror("ftok");
exit(1);
}

/*  create the segment: */
if ((shmid = shmget(key, SHM_SIZE, 0644 | IPC_CREAT)) == -1) {
perror("shmget");
exit(1);
}

/* attach to the segment to get a pointer to it: */
data = shmat(shmid, NULL, 0);
if (data == (char *)(-1)) {
perror("shmat");
exit(1);
}

/* read or modify the segment, based on the command line: */
if (argc == 2) {
printf("writing to segment: \"%s\"\n", argv[1]);
strncpy(data, argv[1], SHM_SIZE);
} else
printf("segment contains: \"%s\"\n", data);

/* detach from the segment: */
if (shmdt(data) == -1) {
perror("shmdt");
exit(1);
}

return 0;
}
``````

Steps :

1. Use ftok to convert a pathname and a project identifier to a System V IPC key

2. Use shmget which allocates a shared memory segment

3. Use shmat to attache the shared memory segment identified by shmid to the address space of the calling process

4. Do the operations on the memory area

5. Detach using shmdt

If you needed to add a lot of integers it'd proabbly be easiest to use a for loop. For example, adding 28 days to a daysInFebruary array.

``````ArrayList<Integer> daysInFebruary = new ArrayList<>();

for(int i = 1; i <= 28; i++) {
}
``````

### JSONResult to String

``````json = " { \"success\" : false, \"errors\": { \"text\" : \"??????!\" } }";
return new MemoryStream(Encoding.UTF8.GetBytes(json));
``````

### org.springframework.beans.factory.BeanCreationException: Error creating bean with name

According to the stack trace, your issue is that your app cannot find `org.apache.commons.dbcp.BasicDataSource`, as per this line:

``````java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource
``````

I see that you have commons-dbcp in your list of jars, but for whatever reason, your app is not finding the `BasicDataSource` class in it.

### Where is the IIS Express configuration / metabase file found?

For VS 2015 & VS 2017: Right-click the IIS Express system tray icon (when running the application), and select "Show all applications":

Then, select the relevant application and click the applicationhost.config file path:

### Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:

`/user/account`

``````if(\$loggedIn)
{
echo "<p>Logged in as ".\$user."</p>";
}
else
{
}
``````

How the same problem can be solved with an API centric approach by outputting JSON like this:

`api/auth/`

``````{
authorized:true,
user: {
securityToken: 'secret'
}
}
``````

and in Angular you could do a get, and handle the response client side.

``````\$http.post("http://example.com/api/auth", {})
.success(function(data) {
\$scope.isLoggedIn = data.authorized;
});
``````

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

### C++, How to determine if a Windows Process is running?

This is a solution that I've used in the past. Although the example here is in VB.net - I've used this technique with c and c++. It bypasses all the issues with Process IDs & Process handles, and return codes. Windows is very faithful in releasing the mutex no matter how Process2 is terminated. I hope it is helpful to someone...

``````**PROCESS1 :-**

Randomize()
mutexname = "myprocess" & Mid(Format(CDbl(Long.MaxValue) * Rnd(), "00000000000000000000"), 1, 16)
hnd = CreateMutex(0, False, mutexname)

' pass this name to Process2
File.WriteAllText("mutexname.txt", mutexname)

<start Process2>
<wait for Process2 to start>

pr = WaitForSingleObject(hnd, 0)
ReleaseMutex(hnd)

If pr = WAIT_OBJECT_0 Then

<Process2 not running>

Else

<Process2 is running>

End If
...

CloseHandle(hnd)
EXIT

**PROCESS2 :-**

hnd = OpenMutex(MUTEX_ALL_ACCESS Or SYNCHRONIZE, True, mutexname)
...

ReleaseMutex(hnd)
CloseHandle(hnd)
EXIT
``````

### Trying to retrieve first 5 characters from string in bash error?

`echo 'mystring' |cut -c1-5` is an alternative solution to ur problem.

more on unix cut program

### Automatically set appsettings.json for dev and release environments in asp.net core?

Just an update for .NET core 2.0 users, you can specify application configuration after the call to `CreateDefaultBuilder`:

``````public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}

public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(ConfigConfiguration)
.UseStartup<Startup>()
.Build();

static void ConfigConfiguration(WebHostBuilderContext ctx, IConfigurationBuilder config)
{
config.SetBasePath(Directory.GetCurrentDirectory())

}
}
``````

### Quickest way to clear all sheet contents VBA

You can use the .Clear method:

``````Sheets("Zeros").UsedRange.Clear
``````

Using this you can remove the contents and the formatting of a cell or range without affecting the rest of the worksheet.

### How to change icon on Google map marker

we can change the icon of markers, i did it on right click event. Lets see if it works for you...

``````// Create a Marker
position: location,
map: map,
title:'Sample Tool Tip'
});

// Set Icon on any event
marker.setIcon('blank.png'); // set image path here...
});
``````

### Python: convert string from UTF-8 to Latin-1

Instead of `.encode('utf-8')`, use `.encode('latin-1')`.

### How to match "anything up until this sequence of characters" in a regular expression?

I believe you need subexpressions. If I remember right you can use the normal `()` brackets for subexpressions.

This part is From grep manual:

`````` Back References and Subexpressions
The back-reference \n, where n is a single digit, matches the substring
previously matched  by  the  nth  parenthesized  subexpression  of  the
regular expression.
``````

Do something like `^[^(abc)]` should do the trick.

### RestSharp JSON Parameter Posting

Here is complete console working application code. Please install RestSharp package.

``````using RestSharp;
using System;

namespace RESTSharpClient
{
class Program
{
static void Main(string[] args)
{
string url = "https://abc.example.com/";
string jsonString = "{" +
"\"auth\": {" +
"\"type\" : \"basic\"," +
"}," +
"\"requestId\" : 15," +
"\"method\": {" +
"\"name\": \"getProperties\"," +
"\"params\": {" +
"\"showAllStatus\" : \"0\"" +
"}" +
"}" +
"}";

IRestClient client = new RestClient(url);
IRestRequest request = new RestRequest("api/properties", Method.POST, DataFormat.Json);

var response = client.Execute(request);
Console.WriteLine(response.Content);
//TODO: do what you want to do with response.
}
}
}
``````

### Get records of current month

This query should work for you:

``````SELECT *
FROM table
WHERE MONTH(columnName) = MONTH(CURRENT_DATE())
AND YEAR(columnName) = YEAR(CURRENT_DATE())
``````

### C++: Print out enum value as text

This solution doesn't require you to use any data structures or make a different file.

Basically, you define all your enum values in a #define, then use them in the operator <<. Very similar to @jxh's answer.

ideone link for final iteration: http://ideone.com/hQTKQp

Full code:

``````#include <iostream>

#define ERROR_VALUES ERROR_VALUE(NO_ERROR)\
ERROR_VALUE(FILE_NOT_FOUND)\
ERROR_VALUE(LABEL_UNINITIALISED)

enum class Error
{
#define ERROR_VALUE(NAME) NAME,
ERROR_VALUES
#undef ERROR_VALUE
};

inline std::ostream& operator<<(std::ostream& os, Error err)
{
int errVal = static_cast<int>(err);
switch (err)
{
#define ERROR_VALUE(NAME) case Error::NAME: return os << "[" << errVal << "]" #NAME;
ERROR_VALUES
#undef ERROR_VALUE
default:
// If the error value isn't found (shouldn't happen)
return os << errVal;
}
}

int main() {
std::cout << "Error: " << Error::NO_ERROR << std::endl;
std::cout << "Error: " << Error::FILE_NOT_FOUND << std::endl;
std::cout << "Error: " << Error::LABEL_UNINITIALISED << std::endl;
return 0;
}
``````

Output:

``````Error: [0]NO_ERROR
Error: [1]FILE_NOT_FOUND
Error: [2]LABEL_UNINITIALISED
``````

A nice thing about doing it this way is that you can also specify your own custom messages for each error if you think you need them:

``````#include <iostream>

#define ERROR_VALUES ERROR_VALUE(NO_ERROR, "Everything is fine")\
ERROR_VALUE(LABEL_UNINITIALISED, "A component tried to the label before it was initialised")

enum class Error
{
#define ERROR_VALUE(NAME,DESCR) NAME,
ERROR_VALUES
#undef ERROR_VALUE
};

inline std::ostream& operator<<(std::ostream& os, Error err)
{
int errVal = static_cast<int>(err);
switch (err)
{
#define ERROR_VALUE(NAME,DESCR) case Error::NAME: return os << "[" << errVal << "]" #NAME <<"; " << DESCR;
ERROR_VALUES
#undef ERROR_VALUE
default:
return os << errVal;
}
}

int main() {
std::cout << "Error: " << Error::NO_ERROR << std::endl;
std::cout << "Error: " << Error::FILE_NOT_FOUND << std::endl;
std::cout << "Error: " << Error::LABEL_UNINITIALISED << std::endl;
return 0;
}
``````

Output:

``````Error: [0]NO_ERROR; Everything is fine
Error: [2]LABEL_UNINITIALISED; A component tried to the label before it was initialised
``````

If you like making your error codes/descriptions very descriptive, you might not want them in production builds. Turning them off so only the value is printed is easy:

``````inline std::ostream& operator<<(std::ostream& os, Error err)
{
int errVal = static_cast<int>(err);
switch (err)
{
#ifndef PRODUCTION_BUILD // Don't print out names in production builds
#define ERROR_VALUE(NAME,DESCR) case Error::NAME: return os << "[" << errVal << "]" #NAME <<"; " << DESCR;
ERROR_VALUES
#undef ERROR_VALUE
#endif
default:
return os << errVal;
}
}
``````

Output:

``````Error: 0
Error: 1
Error: 2
``````

If this is the case, finding error number 525 would be a PITA. We can manually specify the numbers in the initial enum like this:

``````#define ERROR_VALUES ERROR_VALUE(NO_ERROR, 0, "Everything is fine")\
ERROR_VALUE(LABEL_UNINITIALISED, 2, "A component tried to the label before it was initialised")\
ERROR_VALUE(UKNOWN_ERROR, -1, "Uh oh")

enum class Error
{
#define ERROR_VALUE(NAME,VALUE,DESCR) NAME=VALUE,
ERROR_VALUES
#undef ERROR_VALUE
};

inline std::ostream& operator<<(std::ostream& os, Error err)
{
int errVal = static_cast<int>(err);
switch (err)
{
#ifndef PRODUCTION_BUILD // Don't print out names in production builds
#define ERROR_VALUE(NAME,VALUE,DESCR) case Error::NAME: return os << "[" #VALUE  "]" #NAME <<"; " << DESCR;
ERROR_VALUES
#undef ERROR_VALUE
#endif
default:
return os <<errVal;
}
}
ERROR_VALUES
#undef ERROR_VALUE
#endif
default:
{
// If the error value isn't found (shouldn't happen)
return os << static_cast<int>(err);
break;
}
}
}
``````

Output:

``````Error: [0]NO_ERROR; Everything is fine
Error: [2]LABEL_UNINITIALISED; A component tried to the label before it was initialised
Error: [-1]UKNOWN_ERROR; Uh oh
``````

### ActionBar text color

If you need to set the color programmatically this is the way to do it:

``````static void setActionBarTextColor(Activity activity, int color)
{
ActionBar actionBar = activity instanceof AppCompatActivity
? ((AppCompatActivity) activity).getSupportActionBar()
: activity.getActionBar();
String title = activity.getTitle(); // or any title you want
SpannableString ss = new SpannableString(title);
ss.setSpan(new ForegroundColorSpan(color), 0, title.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
actionBar.setTitle(ss);
}
``````

### Add regression line equation and R^2 on graph

Using ggpubr:

``````library(ggpubr)

# reproducible data
set.seed(1)
df <- data.frame(x = c(1:100))
df\$y <- 2 + 3 * df\$x + rnorm(100, sd = 40)

# By default showing Pearson R
ggscatter(df, x = "x", y = "y", add = "reg.line") +
stat_cor(label.y = 300) +
stat_regline_equation(label.y = 280)
``````

``````# Use R2 instead of R
ggscatter(df, x = "x", y = "y", add = "reg.line") +
stat_cor(label.y = 300,
aes(label = paste(..rr.label.., ..p.label.., sep = "~`,`~"))) +
stat_regline_equation(label.y = 280)

## compare R2 with accepted answer
# m <- lm(y ~ x, df)
# round(summary(m)\$r.squared, 2)
# [1] 0.85
``````

### dynamically set iframe src

try this code. then 'formId' div can set the image.

``````\$('#formId').append('<iframe style="width: 100%;height: 500px" src="/document_path/name.jpg"' +
'title="description"> </iframe> ');
``````

### AVD Manager - Cannot Create Android Virtual Device

I actually hit on this problem a week ago. The issue had to do with not using an updated Eclipse version of the Android SDK plugin with the latest version of the SDK. It was a fun problem overall, but it disappeared as soon as I updated it.

I had even updated the AVD images and no luck. Apparently the old plugin cannot see the new image layout or something. This is for version 22.3 of the SDK.

### Find the maximum value in a list of tuples in Python

Use `max()`:

Using `itemgetter()`:

``````In [53]: lis=[(101, 153), (255, 827), (361, 961)]

In [81]: from operator import itemgetter

In [82]: max(lis,key=itemgetter(1))[0]    #faster solution
Out[82]: 361
``````

using `lambda`:

``````In [54]: max(lis,key=lambda item:item[1])
Out[54]: (361, 961)

In [55]: max(lis,key=lambda item:item[1])[0]
Out[55]: 361
``````

`timeit` comparison:

``````In [30]: %timeit max(lis,key=itemgetter(1))
1000 loops, best of 3: 232 us per loop

In [31]: %timeit max(lis,key=lambda item:item[1])
1000 loops, best of 3: 556 us per loop
``````

### Rails 4 LIKE query - ActiveRecord adds quotes

While string interpolation will work, as your question specifies rails 4, you could be using Arel for this and keeping your app database agnostic.

``````def self.search(query, page=1)
query = "%#{query}%"
name_match = arel_table[:name].matches(query)
postal_match = arel_table[:postal_code].matches(query)
where(name_match.or(postal_match)).page(page).per_page(5)
end
``````

### jQuery \$(".class").click(); - multiple elements, click event once

when you click div with addproduct class one event is fired for that particular element, not five. you're doing something wrong in you code if event is fired 5 times.

### How to create an empty matrix in R?

I'd be cautious as dismissing something as a bad idea because it is slow. If it is a part of the code that does not take much time to execute then the slowness is irrelevant. I just used the following code:

``````for (ic in 1:(dim(centroid)[2]))
{
cluster[[ic]]=matrix(,nrow=2,ncol=0)
}
# code to identify cluster=pindex[ip] to which to add the point
if(pdist[ip]>-1)
{
cluster[[pindex[ip]]]=cbind(cluster[[pindex[ip]]],points[,ip])
}
``````

for a problem that ran in less than 1 second.

### Why is JsonRequestBehavior needed?

To make it easier for yourself you could also create an actionfilterattribute

``````public class AllowJsonGetAttribute : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
var jsonResult = filterContext.Result as JsonResult;

if (jsonResult == null)
throw new ArgumentException("Action does not return a JsonResult,
attribute AllowJsonGet is not allowed");

jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

base.OnResultExecuting(filterContext);
}
}
``````

and use it on your action

``````[AllowJsonGet]
public JsonResult MyAjaxAction()
{
return Json("this is my test");
}
``````

### ViewPager PagerAdapter not updating the View

I found very interesting decision of this problem. Instead of using FragmentPagerAdapter, which keep in memory all fragments, we can use FragmentStatePagerAdapter (android.support.v4.app.FragmentStatePagerAdapter), that reload fragment each time, when we select it.

### Mergesort with Python

``````    def merge(a,low,mid,high):
l=a[low:mid+1]
r=a[mid+1:high+1]
#print(l,r)
k=0;i=0;j=0;
c=[0 for i in range(low,high+1)]
while(i<len(l) and j<len(r)):
if(l[i]<=r[j]):

c[k]=(l[i])
k+=1

i+=1
else:
c[k]=(r[j])
j+=1
k+=1
while(i<len(l)):
c[k]=(l[i])
k+=1
i+=1

while(j<len(r)):
c[k]=(r[j])
k+=1
j+=1
#print(c)
a[low:high+1]=c

def mergesort(a,low,high):
if(high>low):
mid=(low+high)//2

mergesort(a,low,mid)
mergesort(a,mid+1,high)
merge(a,low,mid,high)

a=[12,8,3,2,9,0]
mergesort(a,0,len(a)-1)
print(a)
``````

### Initialize a Map containing arrays

Per Mozilla's Map documentation, you can initialize as follows:

``````private _gridOptions:Map<string, Array<string>> =
new Map([
["1", ["test"]],
["2", ["test2"]]
]);
``````

### Error: Uncaught SyntaxError: Unexpected token <

It usually works when you change the directory name, where the file is. It worked for me when I moved it from "js/" to "../js"

### How to split() a delimited string to a List<String>

Either use:

``````List<string> list = new List<string>(array);
``````

or from LINQ:

``````List<string> list = array.ToList();
``````

Or change your code to not rely on the specific implementation:

``````IList<string> list = array; // string[] implements IList<string>
``````

### Is there a job scheduler library for node.js?

This won't be suitable for everyone, but if your application is already setup to take commands via a socket, you can use netcat to issue a commands via cron proper.

``````echo 'mycommand' | nc -U /tmp/myapp.sock
``````

### Configuring angularjs with eclipse IDE

Since these previous answers above, there is now a release of an Eclipse Plugin to assist with development using AngularJS:

https://marketplace.eclipse.org/content/angularjs-eclipse https://github.com/angelozerr/angularjs-eclipse/wiki/Installation---Update-Site (take a look around the other Wiki pages for information on features)

The release at the time of the answer is 0.1.0.

Please also checkout JSDT (http://www.eclipse.org/webtools/jsdt/) and also Eclipse VJET (http://eclipse.org/vjet/). The VJET project appears to be an attempt to provide better feature sets to the editor without being encumbered by the JSDT project (open source politics at play I guess).

### With CSS, use "..." for overflowed block of multi-lines

Great question... I wish there was an answer, but this is the closest you can get with CSS these days. No ellipsis, but still pretty usable.

``````overflow: hidden;
line-height: 1.2em;
height: 3.6em;      // 3 lines * line-height
``````

### How to specify the JDK version in android studio?

In Android Studio 4.0.1, Help -> About shows the details of the Java version used by the studio, in my case:

``````Android Studio 4.0.1
Build #AI-193.6911.18.40.6626763, built on June 25, 2020
Runtime version: 1.8.0_242-release-1644-b01 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 10 10.0
GC: ParNew, ConcurrentMarkSweep
Memory: 1237M
Cores: 8
Registry: ide.new.welcome.screen.force=true
``````

### Where is the Docker daemon log?

The below solution worked for me in Ubuntu 20.04

Logs stored in: `/var/lib/docker/containers/<container id>/<container id>-json.log`

To know container Id: `\$ docker ps`

### How do I run a batch script from within a batch script?

You can use

``````call script.bat
``````

or just

``````script.bat
``````

### Strip all non-numeric characters from string in JavaScript

Use the string's `.replace` method with a regex of `\D`, which is a shorthand character class that matches all non-digits:

``````myString = myString.replace(/\D/g,'');
``````

### ImportError: No module named 'Tkinter'

On CentOS7, to get this working with Python2, I had to do:

``````yum -y install tkinter
``````

Noting this here because I thought that there would be a pip package, but instead, one needs to actually install an rpm.

### How can I see which Git branches are tracking which remote / upstream branch?

Very much a porcelain command, not good if you want this for scripting:

``````git branch -vv   # doubly verbose!
``````

Note that with git 1.8.3, that upstream branch is displayed in blue (see "What is this branch tracking (if anything) in git?")

If you want clean output, see arcresu's answer - it uses a porcelain command that I don't believe existed at the time I originally wrote this answer, so it's a bit more concise and works with branches configured for rebase, not just merge.

### Java: Get first item from a collection

It sounds like your Collection wants to be List-like, so I'd suggest:

``````List<String> myList = new ArrayList<String>();
...
String first = myList.get(0);
``````

### Access denied; you need (at least one of) the SUPER privilege(s) for this operation

When we create a new RDS DB instance, the default master user is not the root user. But only gets certain privileges for that DB instance. This permission does not include SET permission. Now if your default master user tries to execute mysql SET commands, then you will face this error: Access denied; you need (at least one of) the SUPER or SYSTEM_VARIABLES_ADMIN privilege(s) for this operation

#### Solution 1

Comment out or remove these lines

``````SET @MYSQLDUMP_TEMP_LOG_BIN = @@SESSION.SQL_LOG_BIN;
SET @@SESSION.SQL_LOG_BIN= 1;
SET @@GLOBAL.GTID_PURGED=/*!80000 '+'*/ '';
``````

#### Solution 2

You can also ignore the errors by using the -f option to load the rest of the dump file.

``````mysql -f <REPLACE_DB_NAME> -u <REPLACE_DB_USER> -h <DB_HOST_HERE> -p < dumpfile.sql
``````

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

There is an `.orElseRun` method, but it is called `.orElseGet`.

The main problem with your pseudocode is that `.isPresent` doesn't return an `Optional<>`. But `.map` returns an `Optional<>` which has the `orElseRun` method.

If you really want to do this in one statement this is possible:

``````public Optional<Obj> getObjectFromDB() {
return dao.find()
.map( obj -> {
obj.setAvailable(true);
return Optional.of(obj);
})
.orElseGet( () -> {
logger.fatal("Object not available");
return Optional.empty();
});
}
``````

But this is even clunkier than what you had before.

### Getting String Value from Json Object Android

Include `org.json.jsonobject` in your project.

You can then do this:

``````JSONObject jresponse = new JSONObject(responseString);
responseString = jresponse.getString("NeededString");
``````

Assuming, `responseString` holds the response you receive.

If you need to know how to convert the received response to a String, here's how to do it:

``````ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
String responseString = out.toString();
``````

### Multiple WHERE Clauses with LINQ extension methods

you can use && and write all conditions in to the same where clause, or you can .Where().Where().Where()... and so on.

### .NET data structures: ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary -- Speed, memory, and when to use each?

Off the top of my head:

• `Array`* - represents an old-school memory array - kind of like a alias for a normal `type[]` array. Can enumerate. Can't grow automatically. I would assume very fast insert and retrival speed.

• `ArrayList` - automatically growing array. Adds more overhead. Can enum., probably slower than a normal array but still pretty fast. These are used a lot in .NET

• `List` - one of my favs - can be used with generics, so you can have a strongly typed array, e.g. `List<string>`. Other than that, acts very much like `ArrayList`

• `Hashtable` - plain old hashtable. O(1) to O(n) worst case. Can enumerate the value and keys properties, and do key/val pairs

• `Dictionary` - same as above only strongly typed via generics, such as `Dictionary<string, string>`

• `SortedList` - a sorted generic list. Slowed on insertion since it has to figure out where to put things. Can enum., probably the same on retrieval since it doesn't have to resort, but deletion will be slower than a plain old list.

I tend to use `List` and `Dictionary` all the time - once you start using them strongly typed with generics, its really hard to go back to the standard non-generic ones.

There are lots of other data structures too - there's `KeyValuePair` which you can use to do some interesting things, there's a `SortedDictionary` which can be useful as well.

### How to get screen dimensions as pixels in Android

I would wrap the getSize code like this:

``````@SuppressLint("NewApi")
public static Point getScreenSize(Activity a) {
Point size = new Point();
Display d = a.getWindowManager().getDefaultDisplay();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
d.getSize(size);
} else {
size.x = d.getWidth();
size.y = d.getHeight();
}
return size;
}
``````

### embedding image in html email

I don't find any of the answers here useful, so I am providing my solution.

1. The problem is that you are using `multipart/related` as the content type which is not good in this case. I am using `multipart/mixed` and inside it `multipart/alternative` (it works on most clients).

2. The message structure should be as follows:

``````[Headers]
Content-type:multipart/mixed; boundary="boundary1"
--boundary1
Content-type:multipart/alternative; boundary="boundary2"
--boundary2
Content-Type: text/html; charset=ISO-8859-15
Content-Transfer-Encoding: 7bit
[HTML code with a href="cid:..."]

--boundary2
Content-Type: image/png;
name="moz-screenshot.png"
Content-Transfer-Encoding: base64
Content-ID: <part1.06090408.01060107>
Content-Disposition: inline; filename="moz-screenshot.png"
[base64 image data here]

--boundary2--
--boundary1--
``````

Then it will work

### Spring Boot - Cannot determine embedded database driver class for database type NONE

I don't if it is too late to answer. I could solve this issue by excluding DataSourceAutoConfiguration from spring boot.

### How to check if a variable exists in a FreeMarker template?

I think a lot of people are wanting to be able to check to see if their variable is not empty as well as if it exists. I think that checking for existence and emptiness is a good idea in a lot of cases, and makes your template more robust and less prone to silly errors. In other words, if you check to make sure your variable is not null AND not empty before using it, then your template becomes more flexible, because you can throw either a null variable or an empty string into it, and it will work the same in either case.

``````<#if p?? && p?has_content>1</#if>
``````

Let's say you want to make sure that `p` is more than just whitespace. Then you could trim it before checking to see if it `has_content`.

``````<#if p?? && p?trim?has_content>1</#if>
``````

UPDATE

Please ignore my suggestion -- `has_content` is all that is needed, as it does a null check along with the empty check. Doing `p?? && p?has_content` is equivalent to `p?has_content`, so you may as well just use `has_content`.

### What are the main differences between JWT and OAuth authentication?

JWT is an open standard that defines a compact and self-contained way for securely transmitting information between parties. It is an authentication protocol where we allow encoded claims (tokens) to be transferred between two parties (client and server) and the token is issued upon the identification of a client. With each subsequent request we send the token.

Whereas OAuth2 is an authorization framework, where it has a general procedures and setups defined by the framework. JWT can be used as a mechanism inside OAuth2.

You can read more on this here

OAuth or JWT? Which one to use and why?

### Emulator: ERROR: x86 emulation currently requires hardware acceleration

I had the same issue even when hardware acceleration installed. My solutions was uninstalling and reinstalling it using SDK Manager. Make sure you restart the Android studio after then.

### ALTER TABLE on dependent column

you can drop the Constraint which is restricting you. If the column has access to other table. suppose a view is accessing the column which you are altering then it wont let you alter the column unless you drop the view. and after making changes you can recreate the view.

This is what I normally use when I need to pad a value.

``````SET @PaddedValue = REPLICATE('0', @Length - LEN(@OrigValue)) + CAST(@OrigValue as VARCHAR)
``````

### Go to "next" iteration in JavaScript forEach loop

just return true inside your if statement

``````var myArr = [1,2,3,4];

myArr.forEach(function(elem){
if (elem === 3) {

return true;

// Go to "next" iteration. Or "continue" to next iteration...
}

console.log(elem);
});
``````

### Cannot redeclare function php

Remove the function and check the output of:

``````var_dump(function_exists('parseDate'));
``````

In which case, change the name of the function.

If you get false, you're including the file with that function twice, replace :

``````include
``````

by

``````include_once
``````

And replace :

``````require
``````

by

``````require_once
``````

EDIT : I'm just a little too late, post before beat me to it !

### Check if a number has a decimal place/is a whole number

convert number string to array, split by decimal point. Then, if the array has only one value, that means no decimal in string.

``````if(!number.split(".")[1]){
//do stuff
}
``````

This way you can also know what the integer and decimal actually are. a more advanced example would be.

``````number_to_array = string.split(".");
inte = number_to_array[0];
dece = number_to_array[1];

if(!dece){
//do stuff
}
``````

### Compare cell contents against string in Excel

If a case-insensitive comparison is acceptable, just use `=`:

``````=IF(A1="ENG",1,0)
``````

### Display back button on action bar

my working code to go back screen.

``````@Override

switch (item.getItemId()) {

case android.R.id.home:

Toast.makeText(getApplicationContext(), "Home Clicked",
Toast.LENGTH_LONG).show();

// go to previous activity
onBackPressed();

return true;

}

return super.onOptionsItemSelected(item);
}
``````

### How to change proxy settings in Android (especially in Chrome)

Found one solution for WIFI (works for Android 4.3, 4.4):

1. Connect to WIFI network (e.g. 'Alex')
2. Settings->WIFI
3. Long tap on connected network's name (e.g. on 'Alex')
4. Modify network config-> Show advanced options
5. Set proxy settings

### How to convert a list of numbers to jsonarray in Python

Use the `json` module to produce JSON output:

``````import json

with open(outputfilename, 'wb') as outfile:
json.dump(row, outfile)
``````

This writes the JSON result directly to the file (replacing any previous content if the file already existed).

If you need the JSON result string in Python itself, use `json.dumps()` (added `s`, for 'string'):

``````json_string = json.dumps(row)
``````

The `L` is just Python syntax for a long integer value; the `json` library knows how to handle those values, no `L` will be written.

Demo string output:

``````>>> import json
>>> row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]
>>> json.dumps(row)
'[1, [0.1, 0.2], [[1234, 1], [134, 2]]]'
``````

### How to create a POJO?

When you aren't doing anything to make your class particularly designed to work with a given framework, ORM, or other system that needs a special sort of class, you have a Plain Old Java Object, or POJO.

Ironically, one of the reasons for coining the term is that people were avoiding them in cases where they were sensible and some people concluded that this was because they didn't have a fancy name. Ironic, because your question demonstrates that the approach worked.

Compare the older POD "Plain Old Data" to mean a C++ class that doesn't do anything a C struct couldn't do (more or less, non-virtual members that aren't destructors or trivial constructors don't stop it being considered POD), and the newer (and more directly comparable) POCO "Plain Old CLR Object" in .NET.

### Question mark and colon in JavaScript

``````hsb.s = max != 0 ? 255 * delta / max : 0;
``````

`?` is a ternary operator. It works like an `if` in conjunction with the `:`

`!=` means not equals

So, the long form of this line would be

``````if (max != 0) { //if max is not zero
hsb.s = 255 * delta / max;
} else {
hsb.s = 0;
}
``````

### Android TextView padding between lines

you can look into `android:lineSpacingExtra` and apply it to your XML

or the related method `public void setLineSpacing (float add, float mult)`

### jQuery - Increase the value of a counter when a button is clicked

Go to the below site and tryout. http://www.counter12.com/

From the above link I have selected the one design that I liked to have in my site accepted terms and it has given me a div that I have pasted in my html page.

It did awesomely worked.

I am not answering to your problem on JQuery, but giving you an alternate solution for your problem.

### Android studio Gradle icon error, Manifest Merger

Within the AndroidManifest.xml file, add the following to the `application` node:

``````tools:replace="android:appComponentFactory,android:icon,android:theme,android:label,android:name"
``````

### Passing arguments to AsyncTask, and returning results

I sort of agree with leander on this one.

call:

``````new calc_stanica().execute(stringList.toArray(new String[stringList.size()]));
``````

``````public class calc_stanica extends AsyncTask<String, Void, ArrayList<String>> {
@Override
protected ArrayList<String> doInBackground(String... args) {
...
}

@Override
protected void onPostExecute(ArrayList<String> result) {
... //do something with the result list here
}
}
``````

Or you could just make the result list a class parameter and replace the ArrayList with a boolean (success/failure);

``````public class calc_stanica extends AsyncTask<String, Void, Boolean> {
private List<String> resultList;

@Override
protected boolean doInBackground(String... args) {
...
}

@Override
protected void onPostExecute(boolean success) {
... //if successfull, do something with the result list here
}
}
``````

### Simple way to create matrix of random numbers

A simple way of creating an array of random integers is:

``````matrix = np.random.randint(maxVal, size=(rows, columns))
``````

The following outputs a 2 by 3 matrix of random integers from 0 to 10:

``````a = np.random.randint(10, size=(2,3))
``````

### Convert comma separated string to array in PL/SQL

Using a pipelined table function:

``````SQL> CREATE OR REPLACE TYPE test_type
2  AS
3    TABLE OF VARCHAR2(100)
4  /

Type created.

SQL> CREATE OR REPLACE FUNCTION comma_to_table(
2      p_list IN VARCHAR2)
3    RETURN test_type PIPELINED
4  AS
5    l_string LONG := p_list || ',';
6    l_comma_index PLS_INTEGER;
7    l_index PLS_INTEGER := 1;
8  BEGIN
9    LOOP
10      l_comma_index := INSTR(l_string, ',', l_index);
11      EXIT
12    WHEN l_comma_index = 0;
13      PIPE ROW ( TRIM(SUBSTR(l_string, l_index, l_comma_index - l_index)));
14      l_index := l_comma_index                                + 1;
15    END LOOP;
16  RETURN;
17  END comma_to_table;
18  /

Function created.
``````

Let's see the output:

``````SQL> SELECT *
2  FROM TABLE(comma_to_table('12 3,456,,,,,abc,def'))
3  /

COLUMN_VALUE
------------------------------------------------------------------------------
12 3
456

abc
def

8 rows selected.

SQL>
``````

### What's the use of session.flush() in Hibernate

As rightly said in above answers, by calling `flush()` we force hibernate to execute the SQL commands on Database. But do understand that changes are not "committed" yet. So after doing flush and before doing commit, if you access DB directly (say from SQL prompt) and check the modified rows, you will NOT see the changes.

This is same as opening 2 SQL command sessions. And changes done in 1 session are not visible to others until committed.

### Detect & Record Audio in Python

You might want to look at csounds, also. It has several API's, including Python. It might be able to interact with an A-D interface and gather sound samples.

### Jquery split function

Try this. It uses the `split` function which is a core part of javascript, nothing to do with jQuery.

``````var parts = html.split(":-"),
i, l
;
for (i = 0, l = parts.length; i < l; i += 2) {
\$("#" + parts[i]).text(parts[i + 1]);
}
``````

We don't recommend that you use the FtpWebRequest class for new development. For more information and alternatives to FtpWebRequest, see WebRequest shouldn't be used on GitHub.

The GitHub link directs to this SO page which contains a list of third-party FTP libraries, such as FluentFTP.

### Uncaught TypeError: Cannot read property 'value' of null

If in your HTML you have an input element with a name or id with a _ like e.g. first_name or more than one _ like e.g. student_first_name and you also have the Javascript code at the bottom of your Web Page and you are sure you are doing everything else right, then those dashes could be what is messing you up.

Having id or name for your input elements resembling the below

``````<input type="text" id="first_name" name="first_name">
``````

or

``````<input type="text" id="student_first_name" name="student_first_name">
``````

Then you try make a call like this below in your JavaScript code

``````var first_name = document.getElementById("first_name").value;
``````

or

``````var student_first_name = document.getElementById("student_first_name").value;
``````

You are certainly going to have an error like Uncaught TypeError: Cannot read property 'value' of null in Google Chrome and on Internet Explorer too. I did not get to test that with Firefox.

In my case I removed the dashes, in first_name and renamed it to firstname and from student_first_name to studentfirstname

At the end, I was able to resolve that error with my code now looking as follows for HTML and JavaScript.

HTML

``````<input type="text" id="firstname" name="firstname">
``````

or

``````<input type="text" id="studentfirstname" name="studentfirstname">
``````

Javascript

``````var firstname = document.getElementById("firstname").value;
``````

or

``````var studentfirstname = document.getElementById("studentfirstname").value;
``````

So if it is within your means to rename the HTML and JavaScript code with those dashes, it may help if that is what is ailing your piece of code. In my case that was what was bugging me.

Hope this helps someone stop pulling their hair like I was.

### Python: Assign print output to a variable

This is a standalone example showing how to save the output of a user-written function in Python 3:

``````from io import StringIO
import sys

def print_audio_tagging_result(value):
print(f"value = {value}")

tag_list = []
for i in range(0,1):
save_stdout = sys.stdout
result = StringIO()
sys.stdout = result
print_audio_tagging_result(i)
sys.stdout = save_stdout
tag_list.append(result.getvalue())
print(tag_list)
``````

### Integrate ZXing in Android Studio

From version 4.x, only Android SDK 24+ is supported by default, and androidx is required.

``````repositories {
jcenter()
}

dependencies {
implementation 'com.journeyapps:zxing-android-embedded:4.1.0'
implementation 'androidx.appcompat:appcompat:1.0.2'
}

android {
buildToolsVersion '28.0.3' // Older versions may give compile errors
}
``````

Older SDK versions

For Android SDK versions < 24, you can downgrade zxing:core to 3.3.0 or earlier for Android 14+ support:

``````repositories {
jcenter()
}

dependencies {
implementation('com.journeyapps:zxing-android-embedded:4.1.0') { transitive = false }
implementation 'androidx.appcompat:appcompat:1.0.2'
}

android {
buildToolsVersion '28.0.3'
}
``````

You'll also need this in your Android manifest:

``````<uses-sdk tools:overrideLibrary="com.google.zxing.client.android" />
``````

### Maximum number of threads in a .NET app?

You should be using the thread pool (or async delgates, which in turn use the thread pool) so that the system can decide how many threads should run.

### Abort Ajax requests using jQuery

Most of the jQuery Ajax methods return an XMLHttpRequest (or the equivalent) object, so you can just use `abort()`.

See the documentation:

• abort Method (MSDN). Cancels the current HTTP request.
• abort() (MDN). If the request has been sent already, this method will abort the request.
``````var xhr = \$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});

//kill the request
xhr.abort()
``````

UPDATE: As of jQuery 1.5 the returned object is a wrapper for the native XMLHttpRequest object called jqXHR. This object appears to expose all of the native properties and methods so the above example still works. See The jqXHR Object (jQuery API documentation).

UPDATE 2: As of jQuery 3, the ajax method now returns a promise with extra methods (like abort), so the above code still works, though the object being returned is not an `xhr` any more. See the 3.0 blog here.

UPDATE 3: `xhr.abort()` still works on jQuery 3.x. Don't assume the update 2 is correct. More info on jQuery Github repository.

### How to get \$(this) selected option in jQuery?

Best guess:

``````var cur_value = \$('#select-id').children('option:selected').text();
``````

I like children better in this case because you know you're only going one branch down the DOM tree...

### "/usr/bin/ld: cannot find -lz"

Try one of those three solution. It must work :) :

1. sudo apt-get install zlib1g-dev
2. sudo apt-get install libz-dev
3. sudo apt-get install lib32z1-dev

In fact what is missing is not the `lz` command, but the development files for the `zlib` library.So you should install `zlib1g-dev`lib for ex to get it.

For rhel7 like systems the package is `zlib-devel`

### Add Bean Programmatically to Spring Web App Context

Actually `AnnotationConfigApplicationContext` derived from `AbstractApplicationContext`, which has empty `postProcessBeanFactory` method left for override

``````/**
* Modify the application context's internal bean factory after its standard
* initialization. All bean definitions will have been loaded, but no beans
* will have been instantiated yet. This allows for registering special
* BeanPostProcessors etc in certain ApplicationContext implementations.
* @param beanFactory the bean factory used by the application context
*/
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
}
``````

To leverage this, Create `AnnotationConfigApplicationContextProvider` class which may look like following(given for `Vertx` instance example, you can use `MyClass` instead)...

``````public class CustomAnnotationApplicationContextProvider {
private final Vertx vertx;

public CustomAnnotationApplicationContextProvider(Vertx vertx) {
this.vertx = vertx;
}

/**
* Register all beans to spring bean factory
*
* @param beanFactory, spring bean factory to register your instances
*/
private void configureBeans(ConfigurableListableBeanFactory beanFactory) {
beanFactory.registerSingleton("vertx", vertx);
}

/**
* Proxy method to create {@link AnnotationConfigApplicationContext} instance with no params
*
*/
public AnnotationConfigApplicationContext get() {
return new AnnotationConfigApplicationContext() {

@Override
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
super.postProcessBeanFactory(beanFactory);
configureBeans(beanFactory);
}
};
}

/**
* Proxy method to call {@link AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(DefaultListableBeanFactory)} with our logic
*
* @param beanFactory bean factory for spring
* @return
* @see AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(DefaultListableBeanFactory)
*/
public AnnotationConfigApplicationContext get(DefaultListableBeanFactory beanFactory) {
return new AnnotationConfigApplicationContext(beanFactory) {

@Override
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
super.postProcessBeanFactory(beanFactory);
configureBeans(beanFactory);
}
};
}

/**
* Proxy method to call {@link AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(Class[])} with our logic
*
* @param annotatedClasses, set of annotated classes for spring
* @return
* @see AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(Class[])
*/
public AnnotationConfigApplicationContext get(Class<?>... annotatedClasses) {
return new AnnotationConfigApplicationContext(annotatedClasses) {

@Override
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
super.postProcessBeanFactory(beanFactory);
configureBeans(beanFactory);
}
};
}

/**
* proxy method to call {@link AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(String...)} with our logic
*
* @param basePackages set of base packages for spring
* @return
* @see AnnotationConfigApplicationContext#AnnotationConfigApplicationContext(String...)
*/
public AnnotationConfigApplicationContext get(String... basePackages) {
return new AnnotationConfigApplicationContext(basePackages) {

@Override
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
super.postProcessBeanFactory(beanFactory);
configureBeans(beanFactory);
}
};
}
}
``````

While creating `ApplicationContext` you can create it using

``````Vertx vertx = ...; // either create or for vertx, it'll be passed to main verticle
ApplicationContext context = new CustomAnnotationApplicationContextProvider(vertx).get(ApplicationSpringConfig.class);
``````

### Submit form with Enter key without submit button?

@JayGuilford's answer is a good one, but if you don't want a JS dependency, you could use a submit element and simply hide it using `display: none;`.

### How to keep indent for second line in ordered lists via CSS?

my solution is quite the same as Pumbaa80's one, but I suggest to use `display: table` instead of `display:table-row` for `li` element. So it will be something like this:

``````ol {
counter-reset: foo; /* default display:list-item */
}

ol > li {
counter-increment: foo;
display: table; /* instead of table-row */
}

ol > li::before {
content: counter(foo) ".";
display: table-cell;
text-align: right;
}
``````

So now we can use margins for spacing between `li`'s

### Redirect stderr to stdout in C shell

``````   xxx >& filename
``````

Or do this to see everything on the screen and have it go to your file:

``````  xxx | & tee ./logfile
``````

### Is there an online application that automatically draws tree structures for phrases/sentences?

In short, yes. I assume you're looking to parse English: for that you can use the Link Parser from Carnegie Mellon.

It is important to remember that there are many theories of syntax, that can give completely different-looking phrase structure trees; further, the trees are different for each language, and tools may not exist for those languages.

As a note for the future: if you need a sentence parsed out and tag it as `linguistics` (and `syntax` or whatnot, if that's available), someone can probably parse it out for you and guide you through it.

### How to get item count from DynamoDB?

With the aws dynamodb cli you can get it via scan as follows:

``````aws dynamodb scan --table-name <TABLE_NAME> --select "COUNT"
``````

The response will look similar to this:

``````{
"Count": 123,
"ScannedCount": 123,
"ConsumedCapacity": null
}
``````

notice that this information is in real time in contrast to the describe-table api

### Where is Developer Command Prompt for VS2013?

You can simply go to Menu > All Programs > Visual Studio 2013. Select the folder link "Visual Studio Tools". This will open the folder. There is bunch of shortcuts for command prompt which you can use. They worked perfectly for me.

I think the trick here might be there are different versions for different processors, hence they put them all together.

### background:none vs background:transparent what is the difference?

To complement the other answers: if you want to reset all background properties to their initial value (which includes `background-color: transparent` and `background-image: none`) without explicitly specifying any value such as `transparent` or `none`, you can do so by writing:

``````background: initial;
``````

### Adding devices to team provisioning profile

There are two types of provisioning profiles.

• development and
• distribution

When app is live on app store then distribution profiles works and do not need any devices to be added.

Only development profiles need to add devices.In order to do so these are the steps-

1. Login to developer.apple.com member centre.
2. Go to Certificates, Identifiers & Profiles.
3. Get UDID of your device and add it in the devices.
4. Select a developer provisioning profile and edit it.
5. Click on check box next to the device you just added.
7. Double click on it to install it.
8. Connect your device and retry.

This worked for me hope it works for you.

### How to apply style classes to td classes?

You can use :nth-child(N) CSS selector like :

``````table td:first-child {}  //1
table td:nth-child(2) {} //2
table td:nth-child(3) {} //3
table td:last-child {}   //4
``````

### Retina displays, high-res background images

Here's a solution that also includes High(er)DPI (MDPI) devices > ~160 dots per inch like quite a few non-iOS Devices (f.e.: Google Nexus 7 2012):

``````.box {
background: url( 'img/box-bg.png' ) no-repeat top left;
width: 200px;
height: 200px;
}
@media only screen and ( -webkit-min-device-pixel-ratio: 1.3 ),
only screen and (    min--moz-device-pixel-ratio: 1.3 ),
only screen and (      -o-min-device-pixel-ratio: 2.6/2 ), /* returns 1.3, see Dev.Opera */
only screen and (         min-device-pixel-ratio: 1.3 ),
only screen and ( min-resolution: 124.8dpi ),
only screen and ( min-resolution: 1.3dppx ) {

.box {
background: url( 'img/[email protected]' ) no-repeat top left / 200px 200px;
}

}
``````

As @3rror404 included in his edit after receiving feedback from the comments, there's a world beyond Webkit/iPhone. One thing that bugs me with most solutions around so far like the one referenced as source above at CSS-Tricks, is that this isn't taken fully into account.
The original source went already further.

As an example the Nexus 7 (2012) screen is a TVDPI screen with a weird `device-pixel-ratio` of `1.325`. When loading the images with normal resolution they are upscaled via interpolation and therefore blurry. For me applying this rule in the media query to include those devices succeeded in best customer feedback.

### How do I prevent DIV tag starting a new line?

The `div` tag is a block element, causing that behavior.

You should use a `span` element instead, which is inline.

If you really want to use `div`, add `style="display: inline"`. (You can also put that in a CSS rule)

### sublime text2 python error message /usr/bin/python: can't find '__main__' module in ''

You get that error because you haven't saved your file, save it for example "holamundo.py" then run it Ctrl + B

### How to convert a string to lower or upper case in Ruby

The Rails Active Support gem provides `upcase`, `downcase`, `swapcase`,`capitalize`, etc. methods with internationalization support:

``````gem install activesupport
irb -ractive_support/core_ext/string
"STRING  ÁÂÃÀÇÉÊÍÓÔÕÚ".mb_chars.downcase.to_s
=> "string  áâãàçéêíóôõú"
"string  áâãàçéêíóôõú".mb_chars.upcase.to_s
=> "STRING  ÁÂÃÀÇÉÊÍÓÔÕÚ"
``````

### How to Correctly Check if a Process is running and Stop it

If you don't need to display exact result "running" / "not runnuning", you could simply:

``````ps notepad -ErrorAction SilentlyContinue | kill -PassThru
``````

If the process was not running, you'll get no results. If it was running, you'll receive `get-process` output, and the process will be stopped.

### How to uninstall/upgrade Angular CLI?

use following command if you installed in globally,

`````` npm uninstall -g angular-cli
``````

### What is HTML5 ARIA?

What is ARIA?

ARIA emerged as a way to address the accessibility problem of using a markup language intended for documents, HTML, to build user interfaces (UI). HTML includes a great many features to deal with documents (P, h3,UL,TABLE) but only basic UI elements such as A, INPUT and BUTTON. Windows and other operating systems support APIs that allow (Assistive Technology) AT to access the functionality of UI controls. Internet Explorer and other browsers map the native HTML elements to the accessibility API, but the html controls are not as rich as the controls common on desktop operating systems, and are not enough for modern web applications Custom controls can extend html elements to provide the rich UI needed for modern web applications. Before ARIA, the browser had no way to expose this extra richness to the accessibility API or AT. The classic example of this issue is adding a click handler to an image. It creates what appears to be a clickable button to a mouse user, but is still just an image to a keyboard or AT user.

The solution was to create a set of attributes that allow developers to extend HTML with UI semantics. The ARIA term for a group of HTML elements that have custom functionality and use ARIA attributes to map these functions to accessibility APIs is a “Widget. ARIA also provides a means for authors to document the role of content itself, which in turn, allows AT to construct alternate navigation mechanisms for the content that are much easier to use than reading the full text or only iterating over a list of the links.

It is important to remember that in simple cases, it is much preferred to use native HTML controls and style them rather than using ARIA. That is don’t reinvent wheels, or checkboxes, if you don’t have to.

Fortunately, ARIA markup can be added to existing sites without changing the behavior for mainstream users. This greatly reduces the cost of modifying and testing the website or application.

### boto3 client NoRegionError: You must specify a region error only sometimes

For Python 2 I have found that the boto3 library does not source the region from the `~/.aws/config` if the region is defined in a different profile to default. So you have to define it in the session creation.

``````session = boto3.Session(
profile_name='NotDefault',
region_name='ap-southeast-2'
)

print(session.available_profiles)

client = session.client(
'ec2'
)
``````

Where my `~/.aws/config` file looks like this:

``````[default]
region=ap-southeast-2

[NotDefault]
region=ap-southeast-2
``````

I do this because I use different profiles for different logins to AWS, Personal and Work.

### How to remove time portion of date in C# in DateTime object only?

``````DateTime dd=DateTiem.Now;
string date=dd.toString("dd/MM/YYYY");
``````

### How to set width to 100% in WPF

It is the container of the `Grid` that is imposing on its width. In this case, that's a `ListBoxItem`, which is left-aligned by default. You can set it to stretch as follows:

``````<ListBox>
<!-- other XAML omitted, you just need to add the following bit -->
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalAlignment" Value="Stretch"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
``````

### How do I convert csv file to rdd

You can use the spark-csv library: https://github.com/databricks/spark-csv

This is directly from the documentation:

``````import org.apache.spark.sql.SQLContext

SQLContext sqlContext = new SQLContext(sc);

HashMap<String, String> options = new HashMap<String, String>();
options.put("path", "cars.csv");

``````

### How to wait until WebBrowser is completely loaded in VB.NET?

Salvete! I needed, simply, a function I could call to make the code wait for the page to load before it continued. After scouring the web for answers, and fiddling around for several hours, I came up with this to solve for myself, the exact dilemma you present. I know I am late in the game with an answer, but I wish to post this for anyone else who comes along.

usage: just call `WaitForPageLoad()` just after a call to navigation:

``````whatbrowser.Navigate("http://www.google.com")
``````

another example we don't combine the navigate feature with the page load, because sometimes you need to wait for a load without also navigating, for example, you might need to wait for a page to load that was started with an `invokemember` event:

``````whatbrowser.Document.GetElementById("UserName").InnerText = whatusername
``````

Here is the code: You need both subs plus the accessible variable, `pageready`. First, make sure to fix the variable called `whatbrowser` to be your webbrowser control

Now, somewhere in your module or class, place this:

``````Private Property pageready As Boolean = False

Application.DoEvents()
End While
End Sub

Private Sub PageWaiter(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs)
End If
End Sub

#End Region
``````

### Bootstrap's JavaScript requires jQuery version 1.9.1 or higher

If you are using CMS like Drupal or Wordpress - just install jQuery Update module and error no longer persists.

### SQL - using alias in Group By

Beware of using aliases when grouping the results from a view in SQLite. You will get unexpected results if the alias name is the same as the column name of any underlying tables (to the views.)

### Resize iframe height according to content height in it

Try using `scrolling=no` attribute on the iframe tag. Mozilla also has an `overflow-x` and `overflow-y` CSS property you may look into.

In terms of the height, you could also try `height=100%` on the iframe tag.

### How to compare times in Python?

datetime have comparison capability

``````>>> import datetime
>>> import time
>>> a =  datetime.datetime.now()
>>> time.sleep(2.0)
>>> b =  datetime.datetime.now()
>>> print a < b
True
>>> print a == b
False
``````

### Difference between IsNullOrEmpty and IsNullOrWhiteSpace in C#

In common use, space `" "`, Tab `"\t"` and newline `"\n"` are the difference:

``````string.IsNullOrWhiteSpace("\t"); //true
string.IsNullOrEmpty("\t"); //false

string.IsNullOrWhiteSpace(" "); //true
string.IsNullOrEmpty(" "); //false

string.IsNullOrWhiteSpace("\n"); //true
string.IsNullOrEmpty("\n"); //false
``````

https://dotnetfiddle.net/4hkpKM

There are also a few other white space characters, you probably never used before

https://docs.microsoft.com/en-us/dotnet/api/system.char.iswhitespace

### Multiple conditions in WHILE loop

Your condition is wrong. `myChar != 'n' || myChar != 'N'` will always be true.

Use `myChar != 'n' && myChar != 'N'` instead

### NULL value for int in Update statement

By using `NULL` without any quotes.

``````UPDATE `tablename` SET `fieldName` = NULL;
``````

### how to rename an index in a cluster?

You can use REINDEX to do that.

Reindex does not attempt to set up the destination index. It does not copy the settings of the source index. You should set up the destination index prior to running a _reindex action, including setting up mappings, shard counts, replicas, etc.

1. First copy the index to a new name
``````POST /_reindex
{
"source": {
``````DELETE /twitter