Programs & Examples On #Qthread

QThread is a threading class provided by the cross-platform Qt framework.

Background thread with QThread in PyQt

Take this answer updated for PyQt5, python 3.4

Use this as a pattern to start a worker that does not take data and return data as they are available to the form.

1 - Worker class is made smaller and put in its own file worker.py for easy memorization and independent software reuse.

2 - The main.py file is the file that defines the GUI Form class

3 - The thread object is not subclassed.

4 - Both thread object and the worker object belong to the Form object

5 - Steps of the procedure are within the comments.

# worker.py
from PyQt5.QtCore import QThread, QObject, pyqtSignal, pyqtSlot
import time


class Worker(QObject):
    finished = pyqtSignal()
    intReady = pyqtSignal(int)


    @pyqtSlot()
    def procCounter(self): # A slot takes no params
        for i in range(1, 100):
            time.sleep(1)
            self.intReady.emit(i)

        self.finished.emit()

And the main file is:

  # main.py
  from PyQt5.QtCore import QThread
  from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QGridLayout
  import sys
  import worker


  class Form(QWidget):

    def __init__(self):
       super().__init__()
       self.label = QLabel("0")

       # 1 - create Worker and Thread inside the Form
       self.obj = worker.Worker()  # no parent!
       self.thread = QThread()  # no parent!

       # 2 - Connect Worker`s Signals to Form method slots to post data.
       self.obj.intReady.connect(self.onIntReady)

       # 3 - Move the Worker object to the Thread object
       self.obj.moveToThread(self.thread)

       # 4 - Connect Worker Signals to the Thread slots
       self.obj.finished.connect(self.thread.quit)

       # 5 - Connect Thread started signal to Worker operational slot method
       self.thread.started.connect(self.obj.procCounter)

       # * - Thread finished signal will close the app if you want!
       #self.thread.finished.connect(app.exit)

       # 6 - Start the thread
       self.thread.start()

       # 7 - Start the form
       self.initUI()


    def initUI(self):
        grid = QGridLayout()
        self.setLayout(grid)
        grid.addWidget(self.label,0,0)

        self.move(300, 150)
        self.setWindowTitle('thread test')
        self.show()

    def onIntReady(self, i):
        self.label.setText("{}".format(i))
        #print(i)

    app = QApplication(sys.argv)

    form = Form()

    sys.exit(app.exec_())

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

I am using this javascript to detect IE browser

if (
    navigator.appVersion.toUpperCase().indexOf("MSIE") != -1 ||
    navigator.appVersion.toUpperCase().indexOf("TRIDENT") != -1 ||
    navigator.appVersion.toUpperCase().indexOf("EDGE") != -1
)
{
    $("#ie-warning").css("display", "block");
}

How to get a specific column value from a DataTable in c#

The table normally contains multiple rows. Use a loop and use row.Field<string>(0) to access the value of each row.

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>("File");
}

You can also access it via index:

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>(0);
}

If you expect only one row, you can also use the indexer of DataRowCollection:

string file = dt.Rows[0].Field<string>(0); 

Since this fails if the table is empty, use dt.Rows.Count to check if there is a row:

if(dt.Rows.Count > 0)
    file = dt.Rows[0].Field<string>(0);

Swapping pointers in C (char, int)

In C, a string, as you know, is a character pointer (char *). If you want to swap two strings, you're swapping two char pointers, i.e. just two addresses. In order to do any swap in a function, you need to give it the addresses of the two things you're swapping. So in the case of swapping two pointers, you need a pointer to a pointer. Much like to swap an int, you just need a pointer to an int.

The reason your last code snippet doesn't work is because you're expecting it to swap two char pointers -- it's actually written to swap two characters!

Edit: In your example above, you're trying to swap two int pointers incorrectly, as R. Martinho Fernandes points out. That will swap the two ints, if you had:

int a, b;
intSwap(&a, &b);

Round to at most 2 decimal places (only if necessary)

One can use .toFixed(NumberOfDecimalPlaces).

var str = 10.234.toFixed(2); // => '10.23'
var number = Number(str); // => 10.23

How to calculate the sum of all columns of a 2D numpy array (efficiently)

Check out the documentation for numpy.sum, paying particular attention to the axis parameter. To sum over columns:

>>> import numpy as np
>>> a = np.arange(12).reshape(4,3)
>>> a.sum(axis=0)
array([18, 22, 26])

Or, to sum over rows:

>>> a.sum(axis=1)
array([ 3, 12, 21, 30])

Other aggregate functions, like numpy.mean, numpy.cumsum and numpy.std, e.g., also take the axis parameter.

From the Tentative Numpy Tutorial:

Many unary operations, such as computing the sum of all the elements in the array, are implemented as methods of the ndarray class. By default, these operations apply to the array as though it were a list of numbers, regardless of its shape. However, by specifying the axis parameter you can apply an operation along the specified axis of an array:

Explanation of 'String args[]' and static in 'public static void main(String[] args)'

I just thought I'd chip in on this one. It's been answered perfectly well by others though.

The full main method declaration should be :

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

 }

The args are declared final because technically they should not be altered. They are console parameters given by the user.

You should usually specify that main throws Exception so that stack traces can be echoed to console easily without needing to do e.printStackTrace() etc.

As for Array Syntax. I prefer it this way. I suppose that it's a little bit like the difference between french and english. In English it's "a black car", in french it's "a car black". Which is the important noun, car, or black?

I don't like this sort of thing :

String blah[] = {};

What's important here is that it's a String array, so it should be

String[] blah = {};

blah is just a name. I personally think it's a bit of a mistake in Java that arrays can sometimes be declared in that manner.

CSS: stretching background image to 100% width and height of screen?

The VH unit can be used to fill the background of the viewport, aka the browser window.

(height:100vh;)

html{
    height:100%;
    }
.body {
     background: url(image.jpg) no-repeat center top; 
     background-size: cover; 
     height:100vh;     
}

How to combine multiple inline style objects?

Ways of inline styling:

<View style={[styles.red, {fontSize: 25}]}>
  <Text>Hello World</Text>
</View>

<View style={[styles.red, styles.blue]}>
  <Text>Hello World</Text>
</View>

  <View style={{fontSize:10,marginTop:10}}>
  <Text>Hello World</Text>
</View>

SQL Server 2000: How to exit a stored procedure?

You can use RETURN to stop execution of a stored procedure immediately. Quote taken from Books Online:

Exits unconditionally from a query or procedure. RETURN is immediate and complete and can be used at any point to exit from a procedure, batch, or statement block. Statements that follow RETURN are not executed.

Out of paranoia, I tried yor example and it does output the PRINTs and does stop execution immediately.

How to set min-font-size in CSS

CSS has a clamp() function that holds the value between the upper and lower bound. The clamp() function enables the selection of the middle value in the range of values between the defined minimum and maximum values.

It simply takes three dimensions:

  1. Minimum value.
  2. List item
  3. Preferred value Maximum allowed value.

try with the code below, and check the window resize, which will change the font size you see in the console. i set maximum value 150px and minimum value 100px.

_x000D_
_x000D_
$(window).resize(function(){_x000D_
    console.log($('#element').css('font-size'));_x000D_
});_x000D_
console.log($('#element').css('font-size'));
_x000D_
h1{_x000D_
    font-size: 10vw; /* Browsers that do not support "MIN () - MAX ()" and "Clamp ()" functions will take this value.*/_x000D_
    font-size: max(100px, min(10vw, 150px)); /* Browsers that do not support the "clamp ()" function will take this value. */_x000D_
    font-size: clamp(100px, 10vw, 150px);_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<center>_x000D_
  <h1 id="element">THIS IS TEXT</h1>_x000D_
</center>
_x000D_
_x000D_
_x000D_

How to retrieve a user environment variable in CMake (Windows)

You need to have your variables exported. So for example in Linux:

export EnvironmentVariableName=foo

Unexported variables are empty in CMAKE.

Twitter Bootstrap vs jQuery UI?

Having used both, Twitter's Bootstrap is a superior technology set. Here are some differences,

  • Widgets: jQuery UI wins here. The date widget it provides is immensely useful, and Twitter Bootstrap provides nothing of the sort.
  • Scaffolding: Bootstrap wins here. Twitter's grid both fluid and fixed are top notch. jQuery UI doesn't even provide this direction leaving page layout up to the end user.
  • Out of the box professionalism: Bootstrap using CSS3 is leagues ahead, jQuery UI looks dated by comparison.
  • Icons: I'll go tie on this one. Bootstrap has nicer icons imho than jQuery UI, but I don't like the terms one bit, Glyphicons Halflings are normally not available for free, but an arrangement between Bootstrap and the Glyphicons creators have made this possible at no cost to you as developers. As a thank you, we ask you to include an optional link back to Glyphicons whenever practical.
  • Images & Thumbnails: goes to Bootstrap, jQuery UI doesn't even help here.

Other notes,

  • It's important to understand how these two technologies compete in the spheres too. There is a lot of overlap, but if you want simple scaffolding and fixed/fluid creation Bootstrap isn't another technology, it's the best technology. If you want any single widget, jQuery UI probably isn't even in the top three. Today, jQuery UI is mainly just a toy for consistency and proof of concept for a client-side widget creation using a unified framework.

Pad left or right with string.format (not padleft or padright) with arbitrary string

Edit: I misunderstood your question, I thought you were asking how to pad with spaces.

What you are asking is not possible using the string.Format alignment component; string.Format always pads with whitespace. See the Alignment Component section of MSDN: Composite Formatting.

According to Reflector, this is the code that runs inside StringBuilder.AppendFormat(IFormatProvider, string, object[]) which is called by string.Format:

int repeatCount = num6 - str2.Length;
if (!flag && (repeatCount > 0))
{
    this.Append(' ', repeatCount);
}
this.Append(str2);
if (flag && (repeatCount > 0))
{
    this.Append(' ', repeatCount);
}

As you can see, blanks are hard coded to be filled with whitespace.

Ways to insert javascript into URL?

Javascript in URL will not be executed, on its own. That by no way means its safe or to be trusted.

A URL is another user input not to be trusted, GET or POST (or any other method for that matter) can cause allot of severe vulnerabilities.

A common example was/is the use of the PHP_SELF, REQUEST_URI, SCRIPT_NAME and similar variables. Developers would mistakenly echo them directly to the browser which led to the script being injected into the page and executed.

I would suggest you start to do allot of reading, these are some good places to start:

OWASP

XSS Cheat Sheet

XSS Prevention Cheat Sheet

Also google around for XSS (cross site scripting), XSRF (Cross Site Request Forgery), and SQL Injection. That will get you started, but it is allot of information to absorb so take your time. It will be worth it in the long run.

Intercept and override HTTP requests from WebView

It looks like API level 11 has support for what you need. See WebViewClient.shouldInterceptRequest().

How to create query parameters in Javascript?

ES2017 (ES8)

Making use of Object.entries(), which returns an array of object's [key, value] pairs. For example, for {a: 1, b: 2} it would return [['a', 1], ['b', 2]]. It is not supported (and won't be) only by IE.

Code:

const buildURLQuery = obj =>
      Object.entries(obj)
            .map(pair => pair.map(encodeURIComponent).join('='))
            .join('&');

Example:

buildURLQuery({name: 'John', gender: 'male'});

Result:

"name=John&gender=male"

How to make the corners of a button round?

Simple way i found out was to make a new xml file in the drawable folder and then point the buttons background to that xml file. heres the code i used:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">

<solid android:color="#ff8100"/>
<corners android:radius="5dp"/>

</shape>

ValueError : I/O operation on closed file

I was getting this exception when debugging in PyCharm, given that no breakpoint was being hit. To prevent it, I added a breakpoint just after the with block, and then it stopped happening.

How to test the `Mosquitto` server?

If you wish to have an GUI based broker testing without installing any tool you can use Hive Mqtt web socket for testing your Mosquitto server

just visit http://www.hivemq.com/demos/websocket-client/ and enter server connection details.

If you got connected means your server is configured properly.

You can also test publish and subscribe of messages using this mqtt web socket

'mat-form-field' is not a known element - Angular 5 & Material2

You're trying to use the MatFormFieldComponent in SearchComponent but you're not importing the MatFormFieldModule (which exports MatFormFieldComponent); you only export it.

Your MaterialModule needs to import it.

@NgModule({
  imports: [
    MatFormFieldModule,
  ],
  exports: [
    MatButtonModule,
    MatFormFieldModule,
    MatInputModule,
    MatRippleModule,
  ],
  declarations: [
    SearchComponent,
  ],
})
export class MaterialModule { }

Aligning rotated xticklabels with their respective xticks

Rotating the labels is certainly possible. Note though that doing so reduces the readability of the text. One alternative is to alternate label positions using a code like this:

import numpy as np
n=5

x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Long ticklabel %i' % i for i in range(n)]


fig, ax = plt.subplots()
ax.plot(x,y, 'o-')
ax.set_xticks(x)
labels = ax.set_xticklabels(xlabels)
for i, label in enumerate(labels):
    label.set_y(label.get_position()[1] - (i % 2) * 0.075)

enter image description here

For more background and alternatives, see this post on my blog

URL for public Amazon S3 bucket

The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.


Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.


If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/ is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/ or http://s3-external-1.amazonaws.com/bucket/

The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].

S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.

If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.

However... the two endpoints do not offer the same functionality.

Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.

Choose the correct type of endpoint (REST or web site) for your application:

http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff


¹ s3-external-1.amazonaws.com has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2 had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1 so s3-external-2 appears to have no purpose except backwards-compatibility.

Why did I get the compile error "Use of unassigned local variable"?

The following categories of variables are classified as initially unassigned:

  • Instance variables of initially unassigned struct variables.
  • Output parameters, including the this variable of struct instance constructors.
  • Local variables , except those declared in a catch clause or a foreach statement.

The following categories of variables are classified as initially assigned:

  • Static variables.
  • Instance variables of class instances.
  • Instance variables of initially assigned struct variables.
  • Array elements.
  • Value parameters.
  • Reference parameters.
  • Variables declared in a catch clause or a foreach statement.

What is the unix command to see how much disk space there is and how much is remaining?

I love doing du -sh * | sort -nr | less to sort by the largest files first

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

Line Break in XML?

If you are using CSS to style (Not recommended.) you can use display:block;, however, this will only give you line breaks before and after the styled element.

What is the common header format of Python files?

I strongly favour minimal file headers, by which I mean just:

  • The hashbang (#! line) if this is an executable script
  • Module docstring
  • Imports, grouped in the standard way, eg:
  import os    # standard library
  import sys

  import requests  # 3rd party packages

  from mypackage import (  # local source
      mymodule,
      myothermodule,
  )

ie. three groups of imports, with a single blank line between them. Within each group, imports are sorted. The final group, imports from local source, can either be absolute imports as shown, or explicit relative imports.

Everything else is a waste of time, visual space, and is actively misleading.

If you have legal disclaimers or licencing info, it goes into a separate file. It does not need to infect every source code file. Your copyright should be part of this. People should be able to find it in your LICENSE file, not random source code.

Metadata such as authorship and dates is already maintained by your source control. There is no need to add a less-detailed, erroneous, and out-of-date version of the same info in the file itself.

I don't believe there is any other data that everyone needs to put into all their source files. You may have some particular requirement to do so, but such things apply, by definition, only to you. They have no place in “general headers recommended for everyone”.

Grep for beginning and end of line?

Many answers provided for this question. Just wanted to add one more which uses bashism-

#! /bin/bash
while read -r || [[ -n "$REPLY" ]]; do
[[ "$REPLY" =~ ^(-rwx|drwx).*[[:digit:]]+$ ]] && echo "Got one -> $REPLY"
done <"$1"

@kurumi answer for bash, which uses case is also correct but it will not read last line of file if there is no newline sequence at the end(Just save the file without pressing 'Enter/Return' at the last line).

ElasticSearch: Unassigned Shards, how to fix?

By default, Elasticsearch will re-assign shards to nodes dynamically. However, if you've disabled shard allocation (perhaps you did a rolling restart and forgot to re-enable it), you can re-enable shard allocation.

# v0.90.x and earlier
curl -XPUT 'localhost:9200/_settings' -d '{
    "index.routing.allocation.disable_allocation": false
}'

# v1.0+
curl -XPUT 'localhost:9200/_cluster/settings' -d '{
    "transient" : {
        "cluster.routing.allocation.enable" : "all"
    }
}'

Elasticsearch will then reassign shards as normal. This can be slow, consider raising indices.recovery.max_bytes_per_sec and cluster.routing.allocation.node_concurrent_recoveries to speed it up.

If you're still seeing issues, something else is probably wrong, so look in your Elasticsearch logs for errors. If you see EsRejectedExecutionException your thread pools may be too small.

Finally, you can explicitly reassign a shard to a node with the reroute API.

# Suppose shard 4 of index "my-index" is unassigned, so you want to
# assign it to node search03:
curl -XPOST 'localhost:9200/_cluster/reroute' -d '{
    "commands": [{
        "allocate": {
            "index": "my-index",
            "shard": 4,
            "node": "search03",
            "allow_primary": 1
        }
    }]
}'

Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?

Note: I found this question (varchar(255) v tinyblob v tinytext), which says that VARCHAR(n) requires n+1 bytes of storage for n<=255, n+2 bytes of storage for n>255. Is this the only reason? That seems kind of arbitrary, since you would only be saving two bytes compared to VARCHAR(256), and you could just as easily save another two bytes by declaring it VARCHAR(253).

No. you don't save two bytes by declaring 253. The implementation of the varchar is most likely a length counter and a variable length, nonterminated array. This means that if you store "hello" in a varchar(255) you will occupy 6 bytes: one byte for the length (the number 5) and 5 bytes for the five letters.

How can I Convert HTML to Text in C#?

I've heard from a reliable source that, if you're doing HTML parsing in .Net, you should look at the HTML agility pack again..

http://www.codeplex.com/htmlagilitypack

Some sample on SO..

HTML Agility pack - parsing tables

Fetch the row which has the Max value for a column

Just tested this and it seems to work on a logging table

select ColumnNames, max(DateColumn) from log  group by ColumnNames order by 1 desc

How do I run a class in a WAR from the command line?

