Programs & Examples On #Posting

axios post request to send form data

Check out querystring.

You can use it as follows:

var querystring = require('querystring');'', querystring.stringify({ foo: 'bar' }));

Could not resolve in Android Studio new project

OK It's A Wrong Approach But If You Use it Like This :

compile ""

Android Studio Will Use The Last Version It Has.

In My Case Was 26.0.0alpha-1.

You Can See The Used Version In External Libraries (In The Project View).

I Tried Everything But Couldn't Use Anything Above 26.0.0alpha-1, It Seems My IP Is Blocked By Google. Any Idea? Comment

react-router (v4) how to go back?

I am not sure if anyone else ran into this problem or may need to see this. But I spent about 3 hours trying to solve this issue:

I wanted to implement a simple goBack() on the click of a button. I thought I was off to a good start because my App.js was already wrapped in the Router and I was importing { BrowserRouter as Router } from 'react-router-dom'; ... Since the Router element allows me to assess the history object.


import React from 'react';
import './App.css';
import Splash from './components/Splash';
import Header from './components/Header.js';
import Footer from './components/Footer';
import Info from './components/Info';
import Timer from './components/Timer';
import Options from './components/Options';
import { BrowserRouter as Router, Route } from 'react-router-dom';
function App() {
  return (
      <Header />
      <Route path='/' component={Splash} exact />
      <Route path='/home' component={Info} exact />
      <Route path='/timer' component={Timer} exact />
      <Route path='/options' component={Options} exact />
      <Footer />
export default App;

BUT the trouble was on my Nav (a child component) module, I had to 'import { withRouter } from 'react-router-dom';' and then force an export with:

export default withRouter(Nav);


import React from 'react';
import { withRouter } from 'react-router-dom';
class Nav extends React.Component {
    render() {
        return (
                <label htmlFor='back'></label>
                <button id='back' onClick={ () => this.props.history.goBack() }>Back</button>
                <label htmlFor='logOut'></label>
                <button id='logOut' ><a href='./'>Log-Out</a>            
export default withRouter(Nav);

in summary, withRouter was created because of a known issue in React where in certain scenarios when inheritance from a router is refused, a forced export is necessary.

Ajax LARAVEL 419 POST error

In your action you need first to load companies like so :

$companies = App\Company::all();
return view('')->with('companies' => $companies)->render();

This will make the companies variable available in the view, and it should render the HTML correctly.

Try to use postman chrome extension to debug your view.

Only on Firefox "Loading failed for the <script> with source"

I ran in the same situation and the script was correctly loading in safe mode. However, disabling all the Add-ons and other Firefox security features didn't help. One thing I tried, and this was the solution in my case, was to temporary disable the cache from the developer window for this particular request. After I saw this was the cause, I wiped out the cache for that site and everything started word normally.

Handling Enter Key in Vue.js

In vue 2, You can catch enter event with v-on:keyup.enter check the documentation:

I leave a very simple example:

var vm = new Vue({_x000D_
  el: '#app',_x000D_
  data: {msg: ''},_x000D_
  methods: {_x000D_
    onEnter: function() {_x000D_
       this.msg = 'on enter event';_x000D_
<script src=""></script>_x000D_
<div id="app">_x000D_
  <input v-on:keyup.enter="onEnter" />_x000D_
  <h1>{{ msg }}</h1>_x000D_

Good luck

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined


import { Router, Route, Link, browserHistory } from 'react-router';


import { BrowserRouter as Router, Route } from 'react-router-dom';

It will start working. It is because react-router-dom exports BrowserRouter

How to import an Excel file into SQL Server?

There are many articles about writing code to import an excel file, but this is a manual/shortcut version:

If you don't need to import your Excel file programmatically using code you can do it very quickly using the menu in SQL Management Studio.

The quickest way to get your Excel file into SQL is by using the import wizard:

  1. Open SSMS (Sql Server Management Studio) and connect to the database where you want to import your file into.
  2. Import Data: in SSMS in Object Explorer under 'Databases' right-click the destination database, select Tasks, Import Data. An import wizard will pop up (you can usually just click 'Next' on the first screen).

enter image description here

  1. The next window is 'Choose a Data Source', select Excel:

    • In the 'Data Source' dropdown list select Microsoft Excel (this option should appear automatically if you have excel installed).

    • Click the 'Browse' button to select the path to the Excel file you want to import.

    • Select the version of the excel file (97-2003 is usually fine for files with a .XLS extension, or use 2007 for newer files with a .XLSX extension)
    • Tick the 'First Row has headers' checkbox if your excel file contains headers.
    • Click next.

enter image description here

  1. On the 'Choose a Destination' screen, select destination database:
    • Select the 'Server name', Authentication (typically your sql username & password) and select a Database as destination. Click Next.

enter image description here

  1. On the 'Specify Table Copy or Query' window:

    • For simplicity just select 'Copy data from one or more tables or views', click Next.
  2. 'Select Source Tables:' choose the worksheet(s) from your Excel file and specify a destination table for each worksheet. If you don't have a table yet the wizard will very kindly create a new table that matches all the columns from your spreadsheet. Click Next.

enter image description here

  1. Click Finish. Received fatal alert: handshake_failure

I am getting similar errors recently because recent JDKs (and browsers, and the Linux TLS stack, etc.) refuse to communicate with some servers in my customer's corporate network. The reason of this is that some servers in this network still have SHA-1 certificates.

Please see:

If this would be your current case (recent JDK vs deprecated certificate encription) then your best move is to update your network to the proper encription technology.

In case that you should provide a temporal solution for that, please see another answers to have an idea about how to make your JDK trust or distrust certain encription algorithms:

How to force java server to accept only tls 1.2 and reject tls 1.0 and tls 1.1 connections

Anyway I insist that, in case that I have guessed properly your problem, this is not a good solution to the problem and that your network admin should consider removing these deprecated certificates and get a new one.

Add jars to a Spark Job - spark-submit


ClassPath is affected depending on what you provide. There are a couple of ways to set something on the classpath:

  • spark.driver.extraClassPath or it's alias --driver-class-path to set extra classpaths on the node running the driver.
  • spark.executor.extraClassPath to set extra class path on the Worker nodes.

If you want a certain JAR to be effected on both the Master and the Worker, you have to specify these separately in BOTH flags.

Separation character:

Following the same rules as the JVM:

  • Linux: A colon :
    • e.g: --conf "spark.driver.extraClassPath=/opt/prog/hadoop-aws-2.7.1.jar:/opt/prog/aws-java-sdk-1.10.50.jar"
  • Windows: A semicolon ;
    • e.g: --conf "spark.driver.extraClassPath=/opt/prog/hadoop-aws-2.7.1.jar;/opt/prog/aws-java-sdk-1.10.50.jar"

File distribution:

This depends on the mode which you're running your job under:

  1. Client mode - Spark fires up a Netty HTTP server which distributes the files on start up for each of the worker nodes. You can see that when you start your Spark job:

    16/05/08 17:29:12 INFO HttpFileServer: HTTP File server directory is /tmp/spark-48911afa-db63-4ffc-a298-015e8b96bc55/httpd-84ae312b-5863-4f4c-a1ea-537bfca2bc2b
    16/05/08 17:29:12 INFO HttpServer: Starting HTTP Server
    16/05/08 17:29:12 INFO Utils: Successfully started service 'HTTP file server' on port 58922.
    16/05/08 17:29:12 INFO SparkContext: Added JAR /opt/foo.jar at http://***:58922/jars/com.mycode.jar with timestamp 1462728552732
    16/05/08 17:29:12 INFO SparkContext: Added JAR /opt/aws-java-sdk-1.10.50.jar at http://***:58922/jars/aws-java-sdk-1.10.50.jar with timestamp 1462728552767
  2. Cluster mode - In cluster mode spark selected a leader Worker node to execute the Driver process on. This means the job isn't running directly from the Master node. Here, Spark will not set an HTTP server. You have to manually make your JARS available to all the worker node via HDFS/S3/Other sources which are available to all nodes.

Accepted URI's for files

In "Submitting Applications", the Spark documentation does a good job of explaining the accepted prefixes for files:

When using spark-submit, the application jar along with any jars included with the --jars option will be automatically transferred to the cluster. Spark uses the following URL scheme to allow different strategies for disseminating jars:

  • file: - Absolute paths and file:/ URIs are served by the driver’s HTTP file server, and every executor pulls the file from the driver HTTP server.
  • hdfs:, http:, https:, ftp: - these pull down files and JARs from the URI as expected
  • local: - a URI starting with local:/ is expected to exist as a local file on each worker node. This means that no network IO will be incurred, and works well for large files/JARs that are pushed to each worker, or shared via NFS, GlusterFS, etc.

Note that JARs and files are copied to the working directory for each SparkContext on the executor nodes.

As noted, JARs are copied to the working directory for each Worker node. Where exactly is that? It is usually under /var/run/spark/work, you'll see them like this:

drwxr-xr-x    3 spark spark   4096 May 15 06:16 app-20160515061614-0027
drwxr-xr-x    3 spark spark   4096 May 15 07:04 app-20160515070442-0028
drwxr-xr-x    3 spark spark   4096 May 15 07:18 app-20160515071819-0029
drwxr-xr-x    3 spark spark   4096 May 15 07:38 app-20160515073852-0030
drwxr-xr-x    3 spark spark   4096 May 15 08:13 app-20160515081350-0031
drwxr-xr-x    3 spark spark   4096 May 18 17:20 app-20160518172020-0032
drwxr-xr-x    3 spark spark   4096 May 18 17:20 app-20160518172045-0033

And when you look inside, you'll see all the JARs you deployed along:

[*@*]$ cd /var/run/spark/work/app-20160508173423-0014/1/
[*@*]$ ll
total 89988
-rwxr-xr-x 1 spark spark   801117 May  8 17:34 awscala_2.10-0.5.5.jar
-rwxr-xr-x 1 spark spark 29558264 May  8 17:34 aws-java-sdk-1.10.50.jar
-rwxr-xr-x 1 spark spark 59466931 May  8 17:34 com.mycode.code.jar
-rwxr-xr-x 1 spark spark  2308517 May  8 17:34 guava-19.0.jar
-rw-r--r-- 1 spark spark      457 May  8 17:34 stderr
-rw-r--r-- 1 spark spark        0 May  8 17:34 stdout

Affected options:

The most important thing to understand is priority. If you pass any property via code, it will take precedence over any option you specify via spark-submit. This is mentioned in the Spark documentation:

Any values specified as flags or in the properties file will be passed on to the application and merged with those specified through SparkConf. Properties set directly on the SparkConf take highest precedence, then flags passed to spark-submit or spark-shell, then options in the spark-defaults.conf file

So make sure you set those values in the proper places, so you won't be surprised when one takes priority over the other.

Lets analyze each option in question:

  • --jars vs SparkContext.addJar: These are identical, only one is set through spark submit and one via code. Choose the one which suites you better. One important thing to note is that using either of these options does not add the JAR to your driver/executor classpath, you'll need to explicitly add them using the extraClassPath config on both.
  • SparkContext.addJar vs SparkContext.addFile: Use the former when you have a dependency that needs to be used with your code. Use the latter when you simply want to pass an arbitrary file around to your worker nodes, which isn't a run-time dependency in your code.
  • --conf spark.driver.extraClassPath=... or --driver-class-path: These are aliases, doesn't matter which one you choose
  • --conf spark.driver.extraLibraryPath=..., or --driver-library-path ... Same as above, aliases.
  • --conf spark.executor.extraClassPath=...: Use this when you have a dependency which can't be included in an uber JAR (for example, because there are compile time conflicts between library versions) and which you need to load at runtime.
  • --conf spark.executor.extraLibraryPath=... This is passed as the java.library.path option for the JVM. Use this when you need a library path visible to the JVM.

Would it be safe to assume that for simplicity, I can add additional application jar files using the 3 main options at the same time:

You can safely assume this only for Client mode, not Cluster mode. As I've previously said. Also, the example you gave has some redundant arguments. For example, passing JARs to --driver-library-path is useless, you need to pass them to extraClassPath if you want them to be on your classpath. Ultimately, what you want to do when you deploy external JARs on both the driver and the worker is:

spark-submit --jars additional1.jar,additional2.jar \
  --driver-class-path additional1.jar:additional2.jar \
  --conf spark.executor.extraClassPath=additional1.jar:additional2.jar \
  --class MyClass main-application.jar

How to restart kubernetes nodes?

Get nodes

kubectl get nodes


NAME            STATUS     AGE   NotReady   42d   Ready      42d   Ready      42d

Describe node

Here is a NotReady on the node of Then debugging this notready node, and you can read offical documents - Application Introspection and Debugging.

kubectl describe node

Partial Result:

Type          Status          LastHeartbeatTime                       LastTransitionTime                      Reason                  Message
----          ------          -----------------                       ------------------                      ------                  -------
OutOfDisk     Unknown         Sat, 28 Dec 2016 12:56:01 +0000         Sat, 28 Dec 2016 12:56:41 +0000         NodeStatusUnknown       Kubelet stopped posting node status.
Ready         Unknown         Sat, 28 Dec 2016 12:56:01 +0000         Sat, 28 Dec 2016 12:56:41 +0000         NodeStatusUnknown       Kubelet stopped posting node status.

There is a OutOfDisk on my node, then Kubelet stopped posting node status. So, I must free some disk space, using the command of df on my Ubuntu14.04 I can check the details of memory, and using the command of docker rmi image_id/image_name under the role of su I can remove the useless images.

Login in node

Login in by using ssh, like ssh [email protected], and switch to the 'su' by sudo su;

Restart kubelet

/etc/init.d/kubelet restart


stop: Unknown instance: 
kubelet start/running, process 59261

Get nodes again

On the master:

kubectl get nodes


NAME            STATUS    AGE   Ready     42d   Ready     42d   Ready     42d

Ok, that node works fine.

Here is a reference: Kubernetes

Pandas - replacing column values

Yes, you are using it incorrectly, Series.replace() is not inplace operation by default, it returns the replaced dataframe/series, you need to assign it back to your dataFrame/Series for its effect to occur. Or if you need to do it inplace, you need to specify the inplace keyword argument as True Example -

data['sex'].replace(0, 'Female',inplace=True)
data['sex'].replace(1, 'Male',inplace=True)

Also, you can combine the above into a single replace function call by using list for both to_replace argument as well as value argument , Example -


Example/Demo -

In [10]: data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])

In [11]: data['sex'].replace([0,1],['Female','Male'],inplace=True)

In [12]: data
      sex  split
0    Male      0
1  Female      1
2    Male      0
3  Female      1

You can also use a dictionary, Example -

In [15]: data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])

In [16]: data['sex'].replace({0:'Female',1:'Male'},inplace=True)

In [17]: data
      sex  split
0    Male      0
1  Female      1
2    Male      0
3  Female      1

How to add "active" class to wp_nav_menu() current menu item (simple way)

To also highlight the menu item when one of the child pages is active, also check for the other class (current-page-ancestor) like below:

add_filter('nav_menu_css_class' , 'special_nav_class' , 10 , 2);

function special_nav_class ($classes, $item) {
    if (in_array('current-page-ancestor', $classes) || in_array('current-menu-item', $classes) ){
        $classes[] = 'active ';
    return $classes;

Angular bootstrap datepicker date format does not format ng-model value

With so many answers already written, Here's my take.

With Angular 1.5.6 & ui-bootstrap 1.3.3 , just add this on the model & you are done.

ng-model-options="{timezone: 'UTC'}" 

Note: Use this only if you are concerned about the date being 1 day behind & not bothered with extra time of T00:00:00.000Z

Updated Plunkr Here :

yii2 redirect in controller action does not work?

In Yii2 we need to return() the result from the action.I think you need to add a return in front of your redirect.

  return $this->redirect(['user/index']);

How to use OKHTTP to make a post request?

The current accepted answer is out of date. Now if you want to create a post request and add parameters to it you should user MultipartBody.Builder as Mime Craft now is deprecated.

RequestBody requestBody = new MultipartBody.Builder()
        .addFormDataPart("somParam", "someValue")

Request request = new Request.Builder()
        .url(BASE_URL + route)

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

It seems that entity you are trying to modify is not being tracked correctly and therefore is not recognized as edited, but added instead.

Instead of directly setting state, try to do the following:

//db.Entry(aViewModel.a).State = EntityState.Modified;

Also, I would like to warn you that your code contains potential security vulnerability. If you are using entity directly in your view model, then you risk that somebody could modify contents of entity by adding correctly named fields in submitted form. For example, if user added input box with name "A.FirstName" and the entity contained such field, then the value would be bound to viewmodel and saved to database even if the user would not be allowed to change that in normal operation of application.


To get over security vulnerability mentioned previously, you should never expose your domain model as your viewmodel but use separate viewmodel instead. Then your action would receive viewmodel which you could map back to domain model using some mapping tool like AutoMapper. This would keep you safe from user modifying sensitive data.

Here is extended explanation:

Label python data points on plot

How about print (x, y) at once.

from matplotlib import pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

for xy in zip(A, B):                                       # <--
    ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') # <--


enter image description here

Rails formatting date

Try this:


It's a time formatting function which provides you a way to present the string representation of the date. (

From APIdock:

%Y%m%d           => 20071119                  Calendar date (basic)
%F               => 2007-11-19                Calendar date (extended)
%Y-%m            => 2007-11                   Calendar date, reduced accuracy, specific month
%Y               => 2007                      Calendar date, reduced accuracy, specific year
%C               => 20                        Calendar date, reduced accuracy, specific century
%Y%j             => 2007323                   Ordinal date (basic)
%Y-%j            => 2007-323                  Ordinal date (extended)
%GW%V%u          => 2007W471                  Week date (basic)
%G-W%V-%u        => 2007-W47-1                Week date (extended)
%GW%V            => 2007W47                   Week date, reduced accuracy, specific week (basic)
%G-W%V           => 2007-W47                  Week date, reduced accuracy, specific week (extended)
%H%M%S           => 083748                    Local time (basic)
%T               => 08:37:48                  Local time (extended)
%H%M             => 0837                      Local time, reduced accuracy, specific minute (basic)
%H:%M            => 08:37                     Local time, reduced accuracy, specific minute (extended)
%H               => 08                        Local time, reduced accuracy, specific hour
%H%M%S,%L        => 083748,000                Local time with decimal fraction, comma as decimal sign (basic)
%T,%L            => 08:37:48,000              Local time with decimal fraction, comma as decimal sign (extended)
%H%M%S.%L        => 083748.000                Local time with decimal fraction, full stop as decimal sign (basic)
%T.%L            => 08:37:48.000              Local time with decimal fraction, full stop as decimal sign (extended)
%H%M%S%z         => 083748-0600               Local time and the difference from UTC (basic)
%T%:z            => 08:37:48-06:00            Local time and the difference from UTC (extended)
%Y%m%dT%H%M%S%z  => 20071119T083748-0600      Date and time of day for calendar date (basic)
%FT%T%:z         => 2007-11-19T08:37:48-06:00 Date and time of day for calendar date (extended)
%Y%jT%H%M%S%z    => 2007323T083748-0600       Date and time of day for ordinal date (basic)
%Y-%jT%T%:z      => 2007-323T08:37:48-06:00   Date and time of day for ordinal date (extended)
%GW%V%uT%H%M%S%z => 2007W471T083748-0600      Date and time of day for week date (basic)
%G-W%V-%uT%T%:z  => 2007-W47-1T08:37:48-06:00 Date and time of day for week date (extended)
%Y%m%dT%H%M      => 20071119T0837             Calendar date and local time (basic)
%FT%R            => 2007-11-19T08:37          Calendar date and local time (extended)
%Y%jT%H%MZ       => 2007323T0837Z             Ordinal date and UTC of day (basic)
%Y-%jT%RZ        => 2007-323T08:37Z           Ordinal date and UTC of day (extended)
%GW%V%uT%H%M%z   => 2007W471T0837-0600        Week date and local time and difference from UTC (basic)
%G-W%V-%uT%R%:z  => 2007-W47-1T08:37-06:00    Week date and local time and difference from UTC (extended)

UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte

If the above methods are not working for you, you may want to look into changing the encoding of the csv file itself.

Using Excel:

  1. Open csv file using Excel
  2. Navigate to File menu option and click Save As
  3. Click Browse to select a location to save the file
  4. Enter intended filename
  5. Select CSV (Comma delimited) (*.csv) option
  6. Click Tools drop-down box and click Web Options
  7. Under Encoding tab, select the option Unicode (UTF-8) from Save this document as drop-down list
  8. Save the file

Using Notepad:

  1. Open csv file using notepad
  2. Navigate to File > Save As option
  3. Next, select the location to the file
  4. Select the Save as type option as All Files(.)
  5. Specify the file name with .csv extension
  6. From Encoding drop-down list, select UTF-8 option.
  7. Click Save to save the file

By doing this, you should be able to import csv files without encountering the UnicodeCodeError.

Posting raw image data as multipart/form-data in curl


// files to upload

$filename = "";       

// URL to upload to (Destination server)

$url = "https://otherserver/image";


    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => file_get_contents($filename),
        CURLOPT_HTTPHEADER => array(
            //"Authorization: Bearer $TOKEN",
            "Content-Type: multipart/form-data",
            "Content-Length: " . strlen(file_get_contents($filename)),
            "API-Key: abcdefghi" //Optional if required

   $response = curl_exec($curl);

    $info = curl_getinfo($curl);
//echo "code: ${info['http_code']}";


    $err = curl_error($curl);

    echo "error";

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

i don't see any for loop to initalize the can do something like this.

 /* Code which is necessary with a simple if statement*/


Posting form to different MVC post action depending on the clicked submit button

you can use ajax calls to call different methods without a postback

    type: "POST",
     url: "@(Url.Action("Action", "Controller"))",
     data: {id: 'id', id1: 'id1' },
     contentType: "application/json; charset=utf-8",
     cache: false,
     async: true,
     success: function (result) {
        //do something

Has Facebook sharer.php changed to no longer accept detailed parameters?

Facebook no longer supports custom parameters in sharer.php

The sharer will no longer accept custom parameters and facebook will pull the information that is being displayed in the preview the same way that it would appear on facebook as a post from the url OG meta tags.

Use dialog/feeds instead of sharer.php

Official answer from fb team

OpenSSL: PEM routines:PEM_read_bio:no start line:pem_lib.c:703:Expecting: TRUSTED CERTIFICATE

I had the same issue using Windows, got if fixed by opening it in Notepad++ and changing the encoding from "UCS-2 LE BOM" to "UTF-8".

Uploading Images to Server android

use below code it helps you....

        BitmapFactory.Options options = new BitmapFactory.Options();

        options.inSampleSize = 4;
        options.inPurgeable = true;
        Bitmap bm = BitmapFactory.decodeFile("your path of image",options);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();


        // bitmap object

        byteImage_photo = baos.toByteArray();

                    //generate base64 string of image

                   String encodedImage =Base64.encodeToString(byteImage_photo,Base64.DEFAULT);

  //send this encoded string to server

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

If you want to bypass that restriction when fetching the contents with fetch API or XMLHttpRequest in javascript, you can use a proxy server so that it sets the header Access-Control-Allow-Origin to *.

const express = require('express');
const request = require('request');

const app = express();

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');

app.get('/fetch', (req, res) => {
    { url: req.query.url },
    (error, response, body) => {
      if (error || response.statusCode !== 200) {
        return res.status(500).send('error');

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`listening on ${PORT}`));

Above is a sample code( node Js required ) which can act as a proxy server. For eg: If I want to fetch normally a CORS error is thrown, but now since the request is sent through the proxy server hosted locally at port 3000, the proxy server adds the Access-Control-Allow-Origin header in the response and there wont be any issue.

Send a GET request to http://localhost:3000/fetch?url=Your URL here , instead of directly sending the request to the URl you want to fetch.

Your URL here stands for the URL you wish to fetch eg:

Angularjs - simple form submit

I think the reason AngularJS does not say much about form submission because it depends more on 'two-way data binding'. In traditional html development you had one way data binding, i.e. once DOM rendered any changes you make to DOM element did not reflect in JS Object, however in AngularJS it works both way. Hence there's in fact no need to form submission. I have done a mid sized application using AngularJS without the need to form submission. If you are keen to submit form you can write a directive wrapping up your form which handles ENTER keydown and SUBMIT button click events and call form.submit().

If you want the sample source code of such a directive, please let me know by commenting on this. I figured out it would a simple directive that you can write yourself.

MVC Form not able to post List of objects

Your model is null because the way you're supplying the inputs to your form means the model binder has no way to distinguish between the elements. Right now, this code:

@foreach (var planVM in Model)
    @Html.Partial("_partialView", planVM)

is not supplying any kind of index to those items. So it would repeatedly generate HTML output like this:

<input type="hidden" name="yourmodelprefix.PlanID" />
<input type="hidden" name="yourmodelprefix.CurrentPlan" />
<input type="checkbox" name="yourmodelprefix.ShouldCompare" />

However, as you're wanting to bind to a collection, you need your form elements to be named with an index, such as:

<input type="hidden" name="yourmodelprefix[0].PlanID" />
<input type="hidden" name="yourmodelprefix[0].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[0].ShouldCompare" />
<input type="hidden" name="yourmodelprefix[1].PlanID" />
<input type="hidden" name="yourmodelprefix[1].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[1].ShouldCompare" />

That index is what enables the model binder to associate the separate pieces of data, allowing it to construct the correct model. So here's what I'd suggest you do to fix it. Rather than looping over your collection, using a partial view, leverage the power of templates instead. Here's the steps you'd need to follow:

  1. Create an EditorTemplates folder inside your view's current folder (e.g. if your view is Home\Index.cshtml, create the folder Home\EditorTemplates).
  2. Create a strongly-typed view in that directory with the name that matches your model. In your case that would be PlanCompareViewModel.cshtml.

Now, everything you have in your partial view wants to go in that template:

@model PlanCompareViewModel
    @Html.HiddenFor(p => p.PlanID)
    @Html.HiddenFor(p => p.CurrentPlan)
    @Html.CheckBoxFor(p => p.ShouldCompare)
   <input type="submit" value="Compare"/>

Finally, your parent view is simplified to this:

@model IEnumerable<PlanCompareViewModel>
@using (Html.BeginForm("ComparePlans", "Plans", FormMethod.Post, new { id = "compareForm" }))

DisplayTemplates and EditorTemplates are smart enough to know when they are handling collections. That means they will automatically generate the correct names, including indices, for your form elements so that you can correctly model bind to a collection.

Error: request entity too large

I had the same error recently, and all the solutions I've found did not work.

After some digging, I found that setting app.use(express.bodyParser({limit: '50mb'})); did set the limit correctly.

When adding a console.log('Limit file size: '+limit); in node_modules/express/node_modules/connect/lib/middleware/json.js:46 and restarting node, I get this output in the console:

Limit file size: 1048576
connect.multipart() will be removed in connect 3.0
visit for alternatives
connect.limit() will be removed in connect 3.0
Limit file size: 52428800
Express server listening on port 3002

We can see that at first, when loading the connect module, the limit is set to 1mb (1048576 bytes). Then when I set the limit, the console.log is called again and this time the limit is 52428800 (50mb). However, I still get a 413 Request entity too large.

Then I added console.log('Limit file size: '+limit); in node_modules/express/node_modules/connect/node_modules/raw-body/index.js:10 and saw another line in the console when calling the route with a big request (before the error output) :

Limit file size: 1048576

This means that somehow, somewhere, connect resets the limit parameter and ignores what we specified. I tried specifying the bodyParser parameters in the route definition individually, but no luck either.

While I did not find any proper way to set it permanently, you can "patch" it in the module directly. If you are using Express 3.4.4, add this at line 46 of node_modules/express/node_modules/connect/lib/middleware/json.js :

limit = 52428800; // for 50mb, this corresponds to the size in bytes

The line number might differ if you don't run the same version of Express. Please note that this is bad practice and it will be overwritten if you update your module.

So this temporary solution works for now, but as soon as a solution is found (or the module fixed, in case it's a module problem) you should update your code accordingly.

I have opened an issue on their GitHub about this problem.

[edit - found the solution]

After some research and testing, I found that when debugging, I added app.use(express.bodyParser({limit: '50mb'}));, but after app.use(express.json());. Express would then set the global limit to 1mb because the first parser he encountered when running the script was express.json(). Moving bodyParser above it did the trick.

That said, the bodyParser() method will be deprecated in Connect 3.0 and should not be used. Instead, you should declare your parsers explicitly, like so :

app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({limit: '50mb'}));

In case you need multipart (for file uploads) see this post.

[second edit]

Note that in Express 4, instead of express.json() and express.urlencoded(), you must require the body-parser module and use its json() and urlencoded() methods, like so:

var bodyParser = require('body-parser');
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));

If the extended option is not explicitly defined for bodyParser.urlencoded(), it will throw a warning (body-parser deprecated undefined extended: provide extended option). This is because this option will be required in the next version and will not be optional anymore. For more info on the extended option, you can refer to the readme of body-parser.

[third edit]

It seems that in Express v4.16.0 onwards, we can go back to the initial way of doing this (thanks to @GBMan for the tip):

app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({limit: '50mb'}));

400 BAD request HTTP error code meaning?

First check the URL it might be wrong, if it is correct then check the request body which you are sending, the possible cause is request that you are sending is missing right syntax.

To elaborate , check for special characters in the request string. If it is (special char) being used this is the root cause of this error.

try copying the request and analyze each and every tags data.

415 Unsupported Media Type - POST json to OData service in lightswitch 2012

It looks like this issue has to do with the difference between the Content-Type and Accept headers. In HTTP, Content-Type is used in request and response payloads to convey the media type of the current payload. Accept is used in request payloads to say what media types the server may use in the response payload.

So, having a Content-Type in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type does matter.

If a server is not able to process the Content-Type of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept header, it will return a 406 error.)

In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.

You could fix this in one of two ways:

  1. Make the Content-Type "application/json;odata=verbose" in your POST request, or
  2. Include the DataServiceVersion header in the request and set it be less than v3. For example:

    DataServiceVersion: 2.0;

(Option 2 assumes that you aren't using any v3 features in your request payload.)

How to fix: /usr/lib/ version `GLIBCXX_3.4.15' not found

this problem can be solved by installing the latest libstdc++.

$ sudo add-apt-repository ppa:ubuntu-toolchain-r/test
$ sudo apt-get update
$ sudo apt-get install libstdc++6-7-dbg

Collectors.toMap() keyMapper -- more succinct expression?

List<Person> roster = ...;

Map<String, Person> map = 
            Collectors.toMap(p -> p.getLast(), p -> p)

that would be the translation, but i havent run this or used the API. most likely you can substitute p -> p, for Function.identity(). and statically import toMap(...)

Make a URL-encoded POST request using `http.NewRequest(...)`

URL-encoded payload must be provided on the body parameter of the http.NewRequest(method, urlStr string, body io.Reader) method, as a type that implements io.Reader interface.

Based on the sample code:

package main

import (

func main() {
    apiUrl := ""
    resource := "/user/"
    data := url.Values{}
    data.Set("name", "foo")
    data.Set("surname", "bar")

    u, _ := url.ParseRequestURI(apiUrl)
    u.Path = resource
    urlStr := u.String() // ""

    client := &http.Client{}
    r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
    r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
    r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))

    resp, _ := client.Do(r)

resp.Status is 200 OK this way.

Reading JSON POST using PHP

you can put your json in a parameter and send it instead of put only your json in header:

$post_string= 'json_param=' . json_encode($data);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $post_string);
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/');  // Set the url path we want to call

//execute post
$result = curl_exec($curl);

//see the results

on the service side you can get your json string as a parameter:

$json_string = $_POST['json_param'];
$obj = json_decode($json_string);

then you can use your converted data as object.

curl posting with header application/x-www-form-urlencoded

Try something like:


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));   
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$result = curl_exec($ch);

echo $result;

EXCEL Multiple Ranges - need different answers for each range

Nested if's in Excel Are ugly:

=If(G2 < 1, .1, IF(G2 < 5,.15,if(G2 < 15,.2,if(G2 < 30,.5,if(G2 < 100,.1,1.3)))))

That should cover it.

IOException: read failed, socket might closed - Bluetooth on Android 4.3

i also faced with this problem,you could solve it in 2 ways , as mentioned earlier use reflection to create the socket Second one is, client is looking for a server with given UUID and if your server isn't running parallel to client then this happens. Create a server with given client UUID and then listen and accept the client from server side.It will work.

PHP parse/syntax errors; and how to solve them

Unexpected (

Opening parentheses typically follow language constructs such as if/foreach/for/array/list or start an arithmetic expression. They're syntactically incorrect after "strings", a previous (), a lone $, and in some typical declaration contexts.

  1. Function declaration parameters

    A rarer occurrence for this error is trying to use expressions as default function parameters. This is not supported, even in PHP7:

    function header_fallback($value, $expires = time() + 90000) {

    Parameters in a function declaration can only be literal values or constant expressions. Unlike for function invocations, where you can freely use whatever(1+something()*2), etc.

  2. Class property defaults

    Same thing for class member declarations, where only literal/constant values are allowed, not expressions:

    class xyz {                   ?
        var $default = get_config("xyz_default");

    Put such things in the constructor. See also Why don't PHP attributes allow functions?

    Again note that PHP 7 only allows var $xy = 1 + 2 +3; constant expressions there.

  3. JavaScript syntax in PHP

    Using JavaScript or jQuery syntax won't work in PHP for obvious reasons:

    <?php      ?
        print $(document).text();

    When this happens, it usually indicates an unterminated preceding string; and literal <script> sections leaking into PHP code context.

  4. isset(()), empty, key, next, current

    Both isset() and empty() are language built-ins, not functions. They need to access a variable directly. If you inadvertently add a pair of parentheses too much, then you'd create an expression however:

    if (isset(($_GET["id"]))) {

    The same applies to any language construct that requires implicit variable name access. These built-ins are part of the language grammar, therefore don't permit decorative extra parentheses.

    User-level functions that require a variable reference -but get an expression result passed- lead to runtime errors instead.

Unexpected )

  1. Absent function parameter

    You cannot have stray commas last in a function call. PHP expects a value there and thusly complains about an early closing ) parenthesis.

    callfunc(1, 2, );

    A trailing comma is only allowed in array() or list() constructs.

  2. Unfinished expressions

    If you forget something in an arithmetic expression, then the parser gives up. Because how should it possibly interpret that:

    $var = 2 * (1 + );

    And if you forgot the closing ) even, then you'd get a complaint about the unexpected semicolon instead.

  3. Foreach as constant

    For forgotten variable $ prefixes in control statements you will see:

                       ?    ?
    foreach ($array as wrong) {

    PHP here sometimes tells you it expected a :: instead. Because a class::$variable could have satisfied the expected $variable expression..

Unexpected {

Curly braces { and } enclose code blocks. And syntax errors about them usually indicate some incorrect nesting.

  1. Unmatched subexpressions in an if

    Most commonly unbalanced ( and ) are the cause if the parser complains about the opening curly { appearing too early. A simple example:

    if (($x == $y) && (2 == true) {

    Count your parentheses or use an IDE which helps with that. Also don't write code without any spaces. Readability counts.

  2. { and } in expression context

    You can't use curly braces in expressions. If you confuse parentheses and curlys, it won't comply to the language grammar:

    $var = 5 * {7 + $x};

    There are a few exceptions for identifier construction, such as local scope variable ${references}.

  3. Variable variables or curly var expressions

    This is pretty rare. But you might also get { and } parser complaints for complex variable expressions:

    print "Hello {$world[2{]} !";

    Though there's a higher likelihood for an unexpected } in such contexts.

Unexpected }

When getting an "unexpected }" error, you've mostly closed a code block too early.

  1. Last statement in a code block

    It can happen for any unterminated expression.

    And if the last line in a function/code block lacks a trailing ; semicolon:

    function whatever() {
    }            ?

    Here the parser can't tell if you perhaps still wanted to add + 25; to the function result or something else.

  2. Invalid block nesting / Forgotten {

    You'll sometimes see this parser error when a code block was } closed too early, or you forgot an opening { even:

    function doStuff() {
        if (true)    ?
            print "yes";
    }   ?

    In above snippet the if didn't have an opening { curly brace. Thus the closing } one below became redundant. And therefore the next closing }, which was intended for the function, was not associable to the original opening { curly brace.

    Such errors are even harder to find without proper code indentation. Use an IDE and bracket matching.

Unexpected {, expecting (

Language constructs which require a condition/declaration header and a code block will trigger this error.

  1. Parameter lists

    For example misdeclared functions without parameter list are not permitted:

    function whatever {
  2. Control statement conditions

    And you can't likewise have an if without condition.

    if {

    Which doesn't make sense, obviously. The same thing for the usual suspects, for/foreach, while/do, etc.

    If you've got this particular error, you definitely should look up some manual examples.

How to POST the data from a modal form of Bootstrap?

I was facing same issue not able to post form without ajax. but found solution , hope it can help and someones time.

<form name="paymentitrform" id="paymentitrform" class="payment"
          <input name="email" value="" placeholder="email" />
          <input type="hidden" name="planamount" id="planamount" value="0">
                                <input type="submit" onclick="form_submit() " value="Continue Payment" class="action"


You can submit post form, from bootstrap modal using below javascript/jquery code : call the below function onclick of input submit button

    function form_submit() {

Posting JSON data via jQuery to ASP .NET MVC 4 controller action

I think you'll find your answer if you refer to this post: Deserialize JSON into C# dynamic object?

There are various ways of achieving what you want here. The System.Web.Helpers.Json approach (a few answers down) seems to be the simplest.

Excel VBA Automation Error: The object invoked has disconnected from its clients

I have just met this problem today: I migrated my Excel project from Office 2007 to 2010. At a certain point, when my macro tried to Insert a new line (e.g. Range("5:5").Insert ), the same error message came. It happens only when previously another sheet has been edited (my macro switches to another sheet).

Thanks to Google, and your discussion, I found the following solution (based on the answer given by "red" at answered Jul 30 '13 at 0:27): after switching to the sheet a Cell has to be edited before inserting a new row. I have added the following code:

'=== Excel bugfix workaround - 2014.08.17
vCellValue = Range("B1").Value
Range("B1").Value = vCellValue

"B1" can be replaced by any cell on the sheet.

Integration Testing POSTing an entire object to Spring MVC controller

Here is the method I made to transform recursively the fields of an object in a map ready to be used with a MockHttpServletRequestBuilder

public static void objectToPostParams(final String key, final Object value, final Map<String, String> map) throws IllegalAccessException {
    if ((value instanceof Number) || (value instanceof Enum) || (value instanceof String)) {
        map.put(key, value.toString());
    } else if (value instanceof Date) {
        map.put(key, new SimpleDateFormat("yyyy-MM-dd HH:mm").format((Date) value));
    } else if (value instanceof GenericDTO) {
        final Map<String, Object> fieldsMap = ReflectionUtils.getFieldsMap((GenericDTO) value);
        for (final Entry<String, Object> entry : fieldsMap.entrySet()) {
            final StringBuilder sb = new StringBuilder();
            if (!GenericValidator.isEmpty(key)) {
            objectToPostParams(sb.toString(), entry.getValue(), map);
    } else if (value instanceof List) {
        for (int i = 0; i < ((List) value).size(); i++) {
            objectToPostParams(key + '[' + i + ']', ((List) value).get(i), map);

GenericDTO is a simple class extending Serializable

public interface GenericDTO extends Serializable {}

and here is the ReflectionUtils class

public final class ReflectionUtils {
    public static List<Field> getAllFields(final List<Field> fields, final Class<?> type) {
        if (type.getSuperclass() != null) {
            getAllFields(fields, type.getSuperclass());
        // if a field is overwritten in the child class, the one in the parent is removed
        fields.addAll(Arrays.asList(type.getDeclaredFields()).stream().map(field -> {
            final Iterator<Field> iterator = fields.iterator();
                final Field fieldTmp =;
                if (fieldTmp.getName().equals(field.getName())) {
            return field;
        return fields;

    public static Map<String, Object> getFieldsMap(final GenericDTO genericDTO) throws IllegalAccessException {
        final Map<String, Object> map = new HashMap<>();
        final List<Field> fields = new ArrayList<>();
        getAllFields(fields, genericDTO.getClass());
        for (final Field field : fields) {
            final boolean isFieldAccessible = field.isAccessible();
            map.put(field.getName(), field.get(genericDTO));
        return map;

You can use it like

final MockHttpServletRequestBuilder post = post("/");
final Map<String, String> map = new TreeMap<>();
objectToPostParams("", genericDTO, map);
for (final Entry<String, String> entry : map.entrySet()) {
    post.param(entry.getKey(), entry.getValue());

I didn't tested it extensively, but it seems to work.

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

If the data is in an UTF-8 compatible format, you can convert the bytes to a string.

>>> import curses
>>> print(str(curses.version, "utf-8"))

Optionally convert to hex first, if the data is not already UTF-8 compatible. E.g. when the data are actual raw bytes.

from binascii import hexlify
from codecs import encode  # alternative
>>> print(hexlify(b"\x13\x37"))
>>> print(str(hexlify(b"\x13\x37"), "utf-8"))
>>>> print(str(encode(b"\x13\x37", "hex"), "utf-8"))

How to use cURL to get jSON data and decode the data?

to get the object you do not need to use cURL (you are loading another dll into memory and have another dependency, unless you really need curl I'd stick with built in php functions), you can use one simple php file_get_contents(url) function:

$unparsed_json = file_get_contents("api.php?action=getThreads&hash=123fajwersa&node_id=4&order_by=post_date&order=desc&limit=1&grab_content&content_limit=1");

$json_object = json_decode($unparsed_json);

then json_decode() parses JSON into a PHP object, or an array if you pass true to the second parameter.

For example:

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));           // Object
var_dump(json_decode($json, true));     // Associative array

Include .so library in apk in android studio

To include native libraries you need:

  1. create "jar" file with special structure containing ".so" files;
  2. include that file in dependencies list.

To create jar file, use the following snippet:

task nativeLibsToJar(type: Zip, description: 'create a jar archive of the native libs') {
    destinationDir file("$buildDir/native-libs")
    baseName 'native-libs'
    extension 'jar'
    from fileTree(dir: 'libs', include: '**/*.so')
    into 'lib/'

tasks.withType(Compile) {
    compileTask -> compileTask.dependsOn(nativeLibsToJar)

To include resulting file, paste the following line into "dependencies" section in "build.gradle" file:

compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')

Have a fixed position div that needs to scroll if content overflows

The problem with using height:100% is that it will be 100% of the page instead of 100% of the window (as you would probably expect it to be). This will cause the problem that you're seeing, because the non-fixed content is long enough to include the fixed content with 100% height without requiring a scroll bar. The browser doesn't know/care that you can't actually scroll that bar down to see it

You can use fixed to accomplish what you're trying to do.

.fixed-content {
    top: 0;

This fork of your fiddle shows my fix:

how to use JSON.stringify and json_decode() properly

None of the other answers worked in my case, most likely because the JSON array contained special characters. What fixed it for me:

Javascript (added encodeURIComponent)

var JSONstr = encodeURIComponent(JSON.stringify(fullInfoArray));
document.getElementById('JSONfullInfoArray').value = JSONstr;

PHP (unchanged from the question)

$data = json_decode($_POST["JSONfullInfoArray"]);


Both echo and var_dump have been verified to work fine on a sample of more than 2000 user-entered datasets that included a URL field and a long text field, and that were returning NULL on var_dump for a subset that included URLs with the characters ?&#.

Python Request Post with param data

Assign the response to a value and test the attributes of it. These should tell you something useful.

response =,params=data,headers=headers)
  • status_code should just reconfirm the code you were given before, of course

Getting Connection timed out in android

I got this same error as I mistakenly changed the order of the statements

OkHttpClient okHttpClient = new OkHttpClient().newBuilder() .connectTimeout(20, TimeUnit.SECONDS).readTimeout(20,TimeUnit.SECONDS).writeTimeout(20, TimeUnit.SECONDS) .build();

After changing the order of writeTimeout and readTimeout, the error resolved. The final code I used is given below:

OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)

POSTing JSON to URL via WebClient in C#

You need a json serializer to parse your content, probably you already have it, for your initial question on how to make a request, this might be an idea:

var baseAddress = "";

var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "POST";

string parsedContent = <<PUT HERE YOUR JSON PARSED CONTENT>>;
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);

Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);

var response = http.GetResponse();

var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();

hope it helps,

Get remote registry value

Try the Remote Registry Module, the registry provider cannot operate remotely:

Import-Module PSRemoteRegistry
Get-RegValue -ComputerName $Computer1 -Key SOFTWARE\Veritas\NetBackup\CurrentVersion -Value PackageVersion 

How to create a HashMap with two keys (Key-Pair, Value)?

When you create your own key pair object, you should face a few thing.

First, you should be aware of implementing hashCode() and equals(). You will need to do this.

Second, when implementing hashCode(), make sure you understand how it works. The given user example

public int hashCode() {
    return this.x ^ this.y;

is actually one of the worst implementations you can do. The reason is simple: you have a lot of equal hashes! And the hashCode() should return int values that tend to be rare, unique at it's best. Use something like this:

public int hashCode() {
  return (X << 16) + Y;

This is fast and returns unique hashes for keys between -2^16 and 2^16-1 (-65536 to 65535). This fits in almost any case. Very rarely you are out of this bounds.

Third, when implementing equals() also know what it is used for and be aware of how you create your keys, since they are objects. Often you do unnecessary if statements cause you will always have the same result.

If you create keys like this: map.put(new Key(x,y),V); you will never compare the references of your keys. Cause everytime you want to acces the map, you will do something like map.get(new Key(x,y));. Therefore your equals() does not need a statement like if (this == obj). It will never occure.

Instead of if (getClass() != obj.getClass()) in your equals() better use if (!(obj instanceof this)). It will be valid even for subclasses.

So the only thing you need to compare is actually X and Y. So the best equals() implementation in this case would be:

public boolean equals (final Object O) {
  if (!(O instanceof Key)) return false;
  if (((Key) O).X != X) return false;
  if (((Key) O).Y != Y) return false;
  return true;

So in the end your key class is like this:

public class Key {

  public final int X;
  public final int Y;

  public Key(final int X, final int Y) {
    this.X = X;
    this.Y = Y;

  public boolean equals (final Object O) {
    if (!(O instanceof Key)) return false;
    if (((Key) O).X != X) return false;
    if (((Key) O).Y != Y) return false;
    return true;

  public int hashCode() {
    return (X << 16) + Y;


You can give your dimension indices X and Y a public access level, due to the fact they are final and do not contain sensitive information. I'm not a 100% sure whether private access level works correctly in any case when casting the Object to a Key.

If you wonder about the finals, I declare anything as final which value is set on instancing and never changes - and therefore is an object constant.

How to log as much information as possible for a Java Exception?

A logging script that I have written some time ago might be of help, although it is not exactly what you want. It acts in a way like a System.out.println but with much more information about StackTrace etc. It also provides Clickable text for Eclipse:

private static final SimpleDateFormat   extended    = new SimpleDateFormat( "dd MMM yyyy (HH:mm:ss) zz" );

public static java.util.logging.Logger initLogger(final String name) {
    final java.util.logging.Logger logger = java.util.logging.Logger.getLogger( name );
    try {

        Handler ch = new ConsoleHandler();
        logger.addHandler( ch );

        logger.setLevel( Level.ALL ); // Level selbst setzen

        logger.setUseParentHandlers( false );

        final java.util.logging.SimpleFormatter formatter = new SimpleFormatter() {

            public synchronized String format(final LogRecord record) {
                StackTraceElement[] trace = new Throwable().getStackTrace();
                String clickable = "(" + trace[ 7 ].getFileName() + ":" + trace[ 7 ].getLineNumber() + ") ";
                /* Clickable text in Console. */

                for( int i = 8; i < trace.length; i++ ) {
                    /* 0 - 6 is the logging trace, 7 - x is the trace until log method was called */
                    if( trace[ i ].getFileName() == null )
                    clickable = "(" + trace[ i ].getFileName() + ":" + trace[ i ].getLineNumber() + ") -> " + clickable;

                final String time = "<" + extended.format( new Date( record.getMillis() ) ) + "> ";

                StringBuilder level = new StringBuilder("[" + record.getLevel() + "] ");
                while( level.length() < 15 ) /* extend for tabby display */
                    level.append(" ");

                StringBuilder name = new StringBuilder(record.getLoggerName()).append(": ");
                while( name.length() < 15 ) /* extend for tabby display */
                    name.append(" ");

                String thread = Thread.currentThread().getName();
                if( thread.length() > 18 ) /* trim if too long */
                    thread = thread.substring( 0, 16 ) + "..."; 
                else {
                    StringBuilder sb = new StringBuilder(thread);
                    while( sb.length() < 18 ) /* extend for tabby display */
                        sb.append(" ");
                    thread = sb.insert( 0, "Thread " ).toString();

                final String message = "\"" + record.getMessage() + "\" ";

                return level + time + thread + name + clickable + message + "\n";
        ch.setFormatter( formatter );
        ch.setLevel( Level.ALL );
    } catch( final SecurityException e ) {
    return logger;

Notice this outputs to the console, you can change that, see for more information on that.

Now, the following will probably do what you want. It will go through all causes of a Throwable and save it in a String. Note that this does not use StringBuilder, so you can optimize by changing it.

Throwable e = ...
String detail = e.getClass().getName() + ": " + e.getMessage();
for( final StackTraceElement s : e.getStackTrace() )
    detail += "\n\t" + s.toString();
while( ( e = e.getCause() ) != null ) {
    detail += "\nCaused by: ";
    for( final StackTraceElement s : e.getStackTrace() )
        detail += "\n\t" + s.toString();


SQL Server CTE and recursion example

Would like to outline a brief semantic parallel to an already correct answer.

In 'simple' terms, a recursive CTE can be semantically defined as the following parts:

1: The CTE query. Also known as ANCHOR.

2: The recursive CTE query on the CTE in (1) with UNION ALL (or UNION or EXCEPT or INTERSECT) so the ultimate result is accordingly returned.

3: The corner/termination condition. Which is by default when there are no more rows/tuples returned by the recursive query.

A short example that will make the picture clear:

;WITH SupplierChain_CTE(supplier_id, supplier_name, supplies_to, level)
SELECT S.supplier_id, S.supplier_name, S.supplies_to, 0 as level
FROM Supplier S
WHERE supplies_to = -1    -- Return the roots where a supplier supplies to no other supplier directly


-- The recursive CTE query on the SupplierChain_CTE
SELECT S.supplier_id, S.supplier_name, S.supplies_to, level + 1
FROM Supplier S
ON S.supplies_to = SC.supplier_id
-- Use the CTE to get all suppliers in a supply chain with levels
SELECT * FROM SupplierChain_CTE

Explanation: The first CTE query returns the base suppliers (like leaves) who do not supply to any other supplier directly (-1)

The recursive query in the first iteration gets all the suppliers who supply to the suppliers returned by the ANCHOR. This process continues till the condition returns tuples.

UNION ALL returns all the tuples over the total recursive calls.

Another good example can be found here.

PS: For a recursive CTE to work, the relations must have a hierarchical (recursive) condition to work on. Ex: elementId = elementParentId.. you get the point.

Conditionally change img src based on model data

Instead of src you need ng-src.

AngularJS views support binary operators

condition && true || false

So your img tag would look like this

<img ng-src="{{interface == 'UP' && 'green-checkmark.png' || 'big-black-X.png'}}"/>

Note : the quotes (ie 'green-checkmark.png') are important here. It won't work without quotes.

plunker here (open dev tools to see the produced HTML)

AngularJS: how to implement a simple file upload with multipart form?

It is more efficient to send a file directly.

The base64 encoding of Content-Type: multipart/form-data adds an extra 33% overhead. If the server supports it, it is more efficient to send the files directly:

$scope.upload = function(url, file) {
    var config = { headers: { 'Content-Type': undefined },
                   transformResponse: angular.identity
    return $, file, config);

When sending a POST with a File object, it is important to set 'Content-Type': undefined. The XHR send method will then detect the File object and automatically set the content type.

To send multiple files, see Doing Multiple $ Requests Directly from a FileList

I figured I should start with input type="file", but then found out that AngularJS can't bind to that..

The <input type=file> element does not by default work with the ng-model directive. It needs a custom directive:

Working Demo of "select-ng-files" Directive that Works with ng-model1


angular.module("app").directive("selectNgFiles", function() {
  return {
    require: "ngModel",
    link: function postLink(scope,elem,attrs,ngModel) {
      elem.on("change", function(e) {
        var files = elem[0].files;
<script src="//"></script>
  <body ng-app="app">
    <h1>AngularJS Input `type=file` Demo</h1>
    <input type="file" select-ng-files ng-model="fileArray" multiple>
    <div ng-repeat="file in fileArray">

$ with content type multipart/form-data

If one must send multipart/form-data:

<form role="form" enctype="multipart/form-data" name="myForm">
    <input type="text"  ng-model="fdata.UserName">
    <input type="text"  ng-model="fdata.FirstName">
    <input type="file"  select-ng-files ng-model="filesArray" multiple>
    <button type="submit" ng-click="upload()">save</button>
$scope.upload = function() {
    var fd = new FormData();
    fd.append("data", angular.toJson($scope.fdata));
    for (i=0; i<$scope.filesArray.length; i++) {
        fd.append("file"+i, $scope.filesArray[i]);

    var config = { headers: {'Content-Type': undefined},
                   transformRequest: angular.identity
    return $, fd, config);

When sending a POST with the FormData API, it is important to set 'Content-Type': undefined. The XHR send method will then detect the FormData object and automatically set the content type header to multipart/form-data with the proper boundary.

Meaning of "[: too many arguments" error from if [] (square brackets)

I have had same problem with my scripts. But when I did some modifications it worked for me. I did like this :-

export k=$(date "+%k");
if [ $k -ge 16 ] 
    then exit 0; 
    echo "good job for nothing"; 

that way I resolved my problem. Hope that will help for you too.

How to convert Nvarchar column to INT

You can always use the ISNUMERIC helper function to convert only what's really numeric:

     CAST(A.my_NvarcharColumn AS BIGINT)
     ISNUMERIC(A.my_NvarcharColumn) = 1

How can I disable mod_security in .htaccess file?

In .htaccess file at site root directory edit following line:

<ifmodule mod_security.c>_x000D_
SecFilterEngine Off_x000D_
SecFilterScanPOST Off_x000D_
<IfModule mod_rewrite.c>_x000D_
RewriteEngine On_x000D_
RewriteBase /_x000D_
RewriteCond %{REQUEST_FILENAME} !-f_x000D_
RewriteCond %{REQUEST_FILENAME} !-d_x000D_
RewriteRule . /index.php [L]_x000D_

Just keep the mod_security rules like SecFilterEngine and parts apart from each other. Its works for apache server

UTF-8 encoding in JSP page

The full JSP tag should be something like this, mind the pageEncoding too:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

Some old browsers mess up with the encoding too. you can use the HTML tag

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

Also the file should be recorded in UTF-8 format, if you are using Eclipse left-click on the file->Properties->Check out ->Text file encoding.

enabling cross-origin resource sharing on IIS7

Elaborating from DavidG answer which is really near of what is required for a basic solution:

  • First, configure the OPTIONSVerbHandler to execute before .Net handlers.

    1. In IIS console, select "Handler Mappings" (either on server level or site level; beware that on site level it will redefine all the handlers for your site and ignore any change done on server level after that; and of course on server level, this could break other sites if they need their own handling of options verb).
    2. In Action pane, select "View ordered list..." Seek OPTIONSVerbHandler, and move it up (lots of clicks...).

    You can also do this in web.config by redefining all handlers under <system.webServer><handlers> (<clear> then <add ...> them back, this is what does the IIS console for you) (By the way, there is no need to ask for "read" permission on this handler.)

  • Second, configure custom http headers for your cors needs, such as:

          <add name="Access-Control-Allow-Origin" value="*"/>
          <add name="Access-Control-Allow-Headers" value="Content-Type"/>
          <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS"/>

    You can also do this in IIS console.

This is a basic solution since it will send cors headers even on request which does not requires it. But with WCF, it looks like being the simpliest one.

With MVC or webapi, we could instead handle OPTIONS verb and cors headers by code (either "manually" or with built-in support available in latest version of webapi).

How can I make a checkbox readonly? not disabled?

There is no property to make the checkbox readonly. But you can try this trick.

<input type="checkbox" onclick="return false" />


Set div height equal to screen size


property and set to the div from script and set


for scrolling

How to access the request body when POSTing using Node.js and Express?

As of Express 4, the following code appears to do the trick. Note that you'll need to install body-parser using npm.

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));

app.listen(8888);'/update', function(req, res) {
    console.log(req.body); // the posted data

C++ Structure Initialization

I might be missing something here, by why not:

#include <cstdio>    
struct Group {
    int x;
    int y;
    const char* s;

int main() 
  Group group {
    .x = 1, 
    .y = 2, 
    .s = "Hello it works"
  printf("%d, %d, %s", group.x, group.y, group.s);

Cross Domain Form POSTing

Same origin policy has nothing to do with sending request to another url (different protocol or domain or port).

It is all about restricting access to (reading) response data from another url. So JavaScript code within a page can post to arbitrary domain or submit forms within that page to anywhere (unless the form is in an iframe with different url).

But what makes these POST requests inefficient is that these requests lack antiforgery tokens, so are ignored by the other url. Moreover, if the JavaScript tries to get that security tokens, by sending AJAX request to the victim url, it is prevented to access that data by Same Origin Policy.

A good example: here

And a good documentation from Mozilla: here

How do I POST an array of objects with $.ajax (jQuery or Zepto)

edit: I guess it's now starting to be safe to use the native JSON.stringify() method, supported by most browsers (yes, even IE8+ if you're wondering).

As simple as:


You should encode you data in JSON before sending it, you can't just send an object like this as POST data.

I recommand using the jQuery json plugin to do so. You can then use something like this in jQuery:

$.post(_saveDeviceUrl, {
    data : $.toJSON(postData)
}, function(response){
    //Process your response here

How to find time complexity of an algorithm

This is an excellent article :

The below answer is copied from above (in case the excellent link goes bust)

The most common metric for calculating time complexity is Big O notation. This removes all constant factors so that the running time can be estimated in relation to N as N approaches infinity. In general you can think of it like this:


Is constant. The running time of the statement will not change in relation to N.

for ( i = 0; i < N; i++ )

Is linear. The running time of the loop is directly proportional to N. When N doubles, so does the running time.

for ( i = 0; i < N; i++ ) {
  for ( j = 0; j < N; j++ )

Is quadratic. The running time of the two loops is proportional to the square of N. When N doubles, the running time increases by N * N.

while ( low <= high ) {
  mid = ( low + high ) / 2;
  if ( target < list[mid] )
    high = mid - 1;
  else if ( target > list[mid] )
    low = mid + 1;
  else break;

Is logarithmic. The running time of the algorithm is proportional to the number of times N can be divided by 2. This is because the algorithm divides the working area in half with each iteration.

void quicksort ( int list[], int left, int right )
  int pivot = partition ( list, left, right );
  quicksort ( list, left, pivot - 1 );
  quicksort ( list, pivot + 1, right );

Is N * log ( N ). The running time consists of N loops (iterative or recursive) that are logarithmic, thus the algorithm is a combination of linear and logarithmic.

In general, doing something with every item in one dimension is linear, doing something with every item in two dimensions is quadratic, and dividing the working area in half is logarithmic. There are other Big O measures such as cubic, exponential, and square root, but they're not nearly as common. Big O notation is described as O ( <type> ) where <type> is the measure. The quicksort algorithm would be described as O ( N * log ( N ) ).

Note that none of this has taken into account best, average, and worst case measures. Each would have its own Big O notation. Also note that this is a VERY simplistic explanation. Big O is the most common, but it's also more complex that I've shown. There are also other notations such as big omega, little o, and big theta. You probably won't encounter them outside of an algorithm analysis course. ;)

Unable to locate an executable at "/usr/bin/java/bin/java" (-1)

Most certainly, export JAVA_HOME=/usr/bin/java is the culprit. This env var should point to the JDK or JRE installation directory. Googling shows that the best option for MacOS X seems to be export JAVA_HOME=/Library/Java/Home.

Counting the number of occurences of characters in a string

This is the problem:


That will keep going until it falls off the end... when i is the same as the length of the string, it will be asking for a character beyond the end of the string. You probably want:

while (i < str.length() && str.charAt(i) == ch)

You also need to set count to 0 at the start of each iteration of the bigger loop - the count resets, after all - and change

count = count + i;

to either:


... or get rid of count or i. They're always going to have the same value, after all. Personally I'd just use one variable, declared and initialized inside the loop. That's a general style point, in fact - it's cleaner to declare local variables when they're needed, rather than declaring them all at the top of the method.

However, then your program will loop forever, as this doesn't do anything useful:


Strings are immutable in Java - substring returns a new string. I think you want:

str = str.substring(count);

Note that this will still output "a2b2a2" for "aabbaa". Is that okay?

getting a checkbox array value from POST

Check out the implode() function as an alternative. This will convert the array into a list. The first param is how you want the items separated. Here I have used a comma with a space after it.

$invite = implode(', ', $_POST['invite']);
echo $invite;

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

This works for me:

ln -s /usr/local/Cellar/mysql/5.6.22/lib/libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.18.dylib

Convert Java Array to Iterable

First of all, I can only agree that Arrays.asList(T...) is clearly the best solution for Wrapper types or arrays with non-primtive datatypes. This method calls a constructor of a simple private static AbstractList implementation in the Arrays class which basically saves the given array reference as field and simulates a list by overriding the needed methods.

If you can choose between a primtive type or a Wrapper type for your array, I would use the Wrapper type for such situations but of course, it's not always useful or required. There would be only two possibilities you can do:

1) You can create a class with a static method for each primitive datatype array (boolean, byte, short, int, long, char, float, double returning an Iterable<WrapperType>. These methods would use anonymous classes of Iterator (besides Iterable) which are allowed to contain the reference of the comprising method's argument (for example an int[]) as field in order to implement the methods.

-> This approach is performant and saves you memory (except for the memory of the newly created methods, even though, using Arrays.asList() would take memory in the same way)

2) Since arrays don't have methods (as to be read on the side you linked) they can't provide an Iterator instance either. If you really are too lazy to write new classes, you must use an instance of an already existing class that implements Iterable because there is no other way around than instantiating Iterable or a subtype.
The ONLY way to create an existing Collection derivative implementing Iterable is to use a loop (except you use anonymous classes as described above) or you instantiate an Iterable implementing class whose constructor allows a primtive type array (because Object[] doesn't allow arrays with primitive type elements) but as far as I know, the Java API doesn't feature a class like that.

The reason for the loop can be explained easily:
for each Collection you need Objects and primtive datatypes aren't objects. Objects are much bigger than primitive types so that they require additional data which must be generated for each element of the primitive type array. That means if two ways of three (using Arrays.asList(T...) or using an existing Collection) require an aggregate of objects, you need to create for each primitive value of your int[] array the wrapper object. The third way would use the array as is and use it in an anonymous class as I think it's preferable due to fast performance.

There is also a third strategy using an Object as argument for the method where you want to use the array or Iterable and it would require type checks to figure out which type the argument has, however I wouldn't recommend it at all as you usually need to consider that the Object hasn't always the required type and that you need seperate code for certain cases.

In conclusion, it's the fault of Java's problematic Generic Type system which doesn't allow to use primitive types as generic type which would save a lot of code by using simply Arrays.asList(T...). So you need to program for each primitive type array, you need, such a method (which basically makes no difference to the memory used by a C++ program which would create for each used type argument a seperate method.

What is a LAMP stack?

The reason they call it a stack is because each level derives off its base layer. Your operating system, Linux, is the base layer. Then Apache, your web daemon sits on top of your OS. Then your database stores all the information served by your web daemon, and PHP (or any P* scripting language) is used to drive and display all the data, and allow for user interaction.

Don't be overly concerned with the term 'stack'. People really just mean software suite or bundle, but you're using it just fine I am sure as you are.

Safari 3rd party cookie iframe trick no longer working?

I had this problem on devices running iOS. I made a shop that is embeddable in a normal website using an iframe. Somehow, on every pageload the user got a new sessionid, resulting in users getting stuck halfway the process because some values weren't present in the session.

I tried some of the solutions given on this page, but popups don't work very well on an iPad and I needed the most transparent solution.

I resolved it using a redirect. The website that embeds my site must first redirect the user to my site, so the top frame contains the url to my site, where I set a cookie and redirect the user to the proper page on the website that embeds my site, that is passed through in the url.

Example PHP code

Remote website redirects user to


// set a cookie for a year
setcookie('initialized','1',time() + 3600 * 24 * 365, '/', '', false, false);
header('location: ' . $_GET['redir']);

The user ends up on where my site is embedded, storing sessions as it should and eating cookies.

Hope this helps someone.

Insert current date/time using now() in a field using MySQL/PHP

These both work fine for me...

  $db = mysql_connect('localhost','user','pass');

  $stmt = "INSERT INTO `test` (`first`,`last`,`whenadded`) VALUES ".
  $rslt = mysql_query($stmt);

  $stmt = "INSERT INTO `users` (`first`,`last`,`whenadded`) VALUES ".
          "('{$first}', '{$last}', CURRENT_TIMESTAMP)";
  $rslt = mysql_query($stmt);


Side note: mysql_query() is not the best way to connect to MySQL in current versions of PHP.

How to remove margin space around body or clear default css styles

I found this problem continued even when setting the BODY MARGIN to zero.

However it turns out there is an easy fix. All you need to do is give your HEADER tag a 1px border, aswell as setting the BODY MARGIN to zero, as shown below.

body { margin:0px; }

header { border:1px black solid; }

If you have any H1, H2, tags within your HEADER you will also need to set the MARGIN for these tags to zero, this will get rid of any extra space which may show up.

Not sure why this works, but I use Chrome browser. Obviously you can also change the colour of the border to match your header colour.

Display all items in array using jquery

for (var i = 0; i < array.length; i++) {
    $(".element").append('<span>' + array[i] + '</span>');

Binary Data Posting with curl

You don't need --header "Content-Length: $LENGTH".

curl --request POST --data-binary "@template_entry.xml" $URL

Note that GET request does not support content body widely.

Also remember that POST request have 2 different coding schema. This is first form:

  $ nc -l -p 6666 &
  $ curl  --request POST --data-binary "@README" http://localhost:6666

User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/ libidn/1.15 libssh2/1.2.6
Host: localhost:6666
Accept: */*
Content-Length: 9309
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

.. -*- mode: rst; coding: cp1251; fill-column: 80 -*-
.. contents::

You probably request this:

-F/--form name=content
           (HTTP) This lets curl emulate a filled-in form in
              which a user has pressed the submit button. This
              causes curl to POST data using the Content- Type
              multipart/form-data according to RFC2388. This
              enables uploading of binary files etc. To force the
              'content' part to be a file, prefix the file name
              with an @ sign. To just get the content part from a
              file, prefix the file name with the symbol <. The
              difference between @ and < is then that @ makes a
              file get attached in the post as a file upload,
              while the < makes a text field and just get the
              contents for that text field from a file.

POST an array from an HTML form without javascript

You can also post multiple inputs with the same name and have them save into an array by adding empty square brackets to the input name like this:

<input type="text" name="comment[]" value="comment1"/>
<input type="text" name="comment[]" value="comment2"/>
<input type="text" name="comment[]" value="comment3"/>
<input type="text" name="comment[]" value="comment4"/>

If you use php:


you will get this:

Array ( [0] => 'comment1' [1] => 'comment2' [2] => 'comment3' [3] => 'comment4' )

Encapsulation vs Abstraction?

in a simple sentence, I cay say: The essence of abstraction is to extract essential properties while omitting inessential details. But why should we omit inessential details? The key motivator is preventing the risk of change. You might consider abstraction is same as encapsulation. But encapsulation means the act of enclosing one or more items within a container, not hiding details. If you make the argument that "everything that was encapsulated was also hidden." This is obviously not true. For example, even though information may be encapsulated within record structures and arrays, this information is usually not hidden (unless hidden via some other mechanism).

log4net hierarchy and logging levels

As others have noted, it is usually preferable to specify a minimum logging level to log that level and any others more severe than it. It seems like you are just thinking about the logging levels backwards.

However, if you want more fine-grained control over logging individual levels, you can tell log4net to log only one or more specific levels using the following syntax:

<filter type="log4net.Filter.LevelMatchFilter">
  <levelToMatch value="WARN"/>

Or to exclude a specific logging level by adding a "deny" node to the filter.

You can stack multiple filters together to specify multiple levels. For instance, if you wanted only WARN and FATAL levels. If the levels you wanted were consecutive, then the LevelRangeFilter is more appropriate.

Reference Doc: log4net.Filter.LevelMatchFilter

If the other answers haven't given you enough information, hopefully this will help you get what you want out of log4net.

#1071 - Specified key was too long; max key length is 1000 bytes

This index size limit seems to be larger on 64 bit builds of MySQL.

I was hitting this limitation trying to dump our dev database and load it on a local VMWare virt. Finally I realized that the remote dev server was 64 bit and I had created a 32 bit virt. I just created a 64 bit virt and I was able to load the database locally.

Android AudioRecord example

Here I am posting you the some code example which record good quality of sound using AudioRecord API.

Note: If you use in emulator the sound quality will not much good because we are using sample rate 8k which only supports in emulator. In device use sample rate to 44.1k for better quality.

public class Audio_Record extends Activity {
    private static final int RECORDER_SAMPLERATE = 8000;
    private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
    private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
    private AudioRecord recorder = null;
    private Thread recordingThread = null;
    private boolean isRecording = false;

    public void onCreate(Bundle savedInstanceState) {


        int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,

    private void setButtonHandlers() {
        ((Button) findViewById(;
        ((Button) findViewById(;

    private void enableButton(int id, boolean isEnable) {
        ((Button) findViewById(id)).setEnabled(isEnable);

    private void enableButtons(boolean isRecording) {
        enableButton(, !isRecording);
        enableButton(, isRecording);

    int BufferElements2Rec = 1024; // want to play 2048 (2K) since 2 bytes we use only 1024
    int BytesPerElement = 2; // 2 bytes in 16bit format

    private void startRecording() {

        recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
                RECORDER_AUDIO_ENCODING, BufferElements2Rec * BytesPerElement);

        isRecording = true;
        recordingThread = new Thread(new Runnable() {
            public void run() {
        }, "AudioRecorder Thread");

        //convert short to byte
    private byte[] short2byte(short[] sData) {
        int shortArrsize = sData.length;
        byte[] bytes = new byte[shortArrsize * 2];
        for (int i = 0; i < shortArrsize; i++) {
            bytes[i * 2] = (byte) (sData[i] & 0x00FF);
            bytes[(i * 2) + 1] = (byte) (sData[i] >> 8);
            sData[i] = 0;
        return bytes;


    private void writeAudioDataToFile() {
        // Write the output audio in byte

        String filePath = "/sdcard/voice8K16bitmono.pcm";
        short sData[] = new short[BufferElements2Rec];

        FileOutputStream os = null;
        try {
            os = new FileOutputStream(filePath);
        } catch (FileNotFoundException e) {

        while (isRecording) {
            // gets the voice output from microphone to byte format

  , 0, BufferElements2Rec);
            System.out.println("Short writing to file" + sData.toString());
            try {
                // // writes the data to file from buffer
                // // stores the voice buffer
                byte bData[] = short2byte(sData);
                os.write(bData, 0, BufferElements2Rec * BytesPerElement);
            } catch (IOException e) {
        try {
        } catch (IOException e) {

    private void stopRecording() {
        // stops the recording activity
        if (null != recorder) {
            isRecording = false;
            recorder = null;
            recordingThread = null;

    private View.OnClickListener btnClick = new View.OnClickListener() {
        public void onClick(View v) {
            switch (v.getId()) {
            case {
            case {

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
        return super.onKeyDown(keyCode, event);

For more detail try this AUDIORECORD BLOG.

Happy Coding !!

Best way to call a JSON WebService from a .NET Console

I use HttpWebRequest to GET from the web service, which returns me a JSON string. It looks something like this for a GET:

// Returns JSON string
string GET(string url) 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    try {
        WebResponse response = request.GetResponse();
        using (Stream responseStream = response.GetResponseStream()) {
            StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
            return reader.ReadToEnd();
    catch (WebException ex) {
        WebResponse errorResponse = ex.Response;
        using (Stream responseStream = errorResponse.GetResponseStream())
            StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
            String errorText = reader.ReadToEnd();
            // log errorText

I then use JSON.Net to dynamically parse the string. Alternatively, you can generate the C# class statically from sample JSON output using this codeplex tool:

POST looks like this:

// POST a JSON string
void POST(string url, string jsonContent) 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";

    System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
    Byte[] byteArray = encoding.GetBytes(jsonContent);

    request.ContentLength = byteArray.Length;
    request.ContentType = @"application/json";

    using (Stream dataStream = request.GetRequestStream()) {
        dataStream.Write(byteArray, 0, byteArray.Length);
    long length = 0;
    try {
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
            length = response.ContentLength;
    catch (WebException ex) {
        // Log exception and throw as for GET example above

I use code like this in automated tests of our web service.

How to check if input date is equal to today's date?

A simple date comparison in pure JS should be sufficient:

// Create date from input value
var inputDate = new Date("11/21/2011");

// Get today's date
var todaysDate = new Date();

// call setHours to take the time out of the comparison
if(inputDate.setHours(0,0,0,0) == todaysDate.setHours(0,0,0,0)) {
    // Date equals today's date

Here's a working JSFiddle.

How does one use the onerror attribute of an img element

very simple

  <img onload="loaded(this, 'success')" onerror="error(this, 
 'error')"  src="someurl"  alt="" />

 function loaded(_this, status){
   console.log(_this, status)
  // do your work in load
 function error(_this, status){
  console.log(_this, status)
  // do your work in error

How to make script execution wait until jquery is loaded

A tangential note on the approaches here that load use setTimeout or setInterval. In those cases it's possible that when your check runs again, the DOM will already have loaded, and the browser's DOMContentLoaded event will have been fired, so you can't detect that event reliably using these approaches. What I found is that jQuery's ready still works, though, so you can embed your usual

jQuery(document).ready(function ($) { ... }

inside your setTimeout or setInterval and everything should work as normal.

Any way to break if statement in PHP?

No, there is no way to "break" an if block like you would inside loops.:(
So turn your test into a switch !

I wonder why nobody encouraged you to use switch statement since (even if you haven't to many test cases)
Do you think it's too verbose?

I would definitely go for it here

    case 'test':
        # do stuff here ...
        if(/* Reason why you may break */){
           break; # this will prevent executing "echo 'yes';" statement
        echo 'yes';  # ...           
        break; # As one may already know, we might always have to break at the end of case to prevent executing following cases instructions.
    # default:
        # something else here  ..
        # break;

To me Exceptions are meant to raise errors and not really to control execution flaw.
If the break behaviour you are trying to set is not about unexpected error(s), Exception handling is not the right solution here :/.

Reading file input from a multipart/form-data POST

I have dealt WCF with large file (serveral GB) upload where store data in memory is not an option. My solution is to store message stream to a temp file and use seek to find out begin and end of binary data.

How to solve error message: "Failed to map the path '/'."

Executing the command iisreset (cmd with elevated rights) fixed this issue for me.

What are the time complexities of various data structures?


  • Set, Check element at a particular index: O(1)
  • Searching: O(n) if array is unsorted and O(log n) if array is sorted and something like a binary search is used,
  • As pointed out by Aivean, there is no Delete operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirements
  • Similarly, Insert for arrays is basically Set as mentioned in the beginning


  • Add: Amortized O(1)
  • Remove: O(n)
  • Contains: O(n)
  • Size: O(1)

Linked List:

  • Inserting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Doubly-Linked List:

  • Inserting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)


  • Push: O(1)
  • Pop: O(1)
  • Top: O(1)
  • Search (Something like lookup, as a special operation): O(n) (I guess so)

Queue/Deque/Circular Queue:

  • Insert: O(1)
  • Remove: O(1)
  • Size: O(1)

Binary Search Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(n)

Red-Black Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(log n)

Heap/PriorityQueue (min/max):

  • Find Min/Find Max: O(1)
  • Insert: O(log n)
  • Delete Min/Delete Max: O(log n)
  • Extract Min/Extract Max: O(log n)
  • Lookup, Delete (if at all provided): O(n), we will have to scan all the elements as they are not ordered like BST


  • Insert/Delete: O(1) amortized
  • Re-size/hash: O(n)
  • Contains: O(1)

jQuery select option elements by value

Just wrap your option in $(option) to make it act the way you want it to. You can also make the code shorter by doing

$('#span_id > select > option[value="input your i here"]').attr("selected", "selected")

Should I URL-encode POST data?

@DougW has clearly answered this question, but I still like to add some codes here to explain Doug's points. (And correct errors in the code above)

Solution 1: URL-encode the POST data with a content-type header :application/x-www-form-urlencoded .

Note: you do not need to urlencode $_POST[] fields one by one, http_build_query() function can do the urlencoding job nicely.

$fields = array(

$fields_string = http_build_query($fields);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);

Solution 2: Pass the array directly as the post data without URL-encoding, while the Content-Type header will be set to multipart/form-data.

$fields = array(

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_POST,1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$fields);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($ch);

Both code snippets work, but using different HTTP headers and bodies.

Iterator invalidation rules

Since this question draws so many votes and kind of becomes an FAQ, I guess it would be better to write a separate answer to mention one significant difference between C++03 and C++11 regarding the impact of std::vector's insertion operation on the validity of iterators and references with respect to reserve() and capacity(), which the most upvoted answer failed to notice.

C++ 03:

Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. It is guaranteed that no reallocation takes place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the size specified in the most recent call to reserve().


Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. It is guaranteed that no reallocation takes place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the value of capacity().

So in C++03, it is not "unless the new container size is greater than the previous capacity (in which case all iterators and references are invalidated)" as mentioned in the other answer, instead, it should be "greater than the size specified in the most recent call to reserve()". This is one thing that C++03 differs from C++11. In C++03, once an insert() causes the size of the vector to reach the value specified in the previous reserve() call (which could well be smaller than the current capacity() since a reserve() could result a bigger capacity() than asked for), any subsequent insert() could cause reallocation and invalidate all the iterators and references. In C++11, this won't happen and you can always trust capacity() to know with certainty that the next reallocation won't take place before the size overpasses capacity().

In conclusion, if you are working with a C++03 vector and you want to make sure a reallocation won't happen when you perform insertion, it's the value of the argument you previously passed to reserve() that you should check the size against, not the return value of a call to capacity(), otherwise you may get yourself surprised at a "premature" reallocation.

Jquery Ajax Posting json to webservice

I tried Dave Ward's solution. The data part was not being sent from the browser in the payload part of the post request as the contentType is set to "application/json". Once I removed this line everything worked great.

var markers = [{ "position": "128.3657142857143", "markerPosition": "7" },

               { "position": "235.1944023323615", "markerPosition": "19" },

               { "position": "42.5978231292517", "markerPosition": "-3" }];


    type: "POST",
    url: "/webservices/PodcastService.asmx/CreateMarkers",
    // The key needs to match your method's input parameter (case-sensitive).
    data: JSON.stringify({ Markers: markers }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){alert(data);},
    failure: function(errMsg) {

Using grep to search for hex strings in a file

I just used this:

grep -c $'\x0c' filename

To search for and count a page control character in the file..

So to include an offset in the output:

grep -b -o $'\x0c' filename | less

I am just piping the result to less because the character I am greping for does not print well and the less displays the results cleanly. Output example:


RestSharp JSON Parameter Posting

You might need to Deserialize your anonymous JSON type from the request body.

var jsonBody = HttpContext.Request.Content.ReadAsStringAsync().Result;
ScoreInputModel myDeserializedClass = JsonConvert.DeserializeObject<ScoreInputModel>(jsonBody);

How does the compilation/linking process work?

The compilation of a C++ program involves three steps:

  1. Preprocessing: the preprocessor takes a C++ source code file and deals with the #includes, #defines and other preprocessor directives. The output of this step is a "pure" C++ file without pre-processor directives.

  2. Compilation: the compiler takes the pre-processor's output and produces an object file from it.

  3. Linking: the linker takes the object files produced by the compiler and produces either a library or an executable file.


The preprocessor handles the preprocessor directives, like #include and #define. It is agnostic of the syntax of C++, which is why it must be used with care.

It works on one C++ source file at a time by replacing #include directives with the content of the respective files (which is usually just declarations), doing replacement of macros (#define), and selecting different portions of text depending of #if, #ifdef and #ifndef directives.

The preprocessor works on a stream of preprocessing tokens. Macro substitution is defined as replacing tokens with other tokens (the operator ## enables merging two tokens when it makes sense).

After all this, the preprocessor produces a single output that is a stream of tokens resulting from the transformations described above. It also adds some special markers that tell the compiler where each line came from so that it can use those to produce sensible error messages.

Some errors can be produced at this stage with clever use of the #if and #error directives.


The compilation step is performed on each output of the preprocessor. The compiler parses the pure C++ source code (now without any preprocessor directives) and converts it into assembly code. Then invokes underlying back-end(assembler in toolchain) that assembles that code into machine code producing actual binary file in some format(ELF, COFF, a.out, ...). This object file contains the compiled code (in binary form) of the symbols defined in the input. Symbols in object files are referred to by name.

Object files can refer to symbols that are not defined. This is the case when you use a declaration, and don't provide a definition for it. The compiler doesn't mind this, and will happily produce the object file as long as the source code is well-formed.

Compilers usually let you stop compilation at this point. This is very useful because with it you can compile each source code file separately. The advantage this provides is that you don't need to recompile everything if you only change a single file.

The produced object files can be put in special archives called static libraries, for easier reusing later on.

It's at this stage that "regular" compiler errors, like syntax errors or failed overload resolution errors, are reported.


The linker is what produces the final compilation output from the object files the compiler produced. This output can be either a shared (or dynamic) library (and while the name is similar, they haven't got much in common with static libraries mentioned earlier) or an executable.

It links all the object files by replacing the references to undefined symbols with the correct addresses. Each of these symbols can be defined in other object files or in libraries. If they are defined in libraries other than the standard library, you need to tell the linker about them.

At this stage the most common errors are missing definitions or duplicate definitions. The former means that either the definitions don't exist (i.e. they are not written), or that the object files or libraries where they reside were not given to the linker. The latter is obvious: the same symbol was defined in two different object files or libraries.

Posting array from form

When you post that data, it is stored as an array in $_POST.

You could optionally do something like:

<input name="arrayname[item1]">
<input name="arrayname[item2]">
<input name="arrayname[item3]">


$item1 = $_POST['arrayname']['item1'];
$item2 = $_POST['arrayname']['item2'];
$item3 = $_POST['arrayname']['item3'];

But I fail to see the point.

RESTful web service - how to authenticate requests from other services?

Besides authentication, I suggest you think about the big picture. Consider make your backend RESTful service without any authentication; then put some very simple authentication required middle layer service between the end user and the backend service.

How can I read Chrome Cache files?

I had some luck with this open-source Python project, seemingly inactive:

I ran:

python2 Chromagnon/ path/to/Chrome/Cache -o browsable_cache/

And I got a locally-browsable extract of all my open tabs cache.

POSTing JsonObject With HttpClient From Web API

the code over it in vbnet:

dim FeToSend as new (object--> define class)

Dim client As New HttpClient
Dim content = New StringContent(FeToSend.ToString(), Encoding.UTF8,"application/json")
content.Headers.ContentType = New MediaTypeHeaderValue( "application/json" )
Dim risp = client.PostAsync(Chiamata, content).Result


Hope this help

Generate a random point within a circle (uniformly)

Here is my Python code to generate num random points from a circle of radius rad:

import matplotlib.pyplot as plt
import numpy as np
rad = 10
num = 1000

t = np.random.uniform(0.0, 2.0*np.pi, num)
r = rad * np.sqrt(np.random.uniform(0.0, 1.0, num))
x = r * np.cos(t)
y = r * np.sin(t)

plt.plot(x, y, "ro", ms=1)
plt.axis([-15, 15, -15, 15])

How do I make a PHP form that submits to self?

The proper way would be to use $_SERVER["PHP_SELF"] (in conjunction with htmlspecialchars to avoid possible exploits). You can also just skip the action= part empty, which is not W3C valid, but currently works in most (all?) browsers - the default is to submit to self if it's empty.

Here is an example form that takes a name and email, and then displays the values you have entered upon submit:

<?php if (!empty($_POST)): ?>
    Welcome, <?php echo htmlspecialchars($_POST["name"]); ?>!<br>
    Your email is <?php echo htmlspecialchars($_POST["email"]); ?>.<br>
<?php else: ?>
    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
        Name: <input type="text" name="name"><br>
        Email: <input type="text" name="email"><br>
        <input type="submit">
<?php endif; ?>

jQuery posting JSON

In case you are sending this post request to a cross domain, you should check out this link.

Your server is not accepting the cross site post request. So the server configuration needs to be changed to allow cross site requests.

stop service in android

To stop the service we must use the method stopService():

  Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);

then the method onDestroy() in the service is called:

    public void onDestroy() {

        Log.i(TAG, "onCreate() , service stopped...");

Here is a complete example including how to stop the service.

Receiving login prompt using integrated windows authentication

I tried the above IIS configuration tricks and loopback registry hack, and I reviewed and recreated app pool permissions and a dozen other things and still wasn't able to get rid of the authentication loop running on my development workstation with IIS Express or IIS 7.5, from a local or remote browsing session. I received four 401.2 status responses and a blank page. The exact same site deployed to my IIS 8.5 staging server works flawlessly.

Finally I noticed markup in the Response Body that was rendered blank by the browser contained the default page for a successful log in. I determined that Custom Error handling for ASP.NET and HTTP for the 401 error was preventing/interfering with Windows Authentication my workstation but not the staging server. I spent several hours fiddling with this, but as soon as I removed custom handling for just the 401 error, the workstation was back to normal. I present this as yet one another way to shoot your own foot.

Dropdownlist validation in Using Required field validator

I was struggling with this for a few days until I chanced on the issue when I had to build a new Dropdown. I had several DropDownList controls and attempted to get validation working with no luck. One was databound and the other was filled from the aspx page. I needed to drop the databound one and add a second manual list. In my case Validators failed if you built a dropdown like this and looked at any value (0 or -1) for either a required or compare validator:

<asp:DropDownList ID="DDL_Reason" CssClass="inputDropDown" runat="server">
<asp:ListItem>Location Change</asp:ListItem>                                                                                            

However adding the InitialValue like this worked instantly for a compare Validator.

<asp:ListItem Text="-- Select --" Value="-1"></asp:ListItem>

How to retrieve form values from HTTPPOST, dictionary or?

Simply, you can use FormCollection like:

public ActionResult SubmitAction(FormCollection collection)
     // Get Post Params Here
 string var1 = collection["var1"];

You can also use a class, that is mapped with Form values, and mvc engine automagically fills it:

//Defined in another file
class MyForm
  public string var1 { get; set; }

public ActionResult SubmitAction(MyForm form)
  string var1 = form1.Var1;

PHP errors NOT being displayed in the browser [Ubuntu 10.10]

After you edit /etc/php5/apache2/php.ini be sure to restart apache.

You can do so by running:

sudo service apache2 restart

Removing duplicates from a SQL query (not just "use distinct")

If I understand you correctly, you want to list to exclude duplicates on one column only, inner join to a sub-select

select u.* [whatever joined values]
from users u
inner join
(select name from users group by name having count(*)=1) uniquenames
on =

How do I use arrays in C++?

Programmers often confuse multidimensional arrays with arrays of pointers.

Multidimensional arrays

Most programmers are familiar with named multidimensional arrays, but many are unaware of the fact that multidimensional array can also be created anonymously. Multidimensional arrays are often referred to as "arrays of arrays" or "true multidimensional arrays".

Named multidimensional arrays

When using named multidimensional arrays, all dimensions must be known at compile time:

int H = read_int();
int W = read_int();

int connect_four[6][7];   // okay

int connect_four[H][7];   // ISO C++ forbids variable length array
int connect_four[6][W];   // ISO C++ forbids variable length array
int connect_four[H][W];   // ISO C++ forbids variable length array

This is how a named multidimensional array looks like in memory:

connect_four: |   |   |   |   |   |   |   |
              |   |   |   |   |   |   |   |
              |   |   |   |   |   |   |   |
              |   |   |   |   |   |   |   |
              |   |   |   |   |   |   |   |
              |   |   |   |   |   |   |   |

Note that 2D grids such as the above are merely helpful visualizations. From the point of view of C++, memory is a "flat" sequence of bytes. The elements of a multidimensional array are stored in row-major order. That is, connect_four[0][6] and connect_four[1][0] are neighbors in memory. In fact, connect_four[0][7] and connect_four[1][0] denote the same element! This means that you can take multi-dimensional arrays and treat them as large, one-dimensional arrays:

int* p = &connect_four[0][0];
int* q = p + 42;
some_int_sequence_algorithm(p, q);

Anonymous multidimensional arrays

With anonymous multidimensional arrays, all dimensions except the first must be known at compile time:

int (*p)[7] = new int[6][7];   // okay
int (*p)[7] = new int[H][7];   // okay

int (*p)[W] = new int[6][W];   // ISO C++ forbids variable length array
int (*p)[W] = new int[H][W];   // ISO C++ forbids variable length array

This is how an anonymous multidimensional array looks like in memory:

        +---> |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
   p: | | |

Note that the array itself is still allocated as a single block in memory.

Arrays of pointers

You can overcome the restriction of fixed width by introducing another level of indirection.

Named arrays of pointers

Here is a named array of five pointers which are initialized with anonymous arrays of different lengths:

int* triangle[5];
for (int i = 0; i < 5; ++i)
    triangle[i] = new int[5 - i];

// ...

for (int i = 0; i < 5; ++i)
    delete[] triangle[i];

And here is how it looks like in memory:

          |   |   |   |   |   |
            | +---+---+---+---+
            | |   |   |   |   |
            | +---+---+---+---+
            |   ^
            |   | +---+---+---+
            |   | |   |   |   |
            |   | +---+---+---+
            |   |   ^
            |   |   | +---+---+
            |   |   | |   |   |
            |   |   | +---+---+
            |   |   |   ^
            |   |   |   | +---+
            |   |   |   | |   |
            |   |   |   | +---+
            |   |   |   |   ^
            |   |   |   |   |
            |   |   |   |   |
triangle: | | | | | | | | | | |

Since each line is allocated individually now, viewing 2D arrays as 1D arrays does not work anymore.

Anonymous arrays of pointers

Here is an anonymous array of 5 (or any other number of) pointers which are initialized with anonymous arrays of different lengths:

int n = calculate_five();   // or any other number
int** p = new int*[n];
for (int i = 0; i < n; ++i)
    p[i] = new int[n - i];

// ...

for (int i = 0; i < n; ++i)
    delete[] p[i];
delete[] p;   // note the extra delete[] !

And here is how it looks like in memory:

          |   |   |   |   |   |
            | +---+---+---+---+
            | |   |   |   |   |
            | +---+---+---+---+
            |   ^
            |   | +---+---+---+
            |   | |   |   |   |
            |   | +---+---+---+
            |   |   ^
            |   |   | +---+---+
            |   |   | |   |   |
            |   |   | +---+---+
            |   |   |   ^
            |   |   |   | +---+
            |   |   |   | |   |
            |   |   |   | +---+
            |   |   |   |   ^
            |   |   |   |   |
            |   |   |   |   |
          | | | | | | | | | | |
       p: | | |


Array-to-pointer decay naturally extends to arrays of arrays and arrays of pointers:

int array_of_arrays[6][7];
int (*pointer_to_array)[7] = array_of_arrays;

int* array_of_pointers[6];
int** pointer_to_pointer = array_of_pointers;

However, there is no implicit conversion from T[h][w] to T**. If such an implicit conversion did exist, the result would be a pointer to the first element of an array of h pointers to T (each pointing to the first element of a line in the original 2D array), but that pointer array does not exist anywhere in memory yet. If you want such a conversion, you must create and fill the required pointer array manually:

int connect_four[6][7];

int** p = new int*[6];
for (int i = 0; i < 6; ++i)
    p[i] = connect_four[i];

// ...

delete[] p;

Note that this generates a view of the original multidimensional array. If you need a copy instead, you must create extra arrays and copy the data yourself:

int connect_four[6][7];

int** p = new int*[6];
for (int i = 0; i < 6; ++i)
    p[i] = new int[7];
    std::copy(connect_four[i], connect_four[i + 1], p[i]);

// ...

for (int i = 0; i < 6; ++i)
    delete[] p[i];
delete[] p;

posting hidden value

You have to use $_POST['date'] instead of $date if it's coming from a POST request ($_GET if it's a GET request).

How do I navigate to another page when PHP script is done?

if ($done)
    header("Location: /url/to/the/other/page");

Using {% url ??? %} in django templates

Judging from your example, shouldn't it be {% url myproject.login.views.login_view %} and end of story? (replace myproject with your actual project name)

What are the basic rules and idioms for operator overloading?

Overloading new and delete

Note: This only deals with the syntax of overloading new and delete, not with the implementation of such overloaded operators. I think that the semantics of overloading new and delete deserve their own FAQ, within the topic of operator overloading I can never do it justice.


In C++, when you write a new expression like new T(arg) two things happen when this expression is evaluated: First operator new is invoked to obtain raw memory, and then the appropriate constructor of T is invoked to turn this raw memory into a valid object. Likewise, when you delete an object, first its destructor is called, and then the memory is returned to operator delete.
C++ allows you to tune both of these operations: memory management and the construction/destruction of the object at the allocated memory. The latter is done by writing constructors and destructors for a class. Fine-tuning memory management is done by writing your own operator new and operator delete.

The first of the basic rules of operator overloading – don’t do it – applies especially to overloading new and delete. Almost the only reasons to overload these operators are performance problems and memory constraints, and in many cases, other actions, like changes to the algorithms used, will provide a much higher cost/gain ratio than attempting to tweak memory management.

The C++ standard library comes with a set of predefined new and delete operators. The most important ones are these:

void* operator new(std::size_t) throw(std::bad_alloc); 
void  operator delete(void*) throw(); 
void* operator new[](std::size_t) throw(std::bad_alloc); 
void  operator delete[](void*) throw(); 

The first two allocate/deallocate memory for an object, the latter two for an array of objects. If you provide your own versions of these, they will not overload, but replace the ones from the standard library.
If you overload operator new, you should always also overload the matching operator delete, even if you never intend to call it. The reason is that, if a constructor throws during the evaluation of a new expression, the run-time system will return the memory to the operator delete matching the operator new that was called to allocate the memory to create the object in. If you do not provide a matching operator delete, the default one is called, which is almost always wrong.
If you overload new and delete, you should consider overloading the array variants, too.

Placement new

C++ allows new and delete operators to take additional arguments.
So-called placement new allows you to create an object at a certain address which is passed to:

class X { /* ... */ };
char buffer[ sizeof(X) ];
void f()
  X* p = new(buffer) X(/*...*/);
  // ... 
  p->~X(); // call destructor 

The standard library comes with the appropriate overloads of the new and delete operators for this:

void* operator new(std::size_t,void* p) throw(std::bad_alloc); 
void  operator delete(void* p,void*) throw(); 
void* operator new[](std::size_t,void* p) throw(std::bad_alloc); 
void  operator delete[](void* p,void*) throw(); 

Note that, in the example code for placement new given above, operator delete is never called, unless the constructor of X throws an exception.

You can also overload new and delete with other arguments. As with the additional argument for placement new, these arguments are also listed within parentheses after the keyword new. Merely for historical reasons, such variants are often also called placement new, even if their arguments are not for placing an object at a specific address.

Class-specific new and delete

Most commonly you will want to fine-tune memory management because measurement has shown that instances of a specific class, or of a group of related classes, are created and destroyed often and that the default memory management of the run-time system, tuned for general performance, deals inefficiently in this specific case. To improve this, you can overload new and delete for a specific class:

class my_class { 
    // ... 
    void* operator new();
    void  operator delete(void*,std::size_t);
    void* operator new[](size_t);
    void  operator delete[](void*,std::size_t);
    // ... 

Overloaded thus, new and delete behave like static member functions. For objects of my_class, the std::size_t argument will always be sizeof(my_class). However, these operators are also called for dynamically allocated objects of derived classes, in which case it might be greater than that.

Global new and delete

To overload the global new and delete, simply replace the pre-defined operators of the standard library with our own. However, this rarely ever needs to be done.

Key hash for Android-Facebook app

Here are the steps-

  1. Download openssl from Google code (If you have a 64 bit machine you must download openssl-0.9.8e X64 not the latest version)

  2. Extract it. create a folder- OpenSSL in C:/ and copy the extracted code here.

  3. detect debug.keystore file path. If u didn't find, then do a search in C:/ and use the Path in the command in next step.

  4. detect your keytool.exe path and go to that dir/ in command prompt and run this command in 1 line-

    $ keytool -exportcert -alias androiddebugkey -keystore "C:\Documents and Settings\\debug.keystore" | "C:\OpenSSL\bin\openssl" sha1 -binary |"C:\OpenSSL\bin\openssl" base64

    • it will ask for password, put android
    • that's all. u will get a key-hash

For more info visit here

How to access accelerometer/gyroscope data from Javascript?

There are currently three distinct events which may or may not be triggered when the client devices moves. Two of them are focused around orientation and the last on motion:

  • ondeviceorientation is known to work on the desktop version of Chrome, and most Apple laptops seems to have the hardware required for this to work. It also works on Mobile Safari on the iPhone 4 with iOS 4.2. In the event handler function, you can access alpha, beta, gamma values on the event data supplied as the only argument to the function.

  • onmozorientation is supported on Firefox 3.6 and newer. Again, this is known to work on most Apple laptops, but might work on Windows or Linux machines with accelerometer as well. In the event handler function, look for x, y, z fields on the event data supplied as first argument.

  • ondevicemotion is known to work on iPhone 3GS + 4 and iPad (both with iOS 4.2), and provides data related to the current acceleration of the client device. The event data passed to the handler function has acceleration and accelerationIncludingGravity, which both have three fields for each axis: x, y, z

The "earthquake detecting" sample website uses a series of if statements to figure out which event to attach to (in a somewhat prioritized order) and passes the data received to a common tilt function:

if (window.DeviceOrientationEvent) {
    window.addEventListener("deviceorientation", function () {
        tilt([event.beta, event.gamma]);
    }, true);
} else if (window.DeviceMotionEvent) {
    window.addEventListener('devicemotion', function () {
        tilt([event.acceleration.x * 2, event.acceleration.y * 2]);
    }, true);
} else {
    window.addEventListener("MozOrientation", function () {
        tilt([orientation.x * 50, orientation.y * 50]);
    }, true);

The constant factors 2 and 50 are used to "align" the readings from the two latter events with those from the first, but these are by no means precise representations. For this simple "toy" project it works just fine, but if you need to use the data for something slightly more serious, you will have to get familiar with the units of the values provided in the different events and treat them with respect :)

How to parse SOAP XML?

In your code you are querying for the payment element in default namespace, but in the XML response it is declared as in namespace.

So, you are missing a namespace declaration:

$xml->registerXPathNamespace('envoy', '');

Now you can use the envoy namespace prefix in your xpath query:


The full code would be:

$xml = simplexml_load_string($soap_response);
$xml->registerXPathNamespace('envoy', '');
foreach ($xml->xpath('//envoy:payment') as $item)

Note: I removed the soap namespace declaration as you do not seem to be using it (it is only useful if you would use the namespace prefix in you xpath queries).

Undefined behavior and sequence points

C++98 and C++03

This answer is for the older versions of the C++ standard. The C++11 and C++14 versions of the standard do not formally contain 'sequence points'; operations are 'sequenced before' or 'unsequenced' or 'indeterminately sequenced' instead. The net effect is essentially the same, but the terminology is different.

Disclaimer : Okay. This answer is a bit long. So have patience while reading it. If you already know these things, reading them again won't make you crazy.

Pre-requisites : An elementary knowledge of C++ Standard

What are Sequence Points?

The Standard says

At certain specified points in the execution sequence called sequence points, all side effects of previous evaluations shall be complete and no side effects of subsequent evaluations shall have taken place. (§1.9/7)

Side effects? What are side effects?

Evaluation of an expression produces something and if in addition there is a change in the state of the execution environment it is said that the expression (its evaluation) has some side effect(s).

For example:

int x = y++; //where y is also an int

In addition to the initialization operation the value of y gets changed due to the side effect of ++ operator.

So far so good. Moving on to sequence points. An alternation definition of seq-points given by the comp.lang.c author Steve Summit:

Sequence point is a point in time at which the dust has settled and all side effects which have been seen so far are guaranteed to be complete.

What are the common sequence points listed in the C++ Standard ?

Those are:

  • at the end of the evaluation of full expression (§1.9/16) (A full-expression is an expression that is not a subexpression of another expression.)1

    Example :

    int a = 5; // ; is a sequence point here
  • in the evaluation of each of the following expressions after the evaluation of the first expression (§1.9/18) 2

    • a && b (§5.14)
    • a || b (§5.15)
    • a ? b : c (§5.16)
    • a , b (§5.18) (here a , b is a comma operator; in func(a,a++) , is not a comma operator, it's merely a separator between the arguments a and a++. Thus the behaviour is undefined in that case (if a is considered to be a primitive type))
  • at a function call (whether or not the function is inline), after the evaluation of all function arguments (if any) which takes place before execution of any expressions or statements in the function body (§1.9/17).

1 : Note : the evaluation of a full-expression can include the evaluation of subexpressions that are not lexically part of the full-expression. For example, subexpressions involved in evaluating default argument expressions (8.3.6) are considered to be created in the expression that calls the function, not the expression that defines the default argument

2 : The operators indicated are the built-in operators, as described in clause 5. When one of these operators is overloaded (clause 13) in a valid context, thus designating a user-defined operator function, the expression designates a function invocation and the operands form an argument list, without an implied sequence point between them.

What is Undefined Behaviour?

The Standard defines Undefined Behaviour in Section §1.3.12 as

behavior, such as might arise upon use of an erroneous program construct or erroneous data, for which this International Standard imposes no requirements 3.

Undefined behavior may also be expected when this International Standard omits the description of any explicit definition of behavior.

3 : permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or with- out the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

In short, undefined behaviour means anything can happen from daemons flying out of your nose to your girlfriend getting pregnant.

What is the relation between Undefined Behaviour and Sequence Points?

Before I get into that you must know the difference(s) between Undefined Behaviour, Unspecified Behaviour and Implementation Defined Behaviour.

You must also know that the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified.

For example:

int x = 5, y = 6;

int z = x++ + y++; //it is unspecified whether x++ or y++ will be evaluated first.

Another example here.

Now the Standard in §5/4 says

  • 1) Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression.

What does it mean?

Informally it means that between two sequence points a variable must not be modified more than once. In an expression statement, the next sequence point is usually at the terminating semicolon, and the previous sequence point is at the end of the previous statement. An expression may also contain intermediate sequence points.

From the above sentence the following expressions invoke Undefined Behaviour:

i++ * ++i;   // UB, i is modified more than once btw two SPs
i = ++i;     // UB, same as above
++i = 2;     // UB, same as above
i = ++i + 1; // UB, same as above
++++++i;     // UB, parsed as (++(++(++i)))

i = (i, ++i, ++i); // UB, there's no SP between `++i` (right most) and assignment to `i` (`i` is modified more than once btw two SPs)

But the following expressions are fine:

i = (i, ++i, 1) + 1; // well defined (AFAIK)
i = (++i, i++, i);   // well defined 
int j = i;
j = (++i, i++, j*i); // well defined

  • 2) Furthermore, the prior value shall be accessed only to determine the value to be stored.

What does it mean? It means if an object is written to within a full expression, any and all accesses to it within the same expression must be directly involved in the computation of the value to be written.

For example in i = i + 1 all the access of i (in L.H.S and in R.H.S) are directly involved in computation of the value to be written. So it is fine.

This rule effectively constrains legal expressions to those in which the accesses demonstrably precede the modification.

Example 1:

std::printf("%d %d", i,++i); // invokes Undefined Behaviour because of Rule no 2

Example 2:

a[i] = i++ // or a[++i] = i or a[i++] = ++i etc

is disallowed because one of the accesses of i (the one in a[i]) has nothing to do with the value which ends up being stored in i (which happens over in i++), and so there's no good way to define--either for our understanding or the compiler's--whether the access should take place before or after the incremented value is stored. So the behaviour is undefined.

Example 3 :

int x = i + i++ ;// Similar to above

Follow up answer for C++11 here.

Posting JSON Data to ASP.NET MVC

Take a look at Phil Haack's post on model binding JSON data. The problem is that the default model binder doesn't serialize JSON properly. You need some sort of ValueProvider OR you could write a custom model binder:

using System.IO;
using System.Web.Script.Serialization;

public class JsonModelBinder : DefaultModelBinder {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
            if(!IsJSONRequest(controllerContext)) {
                return base.BindModel(controllerContext, bindingContext);

            // Get the JSON data that's been posted
            var request = controllerContext.HttpContext.Request;
            //in some setups there is something that already reads the input stream if content type = 'application/json', so seek to the begining
            request.InputStream.Seek(0, SeekOrigin.Begin);
            var jsonStringData = new StreamReader(request.InputStream).ReadToEnd();

            // Use the built-in serializer to do the work for us
            return new JavaScriptSerializer()
                .Deserialize(jsonStringData, bindingContext.ModelMetadata.ModelType);

            // -- REQUIRES .NET4
            // If you want to use the .NET4 version of this, change the target framework and uncomment the line below
            // and comment out the above return statement
            //return new JavaScriptSerializer().Deserialize(jsonStringData, bindingContext.ModelMetadata.ModelType);

        private static bool IsJSONRequest(ControllerContext controllerContext) {
            var contentType = controllerContext.HttpContext.Request.ContentType;
            return contentType.Contains("application/json");

public static class JavaScriptSerializerExt {
        public static object Deserialize(this JavaScriptSerializer serializer, string input, Type objType) {
            var deserializerMethod = serializer.GetType().GetMethod("Deserialize", BindingFlags.NonPublic | BindingFlags.Static);

            // internal static method to do the work for us
            //Deserialize(this, input, null, this.RecursionLimit);

            return deserializerMethod.Invoke(serializer,
                new object[] { serializer, input, objType, serializer.RecursionLimit });

And tell MVC to use it in your Global.asax file:

ModelBinders.Binders.DefaultBinder = new JsonModelBinder();

Also, this code makes use of the content type = 'application/json' so make sure you set that in jquery like so:

    dataType: "json",
    contentType: "application/json",            
    type: 'POST',
    url: '/Controller/Action',
    data: { 'items': JSON.stringify(lineItems), 'id': documentId }

jQuery posting valid json in request body

An actual JSON request would look like this:

data: '{"command":"on"}',

Where you're sending an actual JSON string. For a more general solution, use JSON.stringify() to serialize an object to JSON, like this:

data: JSON.stringify({ "command": "on" }),

To support older browsers that don't have the JSON object, use json2.js which will add it in.

What's currently happening is since you have processData: false, it's basically sending this: ({"command":"on"}).toString() which is [object Object]...what you see in your request.

Posting a File and Associated Data to a RESTful WebService preferably as JSON

Here is my approach API (i use example) - as you can see, you I don't use any file_id (uploaded file identifier to the server) in API:

  1. Create photo object on server:

     POST: /projects/{project_id}/photos   
     body: { name: "some_schema.jpg", comment: "blah"}
     response: photo_id
  2. Upload file (note that file is in singular form because it is only one per photo):

     POST: /projects/{project_id}/photos/{photo_id}/file
     body: file to upload
     response: -

And then for instance:

  1. Read photos list

     GET: /projects/{project_id}/photos
     response: [ photo, photo, photo, ... ] (array of objects)
  2. Read some photo details

     GET: /projects/{project_id}/photos/{photo_id}
     response: { id: 666, name: 'some_schema.jpg', comment:'blah'} (photo object)
  3. Read photo file

     GET: /projects/{project_id}/photos/{photo_id}/file
     response: file content

So the conclusion is that, first you create an object (photo) by POST, and then you send second request with the file (again POST). To not have problems with CACHE in this approach we assume that we can only delete old photos and add new - no update binary photo files (because new binary file is in fact... NEW photo). However if you need to be able to update binary files and cache them, then in point 4 return also fileId and change 5 to GET: /projects/{project_id}/photos/{photo_id}/files/{fileId}.

How to echo in PHP, HTML tags

If you want to output large quantities of HTML you should consider using heredoc or nowdoc syntax. This will allow you to write your strings without the need for escaping.

echo <<<EOD
You can put "s and 's here if you like.

Also note that because PHP is an embedded language you can add it between you HTML content and you don't need to echo any tags.

    <p>No PHP here!</p>
    $name = "Marcel";
    echo "<p>Hello $name!</p>";

Also if you just want to output a variable you should use the short-hand output tags <?=$var?>. This is equivalent to <?php echo $var; ?>.

Including external jar-files in a new jar-file build with Ant

As Cheesle said, you can unpack and your library Jars and re-jar them all with the following modification.

    <jar destfile="${jar.file}"  
        <fileset dir="${classes.dir}" includes="**/*.class" /> 
        <zipgroupfileset dir="${lib.dir}" includes="**/*.jar" /> 

Jar files are really just zip files with a manifest file embedded. You can extract and repackage the dependency Jars into your application's Jar file. "The Zip task also supports the merging of multiple zip files into the zip file. This is possible through either the src attribute of any nested filesets or by using the special nested fileset zipgroupfileset."

Do pay attention to the licenses involved with your dependency libaries. Linking externally to a library and including the library in your application are very different things legally.

EDIT 1: Darn my slow typing. Grodriguez beat me to it. :)

EDIT 2: If you decide you can't include your dependencies into your application then you have to specify them in your Jar's classpath either at the command line at startup or via the Manifest file. There's a nice command in ANT to handle the special formatting of the classpath in a Manifest file for you.

<manifestclasspath property="manifest.classpath" jarfile="${jar.file}">
    <classpath location="${lib.dir}" />

 <manifest file="${manifest.file}" >      
        <attribute name="built-by" value="${}" />      
        <attribute name="Main-Class" value="${main.class}" />    
        <attribute name="Class-Path" value="${manifest.classpath}" />

jQuery addClass onClick

Using jQuery:


This way, you don't have to pollute your HTML markup with onclick handlers.

Adding system header search path to Xcode

Follow up to Eonil's answer related to project level settings. With the target selected and the Build Settings tab selected, there may be no listing under Search Paths for Header Search Paths. In this case, you can change to "All" from "Basic" in the search bar and Header Search Paths will show up in the Search Paths section.

C++: Rounding up to the nearest multiple of a number

I think this works:

int roundUp(int numToRound, int multiple) {
    return multiple? !(numToRound%multiple)? numToRound : ((numToRound/multiple)+1)*multiple: numToRound;

How do I list all tables in all databases in SQL Server in a single result set?

please fill the @likeTablename param for search table.

now this parameter set to %tbltrans% for search all table contain tbltrans in name.

set @likeTablename to '%' to show all table.

declare @AllTableNames nvarchar(max);

 FROM master.sys.databases 
).value('.', 'NVARCHAR(MAX)') 

set @AllTableNames=left(@AllTableNames,len(@AllTableNames)-6)

declare @likeTablename nvarchar(200)='%tbltrans%';
set @AllTableNames=N'select tablename from('+@AllTableNames+N')at where tablename like '''+N'%'+@likeTablename+N'%'+N''''
exec sp_executesql  @AllTableNames

How to use WebRequest to POST some data and read response?

Here's what works for me. I'm sure it can be improved, so feel free to make suggestions or edit to make it better.

const string WEBSERVICE_URL = "http://localhost/projectname/ServiceName.svc/ServiceMethod";
//This string is untested, but I think it's ok.
string jsonData = "{ \"key1\" : \"value1\", \"key2\":\"value2\"  }"; 
    var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
    if (webRequest != null)
        webRequest.Method = "POST";
        webRequest.Timeout = 20000;
        webRequest.ContentType = "application/json";

    using (System.IO.Stream s = webRequest.GetRequestStream())
        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(s))

    using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
        using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
            var jsonResponse = sr.ReadToEnd();
            System.Diagnostics.Debug.WriteLine(String.Format("Response: {0}", jsonResponse));
catch (Exception ex)

Remove characters after specific character in string, then remove substring?

To remove everything before a specific char, use below.

string1 = string1.Substring(string1.IndexOf('$') + 1);

What this does is, takes everything before the $ char and removes it. Now if you want to remove the items after a character, just change the +1 to a -1 and you are set!

But for a URL, I would use the built in .NET class to take of that.

Best Practice: Access form elements by HTML id or name attribute?

Check out this page:

document.getElementsByName('foo')[0]; // returns you element.

It has to be 'elements' and must return an array because more than one element could have the same name.

How to return data from PHP to a jQuery ajax call

I figured it out. Need to use echo in PHP instead of return.

  $output = some_function();
  echo $output;

And the jQ:

success: function(data) {

What is the size limit of a post request?

The url portion of a request (GET and POST) can be limited by both the browser and the server - generally the safe size is 2KB as there are almost no browsers or servers that use a smaller limit.

The body of a request (POST) is normally* limited by the server on a byte size basis in order to prevent a type of DoS attack (note that this means character escaping can increase the byte size of the body). The most common server setting is 10MB, though all popular servers allow this to be increased or decreased via a setting file or panel.

*Some exceptions exist with older cell phone or other small device browsers - in those cases it is more a function of heap space reserved for this purpose on the device then anything else.

What is an application binary interface (ABI)?

An application binary interface (ABI) is similar to an API, but the function is not accessible to the caller at source code level. Only a binary representation is accessible/available.

ABIs may be defined at the processor-architecture level or at the OS level. The ABIs are standards to be followed by the code-generator phase of the compiler. The standard is fixed either by the OS or by the processor.

Functionality: Define the mechanism/standard to make function calls independent of the implementation language or a specific compiler/linker/toolchain. Provide the mechanism which allows JNI, or a Python-C interface, etc.

Existing entities: Functions in machine code form.

Consumer: Another function (including one in another language, compiled by another compiler, or linked by another linker).

Which is more efficient, a for-each loop, or an iterator?

Iterator is an interface in the Java Collections framework that provides methods to traverse or iterate over a collection.

Both iterator and for loop acts similar when your motive is to just traverse over a collection to read its elements.

for-each is just one way to iterate over the Collection.

For example:

List<String> messages= new ArrayList<>();

//using for-each loop
for(String msg: messages){

//using iterator 
Iterator<String> it = messages.iterator();
    String msg =;

And for-each loop can be used only on objects implementing the iterator interface.

Now back to the case of for loop and iterator.

The difference comes when you try to modify a collection. In this case, iterator is more efficient because of its fail-fast property. ie. it checks for any modification in the structure of underlying collection before iterating over the next element. If there are any modifications found, it will throw the ConcurrentModificationException.

(Note: This functionality of iterator is only applicable in case of collection classes in java.util package. It is not applicable for concurrent collections as they are fail-safe by nature)

Renaming a directory in C#

You should move it:

Directory.Move(source, destination);

How to use JavaScript regex over multiple lines?

In addition to above-said examples, it is an alternate.


Where \w is for words and \s is for white spaces

Create directories using make file

All solutions including the accepted one have some issues as stated in their respective comments. The accepted answer by @jonathan-leffler is already quite good but does not take into effect that prerequisites are not necessarily to be built in order (during make -j for example). However simply moving the directories prerequisite from all to program provokes rebuilds on every run AFAICT. The following solution does not have that problem and AFAICS works as intended.

MKDIR_P := mkdir -p
OUT_DIR := build

.PHONY: directories all clean

all: $(OUT_DIR)/program

directories: $(OUT_DIR)

    ${MKDIR_P} $(OUT_DIR)

$(OUT_DIR)/program: | directories
    touch $(OUT_DIR)/program

    rm -rf $(OUT_DIR)

How to check file input size with jQuery?

This code:


Returns the file size for an form input.

On FF 3.6 and later this code should be:


How to get last inserted row ID from WordPress database?

I needed to get the last id way after inserting it, so

$lastid = $wpdb->insert_id;

Was not an option.

Did the follow:

global $wpdb;
$id = $wpdb->get_var( 'SELECT id FROM ' . $wpdb->prefix . 'table' . ' ORDER BY id DESC LIMIT 1');

What causes an HTTP 405 "invalid method (HTTP verb)" error when POSTing a form to PHP on IIS?

We just ran into this same issue. Our Cpanel has expanded from PHP only to PHP and .NET and defaulted to .NET.

Log in to you Cpanel and make sure you don’t have the same issue.

AJAX POST and Plus Sign ( + ) -- How to Encode?

In JavaScript try:


and in PHP:


Tricks to manage the available memory in an R session

I use the data.table package. With its := operator you can :

  • Add columns by reference
  • Modify subsets of existing columns by reference, and by group by reference
  • Delete columns by reference

None of these operations copy the (potentially large) data.table at all, not even once.

  • Aggregation is also particularly fast because data.table uses much less working memory.

Related links :

How to post ASP.NET MVC Ajax form using JavaScript rather than submit button

Unfortunately triggering the onsubmit or submit events wont work in all browsers.

  • Works in IE and Chrome: #('form#ajaxForm')trigger('onsubmit');
  • Works in Firefox and Safari: #('form#ajaxForm')trigger('submit');

Also, if you trigger('submit') in Chrome or IE, it causes the entire page to be posted rather than doing an AJAX behavior.

What works for all browsers is removing the onsubmit event behavior and just calling submit() on the form itself.

<script type="text/javascript">
$(function() {

    $('form#ajaxForm').submit(function(event) { 
        eval($(this).attr('onsubmit')); return false; 

    $('form#ajaxForm').find('a.submit-link').click( function() { 

  <% using (Ajax.BeginForm("Update", "Description", new { id = Model.Id },
     new AjaxOptions
       UpdateTargetId = "DescriptionDiv",
       HttpMethod = "post"
     }, new { id = "ajaxForm" } )) {%>
   <%= Html.TextBox("Description", Model.Description) %><br />
   <a href="#" class="submit-link">Save</a> 
<% } %>

Also, the link doesn't have to be contained within the form in order for this to work.

Posting parameters to a url using the POST method without using a form

If you're trying to link to something, rather than do it from code you can redirect your request through:

Print the address or pointer for value in C

What you have is correct. Of course, you'll see that emp1 and item1 have the same pointer value.

how to customize `show processlist` in mysql?

If you use old version of MySQL you can always use \P combined with some nice piece of awk code. Interesting example here

Isn't it exactly what you need?

Saving an image in OpenCV

In my experience OpenCV writes a black image when SaveImage is given a matrix with bit depth different from 8 bit. In fact, this is sort of documented:

Only 8-bit single-channel or 3-channel (with ‘BGR’ channel order) images can be saved using this function. If the format, depth or channel order is different, use cvCvtScale and cvCvtColor to convert it before saving, or use universal cvSave to save the image to XML or YAML format.

In your case you may first investigate what kind of image is captured, change capture properties (I suppose CV_CAP_PROP_CONVERT_RGB might be important) or convert it manually afterwards.

This is an example how to convert to 8-bit representation with OpenCV. cc here is an original matrix of type CV_32FC1, cc8u is its scaled version which is actually written by SaveImage:

# I want to save cc here
cc8u = CreateMat(cc.rows, cc.cols, CV_8U)
ccmin,ccmax,minij,maxij = MinMaxLoc(cc)
ccscale, ccshift = 255.0/(ccmax-ccmin), -ccmin
CvtScale(cc, cc8u, ccscale, ccshift)
SaveImage("cc.png", cc8u)

(sorry, this is Python code, but it should be easy to translate it to C/C++)

Request format is unrecognized for URL unexpectedly ending in

Make sure you disable custom errors. This can mask the original problem in your code:


<customErrors defaultRedirect="~/Error" mode="On">


<customErrors defaultRedirect="~/Error" mode="Off">

What is the best IDE for C Development / Why use Emacs over an IDE?

I have used Eclipse with the CDT plug in quite successfully.

ASP.NET / C#: DropDownList SelectedIndexChanged in server control not firing

You need to set AutoPostBack to true for the Country DropDownList.

protected override void OnLoad(EventArgs e)
    // base stuff

    ddlCountries.AutoPostBack = true;

    // other stuff


I missed that you had done this. In that case you need to check that ViewState is enabled.

Creating a list of objects in Python

If I understand correctly your question, you ask a way to execute a deep copy of an object. What about using copy.deepcopy?

import copy

x = SimpleClass()

for count in range(0,4):
  y = copy.deepcopy(x)
  y.attr1= '*Bob* '* count

A deepcopy is a recursive copy of the entire object. For more reference, you can have a look at the python documentation:

What is N-Tier architecture?

Martin Fowler demonstrating clearly:

Layering is one of the most common techniques that software designers use to break apart a complicated software system. You see it in machine architectures, where layers descend from a programming language with operating system calls into device drivers and CPU instruction sets, and into logic gates inside chips. Networking has FTP layered on top of TCP, which is on top of IP, which is on top of ethernet.

When thinking of a system in terms of layers, you imagine the principal subsystems in the software arranged in some form of layer cake, where each layer rests on a lower layer. In this scheme the higher layer uses various services defined by the lower layer, but the lower layer is unaware of the higher layer. Furthermore, each layer usually hides its lower layers from the layers above, so layer 4 uses the services of layer 3, which uses the services of layer 2, but layer 4 is unaware of layer 2. (Not all layering architectures are opaque like this, but most are—or rather most are mostly opaque.)

Breaking down a system into layers has a number of important benefits.

• You can understand a single layer as a coherent whole without knowing much about the other layers. You can understand how to build an FTP service on top of TCP without knowing the details of how ethernet works.

• You can substitute layers with alternative implementations of the same basic services. An FTP service can run without change over ethernet, PPP, or whatever a cable company uses.

• You minimize dependencies between layers. If the cable company changes its physical transmission system, providing they make IP work, we don’t have to alter our FTP service.

• Layers make good places for standardization. TCP and IP are standards because they define how their layers should operate.

• Once you have a layer built, you can use it for many higher-level services. Thus, TCP/IP is used by FTP, telnet, SSH, and HTTP. Otherwise, all of these higher-level protocols would have to write their own lower-level protocols. From the Library of Kyle Geoffrey Passarelli

Layering is an important technique, but there are downsides.

• Layers encapsulate some, but not all, things well. As a result you sometimes get cascading changes. The classic example of this in a layered enterprise application is adding a field that needs to display on the UI, must be in the database, and thus must be added to every layer in between.

• Extra layers can harm performance. At every layer things typically need to be transformed from one representation to another. However, the encapsulation of an underlying function often gives you efficiency gains that more than compensate. A layer that controls transactions can be optimized and will then make everything faster. But the hardest part of a layered architecture is deciding what layers to have and what the responsibility of each layer should be.

Using jQuery, Restricting File Size Before Uploading

Like others have said, it's not possible with just JavaScript due to the security model of such.

If you are able to, I'd recommend one of the below solutions..both of which use a flash component for the client side validations; however, are wired up using Javascript/jQuery. Both work very well and can be used with any server-side tech.

Ruby: How to post a file via HTTP as multipart/form-data?

I had the same problem (need to post to jboss web server). Curb works fine for me, except that it caused ruby to crash (ruby 1.8.7 on ubuntu 8.10) when I use session variables in the code.

I dig into the rest-client docs, could not find indication of multipart support. I tried the rest-client examples above but jboss said the http post is not multipart.

Disable the postback on an <ASP:LinkButton>

You can do it too

...LinkButton ID="BtnForgotPassword" runat="server" OnClientClick="ChangeText('1');return false"...

And it stop the link button postback

Best way to define private methods for a class in Objective-C

While I am no Objective-C expert, I personally just define the method in the implementation of my class. Granted, it must be defined before (above) any methods calling it, but it definitely takes the least amount of work to do.

What is the best way to get all the divisors of a number?

I'm just going to add a slightly revised version of Anivarth's (as I believe it's the most pythonic) for future reference.

from math import sqrt

def divisors(n):
    divs = {1,n}
    for i in range(2,int(sqrt(n))+1):
        if n%i == 0:
    return divs

Why does an onclick property set with setAttribute fail to work in IE?

Did you try:

    execBtn.setAttribute("onclick", function() { runCommand() });

How to find the mime type of a file in python?

There are 3 different libraries that wraps libmagic.

2 of them are available on pypi (so pip install will work):

  • filemagic
  • python-magic

And another, similar to python-magic is available directly in the latest libmagic sources, and it is the one you probably have in your linux distribution.

In Debian the package python-magic is about this one and it is used as toivotuo said and it is not obsoleted as Simon Zimmermann said (IMHO).

It seems to me another take (by the original author of libmagic).

Too bad is not available directly on pypi.

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

Show create table in classic asp (handles constraints, primary keys, copying the table structure and/or data ...)

Sql server Show create table Mysql-style "Show create table" and "show create database" commands from Microsoft sql server. The script is written is Microsoft asp-language and is quite easy to port to another language.*

How to do a subquery in LINQ?

Ok, here's a basic join query that gets the correct records:

   int[] selectedRolesArr = GetSelectedRoles();
    if( selectedRolesArr != null && selectedRolesArr.Length > 0 ) 

    //this join version requires the use of distinct to prevent muliple records
        //being returned for users with more than one company role.
    IQueryable retVal = (from u in context.Users
                        join c in context.CompanyRolesToUsers
                          on u.Id equals c.UserId
                        where u.LastName.Contains( "fra" ) &&
                            selectedRolesArr.Contains( c.CompanyRoleId )
                        select  u).Distinct();

But here's the code that most easily integrates with the algorithm that we already had in place:

int[] selectedRolesArr = GetSelectedRoles(); 
if ( useAnd ) 
          predicateAnd = predicateAnd.And( u => (from c in context.CompanyRolesToUsers 
                       where selectedRolesArr.Contains(c.CompanyRoleId) 
                       select c.UserId).Contains(u.Id)); 
           predicateOr = predicateOr.Or( u => (from c in context.CompanyRolesToUsers 
                          where selectedRolesArr.Contains(c.CompanyRoleId) 
                         select c.UserId).Contains(u.Id) ); 

which is thanks to a poster at the LINQtoSQL forum

JAVA_HOME does not point to the JDK

You installed java...

apt-get install default-jre

But not the JDK...

apt-get install default-jdk

Git cli: get user info from username

Use this to see the logged in user (the actual git account):

git config credential.username

And as other answers the user email and user name (this is differenct from user credentials):

git config
git config

To see the list of all configs:

git config --list

How can I see the request headers made by curl when sending a request to the server?

I tried the answers here and found that the most useful and easiest one is not listed as an answer yet, but it is:

curl -v

This prints out the REQUEST headers as well as the RESPONSE headers plus other useful such as the SSL cert and whether an existing TCP connection was reused. the -v flag can be combined with other flags, of course, such as to follow redirects and prompt for HTTP authentication:

curl -vL --user my_username

Hope this helps.

WooCommerce: Finding the products in database

The following tables are store WooCommerce products database :

  • wp_posts -

    The core of the WordPress data is the posts. It is stored a post_type like product or variable_product.

  • wp_postmeta-

    Each post features information called the meta data and it is stored in the wp_postmeta. Some plugins may add their own information to this table like WooCommerce plugin store product_id of product in wp_postmeta table.

Product categories, subcategories stored in this table :

  • wp_terms
  • wp_termmeta
  • wp_term_taxonomy
  • wp_term_relationships
  • wp_woocommerce_termmeta

following Query Return a list of product categories

SELECT wp_terms.* 
    FROM wp_terms 
    LEFT JOIN wp_term_taxonomy ON wp_terms.term_id = wp_term_taxonomy.term_id
    WHERE wp_term_taxonomy.taxonomy = 'product_cat';

for more reference -

DTO and DAO concepts and MVC

DTO is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.

  • DTO should only contain private fields for your data, getters, setters, and constructors.
  • DTO is not recommended to add business logic methods to such classes, but it is OK to add some util methods.

DAO is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).

Here is an example of how the DAO and DTO interfaces would look like:

interface PersonDTO {
    String getName();
    void setName(String name);

interface PersonDAO {
    PersonDTO findById(long id);
    void save(PersonDTO person);

The MVC is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.

As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.

What is "stdafx.h" used for in Visual Studio?

All C++ compilers have one serious performance problem to deal with. Compiling C++ code is a long, slow process.

Compiling headers included on top of C++ files is a very long, slow process. Compiling the huge header structures that form part of Windows API and other large API libraries is a very, very long, slow process. To have to do it over, and over, and over for every single Cpp source file is a death knell.

This is not unique to Windows but an old problem faced by all compilers that have to compile against a large API like Windows.

The Microsoft compiler can ameliorate this problem with a simple trick called precompiled headers. The trick is pretty slick: although every CPP file can potentially and legally give a sligthly different meaning to the chain of header files included on top of each Cpp file (by things like having different macros #define'd in advance of the includes, or by including the headers in different order), that is most often not the case. Most of the time, we have dozens or hundreds of included files, but they all are intended to have the same meaning for all the Cpp files being compiled in your application.

The compiler can make huge time savings if it doesn't have to start to compile every Cpp file plus its dozens of includes literally from scratch every time.

The trick consists of designating a special header file as the starting point of all compilation chains, the so called 'precompiled header' file, which is commonly a file named stdafx.h simply for historical reasons.

Simply list all your big huge headers for your APIs in your stdafx.h file, in the appropriate order, and then start each of your CPP files at the very top with an #include "stdafx.h", before any meaningful content (just about the only thing allowed before is comments).

Under those conditions, instead of starting from scratch, the compiler starts compiling from the already saved results of compiling everything in stdafx.h.

I don't believe that this trick is unique to Microsoft compilers, nor do I think it was an original development.

For Microsoft compilers, the setting that controls the use of precompiled headers is controlled by a command line argument to the compiler: /Yu "stdafx.h". As you can imagine, the use of the stdafx.h file name is simply a convention; you can change the name if you so wish.

In Visual Studio 2010, this setting is controlled from the GUI via Right-clicking on a CPP Project, selecting 'Properties' and navigating to "Configuration Properties\C/C++\Precompiled Headers". For other versions of Visual Studio, the location in the GUI will be different.

Note that if you disable precompiled headers (or run your project through a tool that doesn't support them), it doesn't make your program illegal; it simply means that your tool will compile everything from scratch every time.

If you are creating a library with no Windows dependencies, you can easily comment out or remove #includes from the stdafx.h file. There is no need to remove the file per se, but clearly you may do so as well, by disabling the precompile header setting above.

How to tell if JRE or JDK is installed

A generic, pure Java solution..

For Windows and MacOS, the following can be inferred (most of the time)...

public static boolean isJDK() {
    String path = System.getProperty("sun.boot.library.path");
    if(path != null && path.contains("jdk")) {
        return true;
    return false;

However... on Linux this isn't as reliable... For example...

  • Many JREs on Linux contain openjdk the path
  • There's no guarantee that the JRE doesn't also contain a JDK.

So a more fail-safe approach is to check for the existence of the javac executable.

public static boolean isJDK() {
    String path = System.getProperty("sun.boot.library.path");
    if(path != null) {
        String javacPath = "";
        if(path.endsWith(File.separator + "bin")) {
            javacPath = path;
        } else {
            int libIndex = path.lastIndexOf(File.separator + "lib");
            if(libIndex > 0) {
                javacPath = path.substring(0, libIndex) + File.separator + "bin";
        if(!javacPath.isEmpty()) {
            return new File(javacPath, "javac").exists() || new File(javacPath, "javac.exe").exists();
    return false;

Warning: This will still fail for JRE + JDK combos which report the JRE's sun.boot.library.path identically between the JRE and the JDK. For example, Fedora's JDK will fail (or pass depending on how you look at it) when the above code is run. See unit tests below for more info...

Unit tests:

# Unix
java -XshowSettings:properties -version 2>&1|grep "sun.boot.library.path"
# Windows
java -XshowSettings:properties -version 2>&1|find "sun.boot.library.path"
    # PASS: MacOS AdoptOpenJDK JDK11

    # PASS: Windows Oracle JDK12
    c:\Program Files\Java\jdk-12.0.2\bin

    # PASS: Windows Oracle JRE8
    C:\Program Files\Java\jre1.8.0_181\bin

    # PASS: Windows Oracle JDK8
    C:\Program Files\Java\jdk1.8.0_181\bin

    # PASS: Ubuntu AdoptOpenJDK JDK11

    # PASS: Ubuntu Oracle JDK11

    # PASS: Fedora OpenJDK JDK8

    #### FAIL: Fedora OpenJDK JDK8

java.lang.NoClassDefFoundError: org/json/JSONObject

The Exception it self says it all java.lang.ClassNotFoundException: org.json.JSONObject

You have not added the necessary jar file which will be having org.json.JSONObject class to your classpath.

You can Download it From Here

Remove multiple objects with rm()

An other solution rm(list=ls(pattern="temp")), remove all objects matching the pattern.

Unable to negotiate with XX.XXX.XX.XX: no matching host key type found. Their offer: ssh-dss

You either follow above approach or this one

Create the config file in the .ssh directory and add these line.

 IdentityFile ~/.ssh/id_rsa
 User xxx
 KexAlgorithms +diffie-hellman-group1-sha1

How to change MySQL column definition?

Do you mean altering the table after it has been created? If so you need to use alter table, in particular:

ALTER TABLE tablename MODIFY COLUMN new-column-definition



How to specify table's height such that a vertical scroll bar appears?

Try using the overflow CSS property. There are also separate properties to define the behaviour of just horizontal overflow (overflow-x) and vertical overflow (overflow-y).

Since you only want the vertical scroll, try this:

table {
  height: 500px;
  overflow-y: scroll;


Apparently <table> elements don't respect the overflow property. This appears to be because <table> elements are not rendered as display: block by default (they actually have their own display type). You can force the overflow property to work by setting the <table> element to be a block type:

table {
  display: block;
  height: 500px;
  overflow-y: scroll;

Note that this will cause the element to have 100% width, so if you don't want it to take up the entire horizontal width of the page, you need to specify an explicit width for the element as well.

did you specify the right host or port? error on Kubernetes

I had the same issue after a reboot, I followed the guide described here

So try the following:

$ sudo -i
# swapoff -a
# exit
$ strace -eopenat kubectl version

After that it works fine.

Git commit with no commit message

When working on an important code update, if you really need an intermediate safepoint you might just do:

git commit -am'.'

or shorter:

git commit -am.

Tomcat 7: How to set initial heap size correctly?

Just came across this and I've implemented Nathan's solution:

add the line (changing the values as required):

export JAVA_OPTS="-Xms512M -Xmx1024M"

to /usr/share/tomcat7/bin/

If that file doesn't exists then create it and

chown root:root it
chmod 755 it

And then restart tomcat and check it with

ps aux | grep logging

Which should just pick up the instance and show the java parms

Print array elements on separate lines in Bash?

I tried the answers here in a giant for...if loop, but didn't get any joy - so I did it like this, maybe messy but did the job:

 # EXP_LIST2 is iterated    
 # imagine a for loop
     EXP_LIST="List item"    
 echo -e $EXP_LIST2

although that added a space to the list, which is fine - I wanted it indented a bit. Also presume the "\n" could be printed in the original $EP_LIST.

ReactJS and images in public folder

You should use webpack here to make your life easier. Add below rule in your config:

const srcPath = path.join(__dirname, '..', 'publicfolder')

const rules = []

const includePaths = [
    // handle images
      test: /\.(png|gif|jpe?g|svg|ico)$/,
      include: includePaths,
      use: [{
        loader: 'file-loader',
        options: {
          name: 'images/[name]-[hash].[ext]'

After this, you can simply import the images into your react components:

import myImage from 'publicfolder/images/Image1.png'

Use myImage like below:

<div><img src={myImage}/></div>

or if the image is imported into local state of component

<div><img src={this.state.myImage}/></div> 

Exporting data In SQL Server as INSERT INTO

If you are running SQL Server 2008 R2 the built in options on to do this in SSMS as marc_s described above changed a bit. Instead of selecting Script data = true as shown in his diagram, there is now a new option called "Types of data to script" just above the "Table/View Options" grouping. Here you can select to script data only, schema and data or schema only. Works like a charm.

How do I exit the Vim editor?

After hitting ESC (or cmd + C on my computer) you must hit : for the command prompt to appear. Then, you may enter quit.

You may find that the machine will not allow you to quit because your information hasn't been saved. If you'd like to quit anyway, enter ! directly after the quit (i.e. :quit!).

Cannot push to Git repository on Bitbucket

Reformatted means you probably deleted your public and private ssh keys (in ~/.ssh).

You need to regenerate them and publish your public ssh key on your BitBucket profile, as documented in "Use the SSH protocol with Bitbucket", following "Set up SSH for Git with GitBash".

Accounts->Manage Accounts->SSH Keys:


Images from "Integrating Mercurial/BitBucket with JetBrains software"

React.js create loop through Array

As @Alexander solves, the issue is one of async data load - you're rendering immediately and you will not have participants loaded until the async ajax call resolves and populates data with participants.

The alternative to the solution they provided would be to prevent render until participants exist, something like this:

    render: function() {
        if (! {
            return null;
        return (
            <ul className="PlayerList">
            // I'm the Player List {}
            // <Player author="The Mini John" />
                    return <li key={player}>{player}</li>

Run a JAR file from the command line and specify classpath

You can do a Runtime.getRuntime.exec(command) to relaunch the jar including classpath with args.

Align inline-block DIVs to top of container element

<style type="text/css">
        div {
  text-align: center;

            width: 150px;
            height: 150px;
            border-radius: 50%;

            display: block;

<script src=""></script>
  <input type='password' class='secondInput mt-4 mr-1' placeholder="Password">
  <span class='dif'></span>

<script type="text/javascript">

$('button').click(function() {


Using R to list all files with a specified extension

Try this which uses globs rather than regular expressions so it will only pick out the file names that end in .dbf

filenames <- Sys.glob("*.dbf")

How do I get the path of the Python script I am running in?

7.2 of Dive Into Python: Finding the Path.

import sys, os

print('sys.argv[0] =', sys.argv[0])             
pathname = os.path.dirname(sys.argv[0])        
print('path =', pathname)
print('full path =', os.path.abspath(pathname)) 

How do I make this executable via double click?

  1. Launch Terminal
  2. Type -> nano fileName
  3. Paste Batch file content and save it
  4. Type -> chmod +x fileName
  5. It will create exe file now you can double click and it.

File name should in under double quotes. Since i am using Mac->In my case content of batch file is

cd /Users/yourName/Documents/SeleniumServer

java -jar selenium-server-standalone-3.3.1.jar -role hub

It will work for sure

"RangeError: Maximum call stack size exceeded" Why?

Here it fails at Array.apply(null, new Array(1000000)) and not the .map call.

All functions arguments must fit on callstack(at least pointers of each argument), so in this they are too many arguments for the callstack.

You need to the understand what is call stack.

Stack is a LIFO data structure, which is like an array that only supports push and pop methods.

Let me explain how it works by a simple example:

function a(var1, var2) {
    var3 = 3;
    b(5, 6);
    c(var1, var2);
function b(var5, var6) {
    c(7, 8);
function c(var7, var8) {

When here function a is called, it will call b and c. When b and c are called, the local variables of a are not accessible there because of scoping roles of Javascript, but the Javascript engine must remember the local variables and arguments, so it will push them into the callstack. Let's say you are implementing a JavaScript engine with the Javascript language like Narcissus.

We implement the callStack as array:

var callStack = [];

Everytime a function called we push the local variables into the stack:


Once the function call is finished(like in a, we have called b, b is finished executing and we must return to a), we get back the local variables by poping the stack:

currentLocalVaraibles = callStack.pop();

So when in a we want to call c again, push the local variables in the stack. Now as you know, compilers to be efficient define some limits. Here when you are doing Array.apply(null, new Array(1000000)), your currentLocalVariables object will be huge because it will have 1000000 variables inside. Since .apply will pass each of the given array element as an argument to the function. Once pushed to the call stack this will exceed the memory limit of call stack and it will throw that error.

Same error happens on infinite recursion(function a() { a() }) as too many times, stuff has been pushed to the call stack.

Note that I'm not a compiler engineer and this is just a simplified representation of what's going on. It really is more complex than this. Generally what is pushed to callstack is called stack frame which contains the arguments, local variables and the function address.

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

How do I add button on each row in datatable?

Take a Look.

$(document).ready(function () {     
            columns: [
                { 'data': 'ID' },
                { 'data': 'AuthorName' },
                { 'data': 'TotalBook' },
                { 'data': 'DateofBirth' },
                { 'data': 'OccupationEN' },   
                { 'data': null, title: 'Action', wrap: true, "render": function (item) { return '<div class="btn-group"> <button type="button" onclick="set_value(' + item.ID + ')" value="0" class="btn btn-warning" data-toggle="modal" data-target="#myModal">View</button></div>' } },
            bServerSide: true,
            sAjaxSource: 'EmployeeDataHandler.ashx'           

copying all contents of folder to another folder using batch file?

xcopy.exe is the solution here. It's built into Windows.

xcopy /s c:\Folder1 d:\Folder2

You can find more options at

How to set lifetime of session

Set following php parameters to same value in seconds:


in php.ini, .htaccess or for example with

ini_set('session.cookie_lifetime', 86400);
ini_set('session.gc_maxlifetime', 86400);

for a day.


How get an apostrophe in a string in javascript

You can put an apostrophe in a single quoted JavaScript string by escaping it with a backslash, like so:

theAnchorText = 'I\'m home';

combining two string variables

IMO, froadie's simple concatenation is fine for a simple case like you presented. If you want to put together several strings, the string join method seems to be preferred:

the_text = ''.join(['the ', 'quick ', 'brown ', 'fox ', 'jumped ', 'over ', 'the ', 'lazy ', 'dog.'])

Edit: Note that join wants an iterable (e.g. a list) as its single argument.

Angular ngClass and click event for toggling class

If you're looking for an HTML only way of doing this in angular...

<div #myDiv class="my_class" (click)="myDiv.classList.toggle('active')">
  Some content

The important bit is the #myDiv part.

It's a HTML Node reference, so you can use that variable as if it was assigned to document.querySelector('.my_class')

NOTE: this variable is scope specific, so you can use it in *ngFor statements

How to get bean using application context in spring boot

You can use the ApplicationContextAware class that can provide the application context.

public class ApplicationContextProvider implements ApplicationContextAware {

    private static ApplicationContext ctx = null;

    public static ApplicationContext getApplicationContext() {
        return ctx;

    public void setApplicationContext(final ApplicationContext ctx) throws BeansException {
        ApplicationContextProvider.ctx = ctx;

     * Tries to autowire the specified instance of the class if one of the specified
     * beans which need to be autowired are null.
     * @param classToAutowire        the instance of the class which holds @Autowire
     *                               annotations
     * @param beansToAutowireInClass the beans which have the @Autowire annotation
     *                               in the specified {#classToAutowire}
    public static void autowire(Object classToAutowire, Object... beansToAutowireInClass) {
        for (Object bean : beansToAutowireInClass) {
            if (bean == null) {


pass parameter by link_to ruby on rails

The above did not work for me but this did

<%= link_to "text_to_show_in_url", action_controller_path(:gender => "male", :param2=> "something_else") %>

Best way to represent a fraction in Java?

I'm trying to work with proper fractions in Java.

Apache Commons Math has had a Fraction class for quite some time. Most times the answer to, "Boy I wish Java had something like X in the core library!" can be found under the umbrella of the Apache Commons library.

Linux Shell Script For Each File in a Directory Grab the filename and execute a program

Look at the find command.

What you are looking for is something like

find . -name "*.xls" -type f -exec program 

Post edit

find . -name "*.xls" -type f -exec xls2csv '{}' '{}'.csv;

will execute xls2csv file.xls file.xls.csv

Closer to what you want.

Creating and throwing new exception

You can throw your own custom errors by extending the Exception class.

class CustomException : Exception {
    [string] $additionalData

    CustomException($Message, $additionalData) : base($Message) {
        $this.additionalData = $additionalData

try {
    throw [CustomException]::new('Error message', 'Extra data')
} catch [CustomException] {
    # NOTE: To access your custom exception you must use $_.Exception
    Write-Output $_.Exception.additionalData

    # This will produce the error message: Didn't catch it the second time
    throw [CustomException]::new("Didn't catch it the second time", 'Extra data')

How to select first child with jQuery?

Use the :first-child selector.

In your example...

$('div.alldivs div:first-child')

This will also match any first child descendents that meet the selection criteria.

While :first matches only a single element, the :first-child selector can match more than one: one for each parent. This is equivalent to :nth-child(1).

For the first matched only, use the :first selector.

Alternatively, Felix Kling suggested using the direct descendent selector to get only direct children...

$('div.alldivs > div:first-child')

Adding external library into Qt Creator project

The proper way to do this is like this:

LIBS += -L/path/to -lpsapi

This way it will work on all platforms supported by Qt. The idea is that you have to separate the directory from the library name (without the extension and without any 'lib' prefix). Of course, if you are including a Windows specific lib, this really doesn't matter.

In case you want to store your lib files in the project directory, you can reference them with the $$_PRO_FILE_PWD_ variable, e.g.:

LIBS += -L"$$_PRO_FILE_PWD_/3rdparty/libs/" -lpsapi

How to tell whether a point is to the right or left side of a line

A(x1,y1) B(x2,y2) a line segment with length L=sqrt( (y2-y1)^2 + (x2-x1)^2 )

and a point M(x,y)

making a transformation of coordinates in order to be the point A the new start and B a point of the new X axis

we have the new coordinates of the point M

which are newX = ((x-x1)(x2-x1)+(y-y1)(y2-y1)) / L
from (x-x1)*cos(t)+(y-y1)*sin(t) where cos(t)=(x2-x1)/L, sin(t)=(y2-y1)/L

newY = ((y-y1)(x2-x1)-(x-x1)(y2-y1)) / L
from (y-y1)*cos(t)-(x-x1)*sin(t)

because "left" is the side of axis X where the Y is positive, if the newY (which is the distance of M from AB) is positive, then it is on the left side of AB (the new X axis) You may omit the division by L (allways positive), if you only want the sign

bash: shortest way to get n-th column of output

Note, that file path does not have to be in second column of svn st output. For example if you modify file, and modify it's property, it will be 3rd column.

See possible output examples in:

svn help st

Example output:

 M     wc/bar.c
A  +   wc/qax.c

I suggest to cut first 8 characters by:

svn st | cut -c8- | while read FILE; do echo whatever with "$FILE"; done

If you want to be 100% sure, and deal with fancy filenames with white space at the end for example, you need to parse xml output:

svn st --xml | grep -o 'path=".*"' | sed 's/^path="//; s/"$//'

Of course you may want to use some real XML parser instead of grep/sed.

Android - save/restore fragment state

I'm not quite sure if this question is still bothering you, since it has been several months. But I would like to share how I dealt with this. Here is the source code:

int FLAG = 0;
private View rootView;
private LinearLayout parentView;

 * The fragment argument representing the section number for this fragment.
private static final String ARG_SECTION_NUMBER = "section_number";

 * Returns a new instance of this fragment for the given section number.
public static Fragment2 newInstance(Bundle bundle) {
    Fragment2 fragment = new Fragment2();
    Bundle args = bundle;
    return fragment;

public Fragment2() {


public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
        rootView = inflater.inflate(R.layout.fragment_create_new_album, container, false);
    parentView=new LinearLayout(getActivity());

    return parentView;

/* (non-Javadoc)
 * @see
public void onDestroy() {
    // TODO Auto-generated method stub

/* (non-Javadoc)
 * @see
public void onStart() {
    // TODO Auto-generated method stub

/* (non-Javadoc)
 * @see
public void onStop() {
    // TODO Auto-generated method stub
        Bundle savedInstance=getArguments();
        LinearLayout viewParent;

        viewParent= (LinearLayout) rootView.getParent();


public void onPause() {

public void onResume() {

And here is the MainActivity:

 * Fragment managing the behaviors, interactions and presentation of the
 * navigation drawer.
private NavigationDrawerFragment mNavigationDrawerFragment;

 * Used to store the last screen title. For use in
 * {@link #restoreActionBar()}.

public static boolean fragment2InstanceExists=false;
public static Fragment2 fragment2=null;

protected void onCreate(Bundle savedInstanceState) {

    mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
    mTitle = getTitle();

    // Set up the drawer.
            (DrawerLayout) findViewById(;

public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
    case 0:
        fragmentTransaction.replace(, Fragment1.newInstance(position+1)).commit();
    case 1:

        Bundle bundle=new Bundle();

        fragmentTransaction.replace(, fragment2).commit();

    case 2:
        fragmentTransaction.replace(, FolderExplorerFragment.newInstance(position+1)).commit();

The parentView is the keypoint. Normally, when onCreateView, we just use return rootView. But now, I add rootView to parentView, and then return parentView. To prevent "The specified child already has a parent. You must call removeView() on the ..." error, we need to call parentView.removeView(rootView), or the method I supplied is useless. I also would like to share how I found it. Firstly, I set up a boolean to indicate if the instance exists. When the instance exists, the rootView will not be inflated again. But then, logcat gave the child already has a parent thing, so I decided to use another parent as a intermediate Parent View. That's how it works.

Hope it's helpful to you.

How do I replace text in a selection?

You can use ctrl+F to find the text.
ctrl+h to enter the replacement text. Then ctrl+shift+h to replace the current selected text and move to next matched text.

This is for windows. But you can check in mac also for which you might want to check the key bindings under Preferences.

Android ListView Selector Color

The list selector drawable is a StateListDrawable — it contains reference to multiple drawables for each state the list can be, like selected, focused, pressed, disabled...

While you can retrieve the drawable using getSelector(), I don't believe you can retrieve a specific Drawable from a StateListDrawable, nor does it seem possible to programmatically retrieve the colour directly from a ColorDrawable anyway.

As for setting the colour, you need a StateListDrawable as described above. You can set this on your list using the android:listSelector attribute, defining the drawable in XML like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="">
  <item android:state_enabled="false" android:state_focused="true"
        android:drawable="@drawable/item_disabled" />
  <item android:state_pressed="true"
        android:drawable="@drawable/item_pressed" />
  <item android:state_focused="true"
        android:drawable="@drawable/item_focused" />

get UTC timestamp in python with datetime

The accepted answer seems not work for me. My solution:

import time
utc_0 = int(time.mktime(datetime(1970, 01, 01).timetuple()))
def datetime2ts(dt):
    """Converts a datetime object to UTC timestamp"""
    return int(time.mktime(dt.utctimetuple())) - utc_0

RunAs A different user when debugging in Visual Studio

As mentioned in have debugger run application as different user (linked above), another extremely simple way to do this which doesn't require any more tools:

  • Hold Shift + right-click to open a new instance of Visual Studio.
  • Click "Run as different user"

    Run as Different user

  • Enter credentials of the other user in the next pop-up window

  • Open the same solution you are working with

Now when you debug the solution it will be with the other user's permissions.

Hint: if you are going to run multiple instances of Visual Studio, change the theme of it (like to "dark") so you can keep track of which one is which easily).

Iterating each character in a string using Python

Well you can also do something interesting like this and do your job by using for loop

#suppose you have variable name
name = "Mr.Suryaa"
for index in range ( len ( name ) ):
    print ( name[index] ) #just like c and c++ 

Answer is

M r . S u r y a a

However since range() create a list of the values which is sequence thus you can directly use the name

for e in name:

This also produces the same result and also looks better and works with any sequence like list, tuple, and dictionary.

We have used tow Built in Functions ( BIFs in Python Community )

1) range() - range() BIF is used to create indexes Example

for i in range ( 5 ) :
can produce 0 , 1 , 2 , 3 , 4

2) len() - len() BIF is used to find out the length of given string

`export const` vs. `export default` in ES6

It's a named export vs a default export. export const is a named export that exports a const declaration or declarations.

To emphasize: what matters here is the export keyword as const is used to declare a const declaration or declarations. export may also be applied to other declarations such as class or function declarations.

Default Export (export default)

You can have one default export per file. When you import you have to specify a name and import like so:

import MyDefaultExport from "./MyFileWithADefaultExport";

You can give this any name you like.

Named Export (export)

With named exports, you can have multiple named exports per file. Then import the specific exports you want surrounded in braces:

// ex. importing multiple exports:
import { MyClass, MyOtherClass } from "./MyClass";
// ex. giving a named import a different name by using "as":
import { MyClass2 as MyClass2Alias } from "./MyClass2";

// use MyClass, MyOtherClass, and MyClass2Alias here

Or it's possible to use a default along with named imports in the same statement:

import MyDefaultExport, { MyClass, MyOtherClass} from "./MyClass";

Namespace Import

It's also possible to import everything from the file on an object:

import * as MyClasses from "./MyClass";
// use MyClasses.MyClass, MyClasses.MyOtherClass and MyClasses.default here


  • The syntax favours default exports as slightly more concise because their use case is more common (See the discussion here).
  • A default export is actually a named export with the name default so you are able to import it with a named import:

    import { default as MyDefaultExport } from "./MyFileWithADefaultExport";

What does this expression language ${pageContext.request.contextPath} exactly do in JSP EL?

Include <%@ page isELIgnored="false"%> on top of your jsp page.

How can I get the average (mean) of selected columns

Here are some examples:

> z$mean <- rowMeans(subset(z, select = c(x, y)), na.rm = TRUE)
> z
  w x  y mean
1 5 1  1    1
2 6 2  2    2
3 7 3  3    3
4 8 4 NA    4

weighted mean

> z$y <- rev(z$y)
> z
  w x  y mean
1 5 1 NA    1
2 6 2  3    2
3 7 3  2    3
4 8 4  1    4
> weight <- c(1, 2) # x * 1/3 + y * 2/3
> z$wmean <- apply(subset(z, select = c(x, y)), 1, function(d) weighted.mean(d, weight, na.rm = TRUE))
> z
  w x  y mean    wmean
1 5 1 NA    1 1.000000
2 6 2  3    2 2.666667
3 7 3  2    3 2.333333
4 8 4  1    4 2.000000

How can I tell if an algorithm is efficient?

Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english

Slidedown and slideup layout with animation

Above method is working, but here are more realistic slide up and slide down animations from the top of the screen.

Just create these two animations under the anim folder


<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="" >

        android:toYDelta="0" />


<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="" >

        android:toYDelta="-100%" />

Load animation in java class like this


Python: Get the first character of the first string in a list?

Try mylist[0][0]. This should return the first character.

Insert string at specified position

str_replace($sub_str, $insert_str.$sub_str, $org_str);

Why would I use dirname(__FILE__) in an include or include_once statement?

If you want code is running on multiple servers with different environments,then we have need to use dirname(FILE) in an include or include_once statement. reason is follows. 1. Do not give absolute path to include files on your server. 2. Dynamically calculate the full path like absolute path.

Use a combination of dirname(FILE) and subsequent calls to itself until you reach to the home of your '/myfile.php'. Then attach this variable that contains the path to your included files.

Save a subplot in matplotlib

Applying the full_extent() function in an answer by @Joe 3 years later from here, you can get exactly what the OP was looking for. Alternatively, you can use Axes.get_tightbbox() which gives a little tighter bounding box

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from matplotlib.transforms import Bbox

def full_extent(ax, pad=0.0):
    """Get the full extent of an axes, including axes labels, tick labels, and
    # For text objects, we need to draw the figure first, otherwise the extents
    # are undefined.
    items = ax.get_xticklabels() + ax.get_yticklabels() 
#    items += [ax, ax.title, ax.xaxis.label, ax.yaxis.label]
    items += [ax, ax.title]
    bbox = Bbox.union([item.get_window_extent() for item in items])

    return bbox.expanded(1.0 + pad, 1.0 + pad)

# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')

ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')

# Save the full figure...

# Save just the portion _inside_ the second axis's boundaries
extent = full_extent(ax2).transformed(fig.dpi_scale_trans.inverted())
# Alternatively,
# extent = ax.get_tightbbox(fig.canvas.renderer).transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)

I'd post a pic but I lack the reputation points

How to convert a Hibernate proxy to a real entity object

Thank you for the suggested solutions! Unfortunately, none of them worked for my case: receiving a list of CLOB objects from Oracle database through JPA - Hibernate, using a native query.

All of the proposed approaches gave me either a ClassCastException or just returned java Proxy object (which deeply inside contained the desired Clob).

So my solution is the following (based on several above approaches):

Query sqlQuery = manager.createNativeQuery(queryStr);
List resultList = sqlQuery.getResultList();
for ( Object resultProxy : resultList ) {
    String unproxiedClob = unproxyClob(resultProxy);
    if ( unproxiedClob != null ) {

private String unproxyClob(Object proxy) {
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(proxy.getClass());
        for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
            Method readMethod = property.getReadMethod();
            if ( readMethod.getName().contains("getWrappedClob") ) {
                Object result = readMethod.invoke(proxy);
                return clobToString((Clob) result);
    catch (InvocationTargetException | IntrospectionException | IllegalAccessException | SQLException | IOException e) {
        LOG.error("Unable to unproxy CLOB value.", e);
    return null;

private String clobToString(Clob data) throws SQLException, IOException {
    StringBuilder sb = new StringBuilder();
    Reader reader = data.getCharacterStream();
    BufferedReader br = new BufferedReader(reader);

    String line;
    while( null != (line = br.readLine()) ) {

    return sb.toString();

Hope this will help somebody!

how to draw smooth curve through N points using javascript HTML5 canvas?

I decide to add on, rather than posting my solution to another post. Below are the solution that I build, may not be perfect, but so far the output are good.

Important: it will pass through all the points!

If you have any idea, to make it better, please share to me. Thanks.

Here are the comparison of before after:

enter image description here

Save this code to HTML to test it out.

    <!DOCTYPE html>_x000D_
     <canvas id="myCanvas" width="1200" height="700" style="border:1px solid #d3d3d3;">Your browser does not support the HTML5 canvas tag.</canvas>_x000D_
      var cv = document.getElementById("myCanvas");_x000D_
      var ctx = cv.getContext("2d");_x000D_
      function gradient(a, b) {_x000D_
       return (b.y-a.y)/(b.x-a.x);_x000D_
      function bzCurve(points, f, t) {_x000D_
       //f = 0, will be straight line_x000D_
       //t suppose to be 1, but changing the value can control the smoothness too_x000D_
       if (typeof(f) == 'undefined') f = 0.3;_x000D_
       if (typeof(t) == 'undefined') t = 0.6;_x000D_
       ctx.moveTo(points[0].x, points[0].y);_x000D_
       var m = 0;_x000D_
       var dx1 = 0;_x000D_
       var dy1 = 0;_x000D_
       var preP = points[0];_x000D_
       for (var i = 1; i < points.length; i++) {_x000D_
        var curP = points[i];_x000D_
        nexP = points[i + 1];_x000D_
        if (nexP) {_x000D_
         m = gradient(preP, nexP);_x000D_
         dx2 = (nexP.x - curP.x) * -f;_x000D_
         dy2 = dx2 * m * t;_x000D_
        } else {_x000D_
         dx2 = 0;_x000D_
         dy2 = 0;_x000D_
        ctx.bezierCurveTo(preP.x - dx1, preP.y - dy1, curP.x + dx2, curP.y + dy2, curP.x, curP.y);_x000D_
        dx1 = dx2;_x000D_
        dy1 = dy2;_x000D_
        preP = curP;_x000D_
      // Generate random data_x000D_
      var lines = [];_x000D_
      var X = 10;_x000D_
      var t = 40; //to control width of X_x000D_
      for (var i = 0; i < 100; i++ ) {_x000D_
       Y = Math.floor((Math.random() * 300) + 50);_x000D_
       p = { x: X, y: Y };_x000D_
       X = X + t;_x000D_
      //draw straight line_x000D_
      ctx.lineWidth = 1;_x000D_
      bzCurve(lines, 0, 1);_x000D_
      //draw smooth line_x000D_
      ctx.lineWidth = 2;_x000D_
      ctx.strokeStyle = "blue";_x000D_
      bzCurve(lines, 0.3, 1);_x000D_

How to make sql-mode="NO_ENGINE_SUBSTITUTION" permanent in MySQL my.cnf

Just to add my configuration to the mix, I'm using MySQL 5.7.8 which has the same strict sql_mode rules by default.

  • I finally figured the following working in my /etc/mysql/my.conf:


i.e. dash, not underscore and quotes around the value.

  • I have NO other my.conf files other than /etc/mysql/my.conf

  • There are some extra config includes being loaded from /etc/mysql/conf.d/ but they are blank.

And that seems to work for me.

C# - Multiple generic types in one list

I have also used a non-generic version, using the new keyword:

public interface IMetadata
    Type DataType { get; }

    object Data { get; }

public interface IMetadata<TData> : IMetadata
    new TData Data { get; }

Explicit interface implementation is used to allow both Data members:

public class Metadata<TData> : IMetadata<TData>
    public Metadata(TData data)
       Data = data;

    public Type DataType
        get { return typeof(TData); }

    object IMetadata.Data
        get { return Data; }

    public TData Data { get; private set; }

You could derive a version targeting value types:

public interface IValueTypeMetadata : IMetadata


public interface IValueTypeMetadata<TData> : IMetadata<TData>, IValueTypeMetadata where TData : struct


public class ValueTypeMetadata<TData> : Metadata<TData>, IValueTypeMetadata<TData> where TData : struct
    public ValueTypeMetadata(TData data) : base(data)

This can be extended to any kind of generic constraints.

How to change the blue highlight color of a UITableViewCell?

Based on @user's answer, you can just add this extension anywhere in your app code and have your selection color directly in storyboard editor for every cells of your app :

@IBDesignable extension UITableViewCell {
    @IBInspectable var selectedColor: UIColor? {
        set {
            if let color = newValue {
                selectedBackgroundView = UIView()
                selectedBackgroundView!.backgroundColor = color
            } else {
                selectedBackgroundView = nil
        get {
            return selectedBackgroundView?.backgroundColor

UITableViewCell selection color in storyboard

TCPDF output without saving file

If You want to open dialogue window in browser to save, not open with PDF browser viewer (I was looking for this solution for a while), You should use 'D':

$pdf->Output('name.pdf', 'D');

How do I get the color from a hexadecimal color code using .NET?

The three variants below give exactly the same color. The last one has the benefit of being highlighted in the Visual Studio 2010 IDE (maybe it's ReSharper that's doing it) with proper color.

var cc1 = System.Drawing.ColorTranslator.FromHtml("#479DEE");

var cc2 = System.Drawing.Color.FromArgb(0x479DEE);

var cc3 = System.Drawing.Color.FromArgb(0x47, 0x9D, 0xEE);

CSS3 Spin Animation

HTML with font-awesome glyphicon.

<span class="fa fa-spinner spin"></span>


@-moz-keyframes spin {
    to { -moz-transform: rotate(360deg); }
@-webkit-keyframes spin {
    to { -webkit-transform: rotate(360deg); }
@keyframes spin {
    to {transform:rotate(360deg);}

.spin {
    animation: spin 1000ms linear infinite;

Git Bash won't run my python files?

That command did not work for me, I used:

$ export PATH="$PATH:/c/Python27"

Then to make sure that git remembers the python path every time you open git type the following.

echo 'export PATH="$PATH:/c/Python27"' > .profile

Finding a substring within a list in Python

print [s for s in list if sub in s]

If you want them separated by newlines:

print "\n".join(s for s in list if sub in s)

Full example, with case insensitivity:

mylist = ['abc123', 'def456', 'ghi789', 'ABC987', 'aBc654']
sub = 'abc'

print "\n".join(s for s in mylist if sub.lower() in s.lower())

Sort hash by key, return hash in Ruby

I've always used sort_by. You need to wrap the #sort_by output with Hash[] to make it output a hash, otherwise it outputs an array of arrays. Alternatively, to accomplish this you can run the #to_h method on the array of tuples to convert them to a k=>v structure (hash).

hsh ={"a" => 1000, "b" => 10, "c" => 200000}
Hash[hsh.sort_by{|k,v| v}] #or hsh.sort_by{|k,v| v}.to_h

There is a similar question in "How to sort a Ruby Hash by number value?".

Why am I getting this error Premature end of file?

I came across the same error, and could easily find what was the problem by logging the exception:

documentBuilder.setErrorHandler(new ErrorHandler() {
    public void warning(SAXParseException exception) throws SAXException {

    public void fatalError(SAXParseException exception) throws SAXException {
        log.error("Fatal error ", exception);

    public void error(SAXParseException exception) throws SAXException {
        log.error("Exception ", exception);

Or, instead of logging the error, you can throw it and catch it where you handle the entries, so you can print the entry itself to get a better indication on the error.

Can dplyr package be used for conditional mutating?

Use ifelse

df %>%
  mutate(g = ifelse(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4), 2,
               ifelse(a == 0 | a == 1 | a == 4 | a == 3 |  c == 4, 3, NA)))

Added - if_else: Note that in dplyr 0.5 there is an if_else function defined so an alternative would be to replace ifelse with if_else; however, note that since if_else is stricter than ifelse (both legs of the condition must have the same type) so the NA in that case would have to be replaced with NA_real_ .

df %>%
  mutate(g = if_else(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4), 2,
               if_else(a == 0 | a == 1 | a == 4 | a == 3 |  c == 4, 3, NA_real_)))

Added - case_when Since this question was posted dplyr has added case_when so another alternative would be:

df %>% mutate(g = case_when(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4) ~ 2,
                            a == 0 | a == 1 | a == 4 | a == 3 |  c == 4 ~ 3,
                            TRUE ~ NA_real_))

Added - arithmetic/na_if If the values are numeric and the conditions (except for the default value of NA at the end) are mutually exclusive, as is the case in the question, then we can use an arithmetic expression such that each term is multiplied by the desired result using na_if at the end to replace 0 with NA.

df %>%
  mutate(g = 2 * (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)) +
             3 * (a == 0 | a == 1 | a == 4 | a == 3 |  c == 4),
         g = na_if(g, 0))

What are the proper permissions for an upload folder with PHP/Apache?

I will add that if you are using SELinux that you need to make sure the type context is tmp_t You can accomplish this by using the chcon utility

chcon -t tmp_t uploads

Efficiency of Java "Double Brace Initialization"?

leak prone

I've decided to chime in. The performance impact includes: disk operation + unzip (for jar), class verification, perm-gen space (for Sun's Hotspot JVM). However, worst of all: it's leak prone. You can't simply return.

Set<String> getFlavors(){
  return Collections.unmodifiableSet(flavors)

So if the set escapes to any other part loaded by a different classloader and a reference is kept there, the entire tree of classes+classloader will be leaked. To avoid that, a copy to HashMap is necessary, new LinkedHashSet(new ArrayList(){{add("xxx);add("yyy");}}). Not so cute any more. I don't use the idiom, myself, instead it is like new LinkedHashSet(Arrays.asList("xxx","YYY"));

Multi value Dictionary

I solved Using:

Dictionary<short, string[]>

Like this

Dictionary<short, string[]> result = new Dictionary<short, string[]>();
           new string[] 
return result;

How to use the divide function in the query?

Assuming all of these columns are int, then the first thing to sort out is converting one or more of them to a better data type - int division performs truncation, so anything less than 100% would give you a result of 0:


Here, I've mutiplied one of the numbers by 100.0 which will force the result of the calculation to be done with floats rather than ints. By choosing 100, I'm also getting it ready to be treated as a %.

I was also a little confused by your bracketing - I think I've got it correct - but you had brackets around single values, and then in other places you had a mix of operators (- and /) at the same level, and so were relying on the precedence rules to define which operator applied first.

Python object.__repr__(self) should be an expression?

>>> from datetime import date
>>> repr(        # calls
', 1, 16)'
>>> eval(_)                   # _ is the output of the last command, 1, 16)

The output is a string that can be parsed by the python interpreter and results in an equal object.

If that's not possible, it should return a string in the form of <...some useful description...>.

How to change onClick handler dynamically?


$('#foo').click(function() { alert('foo'); });

Or if you don't want it to follow the link href:

$('#foo').click(function() { alert('foo'); return false; });

How do I display the value of a Django form field in a template?

If you've populated the form with an instance and not with POST data (as the suggested answer requires), you can access the data using {{ form.instance.my_field_name }}.

How to automatically indent source code?

I have tried both ways, and from the Edit|Advanced menu, and they are not doing anything to my source code. Other options like line indent are working. What could be wrong? – Chucky Jul 12 '13 at 11:06

Sometimes if it doesnt work, try to select a couple lines above and below or the whole block of code (whole function, whole cycle, whole switch, etc.), so that it knows how to indent.

Like for example if you copy/paste something into a case statement of a switch and it has wrong indentation, you need to select the text + the line with the case statement above to get it to work.

Angular 4 checkbox change value

Give a try on this,


<input (change)="fieldsChange($event)" value="angular" type="checkbox"/>

Ts File

fieldsChange(values:any):void {

Add spaces between the characters of a string in Java?

I believe what he was looking for was mime code carrier return type code such as %0D%0A (for a Return or line break) and \u00A0 (for spacing) or alternatively $#032

Bootstrap alert in a fixed floating div at the top of page

Others are suggesting a wrapping div but you should be able to do this without adding complexity to your html...

check this out:

#message {
  box-sizing: border-box;
  padding: 8px;

How to create XML file with specific structure in Java


package com.mkyong.core;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public int getAge() {
        return age;

    public void setAge(int age) {
        this.age = age;

    public int getId() {
        return id;

    public void setId(int id) { = id;

package com.mkyong.core;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {
    public static void main(String[] args) {

      Customer customer = new Customer();

      try {

        File file = new File("C:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(customer, file);
        jaxbMarshaller.marshal(customer, System.out);

      } catch (JAXBException e) {


How can I check the size of a collection within a Django template?

If you tried myList|length and myList|length_is and its not getting desired results, then you should use myList.count

Could not install packages due to an EnvironmentError: [Errno 13]

I already tried all suggestion posted in here, yet I'm still getting the errno 13,

I'm using Windows and my python version is 3.7.3

After 5 hours of trying to solve it, this step worked for me:

I try to open the command prompt by run as administrator

MySQL Select last 7 days

Since you are using an INNER JOIN you can just put the conditions in the WHERE clause, like this:

    tartikel AS p1 INNER JOIN tartikelpict AS p2 
    ON p1.kArtikel = p2.kArtikel
  DATE(dErstellt) > (NOW() - INTERVAL 7 DAY)
  AND p2.nNr = 1
  p1.kArtikel DESC

Ambiguous overload call to abs(double)

Use fabs() instead of abs(), it's the same but for floats instead of integers.

C# find biggest number

Use Math.Max:

int x = 3, y = 4, z = 5;
Console.WriteLine(Math.Max(Math.Max(x, y), z));

How do I catch an Ajax query post error?

You have to log the responseText:

    type: 'POST',
    url: 'status.ajax.php',
    data: {
    deviceId: id
 function (data) {
  //your code
.fail(function (data) {
      console.log( "Ajax failed: " + data['responseText'] );

SQL Server Restore Error - Access is Denied

This also happens if the paths are correct, but the service account is not the owner of the data files (yet it still has enough rights for read/write access). This can occur if the permissions for the files were reset to match the permissions of the folder (of course, while the service was stopped).

The easiest solution in this case is to detach each database and attach it again (because when attaching the owner is changed to be the service account).

Iterate over array of objects in Typescript

In Typescript and ES6 you can also use for..of:

for (var product of products) {

which will be transcoded to javascript:

for (var _i = 0, products_1 = products; _i < products_1.length; _i++) {
    var product = products_1[_i];

Select2() is not a function

The issue is quite old, but I'll put some small note as I spent couple of hours today investigating pretty same issue. After I loaded a part of code dynamically select2 couldn't work out on a new selectboxes with an error "$(...).select2 is not a function".

I found that in non-packed select2.js there is a line preventing it to reprocess the main function (in my 3.5.4 version it is in line 45):

if (window.Select2 !== undefined) {

So I just commented it out there and started to use select2.js (instead of minified version).

//if (window.Select2 !== undefined) {
//    return;

And it started to work just fine, of course it now can do the processing several times loosing the performance, but I need it anyhow.

Hope this helps, Vladimir

Remove all git files from a directory?

ls | xargs find 2>/dev/null | egrep /\.git$ | xargs rm -rf

This command (and it is just one command) will recursively remove .git directories (and files) that are in a directory without deleting the top-level git repo, which is handy if you want to commit all of your files without managing any submodules.

find 2>/dev/null | egrep /\.git$ | xargs rm -rf

This command will do the same thing, but will also delete the .git folder from the top-level directory.

mappedBy reference an unknown target entity property

The mappedBy attribute is referencing customer while the property is mCustomer, hence the error message. So either change your mapping into:

/** The collection of stores. */
@OneToMany(mappedBy = "mCustomer", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Collection<Store> stores;

Or change the entity property into customer (which is what I would do).

The mappedBy reference indicates "Go look over on the bean property named 'customer' on the thing I have a collection of to find the configuration."

How to check the gradle version in Android Studio?

I'm not sure if this is what you ask, but you can check gradle version of your project here in android studio:

(left pane must be in project view, not android for this path) app->gradle->wrapper->

it has a line like this, indicating the gradle version:


There is also a table at the end of this page that shows gradle and gradle plug-in versions supported by each android studio version. (you can check your android studio by checking help->about as you may already know)

Is there a date format to display the day of the week in java?

This should display 'Tue':

new SimpleDateFormat("EEE").format(new Date());

This should display 'Tuesday':

new SimpleDateFormat("EEEE").format(new Date());

This should display 'T':

new SimpleDateFormat("EEEEE").format(new Date());

So your specific example would be:

new SimpleDateFormat("yyyy-MM-EEE").format(new Date());

Android set height and width of Custom view programmatically

This is a Kotlin based version, assuming that the parent view is an instance of LinearLayout.

someView.layoutParams = LinearLayout.LayoutParams(100, 200)

This allows to set the width and height (100 and 200) in a single line.

What is the best way to detect a mobile device?

Sometimes it is desired to know which brand device a client is using in order to show content specific to that device, like a link to the iPhone store or the Android market. Modernizer is great, but only shows you browser capabilities, like HTML5, or Flash.

Here is my UserAgent solution in jQuery to display a different class for each device type:

/*** sniff the UA of the client and show hidden div's for that device ***/
var customizeForDevice = function(){
    var ua = navigator.userAgent;
    var checker = {
      iphone: ua.match(/(iPhone|iPod|iPad)/),
      blackberry: ua.match(/BlackBerry/),
      android: ua.match(/Android/)
    if ({
    else if (checker.iphone){
    else if (checker.blackberry){
    else {

This solution is from Graphics Maniacs

Spring can you autowire inside an abstract class?

I have that kind of spring setup working

an abstract class with an autowired field

public abstract class AbstractJobRoute extends RouteBuilder {

    private GlobalSettingsService settingsService;

and several children defined with @Component annotation.

Disable Required validation attribute under certain circumstances

this was someone else's answer in the comments...but it should be a real answer:


tested on MVC 6 with a field having the [Required] attribute

answer stolen from above

How to dynamically change the color of the selected menu item of a web page?

I use PHP to find the URL and match the page name (without the extension of .php, also I can add multiple pages that all have the same word in common like contact, contactform, etc. All will have that class added) and add a class with PHP to change the color, etc. For that you would have to save your pages with file extension .php.

Here is a demo. Change your links and pages as required. The CSS class for all the links is .tab and for the active link there is also another class of .currentpage (as is the PHP function) so that is where you will overwrite your CSS rules. You could name them whatever you like.

<?php # Using REQUEST_URI
    $currentpage = $_SERVER['REQUEST_URI'];?>
    <div class="nav">
        <div class="tab
                 if(preg_match("/index/i", $currentpage)||($currentpage=="/"))
                     echo " currentpage";
             ?>"><a href="index.php">Home</a>
         <div class="tab
                 if(preg_match("/services/i", $currentpage))
                     echo " currentpage";
             ?>"><a href="services.php">Services</a>
         <div class="tab
                 if(preg_match("/about/i", $currentpage))
                     echo " currentpage";
             ?>"><a href="about.php">About</a>
         <div class="tab
                 if(preg_match("/contact/i", $currentpage))
                     echo " currentpage";
             ?>"><a href="contact.php">Contact</a>
     </div> <!--nav-->

Unable to Install Any Package in Visual Studio 2015

You need to Clear All NuGet Caches; for this you need go to Options and click on it like this:

enter image description here

Convert int to char in java

public class String_Store_In_Array 
    public static void main(String[] args) 
        System.out.println(" Q.37 Can you store string in array of integers. Try it.");

        String str="I am Akash";
        int arr[]=new int[str.length()];
        char chArr[]=str.toCharArray();
          char  ch;
        for(int i=0;i<str.length();i++)

        System.out.println("\nI have stored it in array by using ASCII value");
        for(int i=0;i<arr.length;i++)

            System.out.print(" "+arr[i]);
        System.out.println("\nI have stored it in array by using ASCII value to original content");
        for(int i=0;i<arr.length;i++)

            System.out.print(" "+ch);

Disable future dates after today in Jquery Ui Datepicker

You can simply do this

$(function() {
    $( "#datepicker" ).datepicker({  maxDate: new Date });


FYI: while checking the documentation, found that it also accepts numeric values too.

Number: A number of days from today. For example 2 represents two days from today and -1 represents yesterday.

so 0 represents today. Therefore you can do this too

 $( "#datepicker" ).datepicker({  maxDate: 0 });

Select default option value from typescript angular 6

I had similar issues with Angular6 . After going through many posts. I had to import FormsModule as below in app.module.ts .

import {FormsModule} from '@angular/forms';

Then my ngModel tag worked . Please try this.

<select [(ngModel)]='nrSelect' class='form-control'>                                                                
                                <option [ngValue]='47'>47</option>
                                    <option [ngValue]='46'>46</option>
                                    <option [ngValue]='45'>45</option>

sudo: port: command not found

If you have just installed macports just run and it should work

source ~/.bash_profile

center image in div with overflow hidden

None of the above solutions were working out well for me. I needed a dynamic image size to fit in a circular parent container with overflow:hidden

.circle-container {

.circle-img img {
  margin:0 -100%;

Working example here:

Multiple markers Google Map API v3 from array of addresses and avoid OVER_QUERY_LIMIT while geocoding on pageLoad

Answer to add multiple markers.


Here's the working Example Geocoding with multiple addresses.

 <script type="text/javascript" src="">
 <script type="text/javascript">
  var delay = 100;
  var infowindow = new google.maps.InfoWindow();
  var latlng = new google.maps.LatLng(21.0000, 78.0000);
  var mapOptions = {
    zoom: 5,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  var geocoder = new google.maps.Geocoder(); 
  var map = new google.maps.Map(document.getElementById("map"), mapOptions);
  var bounds = new google.maps.LatLngBounds();

  function geocodeAddress(address, next) {
    geocoder.geocode({address:address}, function (results,status)
         if (status == google.maps.GeocoderStatus.OK) {
          var p = results[0].geometry.location;
          var lng=p.lng();
        else {
           if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
          } else {
 function createMarker(add,lat,lng) {
   var contentString = add;
   var marker = new google.maps.Marker({
     position: new google.maps.LatLng(lat,lng),
     map: map,

  google.maps.event.addListener(marker, 'click', function() {


  var locations = [
           'New Delhi, India',
           'Mumbai, India',
           'Bangaluru, Karnataka, India',
           'Hyderabad, Ahemdabad, India',
           'Gurgaon, Haryana, India',
           'Cannaught Place, New Delhi, India',
           'Bandra, Mumbai, India',
           'Nainital, Uttranchal, India',
           'Guwahati, India',
           'West Bengal, India',
           'Jammu, India',
           'Kanyakumari, India',
           'Kerala, India',
           'Himachal Pradesh, India',
           'Shillong, India',
           'Chandigarh, India',
           'Dwarka, New Delhi, India',
           'Pune, India',
           'Indore, India',
           'Orissa, India',
           'Shimla, India',
           'Gujarat, India'
  var nextAddress = 0;
  function theNext() {
    if (nextAddress < locations.length) {
      setTimeout('geocodeAddress("'+locations[nextAddress]+'",theNext)', delay);
    } else {


As we can resolve this issue with setTimeout() function.

Still we should not geocode known locations every time you load your page as said by @geocodezip

Another alternatives of these are explained very well in the following links:

How To Avoid GoogleMap Geocode Limit!

Geocode Multiple Addresses Tutorial By Mike Williams

Example by Google Developers

How to create a file in Android?

From here:

//Writing a file...  

try { 
       // catches IOException below
       final String TESTSTRING = new String("Hello Android");

       /* We have to use the openFileOutput()-method
       * the ActivityContext provides, to
       * protect your file from others and
       * This is done for security-reasons.
       * We chose MODE_WORLD_READABLE, because
       *  we have nothing to hide in our file */             
       FileOutputStream fOut = openFileOutput("samplefile.txt",
       OutputStreamWriter osw = new OutputStreamWriter(fOut); 

       // Write the string to the file

       /* ensure that everything is
        * really written out and close */

//Reading the file back...

       /* We have to use the openFileInput()-method
        * the ActivityContext provides.
        * Again for security reasons with
        * openFileInput(...) */

        FileInputStream fIn = openFileInput("samplefile.txt");
        InputStreamReader isr = new InputStreamReader(fIn);

        /* Prepare a char-Array that will
         * hold the chars we read back in. */
        char[] inputBuffer = new char[TESTSTRING.length()];

        // Fill the Buffer with data from the file;

        // Transform the chars to a String
        String readString = new String(inputBuffer);

        // Check if we read back the same chars that we had written out
        boolean isTheSame = TESTSTRING.equals(readString);

        Log.i("File Reading stuff", "success = " + isTheSame);

    } catch (IOException ioe) 

Changing ViewPager to enable infinite page scrolling

infinite slider adapter skeleton based on previous samples

some critical issues:

  • remember original (relative) position in page view (tag used in sample), so we will look this position to define relative position of view. otherwise child order in pager is mixed
  • have to fill first time absolute view inside adapter. (the rest of times this fill will be invalid) found no way to force it fill from pager handler. the rest times absolute view will be overriden from pager handler with correct values.
  • when pages are slided quickly, side page (actually left) is not filled from pager handler. no workaround for the moment, just use empty view, it will be filled with actual values when drag is stopped. upd: quick workaround: disable adapter's destroyItem.

you may look at the logcat to understand whats happening in this sample

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
    android:layout_height="match_parent" >

    <TextView xmlns:android=""
        android:text="Text Text Text"


And then:

public class ActivityCalendar extends Activity
    public class CalendarAdapter extends PagerAdapter
        public int getCount()
            return 3;

        public boolean isViewFromObject(View view, Object object)
            return view == ((RelativeLayout) object);

        public Object instantiateItem(ViewGroup container, int position)
            LayoutInflater inflater = (LayoutInflater)ActivityCalendar.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View viewLayout = inflater.inflate(R.layout.layout_calendar, container, false);
            viewLayout.setTag(new Integer(position));

            //TextView tv = (TextView) viewLayout.findViewById(;
            //tv.setText(String.format("Text Text Text relative: %d", position));

            if (!ActivityCalendar.this.scrolledOnce)
                // fill here only first time, the rest will be overriden in pager scroll handler
                switch (position)
                    case 0:
                        ActivityCalendar.this.setPageContent(viewLayout, globalPosition - 1);
                    case 1:
                        ActivityCalendar.this.setPageContent(viewLayout, globalPosition);
                    case 2:
                        ActivityCalendar.this.setPageContent(viewLayout, globalPosition + 1);

            ((ViewPager) container).addView(viewLayout);

            //Log.i("instantiateItem", String.format("position = %d", position));

            return viewLayout;

        public void destroyItem(ViewGroup container, int position, Object object)
            ((ViewPager) container).removeView((RelativeLayout) object);

            //Log.i("destroyItem", String.format("position = %d", position));

    public void setPageContent(View viewLayout, int globalPosition)
        if (viewLayout == null)
        TextView tv = (TextView) viewLayout.findViewById(;
        tv.setText(String.format("Text Text Text global %d", globalPosition));

    private boolean scrolledOnce = false;
    private int focusedPage = 0;
    private int globalPosition = 0;

    public void onCreate(Bundle savedInstanceState)

        final ViewPager viewPager = (ViewPager) findViewById(;

        viewPager.setOnPageChangeListener(new OnPageChangeListener()
            public void onPageSelected(int position)
                focusedPage = position;
                // actual page change only when position == 1
                if (position == 1)
                    setTitle(String.format("relative: %d, global: %d", position, globalPosition));
                Log.i("onPageSelected", String.format("focusedPage/position = %d, globalPosition = %d", position, globalPosition));

            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
                //Log.i("onPageScrolled", String.format("position = %d, positionOffset = %f", position, positionOffset));

            public void onPageScrollStateChanged(int state)
                Log.i("onPageScrollStateChanged", String.format("state = %d, focusedPage = %d", state, focusedPage));
                if (state == ViewPager.SCROLL_STATE_IDLE)
                    if (focusedPage == 0)
                    else if (focusedPage == 2)

                    scrolledOnce = true;

                    for (int i = 0; i < viewPager.getChildCount(); i++)
                        final View v = viewPager.getChildAt(i);
                        if (v == null)

                        // reveal correct child position
                        Integer tag = (Integer)v.getTag();
                        if (tag == null)

                        switch (tag.intValue())
                            case 0:
                                setPageContent(v, globalPosition - 1);
                            case 1:
                                setPageContent(v, globalPosition);
                            case 2:
                                setPageContent(v, globalPosition + 1);

                    Log.i("onPageScrollStateChanged", String.format("globalPosition = %d", globalPosition));

                    viewPager.setCurrentItem(1, false);

        CalendarAdapter calendarAdapter = CalendarAdapter();

        // center item
        viewPager.setCurrentItem(1, false);

Save results to csv file with Python

An easy example would be something like:

writer = csv.writer(open("filename.csv", "wb"))
String[] entries = "first#second#third".split("#");

Nested Recycler view height doesn't wrap its content

I have tried all solutions, they are very useful but this only works fine for me

public class  LinearLayoutManager extends {

    public LinearLayoutManager(Context context, int orientation, boolean reverseLayout)    {
        super(context, orientation, reverseLayout);

    private int[] mMeasuredDimension = new int[2];

    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
                          int widthSpec, int heightSpec) {
        final int widthMode = View.MeasureSpec.getMode(widthSpec);
        final int heightMode = View.MeasureSpec.getMode(heightSpec);
        final int widthSize = View.MeasureSpec.getSize(widthSpec);
        final int heightSize = View.MeasureSpec.getSize(heightSpec);
        int width = 0;
        int height = 0;
        for (int i = 0; i < getItemCount(); i++) {

            if (getOrientation() == HORIZONTAL) {

                measureScrapChild(recycler, i,
                        View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),

                width = width + mMeasuredDimension[0];
                if (i == 0) {
                    height = mMeasuredDimension[1];
            } else {
                measureScrapChild(recycler, i,
                        View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                height = height + mMeasuredDimension[1];
                if (i == 0) {
                    width = mMeasuredDimension[0];

        if (height < heightSize || width < widthSize) {

            switch (widthMode) {
                case View.MeasureSpec.EXACTLY:
                    width = widthSize;
                case View.MeasureSpec.AT_MOST:
                case View.MeasureSpec.UNSPECIFIED:

            switch (heightMode) {
                case View.MeasureSpec.EXACTLY:
                    height = heightSize;
                case View.MeasureSpec.AT_MOST:
                case View.MeasureSpec.UNSPECIFIED:

            setMeasuredDimension(width, height);
        } else {
            super.onMeasure(recycler, state, widthSpec, heightSpec);

    private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
                                   int heightSpec, int[] measuredDimension) {
        View view = recycler.getViewForPosition(position);
        recycler.bindViewToPosition(view, position);
        if (view != null) {
            RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
            int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
                    getPaddingLeft() + getPaddingRight(), p.width);
            int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                    getPaddingTop() + getPaddingBottom(), p.height);
            view.measure(childWidthSpec, childHeightSpec);
            measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
            measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;

Random integer in VB.NET

Function xrand() As Long
        Dim r1 As Long = Now.Day & Now.Month & Now.Year & Now.Hour & Now.Minute & Now.Second & Now.Millisecond
        Dim RAND As Long = Math.Max(r1, r1 * 2)
        Return RAND
End Function

[BBOYSE] This its the best way, from scratch :P

Algorithm to return all combinations of k elements from n

Here is a Lisp approach using a macro. This works in Common Lisp and should work in other Lisp dialects.

The code below creates 'n' nested loops and executes an arbitrary chunk of code (stored in the body variable) for each combination of 'n' elements from the list lst. The variable var points to a list containing the variables used for the loops.

(defmacro do-combinations ((var lst num) &body body)
  (loop with syms = (loop repeat num collect (gensym))
        for i on syms
        for k = `(loop for ,(car i) on (cdr ,(cadr i))
                         do (let ((,var (list ,@(reverse syms)))) (progn ,@body)))
                then `(loop for ,(car i) on ,(if (cadr i) `(cdr ,(cadr i)) lst) do ,k)
        finally (return k)))

Let's see...

(macroexpand-1 '(do-combinations (p '(1 2 3 4 5 6 7) 4) (pprint (mapcar #'car p))))

(LOOP FOR #:G3217 ON '(1 2 3 4 5 6 7) DO
 (LOOP FOR #:G3216 ON (CDR #:G3217) DO
  (LOOP FOR #:G3215 ON (CDR #:G3216) DO
   (LOOP FOR #:G3214 ON (CDR #:G3215) DO
    (LET ((P (LIST #:G3217 #:G3216 #:G3215 #:G3214)))
     (PROGN (PPRINT (MAPCAR #'CAR P))))))))

(do-combinations (p '(1 2 3 4 5 6 7) 4) (pprint (mapcar #'car p)))

(1 2 3 4)
(1 2 3 5)
(1 2 3 6)

Since combinations are not stored by default, storage is kept to a minimum. The possibility of choosing the body code instead of storing all results also affords more flexibility.

How to obtain the number of CPUs/cores in Linux from the command line?

I also thought cat /proc/cpuinfo would give me the correct answer, however I recently saw that my ARM quad core Cortex A53 system only showed a single core. It seems that /proc/cpuinfo only shows the active cores, whereas:

cat /sys/devices/system/cpu/present

is a better measure of what's there. You can also

cat /sys/devices/system/cpu/online

to see which cores are online, and

cat /sys/devices/system/cpu/offline

to see which cores are offline. The online, offline, and present sysfs entries return the index of the CPUS, so a return value of 0 just means core 0, whereas a return value of 1-3 means cores 1,2, and 3.


nginx - read custom header from upstream server


i.e if you have origin = in header, you can use $http_origin to get ""

In nginx does support arbitrary request header field. In the above example last part of a variable name is the field name converted to lower case with dashes replaced by underscores

Reference doc here:

For your example the variable would be $http_my_custom_header.


If you want to know which is more effective, you should try looking at the estimated query plans, or the actual query plans after execution. It'll tell you the costs of the queries (I find CPU and IO cost to be interesting). I wouldn't be surprised much if there's little to no difference, but you never know. I've seen certain queries use multiple cores on our database server, while a rewritten version of that same query would only use one core (needless to say, the query that used all 4 cores was a good 3 times faster). Never really quite put my finger on why that is, but if you're working with large result sets, such differences can occur without your knowing about it.

How to pause javascript code execution for 2 seconds

There's no way to stop execution of your code as you would do with a procedural language. You can instead make use of setTimeout and some trickery to get a parametrized timeout:

for (var i = 1; i <= 5; i++) {
    var tick = function(i) {
        return function() {
    setTimeout(tick(i), 500 * i);

Demo here:

Why use Redux over Facebook Flux?

You might be best starting with reading this post by Dan Abramov where he discusses various implementations of Flux and their trade-offs at the time he was writing redux: The Evolution of Flux Frameworks

Secondly that motivations page you link to does not really discuss the motivations of Redux so much as the motivations behind Flux (and React). The Three Principles is more Redux specific though still does not deal with the implementation differences from the standard Flux architecture.

Basically, Flux has multiple stores that compute state change in response to UI/API interactions with components and broadcast these changes as events that components can subscribe to. In Redux, there is only one store that every component subscribes to. IMO it feels at least like Redux further simplifies and unifies the flow of data by unifying (or reducing, as Redux would say) the flow of data back to the components - whereas Flux concentrates on unifying the other side of the data flow - view to model.

javascript date + 7 days

var days = 7;
var date = new Date();
var res = date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));

var d = new Date(res);
var month = d.getMonth() + 1;
var day = d.getDate();

var output = d.getFullYear() + '/' +
    (month < 10 ? '0' : '') + month + '/' +
    (day < 10 ? '0' : '') + day;


How to find and replace all occurrences of a string recursively in a directory tree?

I know this is a really old question, but...

  1. @vehomzzz's answer uses find and xargs when the questions says explicitly grep and sed only.

  2. @EmployedRussian and @BrooksMoses tried to say it was a dup of awk and sed, but it's not - again, the question explicitly says grep and sed only.

So here is my solution, assuming you are using Bash as your shell:

for f in `grep -rl .` # Use -irl instead of -rl for case insensitive search
    sed -i 's/a\.example\.com/' $f # Use /gi instead of /g for case insensitive search

If you are using a different shell, such as Unix SHell, let me know and I will try to find a syntax adjustment.

P.S.: Here's a one-liner:

OLDIFS=$IFS;IFS=$'\n';for f in `grep -rl .`;do sed -i 's/a\.example\.com/' $f;done;IFS=$OLDIFS


Storing integer values as constants in Enum manner in java

The most common valid reason for wanting an integer constant associated with each enum value is to interoperate with some other component which still expects those integers (e.g. a serialization protocol which you can't change, or the enums represent columns in a table, etc).

In almost all cases I suggest using an EnumMap instead. It decouples the components more completely, if that was the concern, or if the enums represent column indices or something similar, you can easily make changes later on (or even at runtime if need be).

 private final EnumMap<Page, Integer> pageIndexes = new EnumMap<Page, Integer>(Page.class);
 pageIndexes.put(Page.SIGN_CREATE, 1);
 //etc., ...

 int createIndex = pageIndexes.get(Page.SIGN_CREATE);

It's typically incredibly efficient, too.

Adding data like this to the enum instance itself can be very powerful, but is more often than not abused.

Edit: Just realized Bloch addressed this in Effective Java / 2nd edition, in Item 33: Use EnumMap instead of ordinal indexing.

Loop through a Map with JSTL

Like this:

<c:forEach var="entry" items="${myMap}">
  Key: <c:out value="${entry.key}"/>
  Value: <c:out value="${entry.value}"/>

How to convert string to boolean php

The answer by @GordonM is good. But it would fail if the $string is already true (ie, the string isn't a string but boolean TRUE)...which seems illogical.

Extending his answer, I'd use:

$test_mode_mail = ($string === 'true' OR $string === true));

How do I escape spaces in path for scp copy in Linux?

Sorry for using this Linux question to put this tip for Powershell on Windows 10: the space char escaping with backslashes or surrounding with quotes didn't work for me in this case. Not efficient, but I solved it using the "?" char instead:

for the file "tasks.txt Jun-22.bkp" I downloaded it using "tasks.txt?Jun-22.bkp"

Why does Eclipse automatically add appcompat v7 library support whenever I create a new project?

As stated in Android's Support Library Overview, it is considered good practice to include the support library by default because of the large diversity of devices and the fragmentation that exists between the different versions of Android (and thus, of the provided APIs).

This is the reason why Android code templates tools included in Eclipse through the Android Development Tools (ADT) integrate them by default.

I noted that you target API 15 in your sample, but the miminum required SDK for your package is API 10, for which the compatibility libraries can provide a tremendous amount of backward compatible APIs. An example would be the ability of using the Fragment API which appeard on API 11 (Android 3.0 Honeycomb) on a device that runs an older version of this system.

It is also to be noted that you can deactivate automatic inclusion of the Support Library by default.

how to loop through json array in jquery?

var data = [ 
 {"Id": 10004, "PageName": "club"}, 
 {"Id": 10040, "PageName": "qaz"}, 
 {"Id": 10059, "PageName": "jjjjjjj"}

$.each(data, function(i, item) {

$.each(data, function(i, item) {

Or else You can try this method

var data = jQuery.parseJSON(response);
$.each(data, function(key,value) {
   alert(value.Id);    //It will shows the Id values

Printing a 2D array in C

First you need to input the two numbers say num_rows and num_columns perhaps using argc and argv then do a for loop to print the dots.

int j=0;
int k=0;
for (k=0;k<num_columns;k++){
   for (j=0;j<num_rows;j++){

you'd have to replace the dot with something else later.

Unable to start debugging on the web server. Could not start ASP.NET debugging VS 2010, II7, Win 7 x64

I have exactly the same problem after implementing the rewrite module.

If I remove the rewrite entries from my web.config file, debugging works perfectly.

To get around this, I just to comment out the rewrite tags while debugging, like this...

        <rule name="LowerCaseRule_1" stopProcessing="true">
            <match url="[A-Z]" ignoreCase="false" />
            <action type="Redirect" url="{ToLower:{URL}}" />
        <rule name="RedirectDefault.aspx_1" stopProcessing="true">
            <match url="(.*)default.aspx" />
            <action type="Redirect" url="{R:1}" redirectType="Permanent" />

I then remove the comments after debugging.

Must be an bug in visual studio 2010.

Spring Boot Configure and Use Two DataSources

Here you go.

Add in your file:

#first db
spring.datasource.url = [url]
spring.datasource.username = [username]
spring.datasource.password = [password]
spring.datasource.driverClassName = oracle.jdbc.OracleDriver

#second db ...
spring.secondDatasource.url = [url]
spring.secondDatasource.username = [username]
spring.secondDatasource.password = [password]
spring.secondDatasource.driverClassName = oracle.jdbc.OracleDriver

Add in any class annotated with @Configuration the following methods:

public DataSource primaryDataSource() {
    return DataSourceBuilder.create().build();

public DataSource secondaryDataSource() {
    return DataSourceBuilder.create().build();

How do I rename both a Git local and remote branch name?

Attaching a Simple Snippet for renaming your current branch (local and on origin):

git branch -m <oldBranchName> <newBranchName>
git push origin :<oldBranchName>
git push --set-upstream origin <newBranchName>

Explanation from git docs:

git branch -m or -M option, will be renamed to . If had a corresponding reflog, it is renamed to match , and a reflog entry is created to remember the branch renaming. If exists, -M must be used to force the rename to happen.

The special refspec : (or +: to allow non-fast-forward updates) directs Git to push "matching" branches: for every branch that exists on the local side, the remote side is updated if a branch of the same name already exists on the remote side.

--set-upstream Set up 's tracking information so is considered 's upstream branch. If no is specified, then it defaults to the current branch.

Sprintf equivalent in Java

// Store the formatted string in 'result'
String result = String.format("%4d", i * j);

// Write the result to standard output
System.out.println( result );

See format and its syntax

How do I set adaptive multiline UILabel text?

It should work. Try this

var label:UILabel = UILabel(frame: CGRectMake(10
    ,100, 300, 40));
label.textAlignment = NSTextAlignment.Center;
label.numberOfLines = 0;
label.font = UIFont.systemFontOfSize(16.0);
label.text = "First label\nsecond line";

How to export iTerm2 Profiles

Caveats: this answer only allows exports color settings.

iTerm => Preferences => Profiles => Colors => Load Presets => Export

Import shall be similar.

In oracle, how do I change my session to display UTF8?

The character set is part of the locale, which is determined by the value of NLS_LANG. As the documentation makes clear this is an operating system variable:

NLS_LANG is set as an environment variable on UNIX platforms. NLS_LANG is set in the registry on Windows platforms.

Now we can use ALTER SESSION to change the values for a couple of locale elements, NLS_LANGUAGE and NLS_TERRITORY. But not, alas, the character set. The reason for this discrepancy is - I think - that the language and territory simply effect how Oracle interprets the stored data, e.g. whether to display a comma or a period when displaying a large number. Wheareas the character set is concerned with how the client application renders the displayed data. This information is picked up by the client application at startup time, and cannot be changed from within.

How to pick an image from gallery (SD Card) for my app?

private static final int SELECT_PHOTO = 100;

Start intent

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
startActivityForResult(photoPickerIntent, SELECT_PHOTO);    

Process result

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

    switch(requestCode) { 
    case SELECT_PHOTO:
        if(resultCode == RESULT_OK){  
            Uri selectedImage = imageReturnedIntent.getData();
            InputStream imageStream = getContentResolver().openInputStream(selectedImage);
            Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);

Alternatively, you can also downsample your image to avoid OutOfMemory errors.

private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException {

        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o);

        // The new size we want to scale to
        final int REQUIRED_SIZE = 140;

        // Find the correct scale value. It should be the power of 2.
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp / 2 < REQUIRED_SIZE
               || height_tmp / 2 < REQUIRED_SIZE) {
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;

        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o2);


Flutter Countdown Timer

Countdown timer in one line

CountdownTimer(Duration(seconds: 5), Duration(seconds: 1)).listen((data){
  print('data $data');

How to detect scroll direction

I managed to figure it out in the end, so if anyone is looking for the answer:

 $('#elem').bind('DOMMouseScroll', function(e){
     if(e.originalEvent.detail > 0) {
         //scroll down
     }else {
         //scroll up

     //prevent page fom scrolling
     return false;

 //IE, Opera, Safari
 $('#elem').bind('mousewheel', function(e){
     if(e.originalEvent.wheelDelta < 0) {
         //scroll down
     }else {
         //scroll up

     //prevent page fom scrolling
     return false;

How do I get the currently-logged username from a Windows service in .NET?

Modified code of Tapas's answer:

Dim searcher As New ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem")
Dim collection As ManagementObjectCollection = searcher.[Get]()
Dim username As String
For Each oReturn As ManagementObject In collection
    username = oReturn("UserName")

Get paragraph text inside an element

Do you use jQuery? A good option would be

text = $('p').text();

"The stylesheet was not loaded because its MIME type, "text/html" is not "text/css"

You are trying to use it as a CSS file, probably by using

<link rel=stylesheet href=ABCD.html>


@import url("ABCD.html");

Change action bar color in android

ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable("COLOR")); 

it worked for me here

CURRENT_TIMESTAMP in milliseconds

Poster is asking for an integer value of MS since Epoch, not a time or S since Epoch.

For that, you need to use NOW(3) which gives you time in fractional seconds to 3 decimal places (ie MS precision): 2020-02-13 16:30:18.236

Then UNIX_TIMESTAMP(NOW(3)) to get the time to fractional seconds since epoc: 1581611418.236

Finally, FLOOR(UNIX_TIMESTAMP(NOW(3))*1000) to get it to a nice round integer, for ms since epoc: 1581611418236

Make it a MySQL Function:



Note: this was all copied by hand so if there are mistakes feel free to fix ;)

SQL get the last date time record


Will return one result with the latest date.

SELECT * FROM foo WHERE foo.Dates = (SELECT MAX(Dates) FROM foo)

Will return all results that have the same maximum date, to the milissecond.

This is for SQL Server. I'll leave it up to you to use the DATEPART function if you want to use dates but not times.

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

To inject an Object, its class must be known to the CDI mechanism. Usualy adding the @Named annotation will do the trick.

Base64: java.lang.IllegalArgumentException: Illegal character

I got this error for my Linux Jenkins slave. I fixed it by changing from the node from "Known hosts file Verification Strategy" to "Non verifying Verification Strategy".

What's the best way to build a string of delimited items in Java?

So basically something like this:

public static String appendWithDelimiter(String original, String addition, String delimiter) {

if (original.equals("")) {
    return addition;
} else {
    StringBuilder sb = new StringBuilder(original.length() + addition.length() + delimiter.length());
        return sb.toString();

Google Play Services Library update and missing symbol @integer/google_play_services_version

Anybody looking in 2017, the 10.0.1 version of play services requires importing play-services-basement (use to be in play-services-base).

java: HashMap<String, int> not working

You cannot use primitive types in HashMap. int, or double don't work. You have to use its enclosing type. for an example

Map<String,Integer> m = new HashMap<String,Integer>();

Now both are objects, so this will work.

What does href expression <a href="javascript:;"></a> do?

It's used to write js codes inside of href instead of event listeners like onclick and avoiding # links in href to make a tags valid for HTML.

Interesting fact

I had a research on how to use javascript: inside of href attribute and got the result that I can write multiple lines in it!

<a href="
        a = 4;
        a += 2; 
        if(a < 6){ 
            console.log('a is lower than 6');
            console.log('a is greater than 6');
        function log(s){
        log('function implementation working too');

">Click here</a>
  • Tested in chrome Version 68.0.3440.106 (Official Build) (64-bit)

  • Tested in Firefox Quantum 61.0.1 (64-bit)

How to start Spyder IDE on Windows

on windows,

  1. pip install --upgrade spyder

  2. in powershell, start python shell, by typing python

    from import start

That't it.

Exception: Can't bind to 'ngFor' since it isn't a known native property

I missed let in front of talk:

<div *ngFor="let talk of talks">

Note that as of beta.17 usage of #... to declare local variables inside of structural directives like NgFor is deprecated. Use let instead.

<div *ngFor="#talk of talks"> now becomes <div *ngFor="let talk of talks">

Original answer:

I missed # in front of talk:

<div *ngFor="#talk of talks">

It is so easy to forget that #. I wish the Angular exception error message would instead say:
you forgot that # again.

Merge two Excel tables Based on matching data in Columns

Put the table in the second image on Sheet2, columns D to F.

In Sheet1, cell D2 use the formula


copy across and down.

Edit: here is a picture. The data is in two sheets. On Sheet1, enter the formula into cell D2. Then copy the formula across to F2 and then down as many rows as you need.

enter image description here

Counting array elements in Perl

It sounds like you want a sparse array. A normal array would have 24 items in it, but a sparse array would have 3. In Perl we emulate sparse arrays with hashes:


use strict;
use warnings;

my %sparse;

@sparse{0, 5, 23} = (1 .. 3);

print "there are ", scalar keys %sparse, " items in the sparse array\n",
    map { "\t$sparse{$_}\n" } sort { $a <=> $b } keys %sparse;

The keys function in scalar context will return the number of items in the sparse array. The only downside to using a hash to emulate a sparse array is that you must sort the keys before iterating over them if their order is important.

You must also remember to use the delete function to remove items from the sparse array (just setting their value to undef is not enough).

How to use C++ in Go

Update: I've succeeded in linking a small test C++ class with Go

If you wrap you C++ code with a C interface you should be able to call your library with cgo (see the example of gmp in $GOROOT/misc/cgo/gmp).

I'm not sure if the idea of a class in C++ is really expressible in Go, as it doesn't have inheritance.

Here's an example:

I have a C++ class defined as:

// foo.hpp
class cxxFoo {
  int a;
  cxxFoo(int _a):a(_a){};
  void Bar();

// foo.cpp
#include <iostream>
#include "foo.hpp"

which I want to use in Go. I'll use the C interface

// foo.h
#ifdef __cplusplus
extern "C" {
  typedef void* Foo;
  Foo FooInit(void);
  void FooFree(Foo);
  void FooBar(Foo);
#ifdef __cplusplus

(I use a void* instead of a C struct so the compiler knows the size of Foo)

The implementation is:

#include "foo.hpp"
#include "foo.h"
Foo FooInit()
  cxxFoo * ret = new cxxFoo(1);
  return (void*)ret;
void FooFree(Foo f)
  cxxFoo * foo = (cxxFoo*)f;
  delete foo;
void FooBar(Foo f)
  cxxFoo * foo = (cxxFoo*)f;

with all that done, the Go file is:

// foo.go
package foo
// #include "foo.h"
import "C"
import "unsafe"
type GoFoo struct {
     foo C.Foo;
func New()(GoFoo){
     var ret GoFoo; = C.FooInit();
     return ret;
func (f GoFoo)Free(){
func (f GoFoo)Bar(){

The makefile I used to compile this was:

// makefile
include $(GOROOT)/src/Make.$(GOARCH)
include $(GOROOT)/src/Make.pkg
    g++ $(_CGO_CFLAGS_$(GOARCH)) -fPIC -O2 -o $@ -c $(CGO_CFLAGS) $<
    g++ $(_CGO_CFLAGS_$(GOARCH)) -fPIC -O2 -o $@ -c $(CGO_CFLAGS) $<
$(elem) foo.cgo4.o foo.o cfoo.o
    gcc $(_CGO_CFLAGS_$(GOARCH)) $(_CGO_LDFLAGS_$(GOOS)) -o $@ $^ $(CGO_LDFLAGS)

Try testing it with:

// foo_test.go
package foo
import "testing"
func TestFoo(t *testing.T){
    foo := New();

You'll need to install the shared library with make install, then run make test. Expected output is:

rm -f _test/foo.a _gotest_.6
6g -o _gotest_.6 foo.cgo1.go foo.cgo2.go foo_test.go
rm -f _test/foo.a
gopack grc _test/foo.a _gotest_.6  foo.cgo3.6

What's the difference between lists and tuples?

As people have already answered here that tuples are immutable while lists are mutable, but there is one important aspect of using tuples which we must remember

If the tuple contains a list or a dictionary inside it, those can be changed even if the tuple itself is immutable.

For example, let's assume we have a tuple which contains a list and a dictionary as

my_tuple = (10,20,30,[40,50],{ 'a' : 10})

we can change the contents of the list as

my_tuple[3][0] = 400
my_tuple[3][1] = 500

which makes new tuple looks like

(10, 20, 30, [400, 500], {'a': 10})

we can also change the dictionary inside tuple as

my_tuple[4]['a'] = 500

which will make the overall tuple looks like

(10, 20, 30, [400, 500], {'a': 500})

This happens because list and dictionary are the objects and these objects are not changing, but the contents its pointing to.

So the tuple remains immutable without any exception

How to display alt text for an image in chrome

If I'm correct, this is a bug in webkit (according to this). I'm not sure if there is much you can do, sorry for the weak answer.

There is, however, a work around which you can use. If you add the title attribute to your image (e.g. title="Image Not Found") it'll work.

How does MySQL CASE work?

CASE is more like a switch statement. It has two syntaxes you can use. The first lets you use any compare statements you want:

    WHEN user_role = 'Manager' then 4
    WHEN user_name = 'Tom' then 27
    WHEN columnA <> columnB then 99
    ELSE -1 --unknown

The second style is for when you are only examining one value, and is a little more succinct:

CASE user_role
    WHEN 'Manager' then 4
    WHEN 'Part Time' then 7
    ELSE -1 --unknown

Map isn't showing on Google Maps JavaScript API v3 when nested in a div tag


Give initial height of div and specify height in percentage in your style;

#map {
   height: 100%;

<div id="map" style="clear:both; height:200px;"></div> 

Select statement to find duplicates on certain fields

If you're using SQL Server 2005 or later (and the tags for your question indicate SQL Server 2008), you can use ranking functions to return the duplicate records after the first one if using joins is less desirable or impractical for some reason. The following example shows this in action, where it also works with null values in the columns examined.

create table Table1 (
 Field1 int,
 Field2 int,
 Field3 int,
 Field4 int 

insert  Table1 
values    (1,1,1,1)
        , (1,1,1,2)
        , (1,1,1,3)
        , (2,2,2,1)
        , (3,3,3,1)
        , (3,3,3,2)
        , (null, null, 2, 1)
        , (null, null, 2, 3)

select    *
from     (select      Field1
                    , Field2
                    , Field3
                    , Field4
                    , row_number() over (partition by   Field1
                                                      , Field2
                                                      , Field3
                                         order by       Field4) as occurrence
          from      Table1) x
where     occurrence > 1

Notice after running this example that the first record out of every "group" is excluded, and that records with null values are handled properly.

If you don't have a column available to order the records within a group, you can use the partition-by columns as the order-by columns.

ORDER BY date and time BEFORE GROUP BY name in mysql

As I am not allowed to comment on user1908688's answer, here a hint for MariaDB users:

     SELECT *
     ORDER BY date ASC, time ASC
     LIMIT 18446744073709551615
     ) AS sub

Disable password authentication for SSH

The one-liner to disable SSH password authentication:

sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/g' /etc/ssh/sshd_config && service ssh restart

#1142 - SELECT command denied to user ''@'localhost' for table 'pma_table_uiprefs'

Try this before anything else - 'clear your cache'. I had the same issue. I was instructed to clear my cache. It worked.

AngularJS: Service vs provider vs factory

Summary from Angular docs:

  • There are five recipe types that define how to create objects: Value, Factory, Service, Provider and Constant.
  • Factory and Service are the most commonly used recipes. The only difference between them is that the Service recipe works better for objects of a custom type, while the Factory can produce JavaScript primitives and functions.
  • The Provider recipe is the core recipe type and all the other ones are just syntactic sugar on it.
  • Provider is the most complex recipe type. You don't need it unless you are building a reusable piece of code that needs global configuration.

enter image description here

Best answers from SO: (<-- GOOD)

Merge data frames based on rownames in R

See ?merge:

the name "row.names" or the number 0 specifies the row names.


R> de <- merge(d, e, by=0, all=TRUE)  # merge by row names (by=0 or by="row.names")
R> de[] <- 0                 # replace NA values
R> de
  Row.names   a   b   c   d   e   f   g   h   i  j  k  l  m  n  o  p  q  r  s
1         1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2         2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9  1  0  0  0  0  0  0  0  0  0
3         3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0  0 21 22 23 24 25 26 27 28 29
1 20
2  0
3 30

Maximum request length exceeded.

It may be worth noting that you may want to limit this change to the URL you expect to be used for the upload rather then your entire site.

<location path="Documents/Upload">
    <!-- 50MB in kilobytes, default is 4096 or 4MB-->
    <httpRuntime maxRequestLength="51200" />
        <!-- 50MB in bytes, default is 30000000 or approx. 28.6102 Mb-->
        <requestLimits maxAllowedContentLength="52428800" /> 

rbenv not changing ruby version

Linux / Ubuntu Users Step 1:

$ rbenv versions
* 2.7.0 (set by /home/User/Documents/sample-app/.ruby-version) #Yours will be different

Step 2:

$ nano /home/User/Documents/sample-app/.ruby-version

Step 3:

$ ruby -v
ruby 2.7.2p137 (2020-10-01 revision 5445e04352) [x86_64-linux]

Place input box at the center of div

Here's a rather unconventional way of doing it:

    display:table-cell; //display like a <td> to make the vertical-align work
    text-align:center; //centre the input horizontally
    vertical-align:middle; //centre the input vertically

    width:200px; //widen the div for demo purposes
    height:200px; //make the div taller for demo purposes
    background:green; //change the background of the div for demo purposes

It might not be the best way to do it, and margin? won't work, but it does the job. If you need to use margin, then you could wrap the div that displays as a table cell in another 'normal' div.


Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

Both times when you write the package name : 1. When you create a new project in Android Studio and 2. When you create a Configuration File

YOU should write it with lowercase letters - after changing to lowercase it works. If you don't want to waste time just go to you .json file and replace com.myname.MyAPPlicationnamE with com.myname.myapplicationname (for every match in the json file).

Why can't I check if a 'DateTime' is 'Nothing'?

This is one of the biggest sources of confusion with VB.Net, IMO.

Nothing in VB.Net is the equivalent of default(T) in C#: the default value for the given type.

  • For value types, this is essentially the equivalent of 'zero': 0 for Integer, False for Boolean, DateTime.MinValue for DateTime, ...
  • For reference types, it is the null value (a reference that refers to, well, nothing).

The statement d Is Nothing is therefore equivalent to d Is DateTime.MinValue, which obviously does not compile.

Solutions: as others have said

  • Either use DateTime? (i.e. Nullable(Of DateTime)). This is my preferred solution.
  • Or use d = DateTime.MinValue or equivalently d = Nothing

In the context of the original code, you could use:

Dim d As DateTime? = Nothing
Dim boolNotSet As Boolean = d.HasValue

A more comprehensive explanation can be found on Anthony D. Green's blog

Use jQuery to navigate away from page

window.location.href = "/somewhere/else";

How to get longitude and latitude of any address?

PHP has some nice built in functions for getting geographic location. Maybe have a look here:

According to php manual, "This extension requires the GeoIP C library version 1.4.0 or higher to be installed. You can grab the latest version from » and compile it yourself."

How to provide a file download from a JSF backing bean?


You can get everything through ExternalContext. In JSF 1.x, you can get the raw HttpServletResponse object by ExternalContext#getResponse(). In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream() without the need to grab the HttpServletResponse from under the JSF hoods.

On the response, you should set the Content-Type header so that the client knows which application to associate with the provided file. And, you should set the Content-Length header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition header to attachment if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.

Most important part is to call FacesContext#responseComplete() to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException with a message like getoutputstream() has already been called for this response when the JSF implementation calls getWriter() to render HTML.

Turn off ajax / don't use remote command!

You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink> and <h:commandButton>. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.

In case you're using e.g. PrimeFaces <p:commandXxx>, then you need to make sure that you explicitly turn off ajax via ajax="false" attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" /> in the command component.

Generic JSF 2.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();

    ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    ec.setResponseContentType(contentType); // Check for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
    ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = ec.getResponseOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.

Generic JSF 1.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType(contentType); // Check for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = response.getOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.

Common static file example

In case you need to stream a static file from the local disk file system, substitute the code as below:

File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();

// ...

Files.copy(file.toPath(), output);

Common dynamic file example

In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output there where the API being used expects an OutputStream.

E.g. iText PDF:

String fileName = "dynamic.pdf";
String contentType = "application/pdf";

// ...

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);;
// Build PDF content here.

E.g. Apache POI HSSF:

String fileName = "dynamic.xls";
String contentType = "application/";

// ...

HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.

Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.

Utility method

If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile() methods taking either a File, or an InputStream, or a byte[], and specifying whether the file should be downloaded as an attachment (true) or inline (false).

public void download() throws IOException {
    Faces.sendFile(file, true);

Yes, this code is complete as-is. You don't need to invoke responseComplete() and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.

How to read a list of files from a folder using PHP?

<body style="background-color:powderblue;">

<form method='post' action='alex.php'>
 <input type='text' name='name'>
<input type='submit' value='name'>
Enter Name:

  $Name = $_POST['name'];
  $count = 0;
  $fh=fopen("alex.txt",'a+') or die("failed to create");
    $line = chop(fgets($fh));
    if($line==$Name && $line!="")
  if($count==0 && $Name!="")
    fwrite($fh, "\r\n$Name"); 
  else if($count!=0 && $line!="") 
    echo '<font color="red">'.$Name.', the name you entered is already in the list.</font><br><br>';
  fseek($fh, 0);
    $a = chop(fgets($fh));
    echo $a.'<br>';
  echo '<br>There are no names in the list<br>';

Get path from open file in Python

You can get it like this also.

filepath = os.path.abspath(

javascript popup alert on link click

In order to do this you need to attach the handler to a specific anchor on the page. For operations like this it's much easier to use a standard framework like jQuery. For example if I had the following HTML


<a id="theLink">Click Me</a>

I could use the following jQuery to hookup an event to that specific link.

// Use ready to ensure document is loaded before running javascript
$(document).ready(function() {

  // The '#theLink' portion is a selector which matches a DOM element
  // with the id 'theLink' and .click registers a call back for the 
  // element being clicked on 
  $('#theLink').click(function (event) {

    // This stops the link from actually being followed which is the 
    // default action 

    var answer confirm("Please click OK to continue");
    if (!answer) {


System.IO.FileNotFoundException: Could not load file or assembly 'X' or one of its dependencies when deploying the application

's up guys i read every single forum about this topic i still had problem (occurred trying to project from git)

after 4 hours and a lot of swearing i solved this issue by myself just by changing target framework setting in project properties (right click on project -> properties) -> application and changed target framework from .net core 3.0 to .net 5.0 i hope it will help anybody

happy coding gl hf nerds

Angular 2 Dropdown Options Default Value

Add on to @Matthijs 's answer, please make sure your select element has a name attribute and its name is unique in your html template. Angular 2 is using input name to update changes. Thus, if there are duplicated names or there is no name attached to input element, the binding will fail.

Difference between virtual and abstract methods

Virtual methods have an implementation and provide the derived classes with the option of overriding it. Abstract methods do not provide an implementation and force the derived classes to override the method.

So, abstract methods have no actual code in them, and subclasses HAVE TO override the method. Virtual methods can have code, which is usually a default implementation of something, and any subclasses CAN override the method using the override modifier and provide a custom implementation.

public abstract class E
    public abstract void AbstractMethod(int i);

    public virtual void VirtualMethod(int i)
        // Default implementation which can be overridden by subclasses.

public class D : E
    public override void AbstractMethod(int i)
        // You HAVE to override this method
    public override void VirtualMethod(int i)
        // You are allowed to override this method.

How does Subquery in select statement work in oracle

In the Oracle RDBMS, it is possible to use a multi-row subquery in the select clause as long as the (sub-)output is encapsulated as a collection. In particular, a multi-row select clause subquery can output each of its rows as an xmlelement that is encapsulated in an xmlforest.

Change R default library path using .libPaths in fails to work

# [1] "C:/Users/..../software/My R studio"

copy the above link with double inverted comma

.libPaths(new="C:/Users/..../software/My R studio")

Your default path will change for installing pakages

How to format Joda-Time DateTime to only mm/dd/yyyy?

I have a very dumb but working option. if you have the String fullDate = "11/15/2013 08:00:00";

   String finalDate = fullDate.split(" ")[0];

That should work easy and fast. :)

Get Android Phone Model programmatically

Here is my code , To get Manufacturer,Brand name,Os version and support API Level

String manufacturer = Build.MANUFACTURER;

String model = Build.MODEL + " " + android.os.Build.BRAND +" ("
           + android.os.Build.VERSION.RELEASE+")"
           + " API-" + android.os.Build.VERSION.SDK_INT;

if (model.startsWith(manufacturer)) {
    return capitalize(model);
} else {
    return capitalize(manufacturer) + " " + model;


System.out: button press on device name = Lava Alfa L iris(5.0) API-21

Google Chrome form autofill and its yellow background

If you want to get rid of it entirely, I've adjusted the code in the previous answers so it works on hover, active and focus too:

input:-webkit-autofill, input:-webkit-autofill:hover, input:-webkit-autofill:active, input:-webkit-autofill:focus {
    -webkit-box-shadow: 0 0 0 1000px white inset;

get Context in non-Activity class

If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows:

class YourNonActivityClass{

// variable to hold context
private Context context;

//save the context recievied via constructor in a local variable

public YourNonActivityClass(Context context){


You can create instance of this class from the activity as follows:

new YourNonActivityClass(this);

Jquery Ajax Posting json to webservice

I have encountered this one too and this is my solution.

If you are encountering an invalid json object exception when parsing data, even though you know that your json string is correct, stringify the data you received in your ajax code before parsing it to JSON:

        yesTransactionId : yesTransactionId, 
        productOfferId : productOfferId
                var trimData = $.trim(JSON.stringify(data));
                var obj      = $.parseJSON(trimData);
                if(obj.success == 'true'){ 
                    //some codes ...

PYTHONPATH vs. sys.path

I hate PYTHONPATH. I find it brittle and annoying to set on a per-user basis (especially for daemon users) and keep track of as project folders move around. I would much rather set sys.path in the invoke scripts for standalone projects.

However sys.path.append isn't the way to do it. You can easily get duplicates, and it doesn't sort out .pth files. Better (and more readable): site.addsitedir.

And wouldn't normally be the more appropriate place to do it, as it's inside the package you want to make available on the path. Library modules should certainly not be touching sys.path themselves. Instead, you'd normally have a hashbanged-script outside the package that you use to instantiate and run the app, and it's in this trivial wrapper script you'd put deployment details like sys.path-frobbing.

height: calc(100%) not working correctly in CSS

First off - check with Firebug(or what ever your preference is) whether the css property is being interpreted by the browser. Sometimes the tool used will give you the problem right there, so no more hunting.

Second off - check compatibility:

And third - I ran into some problems a few hours ago and just resolved it. It's the smallest thing but it kept me busy for 30 minutes.

Here's how my CSS looked

#someElement {

Looks right doesn't it? WRONG Here's how it should look:

#someElement {
    height:calc(100% - 100px);
    height:-moz-calc(100% - 100px);
    height:-webkit-calc(100% - 100px);

Looks the same right?

Notice the spaces!!! Checked android browser, Firefox for android, Chrome for android, Chrome and Firefox for Windows and Internet Explorer 11. All of them ignored the CSS if there were no spaces.

Hope this helps someone.

Open URL in Java to get the content

Following code should work,

URL url = new URL("");
InputStream is = url.openConnection().getInputStream();

BufferedReader reader = new BufferedReader( new InputStreamReader( is )  );

String line = null;
while( ( line = reader.readLine() ) != null )  {

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.

Apache Tomcat Not Showing in Eclipse Server Runtime Environments

nor does it appear in the list of environments that can be added when I click the "Add" button. All I see is the J2EE Runtime Library.

Go get "Eclipse for Java EE developers". Note the extra "EE". This includes among others the Web Tools Platform with among others a lot of server plugins with among others the one for Apache Tomcat 5.x. It's also logically; JSP/Servlet is part of the Java EE API.

How to install PyQt4 on Windows using pip?

It looks like you may have to do a bit of manual installation for PyQt4.

This might help a bit more, it's a bit more in a tutorial/set-by-step format:

How to dismiss AlertDialog in android

Here is How I close my alertDialog

lv_three.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                GetTalebeDataUser clickedObj = (GetTalebeDataUser) parent.getItemAtPosition(position);
                alertDialog.setMessage("Ögrenci Bilgileri Güncelle?");
                // Setting Positive "Yes" Button
                alertDialog.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // User pressed YES button. Write Logic Here
                alertDialog.setNegativeButton("Iptal", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogInterface, int i) {
                        alertDialog.setCancelable(true); // HERE

                return true;

Python - Locating the position of a regex match in a string?

I don't think this question has been completely answered yet because all of the answers only give single match examples. The OP's question demonstrates the nuances of having 2 matches as well as a substring match which should not be reported because it is not a word/token.

To match multiple occurrences, one might do something like this:

iter = re.finditer(r"\bis\b", String)
indices = [m.start(0) for m in iter]

This would return a list of the two indices for the original string.

Can I embed a custom font in an iPhone application?

I have done this like this:

Load the font:

- (void)loadFont{
  // Get the path to our custom font and create a data provider.
  NSString *fontPath = [[NSBundle mainBundle] pathForResource:@"mycustomfont" ofType:@"ttf"]; 
  CGDataProviderRef fontDataProvider = CGDataProviderCreateWithFilename([fontPath UTF8String]);

  // Create the font with the data provider, then release the data provider.
  customFont = CGFontCreateWithDataProvider(fontDataProvider);

Now, in your drawRect:, do something like this:

    [super drawRect:rect];
    // Get the context.
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClearRect(context, rect);
    // Set the customFont to be the font used to draw.
    CGContextSetFont(context, customFont);

    // Set how the context draws the font, what color, how big.
    CGContextSetTextDrawingMode(context, kCGTextFillStroke);
    CGContextSetFillColorWithColor(context, self.fontColor.CGColor);
    UIColor * strokeColor = [UIColor blackColor];
    CGContextSetStrokeColorWithColor(context, strokeColor.CGColor);
    CGContextSetFontSize(context, 48.0f);

    // Create an array of Glyph's the size of text that will be drawn.
    CGGlyph textToPrint[[self.theText length]];

    // Loop through the entire length of the text.
    for (int i = 0; i < [self.theText length]; ++i) {
        // Store each letter in a Glyph and subtract the MagicNumber to get appropriate value.
        textToPrint[i] = [[self.theText uppercaseString] characterAtIndex:i] + 3 - 32;
    CGAffineTransform textTransform = CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0);
    CGContextSetTextMatrix(context, textTransform);
    CGContextShowGlyphsAtPoint(context, 20, 50, textToPrint, [self.theText length]);

Basically you have to do some brute force looping through the text and futzing about with the magic number to find your offset (here, see me using 29) in the font, but it works.

Also, you have to make sure the font is legally embeddable. Most aren't and there are lawyers who specialize in this sort of thing, so be warned.

How do you load custom UITableViewCells from Xib files?

First import your custom cell file #import "CustomCell.h" and then change the delegate method as below mentioned:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *simpleTableIdentifier = @"CustomCell";

CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
    cell = [nib objectAtIndex:0];

    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

     return cell;

Struct like objects in Java

If the Java way is the OO way, then yes, creating a class with public fields breaks the principles around information hiding which say that an object should manage its own internal state. (So as I'm not just spouting jargon at you, a benefit of information hiding is that the internal workings of a class are hidden behind an interface - say you wanted to change the mechanism by which your struct class saved one of its fields, you'll probably need to go back and change any classes that use the class...)

You also can't take advantage of the support for JavaBean naming compliant classes, which will hurt if you decide to, say, use the class in a JavaServer Page which is written using Expression Language.

The JavaWorld article Why Getter and Setter Methods are Evil article also might be of interest to you in thinking about when not to implement accessor and mutator methods.

If you're writing a small solution and want to minimise the amount of code involved, the Java way may not be the right way - I guess it always depends on you and the problem you're trying to solve.