Well, according to Wikipedia, with a WAR file, the classes that get loaded into the classpath are in the "/WEB-INF/classes" and "/WEB-INF/lib" directory.

You could try simply putting a copy of the classes on the root file system of the zip file (which is what a war/jar is). I'm not sure if that would work though.

You can always just create two separate files.

how to use math.pi in java

Replace

volume = (4 / 3) Math.PI * Math.pow(radius, 3);

With:

volume = (4 * Math.PI * Math.pow(radius, 3)) / 3;

iOS for VirtualBox

You could try qemu, which is what the Android emulator uses. I believe it actually emulates the ARM hardware.

Splitting string into multiple rows in Oracle

regular expressions is a wonderful thing :)

with temp as  (
       select 108 Name, 'test' Project, 'Err1, Err2, Err3' Error  from dual
       union all
       select 109, 'test2', 'Err1' from dual
     )

SELECT distinct Name, Project, trim(regexp_substr(str, '[^,]+', 1, level)) str
  FROM (SELECT Name, Project, Error str FROM temp) t
CONNECT BY instr(str, ',', 1, level - 1) > 0
order by Name

Converting a String to Object

A Java String is an Object. (String extends Object.)

So you can get an Object reference via assignment/initialisation:

String a = "abc";
Object b = a;

How to include jQuery in ASP.Net project?

if you build an MVC project, its included by default. otherwise, what Nick said.

Are there bookmarks in Visual Studio Code?

Visual Studio Code currently does not support bookmarks natively. Please add this as feature request to our Git Hub issue list (https://github.com/Microsoft/vscode).

In the meantime there are some ways to navigate around the code based on your navigation history. You can Ctrl+Tab to quickly jump to previously opened files. You can also navigate within your code based on cursor positions using Goto | Back and Goto | Forward.

Psql could not connect to server: No such file or directory, 5432 error?

FATAL:  could not load server certificate file "/etc/ssl/certs/ssl-cert-snakeoil.pem": No such file or directory
LOG:  database system is shut down
pg_ctl: could not start server

I have a missing ssl-cert-snakeoil.pem file so i created it using make-ssl-cert generate-default-snakeoil --force-overwrite And it worked fine.

How to concatenate two strings to build a complete path

The following script catenates several (relative/absolute) paths (BASEPATH) with a relative path (SUBDIR):

shopt -s extglob
SUBDIR="subdir"
for BASEPATH in '' / base base/ base// /base /base/ /base//; do
  echo "BASEPATH = \"$BASEPATH\" --> ${BASEPATH%%+(/)}${BASEPATH:+/}$SUBDIR"
done

The output of which is:

BASEPATH = "" --> subdir
BASEPATH = "/" --> /subdir
BASEPATH = "base" --> base/subdir
BASEPATH = "base/" --> base/subdir
BASEPATH = "base//" --> base/subdir
BASEPATH = "/base" --> /base/subdir
BASEPATH = "/base/" --> /base/subdir
BASEPATH = "/base//" --> /base/subdir

The shopt -s extglob is only necessary to allow BASEPATH to end on multiple slashes (which is probably nonsense). Without extended globing you can just use:

echo ${BASEPATH%%/}${BASEPATH:+/}$SUBDIR

which would result in the less neat but still working:

BASEPATH = "" --> subdir
BASEPATH = "/" --> /subdir
BASEPATH = "base" --> base/subdir
BASEPATH = "base/" --> base/subdir
BASEPATH = "base//" --> base//subdir
BASEPATH = "/base" --> /base/subdir
BASEPATH = "/base/" --> /base/subdir
BASEPATH = "/base//" --> /base//subdir

How to get VM arguments from inside of Java application?

At startup pass this -Dname=value

and then in your code you should use

value=System.getProperty("name");

to get that value

SQL query, if value is null then return 1

You can use a CASE statement.

SELECT 
    CASE WHEN currate.currentrate IS NULL THEN 1 ELSE currate.currentrate END
FROM ...

How do I get the path of the assembly the code is in?

It's as simple as this:

var dir = AppDomain.CurrentDomain.BaseDirectory;

When do Java generics require <? extends T> instead of <T> and is there any downside of switching?

what if you use

Map<String, ? extends Class<? extends Serializable>> expected = null;

iOS download and save image inside app

Although it is true that the other answers here will work, they really aren't solutions that should ever be used in production code. (at least not without modification)

Problems

The problem with these answers is that if they are implemented as is and are not called from a background thread, they will block the main thread while downloading and saving the image. This is bad.

If the main thread is blocked, UI updates won't happen until the downloading/saving of the image is complete. As an example of what this means, say you add a UIActivityIndicatorView to your app to show the user that the download is still in progress (I will be using this as an example throughout this answer) with the following rough control flow:

  1. Object responsible for starting the download is loaded.
  2. Tell the activity indicator to start animating.
  3. Start the synchronous download process using +[NSData dataWithContentsOfURL:]
  4. Save the data (image) that was just downloaded.
  5. Tell the activity indicator to stop animating.

Now, this might seem like reasonable control flow, but it is disguising a critical problem.

When you call the activity indicator's startAnimating method on the main (UI) thread, the UI updates for this event won't actually happen until the next time the main run loop updates, and this is where the first major problem is.

Before this update has a chance to happen, the download is triggered, and since this is a synchronous operation, it blocks the main thread until it has finished download (saving has the same problem). This will actually prevent the activity indicator from starting its animation. After that you call the activity indicator's stopAnimating method and expect all to be good, but it isn't.

At this point, you'll probably find yourself wondering the following.

Why doesn't my activity indicator ever show up?

Well, think about it like this. You tell the indicator to start but it doesn't get a chance before the download starts. After the download completes, you tell the indicator to stop animating. Since the main thread was blocked through the whole operation, the behavior you actually see is more along the lines telling the indicator to start and then immediately telling it to stop, even though there was a (possibly) large download task in between.

Now, in the best case scenario, all this does is cause a poor user experience (still really bad). Even if you think this isn't a big deal because you're only downloading a small image and the download happens almost instantaneously, that won't always be the case. Some of your users may have slow internet connections, or something may be wrong server side keeping the download from starting immediately/at all.

In both of these cases, the app won't be able to process UI updates, or even touch events while your download task sits around twiddling its thumbs waiting for the download to complete or for the server to respond to its request.

What this means is that synchronously downloading from the main thread prevents you from possibly implementing anything to indicate to the user that a download is currently in progress. And since touch events are processed on the main thread as well, this throws out the possibility of adding any kind of cancel button as well.

Then in the worst case scenario, you'll start receiving crash reports stating the following.

Exception Type: 00000020 Exception Codes: 0x8badf00d

These are easy to identify by the exception code 0x8badf00d, which can be read as "ate bad food". This exception is thrown by the watch dog timer, whose job is to watch for long running tasks that block the main thread, and to kill the offending app if this goes on for too long. Arguably, this is still a poor user experience issue, but if this starts to occur, the app has crossed the line between bad user experience, and terrible user experience.

Here's some more info on what can cause this to happen from Apple's Technical Q&A about synchronous networking (shortened for brevity).

The most common cause for watchdog timeout crashes in a network application is synchronous networking on the main thread. There are four contributing factors here:

  1. synchronous networking — This is where you make a network request and block waiting for the response.
  2. main thread — Synchronous networking is less than ideal in general, but it causes specific problems if you do it on the main thread. Remember that the main thread is responsible for running the user interface. If you block the main thread for any significant amount of time, the user interface becomes unacceptably unresponsive.
  3. long timeouts — If the network just goes away (for example, the user is on a train which goes into a tunnel), any pending network request won't fail until some timeout has expired....

...

  1. watchdog — In order to keep the user interface responsive, iOS includes a watchdog mechanism. If your application fails to respond to certain user interface events (launch, suspend, resume, terminate) in time, the watchdog will kill your application and generate a watchdog timeout crash report. The amount of time the watchdog gives you is not formally documented, but it's always less than a network timeout.

One tricky aspect of this problem is that it's highly dependent on the network environment. If you always test your application in your office, where network connectivity is good, you'll never see this type of crash. However, once you start deploying your application to end users—who will run it in all sorts of network environments—crashes like this will become common.

Now at this point, I'll stop rambling about why the provided answers might be problematic and will start offering up some alternative solutions. Keep in mind that I've used the URL of a small image in these examples and you'll notice a larger difference when using a higher resolution image.


Solutions

I'll start by showing a safe version of the other answers, with the addition of how to handle UI updates. This will be the first of several examples, all of which will assume that the class in which they are implemented has valid properties for a UIImageView, a UIActivityIndicatorView, as well as the documentsDirectoryURL method to access the documents directory. In production code, you may want to implement your own method to access the documents directory as a category on NSURL for better code reusability, but for these examples, this will be fine.

- (NSURL *)documentsDirectoryURL
{
    NSError *error = nil;
    NSURL *url = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory
                                                        inDomain:NSUserDomainMask
                                               appropriateForURL:nil
                                                          create:NO
                                                           error:&error];
    if (error) {
        // Figure out what went wrong and handle the error.
    }
    
    return url;
}

These examples will also assume that the thread that they start off on is the main thread. This will likely be the default behavior unless you start your download task from somewhere like the callback block of some other asynchronous task. If you start your download in a typical place, like a lifecycle method of a view controller (i.e. viewDidLoad, viewWillAppear:, etc.) this will produce the expected behavior.

This first example will use the +[NSData dataWithContentsOfURL:] method, but with some key differences. For one, you'll notice that in this example, the very first call we make is to tell the activity indicator to start animating, then there is an immediate difference between this and the synchronous examples. Immediately, we use dispatch_async(), passing in the global concurrent queue to move execution to the background thread.

At this point, you've already greatly improved your download task. Since everything within the dispatch_async() block will now happen off the main thread, your interface will no longer lock up, and your app will be free to respond to touch events.

What is important to notice here is that all of the code within this block will execute on the background thread, up until the point where the downloading/saving of the image was successful, at which point you might want to tell the activity indicator to stopAnimating, or apply the newly saved image to a UIImageView. Either way, these are updates to the UI, meaning you must dispatch back the the main thread using dispatch_get_main_queue() to perform them. Failing to do so results in undefined behavior, which may cause the UI to update after an unexpected period of time, or may even cause a crash. Always make sure you move back to the main thread before performing UI updates.

// Start the activity indicator before moving off the main thread
[self.activityIndicator startAnimating];
// Move off the main thread to start our blocking tasks.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // Create the image URL from a known string.
    NSURL *imageURL = [NSURL URLWithString:@"http://www.google.com/images/srpr/logo3w.png"];
    
    NSError *downloadError = nil;
    // Create an NSData object from the contents of the given URL.
    NSData *imageData = [NSData dataWithContentsOfURL:imageURL
                                              options:kNilOptions
                                                error:&downloadError];
    // ALWAYS utilize the error parameter!
    if (downloadError) {
        // Something went wrong downloading the image. Figure out what went wrong and handle the error.
        // Don't forget to return to the main thread if you plan on doing UI updates here as well.
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.activityIndicator stopAnimating];
            NSLog(@"%@",[downloadError localizedDescription]);
        });
    } else {
        // Get the path of the application's documents directory.
        NSURL *documentsDirectoryURL = [self documentsDirectoryURL];
        // Append the desired file name to the documents directory path.
        NSURL *saveLocation = [documentsDirectoryURL URLByAppendingPathComponent:@"GCD.png"];

        NSError *saveError = nil;
        BOOL writeWasSuccessful = [imageData writeToURL:saveLocation
                                                options:kNilOptions
                                                  error:&saveError];
        // Successful or not we need to stop the activity indicator, so switch back the the main thread.
        dispatch_async(dispatch_get_main_queue(), ^{
            // Now that we're back on the main thread, you can make changes to the UI.
            // This is where you might display the saved image in some image view, or
            // stop the activity indicator.
            
            // Check if saving the file was successful, once again, utilizing the error parameter.
            if (writeWasSuccessful) {
                // Get the saved image data from the file.
                NSData *imageData = [NSData dataWithContentsOfURL:saveLocation];
                // Set the imageView's image to the image we just saved.
                self.imageView.image = [UIImage imageWithData:imageData];
            } else {
                NSLog(@"%@",[saveError localizedDescription]);
                // Something went wrong saving the file. Figure out what went wrong and handle the error.
            }
            
            [self.activityIndicator stopAnimating];
        });
    }
});

Now keep in mind, that the method shown above is still not an ideal solution considering it can't be cancelled prematurely, it gives you no indication of the progress of the download, it can't handle any kind of authentication challenge, it can't be given a specific timeout interval, etc. (lots and lots of reasons). I'll cover a few of the better options below.

In these examples, I'll only be covering solutions for apps targeting iOS 7 and up considering (at time of writing) iOS 8 is the current major release, and Apple is suggesting only supporting versions N and N-1. If you need to support older iOS versions, I recommend looking into the NSURLConnection class, as well as the 1.0 version of AFNetworking. If you look at the revision history of this answer, you can find basic examples using NSURLConnection and ASIHTTPRequest, although it should be noted that ASIHTTPRequest is no longer being maintained, and should not be used for new projects.


NSURLSession

Lets start with NSURLSession, which was introduced in iOS 7, and greatly improves the ease with which networking can be done in iOS. With NSURLSession, you can easily perform asynchronous HTTP requests with a callback block and handle authentication challenges with its delegate. But what makes this class really special is that it also allows for download tasks to continue running even if the application is sent to the background, gets terminated, or even crashes. Here's a basic example of its usage.

// Start the activity indicator before starting the download task.
[self.activityIndicator startAnimating];

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
// Use a session with a custom configuration
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
// Create the image URL from some known string.
NSURL *imageURL = [NSURL URLWithString:@"http://www.google.com/images/srpr/logo3w.png"];
// Create the download task passing in the URL of the image.
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:imageURL completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
    // Get information about the response if neccessary.
    if (error) {
        NSLog(@"%@",[error localizedDescription]);
        // Something went wrong downloading the image. Figure out what went wrong and handle the error.
        // Don't forget to return to the main thread if you plan on doing UI updates here as well.
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.activityIndicator stopAnimating];
        });
    } else {
        NSError *openDataError = nil;
        NSData *downloadedData = [NSData dataWithContentsOfURL:location
                                                       options:kNilOptions
                                                         error:&openDataError];
        if (openDataError) {
            // Something went wrong opening the downloaded data. Figure out what went wrong and handle the error.
            // Don't forget to return to the main thread if you plan on doing UI updates here as well.
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"%@",[openDataError localizedDescription]);
                [self.activityIndicator stopAnimating];
            });
        } else {
            // Get the path of the application's documents directory.
            NSURL *documentsDirectoryURL = [self documentsDirectoryURL];
            // Append the desired file name to the documents directory path.
            NSURL *saveLocation = [documentsDirectoryURL URLByAppendingPathComponent:@"NSURLSession.png"];
            NSError *saveError = nil;
            
            BOOL writeWasSuccessful = [downloadedData writeToURL:saveLocation
                                                          options:kNilOptions
                                                            error:&saveError];
            // Successful or not we need to stop the activity indicator, so switch back the the main thread.
            dispatch_async(dispatch_get_main_queue(), ^{
                // Now that we're back on the main thread, you can make changes to the UI.
                // This is where you might display the saved image in some image view, or
                // stop the activity indicator.
                
                // Check if saving the file was successful, once again, utilizing the error parameter.
                if (writeWasSuccessful) {
                    // Get the saved image data from the file.
                    NSData *imageData = [NSData dataWithContentsOfURL:saveLocation];
                    // Set the imageView's image to the image we just saved.
                    self.imageView.image = [UIImage imageWithData:imageData];
                } else {
                    NSLog(@"%@",[saveError localizedDescription]);
                    // Something went wrong saving the file. Figure out what went wrong and handle the error.
                }
                
                [self.activityIndicator stopAnimating];
            });
        }
    }
}];

// Tell the download task to resume (start).
[task resume];

From this you'll notice that the downloadTaskWithURL: completionHandler: method returns an instance of NSURLSessionDownloadTask, on which an instance method -[NSURLSessionTask resume] is called. This is the method that actually tells the download task to start. This means that you can spin up your download task, and if desired, hold off on starting it (if needed). This also means that as long as you store a reference to the task, you can also utilize its cancel and suspend methods to cancel or pause the task if need be.

What's really cool about NSURLSessionTasks is that with a little bit of KVO, you can monitor the values of its countOfBytesExpectedToReceive and countOfBytesReceived properties, feed these values to an NSByteCountFormatter, and easily create a download progress indicator to your user with human readable units (e.g. 42 KB of 100 KB).

Before I move away from NSURLSession though, I'd like to point out that the ugliness of having to dispatch_async back to the main threads at several different points in the download's callback block can be avoided. If you chose to go this route, you can initialize the session with its initializer that allows you to specify the delegate, as well as the delegate queue. This will require you to use the delegate pattern instead of the callback blocks, but this may be beneficial because it is the only way to support background downloads.

NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration
                                                      delegate:self
                                                 delegateQueue:[NSOperationQueue mainQueue]];

AFNetworking 2.0

If you've never heard of AFNetworking, it is IMHO the end-all of networking libraries. It was created for Objective-C, but it works in Swift as well. In the words of its author:

AFNetworking is a delightful networking library for iOS and Mac OS X. It's built on top of the Foundation URL Loading System, extending the powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use.

AFNetworking 2.0 supports iOS 6 and up, but in this example, I will be using its AFHTTPSessionManager class, which requires iOS 7 and up due to its usage of all the new APIs around the NSURLSession class. This will become obvious when you read the example below, which shares a lot of code with the NSURLSession example above.

There are a few differences that I'd like to point out though. To start off, instead of creating your own NSURLSession, you'll create an instance of AFURLSessionManager, which will internally manage a NSURLSession. Doing so allows you take advantage of some of its convenience methods like -[AFURLSessionManager downloadTaskWithRequest:progress:destination:completionHandler:]. What is interesting about this method is that it lets you fairly concisely create a download task with a given destination file path, a completion block, and an input for an NSProgress pointer, on which you can observe information about the progress of the download. Here's an example.

// Use the default session configuration for the manager (background downloads must use the delegate APIs)
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
// Use AFNetworking's NSURLSessionManager to manage a NSURLSession.
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

// Create the image URL from some known string.
NSURL *imageURL = [NSURL URLWithString:@"http://www.google.com/images/srpr/logo3w.png"];
// Create a request object for the given URL.
NSURLRequest *request = [NSURLRequest requestWithURL:imageURL];
// Create a pointer for a NSProgress object to be used to determining download progress.
NSProgress *progress = nil;

// Create the callback block responsible for determining the location to save the downloaded file to.
NSURL *(^destinationBlock)(NSURL *targetPath, NSURLResponse *response) = ^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    // Get the path of the application's documents directory.
    NSURL *documentsDirectoryURL = [self documentsDirectoryURL];
    NSURL *saveLocation = nil;
    
    // Check if the response contains a suggested file name
    if (response.suggestedFilename) {
        // Append the suggested file name to the documents directory path.
        saveLocation = [documentsDirectoryURL URLByAppendingPathComponent:response.suggestedFilename];
    } else {
        // Append the desired file name to the documents directory path.
        saveLocation = [documentsDirectoryURL URLByAppendingPathComponent:@"AFNetworking.png"];
    }

    return saveLocation;
};

// Create the completion block that will be called when the image is done downloading/saving.
void (^completionBlock)(NSURLResponse *response, NSURL *filePath, NSError *error) = ^void (NSURLResponse *response, NSURL *filePath, NSError *error) {
    dispatch_async(dispatch_get_main_queue(), ^{
        // There is no longer any reason to observe progress, the download has finished or cancelled.
        [progress removeObserver:self
                      forKeyPath:NSStringFromSelector(@selector(fractionCompleted))];
        
        if (error) {
            NSLog(@"%@",error.localizedDescription);
            // Something went wrong downloading or saving the file. Figure out what went wrong and handle the error.
        } else {
            // Get the data for the image we just saved.
            NSData *imageData = [NSData dataWithContentsOfURL:filePath];
            // Get a UIImage object from the image data.
            self.imageView.image = [UIImage imageWithData:imageData];
        }
    });
};

// Create the download task for the image.
NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request
                                                         progress:&progress
                                                      destination:destinationBlock
                                                completionHandler:completionBlock];
// Start the download task.
[task resume];

// Begin observing changes to the download task's progress to display to the user.
[progress addObserver:self
           forKeyPath:NSStringFromSelector(@selector(fractionCompleted))
              options:NSKeyValueObservingOptionNew
              context:NULL];

Of course since we've added the class containing this code as an observer to one of the NSProgress instance's properties, you'll have to implement the -[NSObject observeValueForKeyPath:ofObject:change:context:] method. In this case, I've included an example of how you might update a progress label to display the download's progress. It's really easy. NSProgress has an instance method localizedDescription which will display progress information in a localized, human readable format.

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    // We only care about updates to fractionCompleted
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(fractionCompleted))]) {
        NSProgress *progress = (NSProgress *)object;
        // localizedDescription gives a string appropriate for display to the user, i.e. "42% completed"
        self.progressLabel.text = progress.localizedDescription;
    } else {
        [super observeValueForKeyPath:keyPath
                             ofObject:object
                               change:change
                              context:context];
    }
}

Don't forget, if you want to use AFNetworking in your project, you'll need to follow its installation instructions and be sure to #import <AFNetworking/AFNetworking.h>.

Alamofire

And finally, I'd like to give a final example using Alamofire. This is a the library that makes networking in Swift a cake-walk. I'm out of characters to go into great detail about the contents of this sample, but it does pretty much the same thing as the last examples, just in an arguably more beautiful way.

// Create the destination closure to pass to the download request. I haven't done anything with them
// here but you can utilize the parameters to make adjustments to the file name if neccessary.
let destination = { (url: NSURL!, response: NSHTTPURLResponse!) -> NSURL in
    var error: NSError?
    // Get the documents directory
    let documentsDirectory = NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory,
        inDomain: .UserDomainMask,
        appropriateForURL: nil,
        create: false,
        error: &error
    )
    
    if let error = error {
        // This could be bad. Make sure you have a backup plan for where to save the image.
        println("\(error.localizedDescription)")
    }
    
    // Return a destination of .../Documents/Alamofire.png
    return documentsDirectory!.URLByAppendingPathComponent("Alamofire.png")
}

Alamofire.download(.GET, "http://www.google.com/images/srpr/logo3w.png", destination)
    .validate(statusCode: 200..<299) // Require the HTTP status code to be in the Successful range.
    .validate(contentType: ["image/png"]) // Require the content type to be image/png.
    .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in
        // Create an NSProgress object to represent the progress of the download for the user.
        let progress = NSProgress(totalUnitCount: totalBytesExpectedToRead)
        progress.completedUnitCount = totalBytesRead
        
        dispatch_async(dispatch_get_main_queue()) {
            // Move back to the main thread and update some progress label to show the user the download is in progress.
            self.progressLabel.text = progress.localizedDescription
        }
    }
    .response { (request, response, _, error) in
        if error != nil {
            // Something went wrong. Handle the error.
        } else {
            // Open the newly saved image data.
            if let imageData = NSData(contentsOfURL: destination(nil, nil)) {
                dispatch_async(dispatch_get_main_queue()) {
                    // Move back to the main thread and add the image to your image view.
                    self.imageView.image = UIImage(data: imageData)
                }
            }
        }
    }

Several ports (8005, 8080, 8009) required by Tomcat Server at localhost are already in use

The problem often arises when Apache Tomcat fails to terminate, properly, even though a shutdown instruction was sent. In my case, using Tomcat 8, this happens with annoying regularity. Luckily, you can use Windows PowerShell and the netstat command to create a simple script to kill the process.

The following PowerShell script will parse the output from netstat to find any process that is listening on 127.0.0.1:8005, extract its PID and then kill that process:

netstat -a -o -n `
 | select -skip 4 `
 | % {$a = $_ -split ' {3,}'; New-Object 'PSObject' -Property @{Original=$_;Fields=$a}} `
 | ? {$_.Fields[1] -match '127\.0\.0\.1\:8005$'} `
 | % {Write-Host "Killing PID" $_.Fields[4] "..."; taskkill /F /PID $_.Fields[4] }

If your server.xml configures Tomcat to use a different port or IP, edit the regular expression on the script's fourth line accordingly.

Finally, I should point out that the situation is better on Linux because you can instruct Tomcat to save its PID to a file at startup-time and use a switch to force the shutdown, later - the shutdown script for 'nix systems already features the ability to kill the process and the sleuth-work with netstat is not required.

What does $1 mean in Perl?

In general, questions regarding "magic" variables in Perl can be answered by looking in the Perl predefined variables documentation a la:

perldoc perlvar

However, when you search this documentation for $1, etc., you'll find references in a number of places except the section on these "digit" variables. You have to search for

$<digits>

I would have added this to Brian's answer either by commenting or editing, but I don't have enough rep. If someone adds this I'll remove this answer.

Cast Object to Generic Type for returning

I stumble upon this question and it grabbed my interest. The accepted answer is completely correct, but I thought I do provide my findings at JVM byte code level to explain why the OP encounter the ClassCastException.

I have the code which is pretty much the same as OP's code:

public static <T> T convertInstanceOfObject(Object o) {
    try {
       return (T) o;
    } catch (ClassCastException e) {
        return null;
    }
}

public static void main(String[] args) {
    String k = convertInstanceOfObject(345435.34);
    System.out.println(k);
}

and the corresponding byte code is:

public static <T> T convertInstanceOfObject(java.lang.Object);
    Code:
       0: aload_0
       1: areturn
       2: astore_1
       3: aconst_null
       4: areturn
    Exception table:
       from    to  target type
           0     1     2   Class java/lang/ClassCastException

  public static void main(java.lang.String[]);
    Code:
       0: ldc2_w        #3                  // double 345435.34d
       3: invokestatic  #5                  // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
       6: invokestatic  #6                  // Method convertInstanceOfObject:(Ljava/lang/Object;)Ljava/lang/Object;
       9: checkcast     #7                  // class java/lang/String
      12: astore_1
      13: getstatic     #8                  // Field java/lang/System.out:Ljava/io/PrintStream;
      16: aload_1
      17: invokevirtual #9                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      20: return

Notice that checkcast byte code instruction happens in the main method not the convertInstanceOfObject and convertInstanceOfObject method does not have any instruction that can throw ClassCastException. Because the main method does not catch the ClassCastException hence when you execute the main method you will get a ClassCastException and not the expectation of printing null.

Now I modify the code to the accepted answer:

public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
        try {
            return clazz.cast(o);
        } catch (ClassCastException e) {
            return null;
        }
    }
    public static void main(String[] args) {
        String k = convertInstanceOfObject(345435.34, String.class);
        System.out.println(k);
    }

The corresponding byte code is:

public static <T> T convertInstanceOfObject(java.lang.Object, java.lang.Class<T>);
    Code:
       0: aload_1
       1: aload_0
       2: invokevirtual #2                  // Method java/lang/Class.cast:(Ljava/lang/Object;)Ljava/lang/Object;
       5: areturn
       6: astore_2
       7: aconst_null
       8: areturn
    Exception table:
       from    to  target type
           0     5     6   Class java/lang/ClassCastException

  public static void main(java.lang.String[]);
    Code:
       0: ldc2_w        #4                  // double 345435.34d
       3: invokestatic  #6                  // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
       6: ldc           #7                  // class java/lang/String
       8: invokestatic  #8                  // Method convertInstanceOfObject:(Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;
      11: checkcast     #7                  // class java/lang/String
      14: astore_1
      15: getstatic     #9                  // Field java/lang/System.out:Ljava/io/PrintStream;
      18: aload_1
      19: invokevirtual #10                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      22: return

Notice that there is an invokevirtual instruction in the convertInstanceOfObject method that calls Class.cast() method which throws ClassCastException which will be catch by the catch(ClassCastException e) bock and return null; hence, "null" is printed to console without any exception.

X-Frame-Options on apache

I found that if the application within the httpd server has a rule like "if the X-Frame-Options header exists and has a value, leave it alone; otherwise add the header X-Frame-Options: SAMEORIGIN" then an httpd.conf mod_headers rule like "Header always unset X-Frame-Options" would not suffice. The SAMEORIGIN value would always reach the client.

To remedy this, I add two, not one, mod_headers rules (in the outermost httpd.conf file):

Header set X-Frame-Options ALLOW-FROM http://to.be.deleted.com early
Header unset X-Frame-Options

The first rule tells any internal request handler that some other agent has taken responsibility for clickjack prevention and it can skip its attempt to save the world. It runs with "early" processing. The second rule strips off the entirely unwanted X-Frame-Options header. It runs with "late" processing.

I also add the appropriate Content-Security-Policy headers so that the world remains protected yet multi-sourced Javascript from trusted sites still gets to run.

Plotting a 3d cube, a sphere and a vector in Matplotlib

My answer is an amalgamation of the above two with extension to drawing sphere of user-defined opacity and some annotation. It finds application in b-vector visualization on a sphere for magnetic resonance image (MRI). Hope you find it useful:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

# draw sphere
u, v = np.mgrid[0:2*np.pi:50j, 0:np.pi:50j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
# alpha controls opacity
ax.plot_surface(x, y, z, color="g", alpha=0.3)


# a random array of 3D coordinates in [-1,1]
bvecs= np.random.randn(20,3)

# tails of the arrows
tails= np.zeros(len(bvecs))

# heads of the arrows with adjusted arrow head length
ax.quiver(tails,tails,tails,bvecs[:,0], bvecs[:,1], bvecs[:,2],
          length=1.0, normalize=True, color='r', arrow_length_ratio=0.15)

ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')

ax.set_title('b-vectors on unit sphere')

plt.show()

Controlling Maven final name of jar artifact

All of the provided answers are more complicated than necessary. Assuming you are building a jar file, all you need to do is add a <jar.finalName> tag to your <properties> section:

<properties>
    <jar.finalName>${project.name}</jar.finalName>
</properties>

This will generate a jar:

project/target/${project.name}.jar

This is in the documentation - note the User Property:

finalName:
Name of the generated JAR.
Type: java.lang.String
Required: No
User Property: jar.finalName
Default: ${project.build.finalName}

Command Line Usage

You should also be able to use this option on the command line with:

mvn -Djar.finalName=myCustomName ...

You should get myCustomName.jar, although I haven't tested this.

How to uninstall Python 2.7 on a Mac OS X 10.6.4?

In regards to deleting the symbolic links, I found this to be useful.

find /usr/local/bin -lname '../../../Library/Frameworks/Python.framework/Versions/2.7/*' -delete

Get file name from a file location in Java

From Apache Commons IO FileNameUtils

String fileName = FilenameUtils.getName(stringNameWithPath);

'xmlParseEntityRef: no name' warnings while loading xml into a php file

If you are getting this issue with opencart try editing

catalog/controller/extension/feed/google_sitemap.php For More info and How to do it refer this: xmlparseentityref-no-name-error

Auto detect mobile browser (via user-agent?)

Just a thought but what if you worked this problem from the opposite direction? Rather than determining which browsers are mobile why not determine which browsers are not? Then code your site to default to the mobile version and redirect to the standard version. There are two basic possibilities when looking at a mobile browser. Either it has javascript support or it doesn't. So if the browser does not have javascript support it will default to the mobile version. If it does have JavaScript support, check the screen size. Anything below a certain size will likely also be a mobile browser. Anything larger will get redirected to your standard layout. Then all you need to do is determine if the user with JavaScript disabled is mobile or not.
According to the W3C the number of users with JavaScript disabled was about 5% and of those users most have turned it off which implies that they actually know what they are doing with a browser. Are they a large part of your audience? If not then don't worry about them. If so, whats the worst case scenario? You have those users browsing the mobile version of your site, and that's a good thing.

What exactly does a jar file contain?

Jar( Java Archive) contains group of .class files.

1.To create Jar File (Zip File)

 if one .class (say, Demo.class) then use command jar -cvf NameOfJarFile.jar Demo.class (usually it’s not feasible for only one .class file)

 if more than one .class (say, Demo.class , DemoOne.class) then use command jar -cvf NameOfJarFile.jar Demo.class DemoOne.class

 if all .class is to be group (say, Demo.class , DemoOne.class etc) then use command jar -cvf NameOfJarFile.jar *.class

2.To extract Jar File (Unzip File)

    jar -xvf NameOfJarFile.jar

3.To display table of content

    jar -tvf NameOfJarFile.jar

Gridview get Checkbox.Checked value

For run all lines of GridView don't use for loop, use foreach loop like:

foreach (GridViewRow row in yourGridName.Rows) //Running all lines of grid
{
    if (row.RowType == DataControlRowType.DataRow)
    {
         CheckBox chkRow = (row.Cells[0].FindControl("chkRow") as CheckBox);

         if (chkRow.Checked)
         {
              //if checked do something
         }
    }
}

Asus Zenfone 5 not detected by computer

This should solve your problem.

  1. Download the Asus USB Driver for Zenfone 5 here
  2. Extract the rar file
  3. Go to your Device Manager if you're on Windows (Make sure you've connected your phone to your computer)
  4. Choose update driver then browse the path to where the extracted rar file is. It should prompt something on your phone, just accept it
  5. Try it on your IDE, just select run configurations

Search in lists of lists by given index

Here's the Pythonic way to do it:

data = [['a','b'], ['a','c'], ['b','d']]
search = 'c'
any(e[1] == search for e in data)

Or... well, I'm not going to claim this is the "one true Pythonic way" to do it because at some point it becomes a little subjective what is Pythonic and what isn't, or which method is more Pythonic than another. But using any() is definitely more typical Python style than a for loop as in e.g. RichieHindle's answer,

Of course there is a hidden loop in the implementation of any, although it breaks out of the loop as soon as it finds a match.


Since I was bored I made a timing script to compare performance of the different suggestions, modifying some of them as necessary to make the API the same. Now, we should bear in mind that fastest is not always best, and being fast is definitely not the same thing as being Pythonic. That being said, the results are... strange. Apparently for loops are very fast, which is not what I expected, so I'd take these with a grain of salt without understanding why they've come out the way they do.

Anyway, when I used the list defined in the question with three sublists of two elements each, from fastest to slowest I get these results:

  1. RichieHindle's answer with the for loop, clocking in at 0.22 µs
  2. Terence Honles' first suggestion which creates a list, at 0.36 µs
  3. Pierre-Luc Bedard's answer (last code block), at 0.43 µs
  4. Essentially tied between Markus's answer and the for loop from the original question, at 0.48 µs
  5. Coady's answer using operator.itemgetter(), at 0.53 µs
  6. Close enough to count as a tie between Alex Martelli's answer with ifilter() and Anon's answer, at 0.67 µs (Alex's is consistently about half a microsecond faster)
  7. Another close-enough tie between jojo's answer, mine, Brandon E Taylor's (which is identical to mine), and Terence Honles' second suggestion using any(), all coming in at 0.81-0.82 µs
  8. And then user27221's answer using nested list comprehensions, at 0.95 µs

Obviously the actual timings are not meaningful on anyone else's hardware, but the differences between them should give some idea of how close the different methods are.

When I use a longer list, things change a bit. I started with the list in the question, with three sublists, and appended another 197 sublists, for a total of 200 sublists each of length two. Using this longer list, here are the results:

  1. RichieHindle's answer, at the same 0.22 µs as with the shorter list
  2. Coady's answer using operator.itemgetter(), again at 0.53 µs
  3. Terence Honles' first suggestion which creates a list, at 0.36 µs
  4. Another virtual tie between Alex Martelli's answer with ifilter() and Anon's answer, at 0.67 µs
  5. Again a close-enough tie between my answer, Brandon E Taylor's identical method, and Terence Honles' second suggestion using any(), all coming in at 0.81-0.82 µs

Those are the ones that keep their original timing when the list is extended. The rest, which don't, are

  1. The for loop from the original question, at 1.24 µs
  2. Terence Honles' first suggestion which creates a list, at 7.49 µs
  3. Pierre-Luc Bedard's answer (last code block), at 8.12 µs
  4. Markus's answer, at 10.27 µs
  5. jojo's answer, at 19.87 µs
  6. And finally user27221's answer using nested list comprehensions, at 60.59 µs

IntelliJ IDEA 13 uses Java 1.5 despite setting to 1.7

[For IntelliJ IDEA 2016.2]

I would like to expand upon part of Peter Gromov's answer with an up-to-date screenshot. Specifically this particular part:

You might also want to take a look at Settings | Compiler | Java Compiler | Per-module bytecode version.

I believe that (at least in 2016.2): checking out different commits in git resets these to 1.5.

Per-module bytecode version

how to find all indexes and their columns for tables, views and synonyms in oracle

Your query should work for synonyms as well as the tables. However, you seem to expect indexes on views where there are not. Maybe is it materialized views ?

How to find the users list in oracle 11g db?

You can think of a mysql database as a schema/user in Oracle. If you have the privileges, you can query the DBA_USERS view to see the list of schema.

Android studio- "SDK tools directory is missing"

If you are using Windows S.O. make sure it is in the folder:

C:\Users\**your-user-name**\AppData\Local\Android\Sdk\platform-tools

Otherwise, open Android Studio and go to:

Tools> SDK Manager> Android SDK> SDK Tools

Select the Android Platform-Tools and Android SDK Tools checkbox and click Apply. After download check the directory again.

Redirect to external URI from ASP.NET MVC controller

Try this (I've used Home controller and Index View):

return RedirectToAction("Index", "Home");

How to fix "unable to write 'random state' " in openssl

I did not find where the .rnd file is so I ran the cmd as administrator and it worked like a charm.

Set order of columns in pandas dataframe

Here is a solution I use very often. When you have a large data set with tons of columns, you definitely do not want to manually rearrange all the columns.

What you can and, most likely, want to do is to just order the first a few columns that you frequently use, and let all other columns just be themselves. This is a common approach in R. df %>%select(one, two, three, everything())

So you can first manually type the columns that you want to order and to be positioned before all the other columns in a list cols_to_order.

Then you construct a list for new columns by combining the rest of the columns:

new_columns = cols_to_order + (frame.columns.drop(cols_to_order).tolist())

After this, you can use the new_columns as other solutions suggested.

import pandas as pd
frame = pd.DataFrame({
    'one thing': [1, 2, 3, 4],
    'other thing': ['a', 'e', 'i', 'o'],
    'more things': ['a', 'e', 'i', 'o'],
    'second thing': [0.1, 0.2, 1, 2],
})

cols_to_order = ['one thing', 'second thing']
new_columns = cols_to_order + (frame.columns.drop(cols_to_order).tolist())
frame = frame[new_columns]

   one thing  second thing other thing more things
0          1           0.1           a           a
1          2           0.2           e           e
2          3           1.0           i           i
3          4           2.0           o           o

Uncaught ReferenceError: <function> is not defined at HTMLButtonElement.onclick

Same Problem I had... I was writing all the script in a seperate file and was adding it through tag into the end of the HTML file after body tag. After moving the the tag inside the body tag it works fine. before :

</body>
<script>require('../script/viewLog.js')</script>

after :

<script>require('../script/viewLog.js')</script>
</body>

How do I declare an array variable in VBA?

Generally, you should declare variables of a specific type, rather than Variant. In this example, the test variable should be of type String.

And, because it's an array, you need to indicate that specifically when you declare the variable. There are two ways of declaring array variables:

  1. If you know the size of the array (the number of elements that it should contain) when you write the program, you can specify that number in parentheses in the declaration:

    Dim test(1) As String   'declares an array with 2 elements that holds strings
    

    This type of array is referred to as a static array, as its size is fixed, or static.

  2. If you do not know the size of the array when you write the application, you can use a dynamic array. A dynamic array is one whose size is not specified in the declaration (Dim statement), but rather is determined later during the execution of the program using the ReDim statement. For example:

    Dim test() As String
    Dim arraySize As Integer
    
    ' Code to do other things, like calculate the size required for the array
    ' ...
    arraySize = 5
    
    ReDim test(arraySize)  'size the array to the value of the arraySize variable
    

7-zip commandline

Instead of the option a use option x, this will create the directories but only for extraction, not compression.

Visual Studio 2015 or 2017 does not discover unit tests

I resolved it by changing X64 to : Right click on project -> Properties -> Build -> Platform target -> Any CPU

How to make shadow on border-bottom?

The issue is shadow coming out the side of the containing div. In order to avoid this, the blur value must equal the absolute value of the spread value.

_x000D_
_x000D_
div {_x000D_
  -webkit-box-shadow: 0 4px 6px -6px #222;_x000D_
  -moz-box-shadow: 0 4px 6px -6px #222;_x000D_
  box-shadow: 0 4px 6px -6px #222;_x000D_
}
_x000D_
<div>wefwefwef</div>
_x000D_
_x000D_
_x000D_

covered in depth here

Copying PostgreSQL database to another server


Dump your database : pg_dump database_name_name > backup.sql


Import your database back: psql db_name < backup.sql

How can I resolve the error: "The command [...] exited with code 1"?

Right click project -> Properties -> Build Events

Remove the text in Post-build event command line text block

Difference between Dictionary and Hashtable

Dictionary is typed (so valuetypes don't need boxing), a Hashtable isn't (so valuetypes need boxing). Hashtable has a nicer way of obtaining a value than dictionary IMHO, because it always knows the value is an object. Though if you're using .NET 3.5, it's easy to write an extension method for dictionary to get similar behavior.

If you need multiple values per key, check out my sourcecode of MultiValueDictionary here: multimap in .NET

Finding smallest value in an array most efficiently

//find the min in an array list of #s
$array = array(45,545,134,6735,545,23,434);

$smallest = $array[0];
for($i=1; $i<count($array); $i++){
    if($array[$i] < $smallest){
        echo $array[$i];
    }
}

python-dev installation error: ImportError: No module named apt_pkg

The solution of @user8178061 worked well but I did it with some modifications for my version wich is python3.7 with Ubuntu

I replaced the apt_pkg.cpython-3m-i386-linux-gnu.so with apt_pkg.cpython-36m-x86_64-linux-gnu.so

Here the two commands to execute:

cd /usr/lib/python3/dist-packages

sudo cp apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.so

How to make a smaller RatingBar?

 <RatingBar
                    android:rating="3.5"
                    android:stepSize="0.5"
                    android:numStars="5"
                    style = "?android:attr/ratingBarStyleSmall"
                    android:theme="@style/RatingBar"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"/>

// if you want to style 

 <style name="RatingBar" parent="Theme.AppCompat">
        <item name="colorControlNormal">@color/colorPrimary</item>
        <item name="colorControlActivated">@color/colorAccent</item>
    </style>

// add these line for small rating bar

style = "?android:attr/ratingBarStyleSmall"

Can you change what a symlink points to after it is created?

Wouldn't unlinking it and creating the new one do the same thing in the end anyway?

java.util.MissingResourceException: Can't find bundle for base name 'property_file name', locale en_US

ResourceBundle doesn't load files? You need to get the files into a resource first. How about just loading into a FileInputStream then a PropertyResourceBundle

   FileInputStream fis = new FileInputStream("skyscrapper.properties");
   resourceBundle = new PropertyResourceBundle(fis);

Or if you need the locale specific code, something like this should work

File file = new File("skyscrapper.properties");
URL[] urls = {file.toURI().toURL()};
ClassLoader loader = new URLClassLoader(urls);
ResourceBundle rb = ResourceBundle.getBundle("skyscrapper", Locale.getDefault(), loader);

Android device does not show up in adb list

Make sure your device is not connected as a media device.

Rails filtering array of objects by attribute value

have you tried eager loading?

@attachments = Job.includes(:attachments).find(1).attachments

SQL injection that gets around mysql_real_escape_string()

Consider the following query:

$iId = mysql_real_escape_string("1 OR 1=1");    
$sSql = "SELECT * FROM table WHERE id = $iId";

mysql_real_escape_string() will not protect you against this. The fact that you use single quotes (' ') around your variables inside your query is what protects you against this. The following is also an option:

$iId = (int)"1 OR 1=1";
$sSql = "SELECT * FROM table WHERE id = $iId";

How can I solve "Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong."?

Nuts. I hit this same error weeks ago, and after a lot of wasted time figured out how to make it work--but I've since forgotten it. (Not much help, other than to say yes, it can be done.)

Have you tried different combinations of brackets, or of with and without brackest? e.g.

EXEC sp_rename 'ENG_TEst.ENG_Test_A/C_TYPE', 'ENG_Test_AC_TYPE', 'COLUMN';
EXEC sp_rename '[ENG_TEst].[ENG_Test_A/C_TYPE]', 'ENG_Test_AC_TYPE', 'COLUMN';
EXEC sp_rename '[ENG_TEst].[ENG_Test_A/C_TYPE]', '[ENG_Test_AC_TYPE]', 'COLUMN';
EXEC sp_rename '[ENG_TEst].ENG_Test_A/C_TYPE', 'ENG_Test_AC_TYPE', 'COLUMN';

If all else fails, there's always

  • Create new table (as "xENG_TEst") with proper names
  • Copy data over from old table
  • Drop old table
  • Rename new table to final name

PHP post_max_size overrides upload_max_filesize

The normal method to send a file upload is POST, thus also post_max_size should be 16 Mb or more.

Incidentally, also memory_limit plays a role. It should be bigger than 16Mb, but since the default value is 128Mb, you won't see this problem. Example php.ini configuration:

post_max_size = 16M
upload_max_filesize = 16M
memory_limit = 128M

Change these value in php.ini if you've access to it, otherwise you can try to change them in an .htaccess file.

php_value upload_max_filesize 16M
php_value post_max_size 16M 

This will work only if the AllowOverride settings permit it. Otherwise, you've to ask to your hosting company.

How to include vars file in a vars file with ansible?

You can put your servers in the default_step group and those vars will apply to it:

# inventory file
[default_step]
prod2
web_v2

Then just move your default_step.yml file to group_vars/default_step.yml.

How to check for a Null value in VB.NET

If you are using a strongly-typed dataset then you should do this:

If Not ediTransactionRow.Ispay_id1Null Then
    'Do processing here
End If

You are getting the error because a strongly-typed data set retrieves the underlying value and exposes the conversion through the property. For instance, here is essentially what is happening:

Public Property pay_Id1 Then
   Get
     return DirectCast(me.GetValue("pay_Id1", short)
   End Get
   'Abbreviated for clarity
End Property

The GetValue method is returning DBNull which cannot be converted to a short.

private final static attribute vs private final attribute

If you mark this variable static then as you know, you would be requiring static methods to again access these values,this will be useful if you already think of using these variables only in static methods. If this is so then this would be the best one.

You can however make the variable now as public since no one can modify it just like "System.out", it again depends upon your intentions and what you want to achieve.

Android SDK location should not contain whitespace, as this cause problems with NDK tools

I just wanted to add a solution for Mac users since this is the top article that comes up for searches related to this issue. If you have macOS 10.13 or later you can make use of APFS Space Sharing.

  • Open Disk Utility
  • Click Partition
  • Click Add Volume -- no need to Partition as we are adding an APFS volume which shares space within the current partition/container)
  • Give the volume a name (without spaces)
  • Click Add
  • You can now mount this drive like any other via Terminal: cd /Volumes/<your_volume_name>
  • Create an empty folder in the new volume -- I called mine sdk
  • You can now select the volume and directory while installing Android Studio

Merge two (or more) lists into one, in C# .NET

Assuming you want a list containing all of the products for the specified category-Ids, you can treat your query as a projection followed by a flattening operation. There's a LINQ operator that does that: SelectMany.

// implicitly List<Product>
var products = new[] { CategoryId1, CategoryId2, CategoryId3 }
                     .SelectMany(id => GetAllProducts(id))
                     .ToList();

In C# 4, you can shorten the SelectMany to: .SelectMany(GetAllProducts)

If you already have lists representing the products for each Id, then what you need is a concatenation, as others point out.

What's the difference between echo, print, and print_r in PHP?

echo

Not having return type

print

Have return type

print_r()

Outputs as formatted,

Stop mouse event propagation

Try this directive

@Directive({
    selector: '[stopPropagation]'
})
export class StopPropagationDirective implements OnInit, OnDestroy {
    @Input()
    private stopPropagation: string | string[];

    get element(): HTMLElement {
        return this.elementRef.nativeElement;
    }

    get events(): string[] {
        if (typeof this.stopPropagation === 'string') {
            return [this.stopPropagation];
        }
        return this.stopPropagation;
    }

    constructor(
        private elementRef: ElementRef
    ) { }

    onEvent = (event: Event) => {
        event.stopPropagation();
    }

    ngOnInit() {
        for (const event of this.events) {
            this.element.addEventListener(event, this.onEvent);
        }
    }

    ngOnDestroy() {
        for (const event of this.events) {
            this.element.removeEventListener(event, this.onEvent);
        }
    }
}

Usage

<input 
    type="text" 
    stopPropagation="input" />

<input 
    type="text" 
    [stopPropagation]="['input', 'click']" />

error MSB6006: "cmd.exe" exited with code 1

I solved this. double click this error leads to behavior.

  1. open .vcxproj file of your project
  2. search for tag
  3. check carefully what's going inside this tag, the path is right? difference between debug and release, and fix it
  4. clean and rebuild

for my case. a miss match of debug and release mod kills my afternoon.

          <Command Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">copy ..\vc2005\%(Filename)%(Extension) ..\..\cvd\
</Command>
      <Command Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">copy ..\vc2005\%(Filename)%(Extension) ..\..\cvd\
</Command>
      <Outputs Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">..\..\cvd\%(Filename)%(Extension);%(Outputs)</Outputs>
      <Outputs Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">..\..\cvd\%(Filename)%(Extension);%(Outputs)</Outputs>
      <Command Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">copy ..\vc2005\%(Filename)%(Extension) ..\..\cvd\
</Command>
      <Command Condition="'$(Configuration)|$(Platform)'=='Release|x64'">copy %(Filename)%(Extension) ..\..\cvd\
</Command>
      <Outputs Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">..\..\cvd\%(Filename)%(Extension);%(Outputs)</Outputs>
      <Outputs Condition="'$(Configuration)|$(Platform)'=='Release|x64'">..\..\cvd\%(Filename)%(Extension);%(Outputs)</Outputs>
    </CustomBuild>

In Swift how to call method with parameters on GCD main thread?

Reload collectionView on Main Thread

DispatchQueue.main.async {
    self.collectionView.reloadData()
}

Where is GACUTIL for .net Framework 4.0 in windows 7?

VS 2012/13 Win 7 64 bit gacutil.exe is located in

C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools

Automatically running a batch file as an administrator

On Windows 7:

  1. Create a shortcut to that batch file

  2. Right click on that shortcut file and choose Properties

  3. Click the Advanced button to find a checkbox for running as administrator

Check the screenshot below

Screenshot

The project description file (.project) for my project is missing

I had the same problem and in my case .project file was also present in the project directory and had correct permissions.

This problem happened to me after I closed and reopened multiple projects quickly one after another and Eclipse tried to rebuild them at the same time.

In my case Eclipse lost .location file in the workspace directory for 2 out of 5 projects: <workspace>/.metadata/.plugins/org.eclipse.core.resources/.projects/<project name>/.location

I've followed instructions on How to get project list if delete .metadata accidentally and imported the project in the workspace manually via File :: Import :: Other :: General :: Existing Projects. After that .location file was created again and Eclipse stopped complaining.

What's the difference between next() and nextLine() methods from Scanner class?

next() can read the input only till the space. It can't read two words separated by a space. Also, next() places the cursor in the same line after reading the input.

nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

For reading the entire line you can use nextLine().

When should I use git pull --rebase?

One practice case is when you are working with Bitbucket PR. There is PR open.

Then you decide to rebase the PR remote branch on the latest Master branch. This will change the commit's ids of your PR.

Then you want to add a new commit to the PR branch.

Since you have rebased the remote branch using GUI first you to sync the local branch on PC with the remote branch.

In this case git pull --rebase works like magic.

After git pull --rebase your remote branch and local branch has same history with same commit ids.

Now you can nicely push a new commit without using force or anything.

Example of a strong and weak entity types

Strong entity

It can exist without any other entity.

Example

Customer(customerid, name, surname)

Weak entity

It depends on a dominant entity, and it cannot exist without a strong entity.

Example

Adress(addressid, adressName, customerid)

Convert double to Int, rounded down

If you explicitly cast double to int, the decimal part will be truncated. For example:

int x = (int) 4.97542;   //gives 4 only
int x = (int) 4.23544;   //gives 4 only

Moreover, you may also use Math.floor() method to round values in case you want double value in return.

How to get pandas.DataFrame columns containing specific dtype

You can also try to get the column names from panda data frame that returns columnn name as well dtype. here i'll read csv file from https://mlearn.ics.uci.edu/databases/autos/imports-85.data but you have define header that contain columns names.

import pandas as pd

url="https://mlearn.ics.uci.edu/databases/autos/imports-85.data"

df=pd.read_csv(url,header = None)

headers=["symboling","normalized-losses","make","fuel-type","aspiration","num-of-doors","body-style",
         "drive-wheels","engine-location","wheel-base","length","width","height","curb-weight","engine-type",
         "num-of-cylinders","engine-size","fuel-system","bore","stroke","compression-ratio","horsepower","peak-rpm"
         ,"city-mpg","highway-mpg","price"]

df.columns=headers

print df.columns

How to Change Font Size in drawString Java

g.setFont(new Font("TimesRoman", Font.PLAIN, fontSize)); 

Where fontSize is a int. The API for drawString states that the x and y parameters are coordinates, and have nothing to do with the size of the text.

CSS - Make divs align horizontally

Float: left, display: inline-block will both fail to align the elements horizontally if they exceed the width of the container.

It's important to note that the container should not wrap if the elements MUST display horizontally: white-space: nowrap

How do I check if file exists in Makefile so I can delete it?

One line solution:

   [ -f ./myfile ] && echo exists

One line solution with error action:

   [ -f ./myfile ] && echo exists || echo not exists

Example used in my make clean directives:

clean:
    @[ -f ./myfile ] && rm myfile || true

And make clean works without error messages!

Programmatically read from STDIN or input file in Perl

Here is how I made a script that could take either command line inputs or have a text file redirected.

if ($#ARGV < 1) {
    @ARGV = ();
    @ARGV = <>;
    chomp(@ARGV);
}


This will reassign the contents of the file to @ARGV, from there you just process @ARGV as if someone was including command line options.

WARNING

If no file is redirected, the program will sit their idle because it is waiting for input from STDIN.

I have not figured out a way to detect if a file is being redirected in yet to eliminate the STDIN issue.

Getting the encoding of a Postgres database

A programmatic solution:

SELECT pg_encoding_to_char(encoding) FROM pg_database WHERE datname = 'yourdb';

How to get CSS to select ID that begins with a string (not in Javascript)?

[id^=product]

^= indicates "starts with". Conversely, $= indicates "ends with".

The symbols are actually borrowed from Regex syntax, where ^ and $ mean "start of string" and "end of string" respectively.

See the specs for full information.

Sending email with gmail smtp with codeigniter email library

It can be this:

If you are using cpanel for your website smtp restrictions are problem and cause this error. SMTP Restrictions

Error while sending an email with CodeIgniter

Interpreting segfault messages

Let's go to the source -- 2.6.32, for example. The message is printed by show_signal_msg() function in arch/x86/mm/fault.c if the show_unhandled_signals sysctl is set.

"error" is not an errno nor a signal number, it's a "page fault error code" -- see definition of enum x86_pf_error_code.

"[7fa44d2f8000+f6f000]" is starting address and size of virtual memory area where offending object was mapped at the time of crash. Value of "ip" should fit in this region. With this info in hand, it should be easy to find offending code in gdb.

GIT clone repo across local file system in windows

Not sure if it was because of my git version (1.7.2) or what, but the approaches listed above using machine name and IP options were not working for me. An additional detail that may/may not be important is that the repo was a bare repo that I had initialized and pushed to from a different machine.

I was trying to clone project1 as advised above with commands like:

$ git clone file:////<IP_ADDRESS>/home/user/git/project1
Cloning into project1...
fatal: '//<IP_ADDRESS>/home/user/git/project1' does not appear to be a git repository
fatal: The remote end hung up unexpectedly

and

$ git clone file:////<MACHINE_NAME>/home/user/git/project1
Cloning into project1...
fatal: '//<MACHINE_NAME>/home/user/git/project1' does not appear to be a git repository
fatal: The remote end hung up unexpectedly

What did work for me was something simpler:

$ git clone ../git/project1
Cloning into project1...
done.

Note - even though the repo being cloned from was bare, this did produce a 'normal' clone with all the actual code/image/resource files that I was hoping for (as opposed to the internals of the git repo).

ffmpeg usage to encode a video to H264 codec format

"C:\Program Files (x86)\ffmpegX86shared\bin\ffmpeg.exe" -y -i "C:\testfile.ts" -an -vcodec libx264 -g 75 -keyint_min 12 -vb 4000k -vprofile high -level 40 -s 1920x1080 -y -threads 0 -r 25 "C:\testfile.h264"

The above worked for me on a Windows machine using a FFmpeg Win32 shared build by Kyle Schwarz. The build was compiled on: Feb 22 2013, at: 01:09:53

Note that -an defines that audio should be skipped.

The simplest way to comma-delimit a list?

public static String join (List<String> list, String separator) {
  String listToString = "";

  if (list == null || list.isEmpty()) {
   return listToString;
  }

  for (String element : list) {
   listToString += element + separator;
  }

  listToString = listToString.substring(0, separator.length());

  return listToString;
}

UICollectionView spacing margins

Set the insetForSectionAt property of the UICollectionViewFlowLayout object attached to your UICollectionView

Make sure to add this protocol

UICollectionViewDelegateFlowLayout

Swift

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets (top: top, left: left, bottom: bottom, right: right)
    }

Objective - C

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(top, left, bottom, right);
}

What is JNDI? What is its basic use? When is it used?

A naming service associates names with objects and finds objects based on their given names.(RMI registry is a good example of a naming service.) JNDI provides a common interface to many existing naming services, such as LDAP, DNS.

Without JNDI, the location or access information of remote resources would have to be hard-coded in applications or made available in a configuration. Maintaining this information is quite tedious and error prone.

Numpy: Checking if a value is NaT

This approach avoids the warnings while preserving the array-oriented evaluation.

import numpy as np
def isnat(x):
    """ 
    datetime64 analog to isnan.
    doesn't yet exist in numpy - other ways give warnings
    and are likely to change.  
    """
    return x.astype('i8') == np.datetime64('NaT').astype('i8')

Print "\n" or newline characters as part of the output on terminal

Another suggestion is to do that way:

string = "abcd\n"
print(string.replace("\n","\\n"))

But be aware that the print function actually print to the terminal the "\n", your terminal interpret that as a newline, that's it. So, my solution just change the newline in \ + n

How can I merge two MySQL tables?

It depends on the semantic of the primary key. If it's just autoincrement, then use something like:

insert into table1 (all columns except pk)
select all_columns_except_pk 
from table2;

If PK means something, you need to find a way to determine which record should have priority. You could create a select query to find duplicates first (see answer by cpitis). Then eliminate the ones you don't want to keep and use the above insert to add records that remain.

Select All as default value for Multivalue parameter

The accepted answer is correct, but not complete. In order for Select All to be the default option, the Available Values dataset must contain at least 2 columns: value and label. They can return the same data, but their names have to be different. The Default Values dataset will then use value column and then Select All will be the default value. If the dataset returns only 1 column, only the last record's value will be selected in the drop down of the parameter.

Calculate days between two Dates in Java 8

Use the DAYS in enum java.time.temporal.ChronoUnit . Below is the Sample Code :

Output : *Number of days between the start date : 2015-03-01 and end date : 2016-03-03 is ==> 368. **Number of days between the start date : 2016-03-03 and end date : 2015-03-01 is ==> -368*

package com.bitiknow.date;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

/**
 * 
 * @author pradeep
 *
 */
public class LocalDateTimeTry {
    public static void main(String[] args) {

        // Date in String format.
        String dateString = "2015-03-01";

        // Converting date to Java8 Local date
        LocalDate startDate = LocalDate.parse(dateString);
        LocalDate endtDate = LocalDate.now();
        // Range = End date - Start date
        Long range = ChronoUnit.DAYS.between(startDate, endtDate);
        System.out.println("Number of days between the start date : " + dateString + " and end date : " + endtDate
                + " is  ==> " + range);

        range = ChronoUnit.DAYS.between(endtDate, startDate);
        System.out.println("Number of days between the start date : " + endtDate + " and end date : " + dateString
                + " is  ==> " + range);

    }

}

Why does ANT tell me that JAVA_HOME is wrong when it is not?

had the same problem;

c:\jb\src\build.xml:191: Unable to find a javac compiler;
com.sun.tools.javac.Main is not on the classpath.
Perhaps JAVA_HOME does not point to the JDK.
It is currently set to "C:\Program Files\Java\jre7"

Total time: 0 seconds

c:\jb\src>echo %JAVA_HOME%
c:\Program Files\Java\jdk1.7.0_13

solution:

path = c:\ant\bin\;%PATH%
path = c:\Program Files\Java\jdk1.7.0_17\bin;%PATH%
set "JAVA_HOME=c:\Program Files\Java\jdk1.7.0_13"

I guess the jdk path instruction alone would do it but I'm to lazy to figure it out above solution is bullet proof. :-)

Also using Windows7

conflicting types for 'outchar'

In C, the order that you define things often matters. Either move the definition of outchar to the top, or provide a prototype at the top, like this:

#include <stdio.h> #include <stdlib.h>  void outchar(char ch);  int main() {     outchar('A');     outchar('B');     outchar('C');     return 0; }  void outchar(char ch) {     printf("%c", ch); } 

Also, you should be specifying the return type of every function. I added that for you.

XAMPP permissions on Mac OS X?

If you are running your page on the new XAMPP-VM version of MacOS you will have to set daemon as user and as group. Here you can find a great step-by-step illustration with screenshots from aXfon on how to do this.

As the htdocs folder under XAMPP-VM will be mounted as external volume, you'll have to do this as root of the mounted volume (root@debian). This can be achieved through the XAMPP-VM GUI: See screenshot.

Once you are running as root of the mounted volume you can as described above change the file permission using:

chown -R daemon:daemon /opt/lampp/htdocs/FOLDER_OF_YOUR_PAGE

Source (w/ step-by-step illustration): aXfon

jQuery .ready in a dynamically inserted iframe

I'm loading the PDF with jQuery ajax into browser cache. Then I create embedded element with data already in browser cache. I guess it will work with iframe too.


var url = "http://example.com/my.pdf";
// show spinner
$.mobile.showPageLoadingMsg('b', note, false);
$.ajax({
    url: url,
    cache: true,
    mimeType: 'application/pdf',
    success: function () {
        // display cached data
        $(scroller).append('<embed type="application/pdf" src="' + url + '" />');
        // hide spinner
        $.mobile.hidePageLoadingMsg();
    }
});

You have to set your http headers correctly as well.


HttpContext.Response.Expires = 1;
HttpContext.Response.Cache.SetNoServerCaching();
HttpContext.Response.Cache.SetAllowResponseInBrowserHistory(false);
HttpContext.Response.CacheControl = "Private";

jquery append external html file into my page

You can use jquery's load function here.

$("#your_element_id").load("file_name.html");

If you need more info, here is the link.

Querying data by joining two tables in two database on different servers

for this simply follow below query

select a.Id,a.type,b.Name,b.City from DatabaseName.dbo.TableName a left join DatabaseName.dbo.TableName b on a.Id=b.Id

Where I wrote databasename, you have to define the name of the database. If you are in same database so you don't need to define the database name but if you are in other database you have to mention database name as path or it will show you error. Hope I made your work easy

Best way to add Activity to an Android project in Eclipse?

I just use the "New Class" dialog in Eclipse and set the base class as Activity. I'm not aware of any other way to do this. What other method would you expect to be available?

Prevent Bootstrap Modal from disappearing when clicking outside or pressing escape?

The following script worked for me:

// prevent event when the modal is about to hide
$('#myModal').on('hide.bs.modal', function (e) {
    e.preventDefault();
    e.stopPropagation();
    return false;
});

Android - running a method periodically using postDelayed() call

Perhaps involve the activity's life-cycle methods to achieve this:

Handler handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      handler.post(sendData);
}

@Override
protected void onDestroy() {
      super.onDestroy();
      handler.removeCallbacks(sendData);
}


private final Runnable sendData = new Runnable(){
    public void run(){
        try {
            //prepare and send the data here..


            handler.postDelayed(this, 1000);    
        }
        catch (Exception e) {
            e.printStackTrace();
        }   
    }
};

In this approach, if you press back-key on your activity or call finish();, it will also stop the postDelayed callings.

MySQL Error 1264: out of range value for column

Work with:

ALTER TABLE `table` CHANGE `cust_fax` `cust_fax` VARCHAR(60) NULL DEFAULT NULL; 

Difference between JOIN and INNER JOIN

Does it differ between different SQL implementations?

Yes, Microsoft Access doesn't allow just join. It requires inner join.

How to parse a string to an int in C++?

I know this is an older question, but I've come across it so many times and, to date, have still not found a nicely templated solution having the following characteristics:

  • Can convert any base (and detect base type)
  • Will detect erroneous data (i.e. ensure the entire string, less leading/trailing whitespace, is consumed by the conversion)
  • Will ensure that, regardless of the type converted to, the range of the string's value is acceptable.

So, here is mine, with a test strap. Because it uses the C functions strtoull/strtoll under the hood, it always converts first to the largest type available. Then, if you are not using the largest type, it will perform additional range checks to verify your type was not over(under)flowed. For this, it is a little less performant than if one properly chose strtol/strtoul. However, it also works for shorts/chars and, to the best of my knowledge, there exists no standard library function that does that, too.

Enjoy; hopefully someone finds it useful.

#include <cstdlib>
#include <cerrno>
#include <limits>
#include <stdexcept>
#include <sstream>

static const int DefaultBase = 10;

template<typename T>
static inline T CstrtoxllWrapper(const char *str, int base = DefaultBase)
{
    while (isspace(*str)) str++; // remove leading spaces; verify there's data
    if (*str == '\0') { throw std::invalid_argument("str; no data"); } // nothing to convert

    // NOTE:  for some reason strtoull allows a negative sign, we don't; if
    //          converting to an unsigned then it must always be positive!
    if (!std::numeric_limits<T>::is_signed && *str == '-')
    { throw std::invalid_argument("str; negative"); }

    // reset errno and call fn (either strtoll or strtoull)
    errno = 0;
    char *ePtr;
    T tmp = std::numeric_limits<T>::is_signed ? strtoll(str, &ePtr, base)
                                              : strtoull(str, &ePtr, base);

    // check for any C errors -- note these are range errors on T, which may
    //   still be out of the range of the actual type we're using; the caller
    //   may need to perform additional range checks.
    if (errno != 0) 
    {
            if (errno == ERANGE) { throw std::range_error("str; out of range"); }
            else if (errno == EINVAL) { throw std::invalid_argument("str; EINVAL"); }
            else { throw std::invalid_argument("str; unknown errno"); }
    }

    // verify everything converted -- extraneous spaces are allowed
    if (ePtr != NULL)
    {
            while (isspace(*ePtr)) ePtr++;
            if (*ePtr != '\0') { throw std::invalid_argument("str; bad data"); }
    }

    return tmp;
}

template<typename T>
T StringToSigned(const char *str, int base = DefaultBase)
{
    static const long long max = std::numeric_limits<T>::max();
    static const long long min = std::numeric_limits<T>::min();

    long long tmp = CstrtoxllWrapper<typeof(tmp)>(str, base); // use largest type

    // final range check -- only needed if not long long type; a smart compiler
    //   should optimize this whole thing out
    if (sizeof(T) == sizeof(tmp)) { return tmp; }

    if (tmp < min || tmp > max)
    {
            std::ostringstream err;
            err << "str; value " << tmp << " out of " << sizeof(T) * 8
                << "-bit signed range (";
            if (sizeof(T) != 1) err << min << ".." << max;
            else err << (int) min << ".." << (int) max;  // don't print garbage chars
            err << ")";
            throw std::range_error(err.str());
    }

    return tmp;
}

template<typename T>
T StringToUnsigned(const char *str, int base = DefaultBase)
{
    static const unsigned long long max = std::numeric_limits<T>::max();

    unsigned long long tmp = CstrtoxllWrapper<typeof(tmp)>(str, base); // use largest type

    // final range check -- only needed if not long long type; a smart compiler
    //   should optimize this whole thing out
    if (sizeof(T) == sizeof(tmp)) { return tmp; }

    if (tmp > max)
    {
            std::ostringstream err;
            err << "str; value " << tmp << " out of " << sizeof(T) * 8
                << "-bit unsigned range (0..";
            if (sizeof(T) != 1) err << max;
            else err << (int) max;  // don't print garbage chars
            err << ")";
            throw std::range_error(err.str());
    }

    return tmp;
}

template<typename T>
inline T
StringToDecimal(const char *str, int base = DefaultBase)
{
    return std::numeric_limits<T>::is_signed ? StringToSigned<T>(str, base)
                                             : StringToUnsigned<T>(str, base);
}

template<typename T>
inline T
StringToDecimal(T &out_convertedVal, const char *str, int base = DefaultBase)
{
    return out_convertedVal = StringToDecimal<T>(str, base);
}

/*============================== [ Test Strap ] ==============================*/ 

#include <inttypes.h>
#include <iostream>

static bool _g_anyFailed = false;

template<typename T>
void TestIt(const char *tName,
            const char *s, int base,
            bool successExpected = false, T expectedValue = 0)
{
    #define FAIL(s) { _g_anyFailed = true; std::cout << s; }

    T x;
    std::cout << "converting<" << tName << ">b:" << base << " [" << s << "]";
    try
    {
            StringToDecimal<T>(x, s, base);
            // get here on success only
            if (!successExpected)
            {
                    FAIL(" -- TEST FAILED; SUCCESS NOT EXPECTED!" << std::endl);
            }
            else
            {
                    std::cout << " -> ";
                    if (sizeof(T) != 1) std::cout << x;
                    else std::cout << (int) x;  // don't print garbage chars
                    if (x != expectedValue)
                    {
                            FAIL("; FAILED (expected value:" << expectedValue << ")!");
                    }
                    std::cout << std::endl;
            }
    }
    catch (std::exception &e)
    {
            if (successExpected)
            {
                    FAIL(   " -- TEST FAILED; EXPECTED SUCCESS!"
                         << " (got:" << e.what() << ")" << std::endl);
            }
            else
            {
                    std::cout << "; expected exception encounterd: [" << e.what() << "]" << std::endl;
            }
    }
}

#define TEST(t, s, ...) \
    TestIt<t>(#t, s, __VA_ARGS__);

int main()
{
    std::cout << "============ variable base tests ============" << std::endl;
    TEST(int, "-0xF", 0, true, -0xF);
    TEST(int, "+0xF", 0, true, 0xF);
    TEST(int, "0xF", 0, true, 0xF);
    TEST(int, "-010", 0, true, -010);
    TEST(int, "+010", 0, true, 010);
    TEST(int, "010", 0, true, 010);
    TEST(int, "-10", 0, true, -10);
    TEST(int, "+10", 0, true, 10);
    TEST(int, "10", 0, true, 10);

    std::cout << "============ base-10 tests ============" << std::endl;
    TEST(int, "-010", 10, true, -10);
    TEST(int, "+010", 10, true, 10);
    TEST(int, "010", 10, true, 10);
    TEST(int, "-10", 10, true, -10);
    TEST(int, "+10", 10, true, 10);
    TEST(int, "10", 10, true, 10);
    TEST(int, "00010", 10, true, 10);

    std::cout << "============ base-8 tests ============" << std::endl;
    TEST(int, "777", 8, true, 0777);
    TEST(int, "-0111 ", 8, true, -0111);
    TEST(int, "+0010 ", 8, true, 010);

    std::cout << "============ base-16 tests ============" << std::endl;
    TEST(int, "DEAD", 16, true, 0xDEAD);
    TEST(int, "-BEEF", 16, true, -0xBEEF);
    TEST(int, "+C30", 16, true, 0xC30);

    std::cout << "============ base-2 tests ============" << std::endl;
    TEST(int, "-10011001", 2, true, -153);
    TEST(int, "10011001", 2, true, 153);

    std::cout << "============ irregular base tests ============" << std::endl;
    TEST(int, "Z", 36, true, 35);
    TEST(int, "ZZTOP", 36, true, 60457993);
    TEST(int, "G", 17, true, 16);
    TEST(int, "H", 17);

    std::cout << "============ space deliminated tests ============" << std::endl;
    TEST(int, "1337    ", 10, true, 1337);
    TEST(int, "   FEAD", 16, true, 0xFEAD);
    TEST(int, "   0711   ", 0, true, 0711);

    std::cout << "============ bad data tests ============" << std::endl;
    TEST(int, "FEAD", 10);
    TEST(int, "1234 asdfklj", 10);
    TEST(int, "-0xF", 10);
    TEST(int, "+0xF", 10);
    TEST(int, "0xF", 10);
    TEST(int, "-F", 10);
    TEST(int, "+F", 10);
    TEST(int, "12.4", 10);
    TEST(int, "ABG", 16);
    TEST(int, "10011002", 2);

    std::cout << "============ int8_t range tests ============" << std::endl;
    TEST(int8_t, "7F", 16, true, std::numeric_limits<int8_t>::max());
    TEST(int8_t, "80", 16);
    TEST(int8_t, "-80", 16, true, std::numeric_limits<int8_t>::min());
    TEST(int8_t, "-81", 16);
    TEST(int8_t, "FF", 16);
    TEST(int8_t, "100", 16);

    std::cout << "============ uint8_t range tests ============" << std::endl;
    TEST(uint8_t, "7F", 16, true, std::numeric_limits<int8_t>::max());
    TEST(uint8_t, "80", 16, true, std::numeric_limits<int8_t>::max()+1);
    TEST(uint8_t, "-80", 16);
    TEST(uint8_t, "-81", 16);
    TEST(uint8_t, "FF", 16, true, std::numeric_limits<uint8_t>::max());
    TEST(uint8_t, "100", 16);

    std::cout << "============ int16_t range tests ============" << std::endl;
    TEST(int16_t, "7FFF", 16, true, std::numeric_limits<int16_t>::max());
    TEST(int16_t, "8000", 16);
    TEST(int16_t, "-8000", 16, true, std::numeric_limits<int16_t>::min());
    TEST(int16_t, "-8001", 16);
    TEST(int16_t, "FFFF", 16);
    TEST(int16_t, "10000", 16);

    std::cout << "============ uint16_t range tests ============" << std::endl;
    TEST(uint16_t, "7FFF", 16, true, std::numeric_limits<int16_t>::max());
    TEST(uint16_t, "8000", 16, true, std::numeric_limits<int16_t>::max()+1);
    TEST(uint16_t, "-8000", 16);
    TEST(uint16_t, "-8001", 16);
    TEST(uint16_t, "FFFF", 16, true, std::numeric_limits<uint16_t>::max());
    TEST(uint16_t, "10000", 16);

    std::cout << "============ int32_t range tests ============" << std::endl;
    TEST(int32_t, "7FFFFFFF", 16, true, std::numeric_limits<int32_t>::max());
    TEST(int32_t, "80000000", 16);
    TEST(int32_t, "-80000000", 16, true, std::numeric_limits<int32_t>::min());
    TEST(int32_t, "-80000001", 16);
    TEST(int32_t, "FFFFFFFF", 16);
    TEST(int32_t, "100000000", 16);

    std::cout << "============ uint32_t range tests ============" << std::endl;
    TEST(uint32_t, "7FFFFFFF", 16, true, std::numeric_limits<int32_t>::max());
    TEST(uint32_t, "80000000", 16, true, std::numeric_limits<int32_t>::max()+1);
    TEST(uint32_t, "-80000000", 16);
    TEST(uint32_t, "-80000001", 16);
    TEST(uint32_t, "FFFFFFFF", 16, true, std::numeric_limits<uint32_t>::max());
    TEST(uint32_t, "100000000", 16);

    std::cout << "============ int64_t range tests ============" << std::endl;
    TEST(int64_t, "7FFFFFFFFFFFFFFF", 16, true, std::numeric_limits<int64_t>::max());
    TEST(int64_t, "8000000000000000", 16);
    TEST(int64_t, "-8000000000000000", 16, true, std::numeric_limits<int64_t>::min());
    TEST(int64_t, "-8000000000000001", 16);
    TEST(int64_t, "FFFFFFFFFFFFFFFF", 16);
    TEST(int64_t, "10000000000000000", 16);

    std::cout << "============ uint64_t range tests ============" << std::endl;
    TEST(uint64_t, "7FFFFFFFFFFFFFFF", 16, true, std::numeric_limits<int64_t>::max());
    TEST(uint64_t, "8000000000000000", 16, true, std::numeric_limits<int64_t>::max()+1);
    TEST(uint64_t, "-8000000000000000", 16);
    TEST(uint64_t, "-8000000000000001", 16);
    TEST(uint64_t, "FFFFFFFFFFFFFFFF", 16, true, std::numeric_limits<uint64_t>::max());
    TEST(uint64_t, "10000000000000000", 16);

    std::cout << std::endl << std::endl
              << (_g_anyFailed ? "!! SOME TESTS FAILED !!" : "ALL TESTS PASSED")
              << std::endl;

    return _g_anyFailed;
}

StringToDecimal is the user-land method; it is overloaded so it can be called either like this:

int a; a = StringToDecimal<int>("100");

or this:

int a; StringToDecimal(a, "100");

I hate repeating the int type, so prefer the latter. This ensures that if the type of 'a' changes one does not get bad results. I wish the compiler could figure it out like:

int a; a = StringToDecimal("100");

...but, C++ does not deduce template return types, so that's the best I can get.

The implementation is pretty simple:

CstrtoxllWrapper wraps both strtoull and strtoll, calling whichever is necessary based on the template type's signed-ness and providing some additional guarantees (e.g. negative input is disallowed if unsigned and it ensures the entire string was converted).

CstrtoxllWrapper is used by StringToSigned and StringToUnsigned with the largest type (long long/unsigned long long) available to the compiler; this allows the maximal conversion to be performed. Then, if it is necessary, StringToSigned/StringToUnsigned performs the final range checks on the underlying type. Finally, the end-point method, StringToDecimal, decides which of the StringTo* template methods to call based on the underlying type's signed-ness.

I think most of the junk can be optimized out by the compiler; just about everything should be compile-time deterministic. Any commentary on this aspect would be interesting to me!

What is the meaning of @_ in Perl?

First hit of a search for perl @_ says this:

@_ is the list of incoming parameters to a sub.

It also has a longer and more detailed explanation of the same.

Wi-Fi Direct and iOS Support

The official list of current iOS Wi-Fi Management APIs

There is no Wi-Fi Direct type of connection available. The primary issue being that Apple does not allow programmatic setting of the Wi-Fi network SSID and password. However, this improves substantially in iOS 11 where you can at least prompt the user to switch to another WiFi network.

QA1942 - iOS Wi-Fi Management APIs

Entitlement option

This technology is useful if you want to provide a list of Wi-Fi networks that a user might want to connect to in a manager type app. It requires that you apply for this entitlement with Apple and the email address is in the documentation.

MFi Program options

These technologies allow the accessory connect to the same network as the iPhone and are not for setting up a peer-to-peer connection.

  • Wireless Accessory Configuration (WAC)
  • HomeKit

Peer-to-peer between Apple devices

These APIs come close to what you want, but they're Apple-to-Apple only.

WiTap Example Code

iOS 11 NEHotspotConfiguration

Brought up at WWDC 2017 Advances in Networking, Part 1 is NEHotspotConfiguration which allows the app to specify and prompt to connect to a specific network.

how to convert a string date into datetime format in python?

The particular format for strptime:

datetime.datetime.strptime(string_date, "%Y-%m-%d %H:%M:%S.%f")
#>>> datetime.datetime(2013, 9, 28, 20, 30, 55, 782000)

How to get value by class name in JavaScript or jquery?

Without jQuery:

textContent:

var text = document.querySelector('.someClassname').textContent;

Markup:

var text = document.querySelector('.someClassname').innerHTML;

Markup including the matched element:

var text = document.querySelector('.someClassname').outerHTML;

though outerHTML may not be supported by all browsers of interest and document.querySelector requires IE 8 or higher.

Get HTML code from website in C#

Here's an example of using the HttpWebRequest class to fetch a URL

private void buttonl_Click(object sender, EventArgs e) 
{ 
    String url = TextBox_url.Text;
    HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url); 
    HttpWebResponse response = (HttpWebResponse) request.GetResponse(); 
    StreamReader sr = new StreamReader(response.GetResponseStream()); 
    richTextBox1.Text = sr.ReadToEnd(); 
    sr.Close(); 
} 

No connection could be made because the target machine actively refused it?

I was facing this issue today. Mine was Asp.Net Core API and it uses Postgresql as the database. We have configured this database as a Docker container. So the first step I did was to check whether I am able to access the database or not. To do that I searched for PgAdmin in the start as I have configured the same. Clicking on the resulted application will redirect you to the http://127.0.0.1:23722/browser/. There you can try access your database on the left menu. For me I was getting an error as in the below image.

enter image description here

Enter the password and try whether you are able to access it or not. For me it was not working. As it is a Docker container, I decided to restart my Docker desktop, to do that right click on the docker icon in the task bar and click restart.

Once after restarting the Docker, I was able to login and see the Database and also the error was gone when I restart the application in Visual Studio.

Hope it helps.

Add a user control to a wpf window

Make sure there is an namespace definition (xmlns) for the namespace your control belong to.

xmlns:myControls="clr-namespace:YourCustomNamespace.Controls;assembly=YourAssemblyName"
<myControls:thecontrol/>

Set a div width, align div center and text align left

Use auto margins.

div {
   margin-left: auto;
   margin-right: auto;
   width: NNNpx;

   /* NOTE: Only works for non-floated block elements */
   display: block;
   float: none;
}

Further reading at SimpleBits CSS Centering 101

How to display pdf in php

Try this below code

<?php
$file = 'dummy.pdf';
$filename = 'dummy.pdf';
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');
@readfile($file);
?>

Demo

Linking to an external URL in Javadoc?

Taken from the javadoc spec

@see <a href="URL#value">label</a> : Adds a link as defined by URL#value. The URL#value is a relative or absolute URL. The Javadoc tool distinguishes this from other cases by looking for a less-than symbol (<) as the first character.

For example : @see <a href="http://www.google.com">Google</a>

SQL Stored Procedure: If variable is not null, update statement

Use a T-SQL IF:

IF @ABC IS NOT NULL AND @ABC != -1
    UPDATE [TABLE_NAME] SET XYZ=@ABC

Take a look at the MSDN docs.

brew install mysql on macOS

TL;DR

MySQL server might not be running after installation with Brew. Try brew services start mysql or just mysql.server start if you don't want MySQL to run as a background service.

Full Story:

I just installed MySQL (stable) 5.7.17 on a new MacBook Pro running Sierra and also got an error when running mysql_secure_installation:

Securing the MySQL server deployment.

Enter password for user root: 
Error: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

Say what?

According to the installation info from Brew, mysql_secure_installation should prompt me to... secure the installation. I figured the MySQL server might not be running and rightly so. Running brew services start mysql and then mysql_secure_installation worked like a charm.

How to auto-generate a C# class file from a JSON string

If you install Web Essentials into Visual studio you can go to Edit => Past special => paste JSON as class.

That is probably the easiest there is.

Web Essentials: http://vswebessentials.com/

How to view the dependency tree of a given npm module?

Here is the unpowerful official command:

npm view <PACKAGE> dependencies

It prints only the direct dependencies, not the whole tree.

How To have Dynamic SQL in MySQL Stored Procedure

I don't believe MySQL supports dynamic sql. You can do "prepared" statements which is similar, but different.

Here is an example:

mysql> PREPARE stmt FROM 
    -> 'select count(*) 
    -> from information_schema.schemata 
    -> where schema_name = ? or schema_name = ?'
;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE stmt 
    -> USING @schema1,@schema2
+----------+
| count(*) |
+----------+
|        2 |
+----------+
1 row in set (0.00 sec)
mysql> DEALLOCATE PREPARE stmt;

The prepared statements are often used to see an execution plan for a given query. Since they are executed with the execute command and the sql can be assigned to a variable you can approximate the some of the same behavior as dynamic sql.

Here is a good link about this:

Don't forget to deallocate the stmt using the last line!

Good Luck!

How does one get started with procedural generation?

the most important thing is to analyze how roads, cities, blocks and buildings are structured. find out what all eg buildings have in common. look at photos, maps, plans and reality. if you do that you will be one step ahead of people who consider city building as a merely computer-technological matter.

next you should develop solutions on how to create that geometry in tiny, distinct steps. you have to define rules that make up a believable city. if you are into 3d modelling you have to rethink a lot of what you have learned so the computer can follow your instructions in any situation.

in order to not loose track you should set up a lot of operators that are only responsible for little parts of the whole process. that makes debugging, expanding and improving your system much easier. in the next step you should link those operators and check the results by changing parameters.

i have seen too many "city generators" that mainly consist of random-shaped boxes with some window textures on them : (

Javascript/DOM: How to remove all events of a DOM object?

Removing all the events on document:

One liner:

for (key in getEventListeners(document)) { getEventListeners(document)[key].forEach(function(c) { c.remove() }) }

Pretty version:

for (key in getEventListeners(document)) {
  getEventListeners(document)[key].forEach(function(c) {
    c.remove()
  })   
}

Android camera android.hardware.Camera deprecated

API Documentation

According to the Android developers guide for android.hardware.Camera, they state:

We recommend using the new android.hardware.camera2 API for new applications.

On the information page about android.hardware.camera2, (linked above), it is stated:

The android.hardware.camera2 package provides an interface to individual camera devices connected to an Android device. It replaces the deprecated Camera class.

The problem

When you check that documentation you'll find that the implementation of these 2 Camera API's are very different.

For example getting camera orientation on android.hardware.camera

@Override
public int getOrientation(final int cameraId) {
    Camera.CameraInfo info = new Camera.CameraInfo();
    Camera.getCameraInfo(cameraId, info);
    return info.orientation;
}

Versus android.hardware.camera2

@Override
public int getOrientation(final int cameraId) {
    try {
        CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
        String[] cameraIds = manager.getCameraIdList();
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraIds[cameraId]);
        return characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
    } catch (CameraAccessException e) {
        // TODO handle error properly or pass it on
        return 0;
    }
}

This makes it hard to switch from one to another and write code that can handle both implementations.

Note that in this single code example I already had to work around the fact that the olde camera API works with int primitives for camera IDs while the new one works with String objects. For this example I quickly fixed that by using the int as an index in the new API. If the camera's returned aren't always in the same order this will already cause issues. Alternative approach is to work with String objects and String representation of the old int cameraIDs which is probably safer.

One away around

Now to work around this huge difference you can implement an interface first and reference that interface in your code.

Here I'll list some code for that interface and the 2 implementations. You can limit the implementation to what you actually use of the camera API to limit the amount of work.

In the next section I'll quickly explain how to load one or another.

The interface wrapping all you need, to limit this example I only have 2 methods here.

public interface CameraSupport {
    CameraSupport open(int cameraId);
    int getOrientation(int cameraId);
}

Now have a class for the old camera hardware api:

@SuppressWarnings("deprecation")
public class CameraOld implements CameraSupport {

    private Camera camera;

    @Override
    public CameraSupport open(final int cameraId) {
        this.camera = Camera.open(cameraId);
        return this;
    }

    @Override
    public int getOrientation(final int cameraId) {
       Camera.CameraInfo info = new Camera.CameraInfo();
       Camera.getCameraInfo(cameraId, info);
       return info.orientation;
    }
}

And another one for the new hardware api:

public class CameraNew implements CameraSupport {

    private CameraDevice camera;
    private CameraManager manager;

    public CameraNew(final Context context) {
        this.manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
    }

    @Override
    public CameraSupport open(final int cameraId) {
        try {
            String[] cameraIds = manager.getCameraIdList();
            manager.openCamera(cameraIds[cameraId], new CameraDevice.StateCallback() {
                @Override
                public void onOpened(CameraDevice camera) {
                    CameraNew.this.camera = camera;
                }

                @Override
                public void onDisconnected(CameraDevice camera) {
                    CameraNew.this.camera = camera;
                    // TODO handle
                }

                @Override
                public void onError(CameraDevice camera, int error) {
                    CameraNew.this.camera = camera;
                    // TODO handle
                }
            }, null);
        } catch (Exception e) {
            // TODO handle
        }
        return this;
    }

    @Override
    public int getOrientation(final int cameraId) {
        try {
            String[] cameraIds = manager.getCameraIdList();
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraIds[cameraId]);
            return characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
        } catch (CameraAccessException e) {
            // TODO handle
            return 0;
        }
    }
}

Loading the proper API

Now to load either your CameraOld or CameraNew class you'll have to check the API level since CameraNew is only available from api level 21.

If you have dependency injection set up already you can do so in your module when providing the CameraSupport implementation. Example:

@Module public class CameraModule {

    @Provides
    CameraSupport provideCameraSupport(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return new CameraNew(context);
        } else {
            return new CameraOld();
        }
    } 
}

If you don't use DI you can just make a utility or use Factory pattern to create the proper one. Important part is that the API level is checked.

How to hide "Showing 1 of N Entries" with the dataTables.js library

Now, this seems to work:

$('#example').DataTable({
  "info": false
});

it hides that div, altogether

C# with MySQL INSERT parameters

Try adjusting the code at "SqlDbType" to match your DB type if necessary and use this code:

comm.Parameters.Add("@person",SqlDbType.VarChar).Value=MyName;

or:

comm.Parameters.AddWithValue("@person", Myname);

That should work but remember with Command.Parameters.Add(), you can define the specific SqlDbType and with Command.Parameters.AddWithValue(), it will try get the SqlDbType based on parameter value implicitly which can break sometimes if it can not implicitly convert the datatype.

Hope this helps.

if else statement in AngularJS templates

Angular itself doesn't provide if/else functionality, but you can get it by including this module:

https://github.com/zachsnow/ng-elif

In its own words, it's just "a simple collection of control flow directives: ng-if, ng-else-if, and ng-else." It's easy and intuitive to use.

Example:

<div ng-if="someCondition">
    ...
</div>
<div ng-else-if="someOtherCondition">
    ...
</div>
<div ng-else>
    ...
</div>

Enum to String C++

enum Enum{ Banana, Orange, Apple } ;
static const char * EnumStrings[] = { "bananas & monkeys", "Round and orange", "APPLE" };

const char * getTextForEnum( int enumVal )
{
  return EnumStrings[enumVal];
}

How do I add a newline to command output in PowerShell?

The option that I tend to use, mostly because it's simple and I don't have to think, is using Write-Output as below. Write-Output will put an EOL marker in the string for you and you can simply output the finished string.

Write-Output $stringThatNeedsEOLMarker | Out-File -FilePath PathToFile -Append

Alternatively, you could also just build the entire string using Write-Output and then push the finished string into Out-File.

How do I use a Boolean in Python?

The boolean builtins are capitalized: True and False.

Note also that you can do checker = bool(some_decision) as a bit of shorthand -- bool will only ever return True or False.

It's good to know for future reference that classes defining __nonzero__ or __len__ will be True or False depending on the result of those functions, but virtually every other object's boolean result will be True (except for the None object, empty sequences, and numeric zeros).

Java - Convert integer to string

Always use either String.valueOf(number) or Integer.toString(number).

Using "" + number is an overhead and does the following:

StringBuilder sb = new StringBuilder();
sb.append("");
sb.append(number);
return sb.toString();

How to run multiple Python versions on Windows

Here's a quick hack:

  1. Go to the directory of the version of python you want to run
  2. Right click on python.exe
  3. Select 'Create Shortcut'
  4. Give that shortcut a name to call by( I use p27, p33 etc.)
  5. Move that shortcut to your home directory(C:\Users\Your name)
  6. Open a command prompt and enter name_of_your_shortcut.lnk(I use p27.lnk)

Get total size of file in bytes

public static void main(String[] args) {
        try {
            File file = new File("test.txt");
            System.out.println(file.length());
        } catch (Exception e) {
        }
    }

Generate SQL Create Scripts for existing tables with Query

Possible this be helpful for you. This script generate indexes, FK's, PK and common structure for any table.

For example -

DDL:

CREATE TABLE [dbo].[WorkOut](
    [WorkOutID] [bigint] IDENTITY(1,1) NOT NULL,
    [TimeSheetDate] [datetime] NOT NULL,
    [DateOut] [datetime] NOT NULL,
    [EmployeeID] [int] NOT NULL,
    [IsMainWorkPlace] [bit] NOT NULL,
    [DepartmentUID] [uniqueidentifier] NOT NULL,
    [WorkPlaceUID] [uniqueidentifier] NULL,
    [TeamUID] [uniqueidentifier] NULL,
    [WorkShiftCD] [nvarchar](10) NULL,
    [WorkHours] [real] NULL,
    [AbsenceCode] [varchar](25) NULL,
    [PaymentType] [char](2) NULL,
    [CategoryID] [int] NULL,
    [Year]  AS (datepart(year,[TimeSheetDate])),
 CONSTRAINT [PK_WorkOut] PRIMARY KEY CLUSTERED 
(
    [WorkOutID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

ALTER TABLE [dbo].[WorkOut] ADD  
CONSTRAINT [DF__WorkOut__IsMainW__2C1E8537]  DEFAULT ((1)) FOR [IsMainWorkPlace]

ALTER TABLE [dbo].[WorkOut]  WITH CHECK ADD  CONSTRAINT [FK_WorkOut_Employee_EmployeeID] FOREIGN KEY([EmployeeID])
REFERENCES [dbo].[Employee] ([EmployeeID])

ALTER TABLE [dbo].[WorkOut] CHECK CONSTRAINT [FK_WorkOut_Employee_EmployeeID]

Query:

DECLARE @table_name SYSNAME
SELECT @table_name = 'dbo.WorkOut'

DECLARE 
      @object_name SYSNAME
    , @object_id INT

SELECT 
      @object_name = '[' + s.name + '].[' + o.name + ']'
    , @object_id = o.[object_id]
FROM sys.objects o WITH (NOWAIT)
JOIN sys.schemas s WITH (NOWAIT) ON o.[schema_id] = s.[schema_id]
WHERE s.name + '.' + o.name = @table_name
    AND o.[type] = 'U'
    AND o.is_ms_shipped = 0

DECLARE @SQL NVARCHAR(MAX) = ''

;WITH index_column AS 
(
    SELECT 
          ic.[object_id]
        , ic.index_id
        , ic.is_descending_key
        , ic.is_included_column
        , c.name
    FROM sys.index_columns ic WITH (NOWAIT)
    JOIN sys.columns c WITH (NOWAIT) ON ic.[object_id] = c.[object_id] AND ic.column_id = c.column_id
    WHERE ic.[object_id] = @object_id
),
fk_columns AS 
(
     SELECT 
          k.constraint_object_id
        , cname = c.name
        , rcname = rc.name
    FROM sys.foreign_key_columns k WITH (NOWAIT)
    JOIN sys.columns rc WITH (NOWAIT) ON rc.[object_id] = k.referenced_object_id AND rc.column_id = k.referenced_column_id 
    JOIN sys.columns c WITH (NOWAIT) ON c.[object_id] = k.parent_object_id AND c.column_id = k.parent_column_id
    WHERE k.parent_object_id = @object_id
)
SELECT @SQL = 'CREATE TABLE ' + @object_name + CHAR(13) + '(' + CHAR(13) + STUFF((
    SELECT CHAR(9) + ', [' + c.name + '] ' + 
        CASE WHEN c.is_computed = 1
            THEN 'AS ' + cc.[definition] 
            ELSE UPPER(tp.name) + 
                CASE WHEN tp.name IN ('varchar', 'char', 'varbinary', 'binary', 'text')
                       THEN '(' + CASE WHEN c.max_length = -1 THEN 'MAX' ELSE CAST(c.max_length AS VARCHAR(5)) END + ')'
                     WHEN tp.name IN ('nvarchar', 'nchar', 'ntext')
                       THEN '(' + CASE WHEN c.max_length = -1 THEN 'MAX' ELSE CAST(c.max_length / 2 AS VARCHAR(5)) END + ')'
                     WHEN tp.name IN ('datetime2', 'time2', 'datetimeoffset') 
                       THEN '(' + CAST(c.scale AS VARCHAR(5)) + ')'
                     WHEN tp.name = 'decimal' 
                       THEN '(' + CAST(c.[precision] AS VARCHAR(5)) + ',' + CAST(c.scale AS VARCHAR(5)) + ')'
                    ELSE ''
                END +
                CASE WHEN c.collation_name IS NOT NULL THEN ' COLLATE ' + c.collation_name ELSE '' END +
                CASE WHEN c.is_nullable = 1 THEN ' NULL' ELSE ' NOT NULL' END +
                CASE WHEN dc.[definition] IS NOT NULL THEN ' DEFAULT' + dc.[definition] ELSE '' END + 
                CASE WHEN ic.is_identity = 1 THEN ' IDENTITY(' + CAST(ISNULL(ic.seed_value, '0') AS CHAR(1)) + ',' + CAST(ISNULL(ic.increment_value, '1') AS CHAR(1)) + ')' ELSE '' END 
        END + CHAR(13)
    FROM sys.columns c WITH (NOWAIT)
    JOIN sys.types tp WITH (NOWAIT) ON c.user_type_id = tp.user_type_id
    LEFT JOIN sys.computed_columns cc WITH (NOWAIT) ON c.[object_id] = cc.[object_id] AND c.column_id = cc.column_id
    LEFT JOIN sys.default_constraints dc WITH (NOWAIT) ON c.default_object_id != 0 AND c.[object_id] = dc.parent_object_id AND c.column_id = dc.parent_column_id
    LEFT JOIN sys.identity_columns ic WITH (NOWAIT) ON c.is_identity = 1 AND c.[object_id] = ic.[object_id] AND c.column_id = ic.column_id
    WHERE c.[object_id] = @object_id
    ORDER BY c.column_id
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, CHAR(9) + ' ')
    + ISNULL((SELECT CHAR(9) + ', CONSTRAINT [' + k.name + '] PRIMARY KEY (' + 
                    (SELECT STUFF((
                         SELECT ', [' + c.name + '] ' + CASE WHEN ic.is_descending_key = 1 THEN 'DESC' ELSE 'ASC' END
                         FROM sys.index_columns ic WITH (NOWAIT)
                         JOIN sys.columns c WITH (NOWAIT) ON c.[object_id] = ic.[object_id] AND c.column_id = ic.column_id
                         WHERE ic.is_included_column = 0
                             AND ic.[object_id] = k.parent_object_id 
                             AND ic.index_id = k.unique_index_id     
                         FOR XML PATH(N''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, ''))
            + ')' + CHAR(13)
            FROM sys.key_constraints k WITH (NOWAIT)
            WHERE k.parent_object_id = @object_id 
                AND k.[type] = 'PK'), '') + ')'  + CHAR(13)
    + ISNULL((SELECT (
        SELECT CHAR(13) +
             'ALTER TABLE ' + @object_name + ' WITH' 
            + CASE WHEN fk.is_not_trusted = 1 
                THEN ' NOCHECK' 
                ELSE ' CHECK' 
              END + 
              ' ADD CONSTRAINT [' + fk.name  + '] FOREIGN KEY(' 
              + STUFF((
                SELECT ', [' + k.cname + ']'
                FROM fk_columns k
                WHERE k.constraint_object_id = fk.[object_id]
                FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
               + ')' +
              ' REFERENCES [' + SCHEMA_NAME(ro.[schema_id]) + '].[' + ro.name + '] ('
              + STUFF((
                SELECT ', [' + k.rcname + ']'
                FROM fk_columns k
                WHERE k.constraint_object_id = fk.[object_id]
                FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
               + ')'
            + CASE 
                WHEN fk.delete_referential_action = 1 THEN ' ON DELETE CASCADE' 
                WHEN fk.delete_referential_action = 2 THEN ' ON DELETE SET NULL'
                WHEN fk.delete_referential_action = 3 THEN ' ON DELETE SET DEFAULT' 
                ELSE '' 
              END
            + CASE 
                WHEN fk.update_referential_action = 1 THEN ' ON UPDATE CASCADE'
                WHEN fk.update_referential_action = 2 THEN ' ON UPDATE SET NULL'
                WHEN fk.update_referential_action = 3 THEN ' ON UPDATE SET DEFAULT'  
                ELSE '' 
              END 
            + CHAR(13) + 'ALTER TABLE ' + @object_name + ' CHECK CONSTRAINT [' + fk.name  + ']' + CHAR(13)
        FROM sys.foreign_keys fk WITH (NOWAIT)
        JOIN sys.objects ro WITH (NOWAIT) ON ro.[object_id] = fk.referenced_object_id
        WHERE fk.parent_object_id = @object_id
        FOR XML PATH(N''), TYPE).value('.', 'NVARCHAR(MAX)')), '')
    + ISNULL(((SELECT
         CHAR(13) + 'CREATE' + CASE WHEN i.is_unique = 1 THEN ' UNIQUE' ELSE '' END 
                + ' NONCLUSTERED INDEX [' + i.name + '] ON ' + @object_name + ' (' +
                STUFF((
                SELECT ', [' + c.name + ']' + CASE WHEN c.is_descending_key = 1 THEN ' DESC' ELSE ' ASC' END
                FROM index_column c
                WHERE c.is_included_column = 0
                    AND c.index_id = i.index_id
                FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') + ')'  
                + ISNULL(CHAR(13) + 'INCLUDE (' + 
                    STUFF((
                    SELECT ', [' + c.name + ']'
                    FROM index_column c
                    WHERE c.is_included_column = 1
                        AND c.index_id = i.index_id
                    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') + ')', '')  + CHAR(13)
        FROM sys.indexes i WITH (NOWAIT)
        WHERE i.[object_id] = @object_id
            AND i.is_primary_key = 0
            AND i.[type] = 2
        FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)')
    ), '')

PRINT @SQL
--EXEC sys.sp_executesql @SQL

Output:

CREATE TABLE [dbo].[WorkOut]
(
      [WorkOutID] BIGINT NOT NULL IDENTITY(1,1)
    , [TimeSheetDate] DATETIME NOT NULL
    , [DateOut] DATETIME NOT NULL
    , [EmployeeID] INT NOT NULL
    , [IsMainWorkPlace] BIT NOT NULL DEFAULT((1))
    , [DepartmentUID] UNIQUEIDENTIFIER NOT NULL
    , [WorkPlaceUID] UNIQUEIDENTIFIER NULL
    , [TeamUID] UNIQUEIDENTIFIER NULL
    , [WorkShiftCD] NVARCHAR(10) COLLATE Cyrillic_General_CI_AS NULL
    , [WorkHours] REAL NULL
    , [AbsenceCode] VARCHAR(25) COLLATE Cyrillic_General_CI_AS NULL
    , [PaymentType] CHAR(2) COLLATE Cyrillic_General_CI_AS NULL
    , [CategoryID] INT NULL
    , [Year] AS (datepart(year,[TimeSheetDate]))
    , CONSTRAINT [PK_WorkOut] PRIMARY KEY ([WorkOutID] ASC)
)

ALTER TABLE [dbo].[WorkOut] WITH CHECK ADD CONSTRAINT [FK_WorkOut_Employee_EmployeeID] FOREIGN KEY([EmployeeID]) REFERENCES [dbo].[Employee] ([EmployeeID])
ALTER TABLE [dbo].[WorkOut] CHECK CONSTRAINT [FK_WorkOut_Employee_EmployeeID]

CREATE NONCLUSTERED INDEX [IX_WorkOut_WorkShiftCD_AbsenceCode] ON [dbo].[WorkOut] ([WorkShiftCD] ASC, [AbsenceCode] ASC)
INCLUDE ([WorkOutID], [WorkHours])

Also check this article -

How to Generate a CREATE TABLE Script For an Existing Table: Part 1

Replace all 0 values to NA

#Sample data
set.seed(1)
dat <- data.frame(x = sample(0:2, 5, TRUE), y = sample(0:2, 5, TRUE))
#-----
  x y
1 0 2
2 1 2
3 1 1
4 2 1
5 0 0

#replace zeros with NA
dat[dat==0] <- NA
#-----
   x  y
1 NA  2
2  1  2
3  1  1
4  2  1
5 NA NA

AngularJS: ng-repeat list is not updated when a model element is spliced from the model array

If you add a $scope.$apply(); right after $scope.pluginsDisplayed.splice(index,1); then it works.

I am not sure why this is happening, but basically when AngularJS doesn't know that the $scope has changed, it requires to call $apply manually. I am also new to AngularJS so cannot explain this better. I need too look more into it.

I found this awesome article that explains it quite properly. Note: I think it might be better to use ng-click (docs) rather than binding to "mousedown". I wrote a simple app here (http://avinash.me/losh, source http://github.com/hardfire/losh) based on AngularJS. It is not very clean, but it might be of help.

WebApi's {"message":"an error has occurred"} on IIS7, not in IIS Express

I had a similar problem when posting to the WebAPI endpoint. By turning the CustomErrors=Off, i was able to see the actual error which is one of the dlls was missing.

Why is Visual Studio 2010 not able to find/open PDB files?

I'm having the same warnings. I'm not sure it's a matter of 32 vs 64 bits. Just loaded the new symbols and some problems were solved, but the ones regarding OpenCV still persist. This is an extract of the output with solved vs unsolved issue:

'OpenCV_helloworld.exe': Loaded 'C:\OpenCV2.2\bin\opencv_imgproc220d.dll', Cannot find or open the PDB file

'OpenCV_helloworld.exe': Loaded 'C:\WINDOWS\system32\imm32.dll', Symbols loaded (source information stripped).

The code is exiting 0 in case someone will ask.

The program '[4424] OpenCV_helloworld.exe: Native' has exited with code 0 (0x0).

Sending SOAP request using Python Requests

It is indeed possible.

Here is an example calling the Weather SOAP Service using plain requests lib:

import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
         <SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
            <SOAP-ENV:Header/>
              <ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
         </SOAP-ENV:Envelope>"""

response = requests.post(url,data=body,headers=headers)
print response.content

Some notes:

  • The headers are important. Most SOAP requests will not work without the correct headers. application/soap+xml is probably the more correct header to use (but the weatherservice prefers text/xml
  • This will return the response as a string of xml - you would then need to parse that xml.
  • For simplicity I have included the request as plain text. But best practise would be to store this as a template, then you can load it using jinja2 (for example) - and also pass in variables.

For example:

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()

Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).

You can do the above with suds like so:

from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service

result = client.service.GetWeatherInformation() 
print result 

Note: when using suds, you will almost always end up needing to use the doctor!

Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:

sudo tcpdump -As 0 

This can be helpful for inspecting the requests that actually go over the wire.

The above two code snippets are also available as gists:

Creating an XmlNode/XmlElement in C# without an XmlDocument?

You could return an XmlDocument for the ToXML method in your class, then when you are going to add the Element with the result document just use something like:

XmlDocument returnedDocument = Your_Class.ToXML();

XmlDocument finalDocument = new XmlDocument();
XmlElement createdElement = finalDocument.CreateElement("Desired_Element_Name");
createdElement.InnerXML = docResult.InnerXML;
finalDocument.AppendChild(createdElement);

That way the entire value for "Desired_Element_Name" on your result XmlDocument will be the entire content of the returned Document.

I hope this helps.

Get list of passed arguments in Windows batch script (.bat)

dancavallaro has it right, %* for all command line parameters (excluding the script name itself). You might also find these useful:

%0 - the command used to call the batch file (could be foo, ..\foo, c:\bats\foo.bat, etc.)
%1 is the first command line parameter,
%2 is the second command line parameter,
and so on till %9 (and SHIFT can be used for those after the 9th).

%~nx0 - the actual name of the batch file, regardless of calling method (some-batch.bat)
%~dp0 - drive and path to the script (d:\scripts)
%~dpnx0 - is the fully qualified path name of the script (d:\scripts\some-batch.bat)

More info examples at https://www.ss64.com/nt/syntax-args.html and https://www.robvanderwoude.com/parameters.html

error C2065: 'cout' : undeclared identifier

I ran across this error after just having installed vs 2010 and just trying to get a nearly identical program to work.

I've done vanilla C coding on unix-style boxes before, decided I'd play with this a bit myself.

The first program I tried was:

#include "stdafx.h"


int _tmain(int argc, _TCHAR* argv[])
{
    cout << "Hello World!";
    return 0;
}

The big thing to notice here... if you've EVER done any C coding,

int _tmain(int argc, _TCHAR* argv[])

Looks weird. it should be:

int main( int argc, char ** argv )

In my case I just changed the program to:

#include <iostream>
using namespace std;

int main()
{
     cout << "Hello world from  VS 2010!\n";
     return 0;
}

And it worked fine.

Note: Use CTRL + F5 so that the console window sticks around so you can see the results.

Delete commit on gitlab

We've had similar problem and it was not enough to only remove commit and force push to GitLab.
It was still available in GitLab interface using url:

https://gitlab.example.com/<group>/<project>/commit/<commit hash>

We've had to remove project from GitLab and recreate it to get rid of this commit in GitLab UI.

Binding value to style

Turns out the binding of style to a string doesn't work. The solution would be to bind the background of the style.

 <div class="circle" [style.background]="color">

Convert XML to JSON (and back) using Javascript

You can also use txml. It can parse into a DOM made of simple objects and stringify. In the result, the content will be trimmed. So formating of the original with whitespaces will be lost. But this could be used very good to minify HTML.

const xml = require('txml');
const data = `
<tag>tag content</tag>
<tag2>another content</tag2>
<tag3>
  <insideTag>inside content</insideTag>
  <emptyTag />
</tag3>`;

const dom = xml(data); // the dom can be JSON.stringified

xml.stringify(dom); // this will return the dom into an xml-string

Disclaimer: I am the author of txml, the fastest xml parser in javascript.

Attempted to read or write protected memory

For VS 2013, .NET Framework 4.5.1 also has a AccessViolationException bug (KB2915689) when dealing with SQL Server / TCP Sockets. Upgrading to .NET Framework 4.5.2 corrects this problem.

Reported VS.NET AccessViolationException

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

How to create cross-domain request?

For me it was another problem. This might be trivial for some, but it took me a while to figure out. So this answer might be helpfull to some.

I had my API_BASE_URL set to localhost:58577. The coin dropped after reading the error message for the millionth time. The problem is in the part where it says that it only supports HTTP and some other protocols. I had to change the API_BASE_URL so that it includes the protocol. So changing API_BASE_URL to http://localhost:58577 it worked perfectly.

How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode?

I've been trying to deploy a simple Angular 7 application, to an Azure Web App. Everything worked fine, until the point where you refreshed the page. Doing so, was presenting me with an 500 error - moved content. I've read both on the Angular docs and in around a good few forums, that I need to add a web.config file to my deployed solution and make sure the rewrite rule fallback to the index.html file. After hours of frustration and trial and error tests, I've found the error was quite simple: adding a tag around my file markup.

How to make a div with a circular shape?

Use a border-radius property of 50%.

So for example:

.example-div {

    border-radius: 50%

}

Converting NSData to NSString in Objective c

-[NSString initWithData:encoding] is your friend but only when you use a proper encoding.

MYSQL into outfile "access denied" - but my user has "ALL" access.. and the folder is CHMOD 777

Try executing this SQL command:

> grant all privileges 
  on YOUR_DATABASE.* 
  to 'asdfsdf'@'localhost' 
  identified by 'your_password';
> flush privileges; 

It seems that you are having issues with connecting to the database and not writing to the folder you’re mentioning.

Also, make sure you have granted FILE to user 'asdfsdf'@'localhost'.

> GRANT FILE ON *.* TO 'asdfsdf'@'localhost';

std::string to float or double

Yes, with a lexical cast. Use a stringstream and the << operator, or use Boost, they've already implemented it.

Your own version could look like:

template<typename to, typename from>to lexical_cast(from const &x) {
  std::stringstream os;
  to ret;

  os << x;
  os >> ret;

  return ret;  
}

Angular: Can't find Promise, Map, Set and Iterator

Updated as of angular-2.0.0-rc.4

TLDR;

  1. Transpile to es6

    • error goes away (w/ some gotchas).
  2. Transpile to es5

    • install typings
    • install the es6 shim
    • make sure it compiles with your code.
    • error goes away.

For the readers:

Option 1: Transpile to es6 or es2015

tsconfig.json:

{
  "compilerOptions": {
    "target": "es6",
    "module": "system",
    "moduleResolution": "node",
     ...
  },
"exclude": [
    "node_modules",
    "jspm_packages"
  ]
}

Keep in mind uglifyjs does not support es6 at the moment. This could affect you making production bundles.

Option 2: Transpile to es5, install typings, and then install the es6-shim:

tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
     ...
  },
  "exclude": [
    "node_modules",
    "jspm_packages"
  ]
}

Install typings, then install es6-shim:

npm install typings --saveDev
typings install dt~es6-shim --global --save

If you go this route, you need to make sure that the typescript compiler can find the .d.ts file.

You have two options:

a. Make sure your tsconfig.json is at the same level as the typings folder.

b. Include a reference in your main.ts file where your angular2 application is bootstrapped.

Option A: Make sure your tsconfig.json is at the same level as the typings folder.

Note: DO NOT use the exclude flag to exclude typings folder.

project
|-- src
|-- node_modules
|-- package.json
|-- typings
|-- tsconfig.json

Option B: Reference in main file before bootstrap (Don't do this):

As shown in other answers, this file is no longer included by Angular

main.ts:

/// <reference path="../../typings/globals/es6-shim/index.d.ts" />

Java Inheritance - calling superclass method

You can't call alpha's alphaMethod1() by using beta's object But you have two solutions:

solution 1: call alpha's alphaMethod1() from beta's alphaMethod1()

class Beta extends Alpha
{
  public void alphaMethod1()
  {
    super.alphaMethod1();
  }
}

or from any other method of Beta like:

class Beta extends Alpha
{
  public void foo()
  {
     super.alphaMethod1();
  }
}

class Test extends Beta 
{
   public static void main(String[] args)
   {
      Beta beta = new Beta();
      beta.foo();
   }
}

solution 2: create alpha's object and call alpha's alphaMethod1()

class Test extends Beta
{
   public static void main(String[] args)
   {
      Alpha alpha = new Alpha();
      alpha.alphaMethod1();
   }
}

How to check if a map contains a key in Go?

Searched on the go-nuts email list and found a solution posted by Peter Froehlich on 11/15/2009.

package main

import "fmt"

func main() {
        dict := map[string]int {"foo" : 1, "bar" : 2}
        value, ok := dict["baz"]
        if ok {
                fmt.Println("value: ", value)
        } else {
                fmt.Println("key not found")
        }
}

Or, more compactly,

if value, ok := dict["baz"]; ok {
    fmt.Println("value: ", value)
} else {
    fmt.Println("key not found")
}

Note, using this form of the if statement, the value and ok variables are only visible inside the if conditions.

bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library?

I am using Python 3.6 and I had the same original error in this post. After I ran the command:

python3 -m pip install lxml

it resolved my problem

how to remove "," from a string in javascript

Use String.replace(), e.g.

var str = "a,d,k";
str = str.replace( /,/g, "" );

Note the g (global) flag on the regular expression, which matches all instances of ",".

Download a single folder or directory from a GitHub repo

Nothing wrong with other answers but I just thought I'd share step-by-step instructions for those wandering through this process for the first time.

How to download a single folder from a github repository (Mac OS X):

~ To open Terminal just click spotlight and type terminal then hit enter

  1. On a Mac you likely already have SVN (to test just open terminal and type "svn" or "which svn" ~ without the quote marks)
  2. On Github: Locate the Github path to your git folder (not the repo) by clicking the specific folder name within a repo
  3. Copy the path from the address bar of the browser
  4. Open Terminal and type: svn export
  5. Next paste in the address (eg.): https://github.com/mingsai/Sample-Code/tree/master/HeadsUpUI
  6. Replace the words: tree/master
  7. with the word: trunk
  8. Type in the destination folder for the files (in this example, I store the target folder inside of the Downloads folder for the current user)
  9. Here space is just the spacebar not the word (space) ~/Downloads/HeadsUpUI
  10. The final terminal command shows the full command to download the folder (compare the address to step 5) svn export https://github.com/mingsai/Sample-Code/trunk/HeadsUpUI ~/Downloads/HeadsUpUI

BTW - If you are on Windows or some other platform you can find a binary download of subversion (svn) at http://subversion.apache.org

~ If you want to checkout the folder rather than simply download it try using the svn help (tldr: replace export with checkout)

Update

Regarding the comment on resuming an interrupted download/checkout. I would try running svn cleanup followed by svn update. Please search SO for additional options.

What does getActivity() mean?

I to had a similar doubt what I got to know was getActivity() returns the Activity to which the fragment is associated.

The getActivity() method is used generally in static fragment as the associated activity will not be static and non static member cannot be used in static member.

I used <code>getActivity()</code> here to get non-static activity to which the the placeholder fragment is associated.

Android Closing Activity Programmatically

you can use this.finish() if you want to close current activity.

this.finish()

Choosing the default value of an Enum type without having to change values

You can't, but if you want, you can do some trick. :)

    public struct Orientation
    {
        ...
        public static Orientation None = -1;
        public static Orientation North = 0;
        public static Orientation East = 1;
        public static Orientation South = 2;
        public static Orientation West = 3;
    }

usage of this struct as simple enum.
where you can create p.a == Orientation.East (or any value that you want) by default
to use the trick itself, you need to convert from int by code.
there the implementation:

        #region ConvertingToEnum
        private int val;
        static Dictionary<int, string> dict = null;

        public Orientation(int val)
        {
            this.val = val;
        }

        public static implicit operator Orientation(int value)
        {
            return new Orientation(value - 1);
        }

        public static bool operator ==(Orientation a, Orientation b)
        {
            return a.val == b.val;
        }

        public static bool operator !=(Orientation a, Orientation b)
        {
            return a.val != b.val;
        }

        public override string ToString()
        {
            if (dict == null)
                InitializeDict();
            if (dict.ContainsKey(val))
                return dict[val];
            return val.ToString();
        }

        private void InitializeDict()
        {
            dict = new Dictionary<int, string>();
            foreach (var fields in GetType().GetFields(BindingFlags.Public | BindingFlags.Static))
            {
                dict.Add(((Orientation)fields.GetValue(null)).val, fields.Name);
            }
        } 
        #endregion

How to loop backwards in python?

To reverse a string without using reversed or [::-1], try something like:

def reverse(text):
    # Container for reversed string
    txet=""

    # store the length of the string to be reversed
    # account for indexes starting at 0
    length = len(text)-1

    # loop through the string in reverse and append each character
    # deprecate the length index
    while length>=0:
        txet += "%s"%text[length]
        length-=1
    return txet

How to hide/show more text within a certain length (like youtube)

For those who just want a simple Bootstrap solution.

    <style>
     .collapse.in { display: inline !important; }
    </style>

    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the
    <span class="collapse" id="more">
      1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
    </span>
    <span><a href="#more" data-toggle="collapse">... <i class="fa fa-caret-down"></i></span>

Here's a CodePen example.

Remember to include jquery and bootstrap.min.js in your header.

If you aren't using fontawesome icons, change <i class="fa fa-caret-down"></i> to any icon of your choice.

Serializing enums with Jackson

An easy way to serialize Enum is using @JsonFormat annotation. @JsonFormat can configure the serialization of a Enum in three ways.

@JsonFormat.Shape.STRING
public Enum OrderType {...}

uses OrderType::name as the serialization method. Serialization of OrderType.TypeA is “TYPEA”

@JsonFormat.Shape.NUMBER
Public Enum OrderTYpe{...}

uses OrderType::ordinal as the serialization method. Serialization of OrderType.TypeA is 1

@JsonFormat.Shape.OBJECT
Public Enum OrderType{...}

treats OrderType as a POJO. Serialization of OrderType.TypeA is {"id":1,"name":"Type A"}

JsonFormat.Shape.OBJECT is what you need in your case.

A little more complicated way is your solution, specifying a serializer for the Enum.

Check out this reference: https://fasterxml.github.io/jackson-annotations/javadoc/2.2.0/com/fasterxml/jackson/annotation/JsonFormat.html

How to Select Every Row Where Column Value is NOT Distinct

select CustomerName,count(1) from Customers group by CustomerName having count(1) > 1

UnicodeEncodeError: 'ascii' codec can't encode character at special name

You really want to do this

flog.write("\nCompany Name: "+ pCompanyName.encode('utf-8'))

This is the "encode late" strategy described in this unicode presentation (slides 32 through 35).

Is there an equivalent to background-size: cover and contain for image elements?

What you could do is use the 'style' attribute to add the background image to the element, that way you will still be calling the image in the HTML but you will still be able to use the background-size: cover css behaviour:

HTML:

    <div class="image-div" style="background-image:url(yourimage.jpg)">
    </div>

CSS:

    .image-div{
    background-size: cover;
    }

This is how I add the background-size: cover behaviour to elements that I need to dynamically load into HTML. You can then use awesome css classes like background-position: center. boom

application/x-www-form-urlencoded or multipart/form-data?

Just a little hint from my side for uploading HTML5 canvas image data:

I am working on a project for a print-shop and had some problems due to uploading images to the server that came from an HTML5 canvas element. I was struggling for at least an hour and I did not get it to save the image correctly on my server.

Once I set the contentType option of my jQuery ajax call to application/x-www-form-urlencoded everything went the right way and the base64-encoded data was interpreted correctly and successfully saved as an image.


Maybe that helps someone!

Using textures in THREE.js

In version r82 of Three.js TextureLoader is the object to use for loading a texture.

Loading one texture (source code, demo)

Extract (test.js):

var scene = new THREE.Scene();
var ratio = window.innerWidth / window.innerHeight;
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight,
  0.1, 50);

var renderer = ...

[...]

/**
 * Will be called when load completes.
 * The argument will be the loaded texture.
 */
var onLoad = function (texture) {
  var objGeometry = new THREE.BoxGeometry(20, 20, 20);
  var objMaterial = new THREE.MeshPhongMaterial({
    map: texture,
    shading: THREE.FlatShading
  });

  var mesh = new THREE.Mesh(objGeometry, objMaterial);

  scene.add(mesh);

  var render = function () {
    requestAnimationFrame(render);

    mesh.rotation.x += 0.010;
    mesh.rotation.y += 0.010;

    renderer.render(scene, camera);
  };

  render();
}

// Function called when download progresses
var onProgress = function (xhr) {
  console.log((xhr.loaded / xhr.total * 100) + '% loaded');
};

// Function called when download errors
var onError = function (xhr) {
  console.log('An error happened');
};

var loader = new THREE.TextureLoader();
loader.load('texture.jpg', onLoad, onProgress, onError);

Loading multiple textures (source code, demo)

In this example the textures are loaded inside the constructor of the mesh, multiple texture are loaded using Promises.

Extract (Globe.js):

Create a new container using Object3D for having two meshes in the same container:

var Globe = function (radius, segments) {

  THREE.Object3D.call(this);

  this.name = "Globe";

  var that = this;

  // instantiate a loader
  var loader = new THREE.TextureLoader();

A map called textures where every object contains the url of a texture file and val for storing the value of a Three.js texture object.

  // earth textures
  var textures = {
    'map': {
      url: 'relief.jpg',
      val: undefined
    },
    'bumpMap': {
      url: 'elev_bump_4k.jpg',
      val: undefined
    },
    'specularMap': {
      url: 'wateretopo.png',
      val: undefined
    }
  };

The array of promises, for each object in the map called textures push a new Promise in the array texturePromises, every Promise will call loader.load. If the value of entry.val is a valid THREE.Texture object, then resolve the promise.

  var texturePromises = [], path = './';

  for (var key in textures) {
    texturePromises.push(new Promise((resolve, reject) => {
      var entry = textures[key]
      var url = path + entry.url

      loader.load(url,
        texture => {
          entry.val = texture;
          if (entry.val instanceof THREE.Texture) resolve(entry);
        },
        xhr => {
          console.log(url + ' ' + (xhr.loaded / xhr.total * 100) +
            '% loaded');
        },
        xhr => {
          reject(new Error(xhr +
            'An error occurred loading while loading: ' +
            entry.url));
        }
      );
    }));
  }

Promise.all takes the promise array texturePromises as argument. Doing so makes the browser wait for all the promises to resolve, when they do we can load the geometry and the material.

  // load the geometry and the textures
  Promise.all(texturePromises).then(loadedTextures => {

    var geometry = new THREE.SphereGeometry(radius, segments, segments);
    var material = new THREE.MeshPhongMaterial({
      map: textures.map.val,
      bumpMap: textures.bumpMap.val,
      bumpScale: 0.005,
      specularMap: textures.specularMap.val,
      specular: new THREE.Color('grey')
    });

    var earth = that.earth = new THREE.Mesh(geometry, material);
    that.add(earth);
  });

For the cloud sphere only one texture is necessary:

  // clouds
  loader.load('n_amer_clouds.png', map => {
    var geometry = new THREE.SphereGeometry(radius + .05, segments, segments);
    var material = new THREE.MeshPhongMaterial({
      map: map,
      transparent: true
    });

    var clouds = that.clouds = new THREE.Mesh(geometry, material);
    that.add(clouds);
  });
}

Globe.prototype = Object.create(THREE.Object3D.prototype);
Globe.prototype.constructor = Globe;

android listview item height

This is my solution(There is a nested LinearLayout):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/item"
            android:layout_width="match_parent"
            android:layout_height="47dp"
            android:background="@drawable/box_arrow_top_bg"
            android:gravity="center"
            android:text="????"
            android:textColor="#666"
            android:textSize="16sp" />
    </LinearLayout>

</LinearLayout>

CSS scale down image to fit in containing div, without specifing original size

if you want both width and the height you can try

 background-size: cover !important;

but this wont distort the image but fill the div.