Programs & Examples On #Annotation processing

An annotation processor is a plug-in for the Java compiler. An annotation processor can do such things as analyze declarations, cause compilation errors and generate new compilation units.

How to generate the JPA entity Metamodel?

For eclipselink, only the following dependency is sufficient to generate metamodel. Nothing else is needed.

    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
        <version>2.5.1</version>
        <scope>provided</scope>
    </dependency>

Toggle button using two image on different state

AkashG's solution don't work for me. When I set up check.xml to background it's just stratched in vertical direction. To solve this problem you should set up check.xml to "android:button" property:

<ToggleButton 
    android:id="@+id/toggle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:button="@drawable/check"   //check.xml
    android:background="@null"/>

check.xml:

<?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- When selected, use grey -->
    <item android:drawable="@drawable/selected_image"
          android:state_checked="true" />
    <!-- When not selected, use white-->
    <item android:drawable="@drawable/unselected_image"
          android:state_checked="false"/>
    </selector>

css divide width 100% to 3 column

2018 Update This is the method I use width: 33%; width: calc(33.33% - 20px); The first 33% is for browsers that do not support calc() inside the width property, the second would need to be vendor prefixed with -webkit- and -moz- for the best possible cross-browser support.

#c1, #c2, #c3 {
    margin: 10px; //not needed, but included to demonstrate the effect of having a margin with calc() widths/heights
    width: 33%; //fallback for browsers not supporting calc() in the width property
    width: -webkit-calc(33.33% - 20px); //We minus 20px from 100% if we're using the border-box box-sizing to account for our 10px margin on each side.
    width: -moz-calc(33.33% - 20px);
    width: calc(33.33% - 20px);
}

tl;dr account for your margin

React component not re-rendering on state change

Another oh-so-easy mistake, which was the source of the problem for me: I’d written my own shouldComponentUpdate method, which didn’t check the new state change I’d added.

Python: How to remove empty lists from a list?

Adding to the answers above, Say you have a list of lists of the form:

theList = [['a','b',' '],[''],[''],['d','e','f','g'],['']]

and you want to take out the empty entries from each list as well as the empty lists you can do:

theList = [x for x in theList if x != ['']] #remove empty lists
for i in range(len(theList)):
    theList[i] = list(filter(None, theList[i])) #remove empty entries from the lists

Your new list will look like

theList = [['a','b'],['d','e','f','g']]

Python multiprocessing PicklingError: Can't pickle <type 'function'>

Building on @rocksportrocker solution, It would make sense to dill when sending and RECVing the results.

import dill
import itertools
def run_dill_encoded(payload):
    fun, args = dill.loads(payload)
    res = fun(*args)
    res = dill.dumps(res)
    return res

def dill_map_async(pool, fun, args_list,
                   as_tuple=True,
                   **kw):
    if as_tuple:
        args_list = ((x,) for x in args_list)

    it = itertools.izip(
        itertools.cycle([fun]),
        args_list)
    it = itertools.imap(dill.dumps, it)
    return pool.map_async(run_dill_encoded, it, **kw)

if __name__ == '__main__':
    import multiprocessing as mp
    import sys,os
    p = mp.Pool(4)
    res = dill_map_async(p, lambda x:[sys.stdout.write('%s\n'%os.getpid()),x][-1],
                  [lambda x:x+1]*10,)
    res = res.get(timeout=100)
    res = map(dill.loads,res)
    print(res)

How to increment a JavaScript variable using a button press event

yes, supposing your variable is in the global namespace:

<button onclick="myVar += 1;alert('myVar now equals ' + myVar)">Increment!!</button>

Python: slicing a multi-dimensional array

If you use numpy, this is easy:

slice = arr[:2,:2]

or if you want the 0's,

slice = arr[0:2,0:2]

You'll get the same result.

*note that slice is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".


Another way, if you're working with lists of lists*:

slice = [arr[i][0:2] for i in range(0,2)]

(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)] would also work.).

What I did here is that I take each desired row 1 at a time (arr[i]). I then slice the columns I want out of that row and add it to the list that I'm building.

If you naively try: arr[0:2] You get the first 2 rows which if you then slice again arr[0:2][0:2], you're just slicing the first two rows over again.

*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.

How do I stretch a background image to cover the entire HTML element?

In short you can try this....

<div data-role="page" style="background:url('backgrnd.png'); background-repeat: no-repeat; background-size: 100% 100%;" >

Where I have used few css and js...

<link rel="stylesheet" href="css/jquery.mobile-1.0.1.min.css" />
<script src="js/jquery-1.7.1.min.js"></script>
<script src="js/jquery.mobile-1.0.1.min.js"></script>

And it is working fine for me.

Seeing if data is normally distributed in R

In addition to qqplots and the Shapiro-Wilk test, the following methods may be useful.

Qualitative:

  • histogram compared to the normal
  • cdf compared to the normal
  • ggdensity plot
  • ggqqplot

Quantitative:

The qualitive methods can be produced using the following in R:

library("ggpubr")
library("car")

h <- hist(data, breaks = 10, density = 10, col = "darkgray") 
xfit <- seq(min(data), max(data), length = 40) 
yfit <- dnorm(xfit, mean = mean(data), sd = sd(data)) 
yfit <- yfit * diff(h$mids[1:2]) * length(data) 
lines(xfit, yfit, col = "black", lwd = 2)

plot(ecdf(data), main="CDF")
lines(ecdf(rnorm(10000)),col="red")

ggdensity(data)

ggqqplot(data)

A word of caution - don't blindly apply tests. Having a solid understanding of stats will help you understand when to use which tests and the importance of assumptions in hypothesis testing.

CSS position:fixed inside a positioned element

I know this is an old post but I had the same question but didn't find an answer that set the element fixed relative to a parent div. The scroll bar on medium.com is a great pure CSS solution for setting something position: fixed; relative to a parent element instead of the viewport (kinda*). It is achieved by setting the parent div to position: relative; and having a button wrapper with position: absolute; and the button of course is position: fixed; as follows:

<div class="wrapper">
  <div class="content">
    Your long content here
  </div>

  <div class="button-wrapper">
    <button class="button">This is your button</button>
  </div>
</div>

<style>
  .wrapper {
    position: relative;
  }

  .button-wrapper {
    position: absolute;
    right: 0;
    top: 0;
    width: 50px;
  }

  .button {
    position: fixed;
    top: 0;
    width: 50px;
  }
</style>

working example

*Since fixed elements don't scroll with the page the vertical position will still be relative to the viewport but the horizontal position is relative to the parent with this solution.

Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?'

Faced same problem after migrating to python 3. Apparently, MySQL-python is incompatible, so as per official django docs, installed mysqlclient using pip install mysqlclient on Mac. Note that there are some OS specific issues mentioned in docs.

Quoting from docs:

Prerequisites

You may need to install the Python and MySQL development headers and libraries like so:

sudo apt-get install python-dev default-libmysqlclient-dev # Debian / Ubuntu

sudo yum install python-devel mysql-devel # Red Hat / CentOS

brew install mysql-connector-c # macOS (Homebrew) (Currently, it has bug. See below)

On Windows, there are binary wheels you can install without MySQLConnector/C or MSVC.

Note on Python 3 : if you are using python3 then you need to install python3-dev using the following command :

sudo apt-get install python3-dev # debian / Ubuntu

sudo yum install python3-devel # Red Hat / CentOS

Note about bug of MySQL Connector/C on macOS

See also: https://bugs.mysql.com/bug.php?id=86971

Versions of MySQL Connector/C may have incorrect default configuration options that cause compilation errors when mysqlclient-python is installed. (As of November 2017, this is known to be true for homebrew's mysql-connector-c and official package)

Modification of mysql_config resolves these issues as follows.

Change

# on macOS, on or about line 112:
# Create options
libs="-L$pkglibdir"
libs="$libs -l "

to

# Create options
libs="-L$pkglibdir"
libs="$libs -lmysqlclient -lssl -lcrypto"

An improper ssl configuration may also create issues; see, e.g, brew info openssl for details on macOS.

Install from PyPI

pip install mysqlclient

NOTE: Wheels for Windows may be not released with source package. You should pin version in your requirements.txt to avoid trying to install newest source package.

Install from source

  1. Download source by git clone or zipfile.
  2. Customize site.cfg
  3. python setup.py install

IllegalStateException: Can not perform this action after onSaveInstanceState with ViewPager

I had the exact same problem. It happened because of the destruction of previous activity. when i backed the previous activity it was destroyed. I put it base activity (WRONG)

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SpinnerCustom2.setFragmentManager(getSupportFragmentManager());
    onCreateDrawerActivity(savedInstanceState);
}

I put it into onStart it was RIGHT

@Override
protected void onStart() {
    super.onStart();
    SpinnerCustom2.setFragmentManager(getSupportFragmentManager());

}

How does the SQL injection from the "Bobby Tables" XKCD comic work?

This is how it works: Lets suppose the administrator is looking for records of student

Robert'); DROP TABLE STUDENTS; --

Since the admin account has high privileges deleting the table from this account is possible.

The code to retrieve user name from request is

Now the query would be something like this (to search the student table)

String query="Select * from student where username='"+student_name+"'";

statement.executeQuery(query); //Rest of the code follows

The resultant query becomes

Select * from student where username='Robert'); DROP TABLE STUDENTS; --

Since the user input is not sanitized, The above query has is manipulated into 2 parts

Select * from student where username='Robert'); 

DROP TABLE STUDENTS; --

The double dash (--) will just comment out remaining part of the query.

This is dangerous as it can nullify password authentication, if present

The first one will do the normal search.

The second one will drop the table student if the account has sufficient privileges (Generally the school admin account will run such query and will have the privileges talked about above).

How do I find a stored procedure containing <text>?

I tried above example but it was not showing more than 4000 characters then I modified it little bit and was able to get whole stored procedure definition. Please see the updated script below -

SELECT SCHEMA_NAME(O.SCHEMA_ID) [SCHEMA_NAME], O.NAME, OBJECT_DEFINITION(OBJECT_ID) TEXT
FROM   SYSCOMMENTS AS C
       INNER JOIN SYS.OBJECTS AS O ON C.ID = O.[OBJECT_ID]
       INNER JOIN SYS.SCHEMAS AS S ON O.SCHEMA_ID = S.SCHEMA_ID
WHERE  OBJECT_DEFINITION(OBJECT_ID) LIKE '%FOO%'
ORDER BY  SCHEMA_NAME(O.SCHEMA_ID), O.NAME

how to compare two elements in jquery

For the record, jQuery has an is() function for this:

a.is(b)

Note that a is already a jQuery instance.

cannot find zip-align when publishing app

In my case SDK Build Tools 20 were already installed. I copied zipalign.exe in Tools folder but without success.

After that I noticed that I updated Eclipse without removing or renaming the old folder.

So I did:

1) Renamed old Eclipse folder 2) Restarted Eclipse

Eclipse asked to correct Android preferences because problem was Eclipse, that was still trying to use the old folder

String vs. StringBuilder

Further to the previous answers, the first thing I always do when thinking of issues like this is to create a small test application. Inside this app, perform some timing test for both scenarios and see for yourself which is quicker.

IMHO, appending 500+ string entries should definitely use StringBuilder.

Java/ JUnit - AssertTrue vs AssertFalse

Your understanding is incorrect, in cases like these always consult the JavaDoc.

assertFalse

public static void assertFalse(java.lang.String message,
                               boolean condition)

Asserts that a condition is false. If it isn't it throws an AssertionError with the given message.

Parameters:

  • message - the identifying message for the AssertionError (null okay)
  • condition - condition to be checked

How do I store an array in localStorage?

Just created this:

https://gist.github.com/3854049

//Setter
Storage.setObj('users.albums.sexPistols',"blah");
Storage.setObj('users.albums.sexPistols',{ sid : "My Way", nancy : "Bitch" });
Storage.setObj('users.albums.sexPistols.sid',"Other songs");

//Getters
Storage.getObj('users');
Storage.getObj('users.albums');
Storage.getObj('users.albums.sexPistols');
Storage.getObj('users.albums.sexPistols.sid');
Storage.getObj('users.albums.sexPistols.nancy');

Loop through all the resources in a .resx file

Simple read loop use this code

var resx = ResourcesName.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, false, false);

foreach (DictionaryEntry dictionaryEntry in resx)
{
    Console.WriteLine("Key: " + dictionaryEntry.Key);
    Console.WriteLine("Val: " + dictionaryEntry.Value);
}

LINQ: combining join and group by

Once you've done this

group p by p.SomeId into pg  

you no longer have access to the range variables used in the initial from. That is, you can no longer talk about p or bp, you can only talk about pg.

Now, pg is a group and so contains more than one product. All the products in a given pg group have the same SomeId (since that's what you grouped by), but I don't know if that means they all have the same BaseProductId.

To get a base product name, you have to pick a particular product in the pg group (As you are doing with SomeId and CountryCode), and then join to BaseProducts.

var result = from p in Products                         
 group p by p.SomeId into pg                         
 // join *after* group
 join bp in BaseProducts on pg.FirstOrDefault().BaseProductId equals bp.Id         
 select new ProductPriceMinMax { 
       SomeId = pg.FirstOrDefault().SomeId, 
       CountryCode = pg.FirstOrDefault().CountryCode, 
       MinPrice = pg.Min(m => m.Price), 
       MaxPrice = pg.Max(m => m.Price),
       BaseProductName = bp.Name  // now there is a 'bp' in scope
 };

That said, this looks pretty unusual and I think you should step back and consider what you are actually trying to retrieve.

How to use java.net.URLConnection to fire and handle HTTP requests?

Update

The new HTTP Client shipped with Java 9 but as part of an Incubator module named jdk.incubator.httpclient. Incubator modules are a means of putting non-final APIs in the hands of developers while the APIs progress towards either finalization or removal in a future release.

In Java 9, you can send a GET request like:

// GET
HttpResponse response = HttpRequest
    .create(new URI("http://www.stackoverflow.com"))
    .headers("Foo", "foovalue", "Bar", "barvalue")
    .GET()
    .response();

Then you can examine the returned HttpResponse:

int statusCode = response.statusCode();
String responseBody = response.body(HttpResponse.asString());

Since this new HTTP Client is in java.httpclient jdk.incubator.httpclient module, you should declare this dependency in your module-info.java file:

module com.foo.bar {
    requires jdk.incubator.httpclient;
}

How to get year/month/day from a date object?

You can simply use This one line code to get date in year-month-date format

var date = new Date().getFullYear() + "-" + new Date().getMonth() + 1 + "-" + new Date().getDate();

prevent property from being serialized in web API

According to the Web API documentation page JSON and XML Serialization in ASP.NET Web API to explicitly prevent serialization on a property you can either use [JsonIgnore] for the Json serializer or [IgnoreDataMember] for the default XML serializer.

However in testing I have noticed that [IgnoreDataMember] prevents serialization for both XML and Json requests, so I would recommend using that rather than decorating a property with multiple attributes.

Simulate low network connectivity for Android

You can use emulator for this. Take a look at this page: Android Emulator. Pay attention to next two arguments:

  1. -netdelay <delay>

    Set network latency emulation to . Default value is none. See the table in Network Delay Emulation for supported values.

  2. -netspeed <speed>

    Set network speed emulation to . Default value is full. See the table in Network Speed Emulation for supported values.

    Speeds for reference in increasing kbps:

                            UP       DOWN
                      -------- ----------
    gsm   GSM/CSD         14.4       14.4
    hscsd HSCSD           14.4       57.6
    gprs  GPRS            28.8       57.6
    umts  UMTS/3G        384.0      384.0
    edge  EDGE/EGPRS     473.6      473.6
    hsdpa HSDPA         5760.0   13,980.0
    lte   LTE         58,000.0  173,000.0
    evdo  EVDO        75,000.0  280,000.0
    full  No limit           8          8
    

error : expected unqualified-id before return in c++

Suggestions:

  • use consistent 3-4 space indenting and you will find these problems much easier
  • use a brace style that lines up {} vertically and you will see these problems quickly
  • always indent control blocks another level
  • use a syntax highlighting editor, it helps, you'll thank me later

for example,

type
functionname( arguments )
{
    if (something)
    {
        do stuff
    }
    else
    {
        do other stuff
    }
    switch (value)
    {
        case 'a':
            astuff
            break;
        case 'b':
            bstuff
            //fallthrough //always comment fallthrough as intentional
        case 'c':
            break;
        default: //always consider default, and handle it explicitly
            break;
    }
    while ( the lights are on )
    {
        if ( something happened )
        {
            run around in circles
            if ( you are scared ) //yeah, much more than 3-4 levels of indent are too many!
            {
                scream and shout
            }
        }
    }
    return typevalue; //always return something, you'll thank me later
}

Using Pip to install packages to Anaconda Environment

Depends on how did you configure your PATH environmental variable. When your shell resolves the call to pip, which is the first bin it will find?

(test)$ whereis pip
pip: /home/borja/anaconda3/envs/test/bin/pip /home/borja/anaconda3/bin/pip

Make sure the bin folder from your anaconda installation is before /usr/lib (depending on how you did install pip). So an example:

(test) borja@xxxx:~$ pip install djangorestframework
....
Successfully installed asgiref-3.2.3 django-3.0.3 djangorestframework-3.11.0 pytz-2019.3 sqlparse-0.3.1

(test) borja@xxxx:~$ conda list | grep django
django                    3.0.3                    pypi_0    pypi
djangorestframework       3.11.0                   pypi_0    pypi

We can see the djangorestframework was installed in my test environment but if I check my base:

(base) borja@xxxx:~$ conda list | grep django

It is empty.

Personally I like to handle all my PATH configuration using .pam_environment, here an example:

(base) borja@xxxx:~$ cat .pam_environment
PATH DEFAULT=/home/@{PAM_USER}/anaconda3/bin:${PATH}

One extra commet. The way how you install pip might create issues:

  • You should use: conda install pip --> new packages installed with pip will be added to conda list.

  • You shodul NOT use: sudo apt install python3-pip --> new packages will not be added to conda list (so are not managed by conda) but you will still be able to use them (chance of conflict).

VB.NET Inputbox - How to identify when the Cancel Button is pressed?

Guys remember that you can use the try catch end event

Dim Green as integer

Try
    Green = InputBox("Please enter a value for green")
    Catch ex as Exception
        MsgBox("Green must be a valid integer!")
End Try

Creating a REST API using PHP

Trying to write a REST API from scratch is not a simple task. There are many issues to factor and you will need to write a lot of code to process requests and data coming from the caller, authentication, retrieval of data and sending back responses.

Your best bet is to use a framework that already has this functionality ready and tested for you.

Some suggestions are:

Phalcon - REST API building - Easy to use all in one framework with huge performance

Apigility - A one size fits all API handling framework by Zend Technologies

Laravel API Building Tutorial

and many more. Simple searches on Bitbucket/Github will give you a lot of resources to start with.

Spring Boot default H2 jdbc connection (and H2 console)

A similar answer with Step by Step guide.

  1. Add Developer tools dependency to your pom.xml or build.gradle

Maven

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>

Gradle

dependencies {
    compile("org.springframework.boot:spring-boot-devtools")
}
  1. Access the db from http://localhost:8080/h2-console/
  2. Specify jdbc:h2:mem:testdb as JDBC URL
  3. You should see the entity you specified in your project as a table.

Call a python function from jinja2

@John32323 's answer is a very clean solution.

Here is the same one, but save into a seperate file, maybe more cleaner.

Create helper file

app\helper.py

from app import app

def clever_function_1():
    return u'HELLO'

def clever_function_2(a, b):
    return a + b



app.jinja_env.globals.update(
    clever_function_1=clever_function_1,
    clever_function_2=clever_function_2,
)

Import from app

app.py

from app import routes
from app import helper   # add this one

Use like this

app\templates\some.html


{{ clever_function_1() }}
{{ clever_function_2(a, b) }}

Using Javascript in CSS

I ran into a similar problem and have developed two standalone tools to accomplish this:

  • CjsSS.js is a Vanilla Javascript tool (so no external dependencies) that supports back to IE6.

  • ngCss is an Angular Module+Filter+Factory (aka: plugin) that supports Angular 1.2+ (so back to IE8)

Both of these tool sets allow you to do this in a STYLE tag or within an external *.css file:

    /*<script src='some.js'></script>
    <script>
        var mainColor = "#cccccc";
    </script>*/

    BODY {
        color: /*{{mainColor}}*/;
    }

And this in your on-page style attributes:

    <div style="color: {{mainColor}}" cjsss="#sourceCSS">blah</div>

or

    <div style="color: {{mainColor}}" ng-css="sourceCSS">blah</div>

NOTE: In ngCss, you could also do $scope.mainColor in place of var mainColor

By default, the Javascript is executed in a sandboxed IFRAME, but since you author your own CSS and host it on your own server (just like your *.js files) then XSS isn't an issue. But the sandbox provides that much more security and peace of mind.

CjsSS.js and ngCss fall somewhere in-between the other tools around to accomplish similar tasks:

  • LESS, SASS and Stylus are all Preprocessors only and require you to learn a new language and mangle your CSS. Basically they extended CSS with new language features. All are also limited to plugins developed for each platform while CjsSS.js and ngCss both allow you to include any Javascript library via <script src='blah.js'></script> straight in your CSS!

  • AbsurdJS saw the same problems and went the exact opposite direction of the Preprocessors above; rather than extending CSS, AbsurdJS created a Javascript library to generate CSS.

CjsSS.js and ngCss took the middle ground; you already know CSS, you already know Javascript, so just let them work together in a simple, intuitive way.

HTML 5 Video "autoplay" not automatically starting in CHROME

You need to add playsinline autoplay muted loop, chrome do not allow a video to autostart if it is not muted, also right now I dont know why it is not working in all android devices, im trying to look if it's a version specific, If I found something I'll let you know

Chrome issue: After some research i have found that it doesnt work on chrome sometimes because in responsive you can activate the data saver, and it blocks any video to autostart

Error in MySQL when setting default value for DATE or DATETIME

This answer it's just for MySQL 5.7:

Best is not really set in blank the sql_mode, instead use in PHP a session variable with:

SET SESSION sql_mode= 'ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'

So at least you keep the other default values.

It's crazy that mysql documentation is not clear, you need delete to these default values in sql_mode:

NO_ZERO_IN_DATE,NO_ZERO_DATE, I understand, but in the future versions this will be discontinued.

STRICT_ALL_TABLES, with this, before parameters will be ignored, so you need to delete it too.

Finally TRADITIONAL too, but documentation speaks about this parameter: “give an error instead of a warning” when inserting an incorrect value into a column", with this parameter, dates with zero values is not inserted, but without yes.

MySQL is not really organised with these parameters and combinations.

Collection was modified; enumeration operation may not execute

This way should cover a situation of concurrency when the function is called again while is still executing (and items need used only once):

 while (list.Count > 0)
 {
    string Item = list[0];
    list.RemoveAt(0);
 
    // do here what you need to do with item
 
 } 
 

If the function get called while is still executing items will not reiterate from the first again as they get deleted as soon as they get used. Should not affect performance much for small lists.

Converting a vector<int> to string

Here is an alternative which uses a custom output iterator. This example behaves correctly for the case of an empty list. This example demonstrates how to create a custom output iterator, similar to std::ostream_iterator.

#include <iterator>
#include <vector>
#include <iostream>
#include <sstream>

struct CommaIterator
:
  public std::iterator<std::output_iterator_tag, void, void, void, void>
{
  std::ostream *os;
  std::string comma;
  bool first;

  CommaIterator(std::ostream& os, const std::string& comma)
  :
    os(&os), comma(comma), first(true)
  {
  }

  CommaIterator& operator++() { return *this; }
  CommaIterator& operator++(int) { return *this; }
  CommaIterator& operator*() { return *this; }
  template <class T>
  CommaIterator& operator=(const T& t) {
    if(first)
      first = false;
    else
      *os << comma;
    *os << t;
    return *this;
  }
};

int main () {
  // The vector to convert
  std::vector<int> v(3,3);

  // Convert vector to string
  std::ostringstream oss;
  std::copy(v.begin(), v.end(), CommaIterator(oss, ","));
  std::string result = oss.str();
  const char *c_result = result.c_str();

  // Display the result;
  std::cout << c_result << "\n";
}

What's the difference between Git Revert, Checkout and Reset?

  • git revert is used to undo a previous commit. In git, you can't alter or erase an earlier commit. (Actually you can, but it can cause problems.) So instead of editing the earlier commit, revert introduces a new commit that reverses an earlier one.
  • git reset is used to undo changes in your working directory that haven't been comitted yet.
  • git checkout is used to copy a file from some other commit to your current working tree. It doesn't automatically commit the file.

Which version of CodeIgniter am I currently using?

Try this code working fine check codeigniter version

Just go to 'system' > 'core' > 'CodeIgniter.php' and look for the lines,

/**
 * CodeIgniter Version
 *
 * @var    string
 *
 */
    define('CI_VERSION', '3.0.0');

Alternate method to check codeigniter version, you can echo the constant value 'CI_VERSION' somewhere in codeigniter controller/view file.

<?php
    echo CI_VERSION;
?>

More Information with demo: how to check codeigniter version

Way to run Excel macros from command line or batch file?

If you're more comfortable working inside Excel/VBA, use the open event and test the environment: either have a signal file, a registry entry or an environment variable that controls what the open event does.

You can create the file/setting outside and test inside (use GetEnviromentVariable for env-vars) and test easily. I've written VBScript but the similarities to VBA cause me more angst than ease..

[more]

As I understand the problem, you want to use a spreadsheet normally most/some of the time yet have it run in batch and do something extra/different. You can open the sheet from the excel.exe command line but you can't control what it does unless it knows where it is. Using an environment variable is relatively simple and makes testing the spreadsheet easy.

To clarify, use the function below to examine the environment. In a module declare:

Private Declare Function GetEnvVar Lib "kernel32" Alias "GetEnvironmentVariableA" _
    (ByVal lpName As String, ByVal lpBuffer As String, ByVal nSize As Long) As Long

Function GetEnvironmentVariable(var As String) As String
Dim numChars As Long

    GetEnvironmentVariable = String(255, " ")

    numChars = GetEnvVar(var, GetEnvironmentVariable, 255)

End Function

In the Workbook open event (as others):

Private Sub Workbook_Open()
    If GetEnvironmentVariable("InBatch") = "TRUE" Then
        Debug.Print "Batch"
    Else
        Debug.Print "Normal"
    End If
End Sub

Add in active code as applicable. In the batch file, use

set InBatch=TRUE

How can I ignore a property when serializing using the DataContractSerializer?

In XML Serializing, you can use the [XmlIgnore] attribute (System.Xml.Serialization.XmlIgnoreAttribute) to ignore a property when serializing a class.

This may be of use to you (Or it just may be of use to anyone who found this question when attempting to find out how to ignore a property when Serializing in XML, as I was).

What is the difference between "px", "dip", "dp" and "sp"?

sp: scale independent pixel

You should use it with texts because it is automatically scaled according to the font size that is being used by the user in his device.

px: pixel or picture element is the single point on the screen

How to calculate the time interval between two time strings

    import datetime
    
    day = int(input("day[1,2,3,..31]: "))
    month = int(input("Month[1,2,3,...12]: "))
    year = int(input("year[0~2020]: "))
    start_date = datetime.date(year, month, day)
    
    day = int(input("day[1,2,3,..31]: "))
    month = int(input("Month[1,2,3,...12]: "))
    year = int(input("year[0~2020]: "))
    end_date = datetime.date(year, month, day)
    
    time_difference = end_date - start_date
    age = time_difference.days
    print("Total days: " + str(age))

How to get selected value from Dropdown list in JavaScript

I would say change var sv = sel.options[sel.selectedIndex].value; to var sv = sel.options[sel.selectedIndex].text;

It worked for me. Directing you to where I found my solution Getting the selected value dropdown jstl

How to Solve Max Connection Pool Error

Check against any long running queries in your database.

Increasing your pool size will only make your webapp live a little longer (and probably get a lot slower)

You can use sql server profiler and filter on duration / reads to see which querys need optimization.

I also see you're probably keeping a global connection?

blnMainConnectionIsCreatedLocal

Let .net do the pooling for you and open / close your connection with a using statement.

Suggestions:

  1. Always open and close a connection like this, so .net can manage your connections and you won't run out of connections:

        using (SqlConnection conn = new SqlConnection(connectionString))
        {
         conn.Open();
         // do some stuff
        } //conn disposed
    
  2. As I mentioned, check your query with sql server profiler and see if you can optimize it. Having a slow query with many requests in a web app can give these timeouts too.

What is a faster alternative to Python's http.server (or SimpleHTTPServer)?

Yet another node based simple command line server

https://github.com/greggman/servez-cli

Written partly in response to http-server having issues, particularly on windows.

installation

Install node.js then

npm install -g servez

usage

servez [options] [path]

With no path it serves the current folder.

By default it serves index.html for folder paths if it exists. It serves a directory listing for folders otherwise. It also serves CORS headers. You can optionally turn on basic authentication with --username=somename --password=somepass and you can serve https.

How to refresh the data in a jqGrid?

This worked for me.

jQuery('#grid').jqGrid('clearGridData');
jQuery('#grid').jqGrid('setGridParam', {data: dataToLoad});
jQuery('#grid').trigger('reloadGrid');

How to do a newline in output

You can do this all in the File.open block:

Dir.chdir 'C:/Users/name/Music'
music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
puts 'what would you like to call the playlist?'
playlist_name = gets.chomp + '.m3u'

File.open playlist_name, 'w' do |f|
  music.each do |z|
    f.puts z
  end
end

Show just the current branch in Git

I'm using

/etc/bash_completion.d/git

It came with Git and provides a prompt with branch name and argument completion.

Google Chrome default opening position and size

First, close all instances of Google Chrome. There should be no instances of chrome.exe running in the Windows Task Manager. Then

  • Go to %LOCALAPPDATA%\Google\Chrome\User Data\Default\.
  • Open the file "Preferences" in a text editor like Notepad.
  • First, resave the file to something like "Preference - Old" without any extension (i.e. no .txt). This will serve as a backup, should something go wrong.
  • Look for a section called "browser." Inside that section, you should find a subsection called window_placement. Under window_placement you will see things like "bottom", "left", "right", etc. with numbers after them.

You will need to play around with these numbers to get your desired window size and placement. When finished, save this file with the name "Preferences" again with no extension. This will overwrite the existing Preferences file. Open Chrome and see how you did. If you're not satisfied with the size and placement, close Chrome and change the numbers in the Preferences file until you get what you want.

Convert a CERT/PEM certificate to a PFX certificate

If you have a self-signed certificate generated by makecert.exe on a Windows machine, you will get two files: cert.pvk and cert.cer. These can be converted to a pfx using pvk2pfx

pvk2pfx is found in the same location as makecert (e.g. C:\Program Files (x86)\Windows Kits\10\bin\x86 or similar)

pvk2pfx -pvk cert.pvk -spc cert.cer -pfx cert.pfx

How can I truncate a double to only two decimal places in Java?

3.545555555 to get 3.54. Try Following for this:

    DecimalFormat df = new DecimalFormat("#.##");

    df.setRoundingMode(RoundingMode.FLOOR);

    double result = new Double(df.format(3.545555555);

This will give= 3.54!

Javascript Uncaught Reference error Function is not defined

If you are using Angular.js then functions imbedded into HTML, such as onclick="function()" or onchange="function()". They will not register. You need to make the change events in the javascript. Such as:

$('#exampleBtn').click(function() {
  function();
});

How to select only the first rows for each unique value of a column?

You can use row_number() to get the row number of the row. It uses the over command - the partition by clause specifies when to restart the numbering and the order by selects what to order the row number on. Even if you added an order by to the end of your query, it would preserve the ordering in the over command when numbering.

select *
from mytable
where row_number() over(partition by Name order by AddressLine) = 1

How to use the PI constant in C++

On windows (cygwin + g++), I've found it necessary to add the flag -D_XOPEN_SOURCE=500 for the preprocessor to process the definition of M_PI in math.h.

How to compare two Carbon Timestamps?

Carbon has a bunch of comparison functions with mnemonic names:

  • equalTo()
  • notEqualTo()
  • greaterThan()
  • greaterThanOrEqualTo()
  • lessThan()
  • lessThanOrEqualTo()

Usage:

 if($model->edited_at->greaterThan($model->created_at)){
     // edited at is newer than created at
 }

Valid for nesbot/carbon 1.36.2

if you are not sure what Carbon version you are on, run this

$composer show "nesbot/carbon"

documentation: https://carbon.nesbot.com/docs/#api-comparison

Make sure that the controller has a parameterless public constructor error

I've got this error when I accidentally defined a property as a specific object type, instead of the interface type I have defined in UnityContainer.

For example:

Defining UnityContainer:

var container = new UnityContainer();
container.RegisterInstance(typeof(IDashboardRepository), DashboardRepository);
config.DependencyResolver = new UnityResolver(container);

SiteController (the wrong way - notice repo type):

private readonly DashboardRepository _repo;

public SiteController(DashboardRepository repo)
{
    _repo = repo;
}

SiteController (the right way):

private readonly IDashboardRepository _repo;

public SiteController(IDashboardRepository repo)
{
    _repo = repo;
}

Change Placeholder Text using jQuery

working example of dynamic placeholder using Javascript and Jquery http://jsfiddle.net/ogk2L14n/1/

<input type="text" id="textbox">
 <select id="selection" onchange="changeplh()">
     <option>one</option>
     <option>two</option>
     <option>three</option>
    </select>

function changeplh(){
    debugger;
 var sel = document.getElementById("selection");
    var textbx = document.getElementById("textbox");
    var indexe = sel.selectedIndex;

    if(indexe == 0) { 
     $("#textbox").attr("placeholder", "age");

}
       if(indexe == 1) { 
     $("#textbox").attr("placeholder", "name");
}
}

C char* to int conversion

Use atoi() from <stdlib.h>

http://linux.die.net/man/3/atoi

Or, write your own atoi() function which will convert char* to int

int a2i(const char *s)
{
  int sign=1;
  if(*s == '-'){
    sign = -1;
    s++;
  }
  int num=0;
  while(*s){
    num=((*s)-'0')+num*10;
    s++;   
  }
  return num*sign;
}

How to redirect output to a file and stdout

Using tail -f output should work.

Where does the @Transactional annotation belong?

Service layer is best place to add @Transactional annotations as most of the business logic present here, it contain detail level use-case behaviour.

Suppose we add it to DAO and from service we are calling 2 DAO classes , one failed and other success , in this case if @Transactional not on service one DB will commit and other will rollback.

Hence my recommendation is use this annotation wisely and use at Service layer only.

Github project- java-algos

Why is there no SortedList in Java?

Since all lists are already "sorted" by the order the items were added (FIFO ordering), you can "resort" them with another order, including the natural ordering of elements, using java.util.Collections.sort().

EDIT:

Lists as data structures are based in what is interesting is the ordering in which the items where inserted.

Sets do not have that information.

If you want to order by adding time, use List. If you want to order by other criteria, use SortedSet.

Firebug-like debugger for Google Chrome

F12 (only on Linux and Windows)

OR

Ctrl ? I

(? ? I if you're on Mac)

Format Date output in JSF

If you use OmniFaces you can also use it's EL functions like of:formatDate() to format Date objects. You would use it like this:

<h:outputText value="#{of:formatDate(someBean.dateField, 'dd.MM.yyyy HH:mm')}" />

This way you can not only use it for output but also to pass it on to other JSF components.

How to switch from POST to GET in PHP CURL

CURL request by default is GET, you don't have to set any options to make a GET CURL request.

pull out p-values and r-squared from a linear regression

r-squared: You can return the r-squared value directly from the summary object summary(fit)$r.squared. See names(summary(fit)) for a list of all the items you can extract directly.

Model p-value: If you want to obtain the p-value of the overall regression model, this blog post outlines a function to return the p-value:

lmp <- function (modelobject) {
    if (class(modelobject) != "lm") stop("Not an object of class 'lm' ")
    f <- summary(modelobject)$fstatistic
    p <- pf(f[1],f[2],f[3],lower.tail=F)
    attributes(p) <- NULL
    return(p)
}

> lmp(fit)
[1] 1.622665e-05

In the case of a simple regression with one predictor, the model p-value and the p-value for the coefficient will be the same.

Coefficient p-values: If you have more than one predictor, then the above will return the model p-value, and the p-value for coefficients can be extracted using:

summary(fit)$coefficients[,4]  

Alternatively, you can grab the p-value of coefficients from the anova(fit) object in a similar fashion to the summary object above.

Checking if a string is empty or null in Java

This way you check if the string is not null and not empty, also considering the empty spaces:

boolean isEmpty = str == null || str.trim().length() == 0;
if (isEmpty) {
    // handle the validation
}

What exactly does the .join() method do?

join() is for concatenating all list elements. For concatenating just two strings "+" would make more sense:

strid = repr(595)
print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
    .tostring() + strid

Swipe ListView item From right to left show delete button

I just got his working using the ViewSwitcher in a ListItem.

list_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >

<ViewSwitcher
    android:id="@+id/list_switcher"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:inAnimation="@android:anim/slide_in_left"
    android:outAnimation="@android:anim/slide_out_right"
    android:measureAllChildren="false" >
    <TextView
        android:id="@+id/tv_item_name"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_gravity="center_vertical"
        android:maxHeight="50dp"
        android:paddingLeft="10dp" />

    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:clickable="false"
        android:gravity="center"
        >

    <Button
        android:id="@+id/b_edit_in_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Edit"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"

         />
    <Button
        android:id="@+id/b_delete_in_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Delete"
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:background="@android:color/holo_red_dark"
        />
    </LinearLayout>
</ViewSwitcher>

In the ListAdapter: Implement OnclickListeners for the Edit and Delete button in the getView() method. The catch here is to get the position of the ListItem clicked inside the onClick methods. setTag() and getTag() methods are used for this.

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    final ViewHolder viewHolder;
    if (convertView == null) {
        viewHolder = new ViewHolder();
        convertView = mInflater.inflate(R.layout.list_item, null);
        viewHolder.viewSwitcher=(ViewSwitcher)convertView.findViewById(R.id.list_switcher);
        viewHolder.itemName = (TextView) convertView
                .findViewById(R.id.tv_item_name);
        viewHolder.deleteitem=(Button)convertView.findViewById(R.id.b_delete_in_list);
        viewHolder.deleteItem.setTag(position);
        viewHolder.editItem=(Button)convertView.findViewById(R.id.b_edit_in_list);
        viewHolder.editItem.setTag(position);
        viewHolder.deleteItem.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                fragment.deleteItemList((Integer)v.getTag());
            }
        });

        viewHolder.editItem.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                fragment.editItemList(position);
            }
        });
        convertView.setTag(viewHolder);
} else {
        viewHolder = (ViewHolder) convertView.getTag();
    }

    viewHolder.itemName.setText(itemlist[position]);
return convertView;  
}

In the Fragment, Add a Gesture Listener to detect the Fling Gesture:

public class MyGestureListener extends SimpleOnGestureListener {
    private ListView list;

    public MyGestureListener(ListView list) {
        this.list = list;
    }

    // CONDITIONS ARE TYPICALLY VELOCITY OR DISTANCE

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
            float velocityY) {
        // if (INSERT_CONDITIONS_HERE)

        ltor=(e2.getX()-e1.getX()>DELTA_X);
        if (showDeleteButton(e1))
        {
            return true;
        }
        return super.onFling(e1, e2, velocityX, velocityY);
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2,
            float distanceX, float distanceY) {
        // TODO Auto-generated method stub
        return super.onScroll(e1, e2, distanceX, distanceY);
    }

    private boolean showDeleteButton(MotionEvent e1) {
        int pos = list.pointToPosition((int) e1.getX(), (int) e1.getY());
        return showDeleteButton(pos);
    }

    private boolean showDeleteButton(int pos) {

        View child = list.getChildAt(pos);
        if (child != null) {
            Button delete = (Button) child
                    .findViewById(R.id.b_edit_in_list);
            ViewSwitcher viewSwitcher = (ViewSwitcher) child
                    .findViewById(R.id.host_list_switcher);
            TextView hostName = (TextView) child
                    .findViewById(R.id.tv_host_name);
            if (delete != null) {
                    viewSwitcher.setInAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.slide_in_left));
                    viewSwitcher.setOutAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.slide_out_right));
                }

                viewSwitcher.showNext();
                // frameLayout.setVisibility(View.VISIBLE);
            }
            return true;
        }
        return false;
    }
}

In the onCreateView method of the Fragment,

GestureDetector gestureDetector = new GestureDetector(getActivity(),
            new MyGestureListener(hostList));
    hostList.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            // TODO Auto-generated method stub
            if (gestureDetector.onTouchEvent(event)) {
                return true;
            } else {
                return false;
            }

        }
    });

This worked for me. Should refine it more.

How do I POST JSON data with cURL?

You could also put your JSON content in a file and pass it to curl using the --upload-file option via standard input, like this:

 echo 'my.awesome.json.function({"do" : "whatever"})' | curl -X POST "http://url" -T -

How can I send a file document to the printer and have it print?

You can tell Acrobat Reader to print the file using (as someone's already mentioned here) the 'print' verb. You will need to close Acrobat Reader programmatically after that, too:

private void SendToPrinter()
{
   ProcessStartInfo info = new ProcessStartInfo();
   info.Verb = "print";
   info.FileName = @"c:\output.pdf";
   info.CreateNoWindow = true;
   info.WindowStyle = ProcessWindowStyle.Hidden;

   Process p = new Process();
   p.StartInfo = info;
   p.Start();

   p.WaitForInputIdle();
   System.Threading.Thread.Sleep(3000);
   if (false == p.CloseMainWindow())
      p.Kill();
}

This opens Acrobat Reader and tells it to send the PDF to the default printer, and then shuts down Acrobat after three seconds.

If you are willing to ship other products with your application then you could use GhostScript (free), or a command-line PDF printer such as http://www.commandlinepdf.com/ (commercial).

Note: the sample code opens the PDF in the application current registered to print PDFs, which is the Adobe Acrobat Reader on most people's machines. However, it is possible that they use a different PDF viewer such as Foxit (http://www.foxitsoftware.com/pdf/reader/). The sample code should still work, though.

Elevating process privilege programmatically?

According to the article Chris Corio: Teach Your Apps To Play Nicely With Windows Vista User Account Control, MSDN Magazine, Jan. 2007, only ShellExecute checks the embedded manifest and prompts the user for elevation if needed, while CreateProcess and other APIs don't. Hope it helps.

See also: same article as .chm.

What is the Maximum Size that an Array can hold?

Per MSDN it is

By default, the maximum size of an Array is 2 gigabytes (GB).

In a 64-bit environment, you can avoid the size restriction by setting the enabled attribute of the gcAllowVeryLargeObjects configuration element to true in the run-time environment.

However, the array will still be limited to a total of 4 billion elements.

Refer Here http://msdn.microsoft.com/en-us/library/System.Array(v=vs.110).aspx

Note: Here I am focusing on the actual length of array by assuming that we will have enough hardware RAM.

JavaScript: replace last occurrence of text in a string

Old fashioned and big code but efficient as possible:

function replaceLast(origin,text){
    textLenght = text.length;
    originLen = origin.length
    if(textLenght == 0)
        return origin;

    start = originLen-textLenght;
    if(start < 0){
        return origin;
    }
    if(start == 0){
        return "";
    }
    for(i = start; i >= 0; i--){
        k = 0;
        while(origin[i+k] == text[k]){
            k++
            if(k == textLenght)
                break;
        }
        if(k == textLenght)
            break;
    }
    //not founded
    if(k != textLenght)
        return origin;

    //founded and i starts on correct and i+k is the first char after
    end = origin.substring(i+k,originLen);
    if(i == 0)
        return end;
    else{
        start = origin.substring(0,i) 
        return (start + end);
    }
}

How do I set the default schema for a user in MySQL

There is no default database for user. There is default database for current session.

You can get it using DATABASE() function -

SELECT DATABASE();

And you can set it using USE statement -

USE database1;

You should set it manually - USE db_name, or in the connection string.

Converting String Array to an Integer Array

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class MultiArg {

    Scanner sc;
    int n;
    String as;
    List<Integer> numList = new ArrayList<Integer>();

    public void fun() {
        sc = new Scanner(System.in);
        System.out.println("enter value");
        while (sc.hasNextInt())
            as = sc.nextLine();
    }

    public void diplay() {
        System.out.println("x");
        Integer[] num = numList.toArray(new Integer[numList.size()]);
        System.out.println("show value " + as);
        for (Integer m : num) {
            System.out.println("\t" + m);
        }
    }
}

but to terminate the while loop you have to put any charecter at the end of input.

ex. input:

12 34 56 78 45 67 .

output:

12 34 56 78 45 67

Horizontal scroll on overflow of table

I think your overflow should be on the outer container. You can also explicitly set a min width for the columns. Like this:

.search-table-outter { overflow-x: scroll; }
th, td { min-width: 200px; }

Fiddle: http://jsfiddle.net/5WsEt/

Convert a string into an int

How about

[@"7" intValue];

Additionally if you want an NSNumber you could do

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter numberFromString:@"7"];

laravel 5.4 upload image

public function store()
{
    $this->validate(request(), [
        'title' => 'required',
        'slug' => 'required',
        'file' => 'required|image|mimes:jpg,jpeg,png,gif'
    ]);

    $fileName = null;
    if (request()->hasFile('file')) {
        $file = request()->file('file');
        $fileName = md5($file->getClientOriginalName() . time()) . "." . $file->getClientOriginalExtension();
        $file->move('./uploads/categories/', $fileName);    
    }

    Category::create([
        'title' => request()->get('title'),
        'slug' => str_slug(request()->get('slug')),
        'description' => request()->get('description'),
        'category_img' => $fileName,
        'category_status' => 'DEACTIVE'
    ]);

    return redirect()->to('/admin/category');
}

Set Date in a single line

You could use

new SimpleDateFormat( "yyyyMMdd" ).parse( "20100520" )

How to implement "confirmation" dialog in Jquery UI dialog?

I just had to solve the same problem. The key to getting this to work was that the dialog must be partially initialized in the click event handler for the link you want to use the confirmation functionality with (if you want to use this for more than one link). This is because the target URL for the link must be injected into the event handler for the confirmation button click. I used a CSS class to indicate which links should have the confirmation behavior.

Here's my solution, abstracted away to be suitable for an example.

<div id="dialog" title="Confirmation Required">
  Are you sure about this?
</div>

<script type="text/javascript">
  $(document).ready(function() {
    $("#dialog").dialog({
      autoOpen: false,
      modal: true
    });
  });

  $(".confirmLink").click(function(e) {
    e.preventDefault();
    var targetUrl = $(this).attr("href");

    $("#dialog").dialog({
      buttons : {
        "Confirm" : function() {
          window.location.href = targetUrl;
        },
        "Cancel" : function() {
          $(this).dialog("close");
        }
      }
    });

    $("#dialog").dialog("open");
  });
</script>

<a class="confirmLink" href="http://someLinkWhichRequiresConfirmation.com">Click here</a>
<a class="confirmLink" href="http://anotherSensitiveLink">Or, you could click here</a>

I believe that this would work for you, if you can generate your links with the CSS class (confirmLink, in my example).

Here is a jsfiddle with the code in it.

In the interest of full disclosure, I'll note that I spent a few minutes on this particular problem and I provided a similar answer to this question, which was also without an accepted answer at the time.

How to get RegistrationID using GCM in android

Here I have written a few steps for How to Get RegID and Notification starting from scratch

  1. Create/Register App on Google Cloud
  2. Setup Cloud SDK with Development
  3. Configure project for GCM
  4. Get Device Registration ID
  5. Send Push Notifications
  6. Receive Push Notifications

You can find a complete tutorial here:

Getting Started with Android Push Notification : Latest Google Cloud Messaging (GCM) - step by step complete tutorial

enter image description here

Code snippet to get Registration ID (Device Token for Push Notification).

Configure project for GCM


Update AndroidManifest file

To enable GCM in our project we need to add a few permissions to our manifest file. Go to AndroidManifest.xml and add this code: Add Permissions

<uses-permission android:name="android.permission.INTERNET”/>
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<uses-permission android:name="android.permission.VIBRATE" />

<uses-permission android:name=“.permission.RECEIVE" />
<uses-permission android:name=“<your_package_name_here>.permission.C2D_MESSAGE" />
<permission android:name=“<your_package_name_here>.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

Add GCM Broadcast Receiver declaration in your application tag:

<application
        <receiver
            android:name=".GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" ]]>
            <intent-filter]]>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="" />
            </intent-filter]]>

        </receiver]]>
     
<application/>

Add GCM Service declaration

<application
     <service android:name=".GcmIntentService" />
<application/>

Get Registration ID (Device Token for Push Notification)

Now Go to your Launch/Splash Activity

Add Constants and Class Variables

private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static String TAG = "LaunchActivity";
protected String SENDER_ID = "Your_sender_id";
private GoogleCloudMessaging gcm =null;
private String regid = null;
private Context context= null;

Update OnCreate and OnResume methods

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_launch);
    context = getApplicationContext();
    if (checkPlayServices()) {
        gcm = GoogleCloudMessaging.getInstance(this);
        regid = getRegistrationId(context);

        if (regid.isEmpty()) {
            registerInBackground();
        } else {
            Log.d(TAG, "No valid Google Play Services APK found.");
        }
    }
}

@Override
protected void onResume() {
    super.onResume();
    checkPlayServices();
}


// # Implement GCM Required methods(Add below methods in LaunchActivity)

private boolean checkPlayServices() {
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS) {
        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
            GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                PLAY_SERVICES_RESOLUTION_REQUEST).show();
        } else {
            Log.d(TAG, "This device is not supported - Google Play Services.");
            finish();
        }
        return false;
    }
    return true;
}

private String getRegistrationId(Context context) {
    final SharedPreferences prefs = getGCMPreferences(context);
    String registrationId = prefs.getString(PROPERTY_REG_ID, "");
    if (registrationId.isEmpty()) {
        Log.d(TAG, "Registration ID not found.");
        return "";
    }
    int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
    int currentVersion = getAppVersion(context);
    if (registeredVersion != currentVersion) {
        Log.d(TAG, "App version changed.");
        return "";
    }
    return registrationId;
}

private SharedPreferences getGCMPreferences(Context context) {
    return getSharedPreferences(LaunchActivity.class.getSimpleName(),
        Context.MODE_PRIVATE);
}

private static int getAppVersion(Context context) {
    try {
        PackageInfo packageInfo = context.getPackageManager()
            .getPackageInfo(context.getPackageName(), 0);
        return packageInfo.versionCode;
    } catch (NameNotFoundException e) {
        throw new RuntimeException("Could not get package name: " + e);
    }
}


private void registerInBackground() {
    new AsyncTask() {
        @Override
        protected Object doInBackground(Object...params) {
            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(context);
                }
                regid = gcm.register(SENDER_ID);
                Log.d(TAG, "########################################");
                Log.d(TAG, "Current Device's Registration ID is: " + msg);
            } catch (IOException ex) {
                msg = "Error :" + ex.getMessage();
            }
            return null;
        }
        protected void onPostExecute(Object result) {
            //to do here
        };
    }.execute(null, null, null);
}

Note : please store REGISTRATION_KEY, it is important for sending PN Message to GCM. Also keep in mind: this key will be unique for all devices and GCM will send Push Notifications by REGISTRATION_KEY only.

Android Canvas.drawText

Worked this out, turns out that android.R.color.black is not the same as Color.BLACK. Changed the code to:

Paint paint = new Paint(); 
paint.setColor(Color.WHITE); 
paint.setStyle(Style.FILL); 
canvas.drawPaint(paint); 

paint.setColor(Color.BLACK); 
paint.setTextSize(20); 
canvas.drawText("Some Text", 10, 25, paint); 

and it all works fine now!!

CSS opacity only to background color, not the text on it?

For Less users only:

If you don't like to set your colors using RGBA, but rather using HEX, there are solutions.

You could use a mixin like:

.transparentBackgroundColorMixin(@alpha,@color) {
  background-color: rgba(red(@color), green(@color), blue(@color), @alpha);
}

And use it like:

.myClass {
    .transparentBackgroundColorMixin(0.6,#FFFFFF);
}

Actually this is what a built-in Less function also provide:

.myClass {
    background-color: fade(#FFFFFF, 50%);
}

See How do I convert a hexadecimal color to rgba with the Less compiler?

Proper MIME type for OTF fonts

FWIW regarding Apache 2.2 VirtualHosting and mod_mime tested on Debian Linux and OS X Leopard and Snow Leopard:

If you have a VirtualHost configuration you will want to add the types via the AddType Directive as follows at least at the bottom of the configuration as follows:

....
   AddType font/opentype .otf
   AddType font/ttf .ttf
</VirtualHost>

Tested against Chrome Unstable/Trunk and Safari WebKit Nightly which eliminates the mime octet-stream warnings for both the ttf and otf font types.

Note: .htaccess has zero effect when dealing with VirtualHosting. If you're developing for several sites you'll be using VirtualHosting development and each configuration will need these AddType additions.

IE7 Z-Index Layering Issues

Z-index is not an absolute measurement. It is possible for an element with z-index: 1000 to be behind an element with z-index: 1 - as long as the respective elements belong to different stacking contexts.

When you specify z-index, you're specifying it relative to other elements in the same stacking context, and although the CSS spec's paragraph on Z-index says a new stacking context is only created for positioned content with a z-index other than auto (meaning your entire document should be a single stacking context), you did construct a positioned span: unfortunately IE7 interprets positioned content without z-index this as a new stacking context.

In short, try adding this CSS:

#envelope-1 {position:relative; z-index:1;}

or redesign the document such that your spans don't have position:relative any longer:

<html>
<head>
    <title>Z-Index IE7 Test</title>
    <style type="text/css">
        ul {
            background-color: #f00; 
            z-index: 1000;
            position: absolute;
            width: 150px;
        }
    </style>
</head>
<body>
    <div>
        <label>Input #1:</label> <input><br>
        <ul><li>item<li>item<li>item<li>item</ul>
    </div>

    <div>
        <label>Input #2:</label> <input>
    </div>
</body>
</html>

See http://www.brenelz.com/blog/2009/02/03/squish-the-internet-explorer-z-index-bug/ for a similar example of this bug. The reason giving a parent element (envelope-1 in your example) a higher z-index works is because then all children of envelope-1 (including the menu) will overlap all siblings of envelope-1 (specifically, envelope-2).

Although z-index lets you explicitly define how things overlap, even without z-index the layering order is well defined. Finally, IE6 has an additional bug that causes selectboxes and iframes to float on top of everything else.

How to get error information when HttpWebRequest.GetResponse() fails

You can also use this library which wraps HttpWebRequest and Response into simple methods that return objects based on the results. It uses some of the techniques described in these answers and has plenty of code inspired by answers from this and similar threads. It automatically catches any exceptions, seeks to abstract as much boiler plate code needed to make these web requests as possible, and automatically deserializes the response object.

An example of what your code would look like using this wrapper is as simple as

    var response = httpClient.Get<SomeResponseObject>(request);
    
    if(response.StatusCode == HttpStatusCode.OK)
    {
        //do something with the response
        console.Writeline(response.Body.Id); //where the body param matches the object you pass in as an anonymous type.  
    }else {
         //do something with the error
         console.Writelint(string.Format("{0}: {1}", response.StatusCode.ToString(), response.ErrorMessage);

    }

Full disclosure This library is a free open source wrapper library, and I am the author of said library. I make no money off of this but have found it immensely useful over the years and am sure anyone who is still using the HttpWebRequest / HttpWebResponse classes will too.

It is not a silver bullet but supports get, post, delete with both async and non-async for get and post as well as JSON or XML requests and responses. It is being actively maintained as of 6/21/2020

Mocking methods of local scope objects with Mockito

You could avoid changing the code (although I recommend Boris' answer) and mock the constructor, like in this example for mocking the creation of a File object inside a method. Don't forget to put the class that will create the file in the @PrepareForTest.

package hello.easymock.constructor;

import java.io.File;

import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
    
@RunWith(PowerMockRunner.class)
@PrepareForTest({File.class})
public class ConstructorExampleTest {
        
    @Test
    public void testMockFile() throws Exception {

        // first, create a mock for File
        final File fileMock = EasyMock.createMock(File.class);
        EasyMock.expect(fileMock.getAbsolutePath()).andReturn("/my/fake/file/path");
        EasyMock.replay(fileMock);

        // then return the mocked object if the constructor is invoked
        Class<?>[] parameterTypes = new Class[] { String.class };
        PowerMock.expectNew(File.class, parameterTypes , EasyMock.isA(String.class)).andReturn(fileMock);
        PowerMock.replay(File.class); 
    
        // try constructing a real File and check if the mock kicked in
        final String mockedFilePath = new File("/real/path/for/file").getAbsolutePath();
        Assert.assertEquals("/my/fake/file/path", mockedFilePath);
    }
}

Regular expression replace in C#

Add the following 2 lines

var regex = new Regex(Regex.Escape(","));
sb_trim = regex.Replace(sb_trim, " ", 1);

If sb_trim= John,Smith,100000,M the above code will return "John Smith,100000,M"

How can I view an object with an alert()

Try this:

alert(JSON.parse(product) );

How to remove all subviews of a view in Swift?

Extension for remove all subviews, it is quickly removed.

import Foundation
import UIKit

extension UIView {
    /// Remove allSubView in view
    func removeAllSubViews() {
        self.subviews.forEach({ $0.removeFromSuperview() })
    }

}

how to set imageview src?

To set image cource in imageview you can use any of the following ways. First confirm your image is present in which format.

If you have image in the form of bitmap then use

imageview.setImageBitmap(bm);

If you have image in the form of drawable then use

imageview.setImageDrawable(drawable);

If you have image in your resource example if image is present in drawable folder then use

imageview.setImageResource(R.drawable.image);

If you have path of image then use

imageview.setImageURI(Uri.parse("pathofimage"));

Spring MVC: how to create a default controller for index page?

I had the same problem, even after following Sinhue's setup, but I solved it.

The problem was that that something (Tomcat?) was forwarding from "/" to "/index.jsp" when I had the file index.jsp in my WebContent directory. When I removed that, the request did not get forwarded anymore.

What I did to diagnose the problem was to make a catch-all request handler and printed the servlet path to the console. This showed me that even though the request I was making was for http://localhost/myapp/, the servlet path was being changed to "/index.html". I was expecting it to be "/".

@RequestMapping("*")
public String hello(HttpServletRequest request) {
    System.out.println(request.getServletPath());
    return "hello";
}

So in summary, the steps you need to follow are:

  1. In your servlet-mapping use <url-pattern>/</url-pattern>
  2. In your controller use RequestMapping("/")
  3. Get rid of welcome-file-list in web.xml
  4. Don't have any files sitting in WebContent that would be considered default pages (index.html, index.jsp, default.html, etc)

Hope this helps.

The most efficient way to remove first N elements in a list?

You can use list slicing to archive your goal:

n = 5
mylist = [1,2,3,4,5,6,7,8,9]
newlist = mylist[n:]
print newlist

Outputs:

[6, 7, 8, 9]

Or del if you only want to use one list:

n = 5
mylist = [1,2,3,4,5,6,7,8,9]
del mylist[:n]
print mylist

Outputs:

[6, 7, 8, 9]

WCF Service , how to increase the timeout?

The best way is to change any setting you want in your code.

Check out the below example:

using(WCFServiceClient client = new WCFServiceClient ())
{ 
    client.Endpoint.Binding.SendTimeout = new TimeSpan(0, 1, 30);
}

MySQL Great Circle Distance (Haversine formula)

calculate distance in Mysql

 SELECT (6371 * acos(cos(radians(lat2)) * cos(radians(lat1) ) * cos(radians(long1) -radians(long2)) + sin(radians(lat2)) * sin(radians(lat1)))) AS distance

thus distance value will be calculated and anyone can apply as required.

PHP - Redirect and send data via POST

Your going to need CURL for that task I'm afraid. Nice easy way to do it here: http://davidwalsh.name/execute-http-post-php-curl

Hope that helps

C function that counts lines in file

You declare

int countlines(char *filename)

to take a char * argument.

You call it like this

countlines(fp)

passing in a FILE *.

That is why you get that compile error.

You probably should change that second line to

countlines("Test.txt")

since you open the file in countlines

Your current code is attempting to open the file in two different places.

How do I print the type or class of a variable in Swift?

In the latest XCode 6.3 with Swift 1.2, this is the only way I found:

if view.classForCoder.description() == "UISegment" {
    ...
}

xlsxwriter: is there a way to open an existing worksheet in my workbook?

After searching a bit about the method to open the existing sheet in xlxs, i discovered

existingWorksheet = wb.get_worksheet_by_name('Your Worksheet name goes here...')
existingWorksheet.write_row(0,0,'xyz')

You can now append/write any data to the open worksheet. I hope it helps. Thanks

List of IP Space used by Facebook

Updated list as of 6/11/2013

204.15.20.0/22
69.63.176.0/20

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

Android Camera : data intent returns null

Kotlin code that works for me:

 private fun takePhotoFromCamera() {
          val intent = Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE)
        startActivityForResult(intent, PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA)
      }

And get Result :

 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
 if (requestCode == PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA) {
         if (resultCode == Activity.RESULT_OK) {
           val photo: Bitmap? =  MediaStore.Images.Media.getBitmap(this.contentResolver, Uri.parse( data!!.dataString)   )
            // Do something here : set image to an ImageView or save it ..   
              imgV_pic.imageBitmap = photo 
        } else if (resultCode == Activity.RESULT_CANCELED) {
            Log.i(TAG, "Camera  , RESULT_CANCELED ")
        }

    }

}

and don't forget to declare request code:

companion object {
 const val PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA = 300
  }

For-loop vs while loop in R

And about timing:

fn1 <- function (N) {
    for(i in as.numeric(1:N)) { y <- i*i }
}
fn2 <- function (N) {
    i=1
    while (i <= N) {
        y <- i*i
        i <- i + 1
    }
}

system.time(fn1(60000))
# user  system elapsed 
# 0.06    0.00    0.07 
system.time(fn2(60000))
# user  system elapsed 
# 0.12    0.00    0.13

And now we know that for-loop is faster than while-loop. You cannot ignore warnings during timing.

How to know installed Oracle Client is 32 bit or 64 bit?

The following, taken from here, was not mentioned here:

If the Oracle Client is 32 bit, it will contain a "lib" folder; but if it is a 64 bit Oracle Client it will have both "lib" and "lib32" folders.

Also, starting in Oracle 11.2.0.1, the client version for 64-bit and the Oracle client for 32-bit are shipped separately, and there is an $ORACLE_HOME/lib64 directory.

$ORACLE_HOME/lib/ ==> 32 bit $ORACLE_HOME/lib64 ==> 64 bit

Or

$ORACLE_HOME/lib/ ==> 64 bit $ORACLE_HOME/lib32 ==> 32 bit

How to list files inside a folder with SQL Server

Can be done using xp_DirTree, then looping through to generate a full file path if required.

Here is an extract of a script I use to restore databases to a test server automatically. It scans a folder and all subfolders for any backup files, then returns the full path.


  DECLARE @BackupDirectory SYSNAME = @BackupFolder

  IF OBJECT_ID('tempdb..#DirTree') IS NOT NULL
    DROP TABLE #DirTree

  CREATE TABLE #DirTree (
    Id int identity(1,1),
    SubDirectory nvarchar(255),
    Depth smallint,
    FileFlag bit,
    ParentDirectoryID int
   )

   INSERT INTO #DirTree (SubDirectory, Depth, FileFlag)
   EXEC master..xp_dirtree @BackupDirectory, 10, 1

   UPDATE #DirTree
   SET ParentDirectoryID = (
    SELECT MAX(Id) FROM #DirTree d2
    WHERE Depth = d.Depth - 1 AND d2.Id < d.Id
   )
   FROM #DirTree d

  DECLARE 
    @ID INT,
    @BackupFile VARCHAR(MAX),
    @Depth TINYINT,
    @FileFlag BIT,
    @ParentDirectoryID INT,
    @wkSubParentDirectoryID INT,
    @wkSubDirectory VARCHAR(MAX)

  DECLARE @BackupFiles TABLE
  (
    FileNamePath VARCHAR(MAX),
    TransLogFlag BIT,
    BackupFile VARCHAR(MAX),    
    DatabaseName VARCHAR(MAX)
  )

  DECLARE FileCursor CURSOR LOCAL FORWARD_ONLY FOR
  SELECT * FROM #DirTree WHERE FileFlag = 1

  OPEN FileCursor
  FETCH NEXT FROM FileCursor INTO 
    @ID,
    @BackupFile,
    @Depth,
    @FileFlag,
    @ParentDirectoryID  

  SET @wkSubParentDirectoryID = @ParentDirectoryID

  WHILE @@FETCH_STATUS = 0
  BEGIN
    --loop to generate path in reverse, starting with backup file then prefixing subfolders in a loop
    WHILE @wkSubParentDirectoryID IS NOT NULL
    BEGIN
      SELECT @wkSubDirectory = SubDirectory, @wkSubParentDirectoryID = ParentDirectoryID 
      FROM #DirTree 
      WHERE ID = @wkSubParentDirectoryID

      SELECT @BackupFile = @wkSubDirectory + '\' + @BackupFile
    END

    --no more subfolders in loop so now prefix the root backup folder
    SELECT @BackupFile = @BackupDirectory + @BackupFile

    --put backupfile into a table and then later work out which ones are log and full backups  
    INSERT INTO @BackupFiles (FileNamePath) VALUES(@BackupFile)

    FETCH NEXT FROM FileCursor INTO 
      @ID,
      @BackupFile,
      @Depth,
      @FileFlag,
      @ParentDirectoryID 

    SET @wkSubParentDirectoryID = @ParentDirectoryID      
  END

  CLOSE FileCursor
  DEALLOCATE FileCursor

How can building a heap be O(n) time complexity?

Lets suppose you have N elements in a heap. Then its height would be Log(N)

Now you want to insert another element, then the complexity would be : Log(N), we have to compare all the way UP to the root.

Now you are having N+1 elements & height = Log(N+1)

Using induction technique it can be proved that the complexity of insertion would be ?logi.

Now using

log a + log b = log ab

This simplifies to : ?logi=log(n!)

which is actually O(NlogN)

But

we are doing something wrong here, as in all the case we do not reach at the top. Hence while executing most of the times we may find that, we are not going even half way up the tree. Whence, this bound can be optimized to have another tighter bound by using mathematics given in answers above.

This realization came to me after a detail though & experimentation on Heaps.

How to parse a JSON and turn its values into an Array?

You can prefer quick-json parser to meet your requirement...

quick-json parser is very straight forward, flexible, very fast and customizable. Try this out

[quick-json parser] (https://code.google.com/p/quick-json/) - quick-json features -

  • Compliant with JSON specification (RFC4627)

  • High-Performance JSON parser

  • Supports Flexible/Configurable parsing approach

  • Configurable validation of key/value pairs of any JSON Heirarchy

  • Easy to use # Very Less foot print

  • Raises developer friendly and easy to trace exceptions

  • Pluggable Custom Validation support - Keys/Values can be validated by configuring custom validators as and when encountered

  • Validating and Non-Validating parser support

  • Support for two types of configuration (JSON/XML) for using quick-json validating parser

  • Require JDK 1.5 # No dependency on external libraries

  • Support for Json Generation through object serialization

  • Support for collection type selection during parsing process

For e.g.

JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);

When is assembly faster than C?

It might be worth looking at Optimizing Immutable and Purity by Walter Bright it's not a profiled test but shows you one good example of a difference between handwritten and compiler generated ASM. Walter Bright writes optimising compilers so it might be worth looking at his other blog posts.

jquery get height of iframe content when loaded

ok I finally found a good solution:

$('iframe').load(function() {
    this.style.height =
    this.contentWindow.document.body.offsetHeight + 'px';
});

Because some browsers (older Safari and Opera) report onload completed before CSS renders you need to set a micro Timeout and blank out and reassign the iframe's src.

$('iframe').load(function() {
    setTimeout(iResize, 50);
    // Safari and Opera need a kick-start.
    var iSource = document.getElementById('your-iframe-id').src;
    document.getElementById('your-iframe-id').src = '';
    document.getElementById('your-iframe-id').src = iSource;
});
function iResize() {
    document.getElementById('your-iframe-id').style.height = 
    document.getElementById('your-iframe-id').contentWindow.document.body.offsetHeight + 'px';
}

Threading Example in Android

One of Androids powerful feature is the AsyncTask class.

To work with it, you have to first extend it and override doInBackground(...). doInBackground automatically executes on a worker thread, and you can add some listeners on the UI Thread to get notified about status update, those functions are called: onPreExecute(), onPostExecute() and onProgressUpdate()

You can find a example here.

Refer to below post for other alternatives:

Handler vs AsyncTask vs Thread

How can I expand and collapse a <div> using javascript?

If you used the data-role collapsible e.g.

    <div id="selector" data-role="collapsible" data-collapsed="true">
    html......
    </div>

then it will close the the expanded div

    $("#selector").collapsible().collapsible("collapse");   

Prevent Default on Form Submit jQuery

Use the new "on" event syntax.

$(document).ready(function() {
  $('form').on('submit', function(e){
    // validation code here
    if(!valid) {
      e.preventDefault();
    }
  });
});

Cite: https://api.jquery.com/on/

Kill python interpeter in linux from the terminal

pkill -9 python

should kill any running python process.

How can I run code on a background thread on Android?

I want some code to run in the background continuously. I don't want to do it in a service. Is there any other way possible?

Most likely mechanizm that you are looking for is AsyncTask. It directly designated for performing background process on background Thread. Also its main benefit is that offers a few methods which run on Main(UI) Thread and make possible to update your UI if you want to annouce user about some progress in task or update UI with data retrieved from background process.

If you don't know how to start here is nice tutorial:

Note: Also there is possibility to use IntentService with ResultReceiver that works as well.

Returning JSON object from an ASP.NET page

If you get code behind, use some like this

        MyCustomObject myObject = new MyCustomObject();
        myObject.name='try';
        //OBJECT -> JSON
        var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        string myObjectJson = javaScriptSerializer.Serialize(myObject);
        //return JSON   
        Response.Clear();     
        Response.ContentType = "application/json; charset=utf-8";
        Response.Write(myObjectJson );
        Response.End();

So you return a json object serialized with all attributes of MyCustomObject.

Programmatically change the height and width of a UIImageView Xcode Swift

Using autoview

image.heightAnchor.constraint(equalToConstant: CGFloat(8)).isActive = true

Is it possible to use 'else' in a list comprehension?

The syntax a if b else c is a ternary operator in Python that evaluates to a if the condition b is true - otherwise, it evaluates to c. It can be used in comprehension statements:

>>> [a if a else 2 for a in [0,1,0,3]]
[2, 1, 2, 3]

So for your example,

table = ''.join(chr(index) if index in ords_to_keep else replace_with
                for index in xrange(15))

ArrayList of String Arrays

try this

ArrayList<ArrayList<String>> PriceModelList = new ArrayList<>();
    ArrayList<ArrayList<String>> PriceQtyList = new ArrayList<>();
    ArrayList<ArrayList<String>> PriceTotalList = new ArrayList<>();

    for (int i = 0; i < CustomerNames.length; i++) {
        PriceModelList.add(new ArrayList<String>());
        String[] PriceModel = {"s6", "s7", "note4", "note5", "j5", "j6"};
        for (int j = 0; j < PriceModel.length; j++) {
            PriceModelList.get(i).add(PriceModel[j]);
        }

        PriceQtyList.add(new ArrayList<String>());
        String[] PriceQut = {"12", "13", "21", "15", "43", "21"};
        for (int k = 0; k < PriceQut.length; k++) {
            PriceQtyList.get(i).add(PriceQut[k]);
        }

        PriceTotalList.add(new ArrayList<String>());
        String[] PriceTotal = {"1323", "1312321", "43123212", "43434", "12312", "43322"};
        for (int m = 0; m < PriceTotal.length; m++) {
            PriceTotalList.get(i).add(PriceTotal[m]);
        }
    }

    ArrayList<ArrayList<ArrayList<String>>> CustomersShoppingLists = new ArrayList<>();
    CustomersShoppingLists.add(PriceModelList);
    CustomersShoppingLists.add(PriceQtyList);
    CustomersShoppingLists.add(PriceTotalList);

Regular expression for first and last name

A simple function using preg_match in php

<?php
function name_validation($name) {
    if (!preg_match("/^[a-zA-Z ]*$/", $name) === false) {
        echo "$name is a valid name";
    } else {
        echo "$name is not a valid name";
    }
}

//Test
name_validation('89name');
?>

Using Default Arguments in a Function

This is case, when object are better - because you can set up your object to hold x and y , set up defaults etc.

Approach with array is near to create object ( In fact, object is bunch of parameters and functions which will work over object, and function taking array will work over some bunch ov parameters )

Cerainly you can always do some tricks to set null or something like this as default

Android Service needs to run always (Never pause or stop)

You don't require broadcast receiver. If one would take some pain copy one of the api(serviceconnection) from above example by Stephen Donecker and paste it in google you would get this, https://www.concretepage.com/android/android-local-bound-service-example-with-binder-and-serviceconnection

Group by in LINQ

var results = from p in persons
              group p by p.PersonID into g
              select new { PersonID = g.Key,
                           /**/car = g.Select(g=>g.car).FirstOrDefault()/**/}

Error: could not find function "%>%"

The benefit is that the output of previous function is used. You do not need to repeat where the data source comes from, for example.

NSArray + remove item from array

NSArray is not mutable, that is, you cannot modify it. You should take a look at NSMutableArray. Check out the "Removing Objects" section, you'll find there many functions that allow you to remove items:

[anArray removeObjectAtIndex: index];
[anArray removeObject: item];
[anArray removeLastObject];

How to dynamically create columns in datatable and assign values to it?

What have you tried, what was the problem?

Creating DataColumns and add values to a DataTable is straight forward:

Dim dt = New DataTable()
Dim dcID = New DataColumn("ID", GetType(Int32))
Dim dcName = New DataColumn("Name", GetType(String))
dt.Columns.Add(dcID)
dt.Columns.Add(dcName)
For i = 1 To 1000
    dt.Rows.Add(i, "Row #" & i)
Next

Edit:

If you want to read a xml file and load a DataTable from it, you can use DataTable.ReadXml.

ASP.NET Temporary files cleanup

Just an update on more current OS's (Vista, Win7, etc.) - the temp file path has changed may be different based on several variables. The items below are not definitive, however, they are a few I have encountered:

"temp" environment variable setting - then it would be:

%temp%\Temporary ASP.NET Files

Permissions and what application/process (VS, IIS, IIS Express) is running the .Net compiler. Accessing the C:\WINDOWS\Microsoft.NET\Framework folders requires elevated permissions and if you are not developing under an account with sufficient permissions then this folder might be used:

c:\Users\[youruserid]\AppData\Local\Temp\Temporary ASP.NET Files

There are also cases where the temp folder can be set via config for a machine or site specific using this:

<compilation tempDirectory="d:\MyTempPlace" />

I even have a funky setup at work where we don't run Admin by default, plus the IT guys have login scripts that set %temp% and I get temp files in 3 different locations depending on what is compiling things! And I'm still not certain about how these paths get picked....sigh.

Still, dthrasher is correct, you can just delete these and VS and IIS will just recompile them as needed.

How to search JSON data in MySQL?

I use this query

SELECT id FROM table_name WHERE field_name REGEXP '"key_name":"([^"])key_word([^"])"';
or
SELECT id FROM table_name WHERE field_name RLIKE '"key_name":"[[:<:]]key_word[[:>:]]"';

The first query I use it to search partial value. The second query I use it to search exact word.

Iterating over ResultSet and adding its value in an ArrayList

Just for the fun, I'm offering an alternative solution using jOOQ and Java 8. Instead of using jOOQ, you could be using any other API that maps JDBC ResultSet to List, such as Spring JDBC or Apache DbUtils, or write your own ResultSetIterator:

jOOQ 3.8 or less

List<Object> list =
DSL.using(connection)
   .fetch("SELECT col1, col2, col3, ...")
   .stream()
   .flatMap(r -> Arrays.stream(r.intoArray()))
   .collect(Collectors.toList());

jOOQ 3.9

List<Object> list =
DSL.using(connection)
   .fetch("SELECT col1, col2, col3, ...")
   .stream()
   .flatMap(Record::intoStream)
   .collect(Collectors.toList());

(Disclaimer, I work for the company behind jOOQ)

How to trim a string after a specific character in java

you can use StringTokenizer:

StringTokenizer st = new StringTokenizer("34.1 -118.33\n<!--ABCDEFG-->", "\n");
System.out.println(st.nextToken());

output:

34.1 -118.33

how to run or install a *.jar file in windows?

Have you tried (from a command line)

java -jar jbpm-installer-3.2.7.jar

or double clicking it with the mouse ?

Found this and this by googling.

Hope it helps

Adding a newline into a string in C#

Then just modify the previous answers to:

Console.Write(strToProcess.Replace("@", "@" + Environment.NewLine));

If you don't want the newlines in the text file, then don't preserve it.

How to check if an appSettings key exists?

I liked codebender's answer, but needed it to work in C++/CLI. This is what I ended up with. There's no LINQ usage, but works.

generic <typename T> T MyClass::ReadAppSetting(String^ searchKey, T defaultValue) {
  for each (String^ setting in ConfigurationManager::AppSettings->AllKeys) {
    if (setting->Equals(searchKey)) { //  if the key is in the app.config
      try {                           // see if it can be converted
        auto converter = TypeDescriptor::GetConverter((Type^)(T::typeid)); 
        if (converter != nullptr) { return (T)converter->ConvertFromString(ConfigurationManager::AppSettings[searchKey]); }
      } catch (Exception^ ex) {} // nothing to do
    }
  }
  return defaultValue;
}

Convert char * to LPWSTR

You may use CString, CStringA, CStringW to do automatic conversions and convert between these types. Further, you may also use CStrBuf, CStrBufA, CStrBufW to get RAII pattern modifiable strings

JavaScript and getElementById for multiple elements with the same ID

You shouldn't do that and even if it's possible it's not reliable and prone to cause issues.

Reason being that an ID is unique on the page. i.e. you cannot have more than 1 element on the page with the same ID.

What is the official name for a credit card's 3 digit code?

It is called the Card Security Code (CSC) according to Wikipedia, but has also been known as other things, such as the Card Verification Value (CVV) or Card Verfication Code (CVC).

The second code, and the most cited, is CVV2 or CVC2. This CSC (also known as a CCID or Credit Card ID) is often asked for by merchants for them to secure "card not present" transactions occurring over the Internet, by mail, fax or over the phone. In many countries in Western Europe, due to increased attempts at card fraud, it is now mandatory to provide this code when the cardholder is not present in person.

Because this seems to be known by multiple names, and its name doesn't seem to be printed on the card itself, you'll probably (unfortunately) still need to tell your users how to find the code - ie by describing it as the "3 digit code on back of card".


2018 update

The situation has not improved, and is now worse - there are even more different names now. However, you can if you like use different terms depending on the card type:

  • "CVC2" or "Card Validation Code" – MasterCard
  • "CVV2" or "Card Verification Value 2" – Visa
  • "CSC" or "Card Security Code" – American Express

Note that some American Express and Discover cards use a 4-digit code on the front of the card. See the above linked Wikipedia article for more.

How can I dismiss the on screen keyboard?

You can use unfocus() method from FocusNode class.

import 'package:flutter/material.dart';

class MyHomePage extends StatefulWidget {
  MyHomePageState createState() => new MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  TextEditingController _controller = new TextEditingController();
  FocusNode _focusNode = new FocusNode(); //1 - declare and initialize variable

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.send),
        onPressed: () {
            _focusNode.unfocus(); //3 - call this method here
        },
      ),
      body: new Container(
        alignment: FractionalOffset.center,
        padding: new EdgeInsets.all(20.0),
        child: new TextFormField(
          controller: _controller,
          focusNode: _focusNode, //2 - assign it to your TextFormField
          decoration: new InputDecoration(labelText: 'Example Text'),
        ),
      ),
    );
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

void main() {
  runApp(new MyApp());
}

Mongod complains that there is no /data/db folder

You need to create /data/db ... that is a directory called /data/ in your root (i.e. /) and subfolder in there called /db/ ...

You're getting permission errors becuase you need to use sudo to create a direcotry in your root dir in MacOS, sudo lets you run commands as an administrator.

So, run this instead ...

$ sudo mkdir -p /data/db

This will prompt you for a password, it's the same password you use to change system settings (that little dialog that opens when you try and change things in System Preferences for ecample), and likely the same as you use to login.

Can I scale a div's height proportionally to its width using CSS?

You can do it with the help of padding on a parent item, because relative padding (even height-wise) is based on the width of the parent element.

CSS:

.imageContainer {
    position: relative;
    width: 25%;
    padding-bottom: 25%;
    float: left;
    height: 0;
}

img {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
}

This is based on this article: Proportional scaling of responsive boxes using just CSS

Change div width live with jQuery

There are two ways to do this:

CSS: Use width as %, like 75%, so the width of the div will change automatically when user resizes the browser.

Javascipt: Use resize event

$(window).bind('resize', function()
{
    if($(window).width() > 500)
        $('#divID').css('width', '300px');
    else
        $('divID').css('width', '200px');
});

Hope this will help you :)

"inappropriate ioctl for device"

Eureka moment!

I have had this error before.

Did you invoke the perl debugger with something like :-

perl -d yourprog.pl > log.txt

If so whats going on is perl debug tries to query and perhaps reset the terminal width. When stdout is not a terminal this fails with the IOCTL message.

The alternative would be for your debug session to hang forever because you did not see the prompt for instructions.

How to convert a normal Git repository to a bare one?

I just wanted to push to a repository on a network path but git would not let me do that unless that repository was marked as bare. All I needed was to change its config:

git config --bool core.bare true

No need to fiddle with the files unless you want to keep it clean.

'profile name is not valid' error when executing the sp_send_dbmail command

You need to grant the user or group rights to use the profile. They need to be added to the msdb database and then you will see them available in the mail wizard when you are maintaining security for mail.

Read up the security here: http://msdn.microsoft.com/en-us/library/ms175887.aspx

See a listing of mail procedures here: http://msdn.microsoft.com/en-us/library/ms177580.aspx

Example script for 'TestUser' to use the profile named 'General Admin Mail'.


USE [msdb]
GO
CREATE USER [TestUser] FOR LOGIN [testuser]
GO
USE [msdb]
GO
EXEC sp_addrolemember N'DatabaseMailUserRole', N'TestUser'
GO

EXECUTE msdb.dbo.sysmail_add_principalprofile_sp
    @profile_name = 'General Admin Mail',
    @principal_name = 'TestUser',
    @is_default = 1 ;

I can't understand why this JAXB IllegalAnnotationException is thrown

This is because, by default, Jaxb when serializes a pojo, looks for the annotations over the public members(getters or setters) of the properties. But, you are providing annotations on fields. so, either change and set the annotations on setters or getters of properties, or sets the XmlAccessortype to field.

Option 1::

@XmlRootElement(name = "fields")
@XmlAccessorType(XmlAccessType.FIELD)
public class Fields {

        @XmlElement(name = "field")
        List<Field> fields = new ArrayList<Field>();
        //getter, setter
}

@XmlAccessorType(XmlAccessType.FIELD)
public class Field {

       @XmlAttribute(name = "mappedField")
       String mappedField;
       //getter,setter
}

Option 2::

@XmlRootElement(name = "fields")
public class Fields {

        List<Field> fields = new ArrayList<Field>();

        @XmlElement(name = "field")
        public List<Field> getFields() {

        }

        //setter
}

@XmlAccessorType(XmlAccessType.FIELD)
public class Field {

       String mappedField;

       @XmlAttribute(name = "mappedField")
       public String getMappedField() {

       }

        //setter
}

For more detail and depth, check the following JDK documentation http://docs.oracle.com/javase/6/docs/api/javax/xml/bind/annotation/XmlAccessorType.html

Remove the string on the beginning of an URL

Another way:

Regex.Replace(urlString, "www.(.+)", "$1");

MIN and MAX in C

It's worth pointing out I think that if you define min and max with the ternary operation such as

#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)>(b))?(a):(b))

then to get the same result for the special case of fmin(-0.0,0.0) and fmax(-0.0,0.0) you need to swap the arguments

fmax(a,b) = MAX(a,b)
fmin(a,b) = MIN(b,a)

newline character in c# string

They might be just a \r or a \n. I just checked and the text visualizer in VS 2010 displays both as newlines as well as \r\n.

This string

string test = "blah\r\nblah\rblah\nblah";

Shows up as

blah
blah
blah
blah

in the text visualizer.

So you could try

string modifiedString = originalString
    .Replace(Environment.NewLine, "<br />")
    .Replace("\r", "<br />")
    .Replace("\n", "<br />");

How to convert a PNG image to a SVG?

A png is a bitmap image style and an SVG is a vector-based graphics design which supports bitmaps so it's not as if it would convert the image to vectors, just an image embedded in a vector-based format. You could do this using http://www.inkscape.org/ which is free. It would embed it, however it also has a Live Trace like engine which will try to convert it to paths if you wish (using potrace). See live trace in adobe illustrator (commericial) is an example:

http://graphicssoft.about.com/od/illustrator/ss/sflivetrace.htm

Android - How to achieve setOnClickListener in Kotlin?

You can use setOnClickListener like this in Kotlin

button.setOnClickListener(View.OnClickListener {        
       //code
})

How to get maximum value from the Collection (for example ArrayList)?

In addition to gotomanners answer, in case anyone else came here looking for a null safe solution to the same problem, this is what I ended up with

Collections.max(arrayList, Comparator.nullsFirst(Comparator.naturalOrder()))

How to re-create database for Entity Framework?

A possible very simple fix that worked for me. After deleting any database references and connections you find in server/serverobject explorer, right click the App_Data folder (didn't show any objects within the application for me) and select open. Once open put all the database/etc. files in a backup folder or if you have the guts just delete them. Run your application and it should recreate everything from scratch.

How do I deploy Node.js applications as a single executable file?

You could create a git repo and setup a link to the node git repo as a dependency. Then any user who clones the repo could also install node.

#git submodule [--quiet] add [-b branch] [-f|--force]
git submodule add /var/Node-repo.git common

You could easily package a script up to automatically clone the git repo you have hosted somewhere and "install" from one that one script file.

#!/bin/sh
#clone git repo
git clone your-repo.git

How do I bind to list of checkbox values with AngularJS?

There are two ways to approach this problem. Either use a simple array or an array of objects. Each solution has it pros and cons. Below you'll find one for each case.


With a simple array as input data

The HTML could look like:

<label ng-repeat="fruitName in fruits">
  <input
    type="checkbox"
    name="selectedFruits[]"
    value="{{fruitName}}"
    ng-checked="selection.indexOf(fruitName) > -1"
    ng-click="toggleSelection(fruitName)"
  > {{fruitName}}
</label>

And the appropriate controller code would be:

app.controller('SimpleArrayCtrl', ['$scope', function SimpleArrayCtrl($scope) {

  // Fruits
  $scope.fruits = ['apple', 'orange', 'pear', 'naartjie'];

  // Selected fruits
  $scope.selection = ['apple', 'pear'];

  // Toggle selection for a given fruit by name
  $scope.toggleSelection = function toggleSelection(fruitName) {
    var idx = $scope.selection.indexOf(fruitName);

    // Is currently selected
    if (idx > -1) {
      $scope.selection.splice(idx, 1);
    }

    // Is newly selected
    else {
      $scope.selection.push(fruitName);
    }
  };
}]);

Pros: Simple data structure and toggling by name is easy to handle

Cons: Add/remove is cumbersome as two lists (the input and selection) have to be managed


With an object array as input data

The HTML could look like:

<label ng-repeat="fruit in fruits">
  <!--
    - Use `value="{{fruit.name}}"` to give the input a real value, in case the form gets submitted
      traditionally

    - Use `ng-checked="fruit.selected"` to have the checkbox checked based on some angular expression
      (no two-way-data-binding)

    - Use `ng-model="fruit.selected"` to utilize two-way-data-binding. Note that `.selected`
      is arbitrary. The property name could be anything and will be created on the object if not present.
  -->
  <input
    type="checkbox"
    name="selectedFruits[]"
    value="{{fruit.name}}"
    ng-model="fruit.selected"
  > {{fruit.name}}
</label>

And the appropriate controller code would be:

app.controller('ObjectArrayCtrl', ['$scope', 'filterFilter', function ObjectArrayCtrl($scope, filterFilter) {

  // Fruits
  $scope.fruits = [
    { name: 'apple',    selected: true },
    { name: 'orange',   selected: false },
    { name: 'pear',     selected: true },
    { name: 'naartjie', selected: false }
  ];

  // Selected fruits
  $scope.selection = [];

  // Helper method to get selected fruits
  $scope.selectedFruits = function selectedFruits() {
    return filterFilter($scope.fruits, { selected: true });
  };

  // Watch fruits for changes
  $scope.$watch('fruits|filter:{selected:true}', function (nv) {
    $scope.selection = nv.map(function (fruit) {
      return fruit.name;
    });
  }, true);
}]);

Pros: Add/remove is very easy

Cons: Somewhat more complex data structure and toggling by name is cumbersome or requires a helper method


Demo: http://jsbin.com/ImAqUC/1/

What is the best way to tell if a character is a letter or number in Java without using regexes?

Use the below code

Character.isLetterOrDigit(string.charAt(index))

make image( not background img) in div repeat?

You have use to repeat-y as style="background-repeat:repeat-y;width: 200px;" instead of style="repeat-y".

Try this inside the image tag or you can use the below css for the div

.div_backgrndimg
{
    background-repeat: repeat-y;
    background-image: url("/image/layout/lotus-dreapta.png");
    width:200px;
}

library not found for -lPods

I was renaming the project to "NBSelector" from "Partners".

I had "Library not found for libPods-Partners" error after renaming the project. Xcode was trying to link to old Partners.a file. Just remove it if you have podInstalled after renaming.

enter image description here

How to part DATE and TIME from DATETIME in MySQL

per the mysql documentation, the DATE() function will pull the date part of a datetime feild, and TIME() for the time portion. so I would try:

select DATE(dateTimeField) as Date, TIME(dateTimeField) as Time, col2, col3, FROM Table1 ...

C++ Returning reference to local variable

This code snippet:

int& func1()
{
    int i;
    i = 1;
    return i;
}

will not work because you're returning an alias (a reference) to an object with a lifetime limited to the scope of the function call. That means once func1() returns, int i dies, making the reference returned from the function worthless because it now refers to an object that doesn't exist.

int main()
{
    int& p = func1();
    /* p is garbage */
}

The second version does work because the variable is allocated on the free store, which is not bound to the lifetime of the function call. However, you are responsible for deleteing the allocated int.

int* func2()
{
    int* p;
    p = new int;
    *p = 1;
    return p;
}

int main()
{
    int* p = func2();
    /* pointee still exists */
    delete p; // get rid of it
}

Typically you would wrap the pointer in some RAII class and/or a factory function so you don't have to delete it yourself.

In either case, you can just return the value itself (although I realize the example you provided was probably contrived):

int func3()
{
    return 1;
}

int main()
{
    int v = func3();
    // do whatever you want with the returned value
}

Note that it's perfectly fine to return big objects the same way func3() returns primitive values because just about every compiler nowadays implements some form of return value optimization:

class big_object 
{ 
public:
    big_object(/* constructor arguments */);
    ~big_object();
    big_object(const big_object& rhs);
    big_object& operator=(const big_object& rhs);
    /* public methods */
private:
    /* data members */
};

big_object func4()
{
    return big_object(/* constructor arguments */);
}

int main()
{
     // no copy is actually made, if your compiler supports RVO
    big_object o = func4();    
}

Interestingly, binding a temporary to a const reference is perfectly legal C++.

int main()
{
    // This works! The returned temporary will last as long as the reference exists
    const big_object& o = func4();    
    // This does *not* work! It's not legal C++ because reference is not const.
    // big_object& o = func4();  
}

How can I build multiple submit buttons django form?

It's an old question now, nevertheless I had the same issue and found a solution that works for me: I wrote MultiRedirectMixin.

from django.http import HttpResponseRedirect

class MultiRedirectMixin(object):
    """
    A mixin that supports submit-specific success redirection.
     Either specify one success_url, or provide dict with names of 
     submit actions given in template as keys
     Example: 
       In template:
         <input type="submit" name="create_new" value="Create"/>
         <input type="submit" name="delete" value="Delete"/>
       View:
         MyMultiSubmitView(MultiRedirectMixin, forms.FormView):
             success_urls = {"create_new": reverse_lazy('create'),
                               "delete": reverse_lazy('delete')}
    """
    success_urls = {}  

    def form_valid(self, form):
        """ Form is valid: Pick the url and redirect.
        """

        for name in self.success_urls:
            if name in form.data:
                self.success_url = self.success_urls[name]
                break

        return HttpResponseRedirect(self.get_success_url())

    def get_success_url(self):
        """
        Returns the supplied success URL.
        """
        if self.success_url:
            # Forcing possible reverse_lazy evaluation
            url = force_text(self.success_url)
        else:
            raise ImproperlyConfigured(
                _("No URL to redirect to. Provide a success_url."))
        return url

How to convert map to url query string?

Another 'one class'/no dependency way of doing it, handling single/multiple:

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class UrlQueryString {
  private static final String DEFAULT_ENCODING = "UTF-8";

  public static String buildQueryString(final LinkedHashMap<String, Object> map) {
    try {
      final Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
      final StringBuilder sb = new StringBuilder(map.size() * 8);
      while (it.hasNext()) {
        final Map.Entry<String, Object> entry = it.next();
        final String key = entry.getKey();
        if (key != null) {
          sb.append(URLEncoder.encode(key, DEFAULT_ENCODING));
          sb.append('=');
          final Object value = entry.getValue();
          final String valueAsString = value != null ? URLEncoder.encode(value.toString(), DEFAULT_ENCODING) : "";
          sb.append(valueAsString);
          if (it.hasNext()) {
            sb.append('&');
          }
        } else {
          // Do what you want...for example:
          assert false : String.format("Null key in query map: %s", map.entrySet());
        }
      }
      return sb.toString();
    } catch (final UnsupportedEncodingException e) {
      throw new UnsupportedOperationException(e);
    }
  }

  public static String buildQueryStringMulti(final LinkedHashMap<String, List<Object>> map) {
    try {
      final StringBuilder sb = new StringBuilder(map.size() * 8);
      for (final Iterator<Entry<String, List<Object>>> mapIterator = map.entrySet().iterator(); mapIterator.hasNext();) {
        final Entry<String, List<Object>> entry = mapIterator.next();
        final String key = entry.getKey();
        if (key != null) {
          final String keyEncoded = URLEncoder.encode(key, DEFAULT_ENCODING);
          final List<Object> values = entry.getValue();
          sb.append(keyEncoded);
          sb.append('=');
          if (values != null) {
            for (final Iterator<Object> listIt = values.iterator(); listIt.hasNext();) {
              final Object valueObject = listIt.next();
              sb.append(valueObject != null ? URLEncoder.encode(valueObject.toString(), DEFAULT_ENCODING) : "");
              if (listIt.hasNext()) {
                sb.append('&');
                sb.append(keyEncoded);
                sb.append('=');
              }
            }
          }
          if (mapIterator.hasNext()) {
            sb.append('&');
          }
        } else {
          // Do what you want...for example:
          assert false : String.format("Null key in query map: %s", map.entrySet());
        }
      }
      return sb.toString();
    } catch (final UnsupportedEncodingException e) {
      throw new UnsupportedOperationException(e);
    }
  }

  public static void main(final String[] args) {
    // Examples: could be turned into unit tests ...
    {
      final LinkedHashMap<String, Object> queryItems = new LinkedHashMap<String, Object>();
      queryItems.put("brand", "C&A");
      queryItems.put("count", null);
      queryItems.put("misc", 42);
      final String buildQueryString = buildQueryString(queryItems);
      System.out.println(buildQueryString);
    }
    {
      final LinkedHashMap<String, List<Object>> queryItems = new LinkedHashMap<String, List<Object>>();
      queryItems.put("usernames", new ArrayList<Object>(Arrays.asList(new String[] { "bob", "john" })));
      queryItems.put("nullValue", null);
      queryItems.put("misc", new ArrayList<Object>(Arrays.asList(new Integer[] { 1, 2, 3 })));
      final String buildQueryString = buildQueryStringMulti(queryItems);
      System.out.println(buildQueryString);
    }
  }
}

You may use either simple (easier to write in most cases) or multiple when required. Note that both can be combined by adding an ampersand... If you find any problems let me know in the comments.

how to convert .java file to a .class file

From the command line, run

javac ClassName.java

error: expected declaration or statement at end of input in c

Try to place a

return 0;

on the end of your code or just erase the

void

from your main function I hope that I helped

pgadmin4 : postgresql application server could not be contacted.

I had this problem with pgadmin4 v2.1 on linux fedora 27

Solved by installing a missing dependency: python3-flask-babelex

How to open standard Google Map application from my application?

Also, you can use external_app_launcher: https://pub.dev/packages/external_app_launcher

To know if is installed:

await LaunchApp.isAppInstalled(androidPackageName: 'com.google.android.maps.MapView', iosUrlScheme: 'comgooglemaps://');

To open:

await LaunchApp.openApp(
                    androidPackageName: 'com.google.android.maps.MapView',
                    iosUrlScheme: 'comgooglemaps://',
                  );

document.getElementById().value doesn't set the value

According to my tests with Chrome:

If you set a number input to a Number, then it works fine.

If you set a number input to a String that contains nothing but a number, then it works fine.

If you set a number input to a String that contains a number and some whitespace, then it blanks the input.

You probably have a space or a new line after the data in the server response that you actually care about.

Use document.getElementById("points").value = parseInt(request.responseText, 10); instead.

Generating a random hex color code with PHP

An RGB hex string is just a number from 0x0 through 0xFFFFFF, so simply generate a number in that range and convert it to hexadecimal:

function rand_color() {
    return '#' . str_pad(dechex(mt_rand(0, 0xFFFFFF)), 6, '0', STR_PAD_LEFT);
}

or:

function rand_color() {
    return sprintf('#%06X', mt_rand(0, 0xFFFFFF));
}

Check If array is null or not in php

you can use

empty($result) 

to check if the main array is empty or not.

But since you have a SimpleXMLElement object, you need to query the object if it is empty or not. See http://www.php.net/manual/en/simplexmlelement.count.php

ex:

if (empty($result) || !isset($result['Tags'])) {
    return false;
}
if ( !($result['Tags'] instanceof SimpleXMLElement)) {
    return false;
}
return ($result['Tags']->count());

How to add button in ActionBar(Android)?

An activity populates the ActionBar in its onCreateOptionsMenu() method.

Instead of using setcustomview(), just override onCreateOptionsMenu like this:

@Override    
public boolean onCreateOptionsMenu(Menu menu) {
  MenuInflater inflater = getMenuInflater();
  inflater.inflate(R.menu.mainmenu, menu);
  return true;
}

If an actions in the ActionBar is selected, the onOptionsItemSelected() method is called. It receives the selected action as parameter. Based on this information you code can decide what to do for example:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
  switch (item.getItemId()) {
    case R.id.menuitem1:
      Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT).show();
      break;
    case R.id.menuitem2:
      Toast.makeText(this, "Menu item 2 selected", Toast.LENGTH_SHORT).show();
      break;
  }
  return true;
}

C++ pass an array by reference

Like the other answer says, put the & after the *.

This brings up an interesting point that can be confusing sometimes: types should be read from right to left. For example, this is (starting from the rightmost *) a pointer to a constant pointer to an int.

int * const *x;

What you wrote would therefore be a pointer to a reference, which is not possible.

What is PECS (Producer Extends Consumer Super)?

Using real life example (with some simplifications):

  1. Imagine a freight train with freight cars as analogy to a list.
  2. You can put a cargo in a freight car if the cargo has the same or smaller size than the freight car = <? super FreightCarSize>
  3. You can unload a cargo from a freight car if you have enough place (more than the size of the cargo) in your depot = <? extends DepotSize>

create unique id with javascript

Here's my own take at it based on the xpath of the element created :

/** Returns the XPATH of an element **/
var getPathTo = function(element) {
  if (element===document.body)
      return element.tagName;

  var ix= 0;
  var siblings= element.parentNode.childNodes;
  for (var i= 0; i<siblings.length; i++) {
      var sibling= siblings[i];
      if (sibling===element)
          // stripped xpath (parent xpath + tagname + index)
          return getPathTo(element.parentNode)+ element.tagName + ix+1;
      if (sibling.nodeType===1 && sibling.tagName===element.tagName)
          ix++;
   }
}

/** hashcode function (credit http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery **/
var hashCode = function(str) {
  var hash = 0, i, chr, len;
  if (str.length === 0) return hash;
  for (i = 0, len = str.length; i < len; i++) {
    chr   = str.charCodeAt(i);
    hash  = ((hash << 5) - hash) + chr;
    hash |= 0; // Convert to 32bit integer
 }
return hash;
};

/** Genaretes according to xpath + timestamp **/
var generateUID = function(ele)
{
  return hashCode(getPathTo(ele)) + new Date().getTime();
}

First the xpath of the element is fetched.

The hashcode of the xpath is then computed. We therefore have a unique id per xpath.

The problem here is that xpath are not necesseraly unique if unique elements are generated on the fly. Thus we add the timestamp at the end.

Maybe we could also garantee more unique elements by adding a final Math.Random().

Checking if any elements in one list are in another

Your original approach can work with a list comprehension:

def listCompare():
  list1 = [1, 2, 3, 4, 5]
  list2 = [5, 6, 7, 8, 9]
  if [item for item in list1 if item in list2]:
    print("Number was found")
  else:
    print("Number not in list")

How to get visitor's location (i.e. country) using geolocation?

You can use ip-api.io to get visitor's location. It supports IPv6.

As a bonus it allows to check whether ip address is a tor node, public proxy or spammer.

JavaScript Code:

function getIPDetails() {
    var ipAddress = document.getElementById("txtIP").value;

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            console.log(JSON.parse(xhttp.responseText));
        }
    };
    xhttp.open("GET", "http://ip-api.io/json/" + ipAddress, true);
    xhttp.send();
}

<input type="text" id="txtIP" placeholder="Enter the ip address" />
<button onclick="getIPDetails()">Get IP Details</button>

jQuery Code:

$(document).ready(function () {
        $('#btnGetIpDetail').click(function () {
            if ($('#txtIP').val() == '') {
                alert('IP address is reqired');
                return false;
            }
            $.getJSON("http://ip-api.io/json/" + $('#txtIP').val(),
                 function (result) {
                     alert('Country Name: ' + result.country_name)
                     console.log(result);
                 });
        });
    });

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div>
    <input type="text" id="txtIP" />
    <button id="btnGetIpDetail">Get Location of IP</button>
</div>

How to set recurring schedule for xlsm file using Windows Task Scheduler

Three important steps - How to Task Schedule an excel.xls(m) file

simply:

  1. make sure the .vbs file is correct
  2. set the Action tab correctly in Task Scheduler
  3. don't turn on "Run whether user is logged on or not"

IN MORE DETAIL...

  1. Here is an example .vbs file:

`

'   a .vbs file is just a text file containing visual basic code that has the extension renamed from .txt  to .vbs

'Write Excel.xls  Sheet's full path here
strPath = "C:\RodsData.xlsm" 

'Write the macro name - could try including module name
strMacro = "Update" '    "Sheet1.Macro2" 

'Create an Excel instance and set visibility of the instance
Set objApp = CreateObject("Excel.Application") 
objApp.Visible = True   '   or False 

'Open workbook; Run Macro; Save Workbook with changes; Close; Quit Excel
Set wbToRun = objApp.Workbooks.Open(strPath) 
objApp.Run strMacro     '   wbToRun.Name & "!" & strMacro 
wbToRun.Save 
wbToRun.Close 
objApp.Quit 

'Leaves an onscreen message!
MsgBox strPath & " " & strMacro & " macro and .vbs successfully completed!",         vbInformation 
'

`

  1. In the Action tab (Task Scheduler):

set Program/script: = C:\Windows\System32\cscript.exe

set Add arguments (optional): = C:\MyVbsFile.vbs

  1. Finally, don't turn on "Run whether user is logged on or not".

That should work.

Let me know!

Rod Bowen

Can I scroll a ScrollView programmatically in Android?

I wanted the scrollView to scroll directly after onCreateView() (not after e.g. a button click). To get it to work I needed to use a ViewTreeObserver:

mScrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            mScrollView.post(new Runnable() {
                public void run() {
                    mScrollView.fullScroll(View.FOCUS_DOWN);
                }
            });
        }
    });

But beware that this will be called everytime something gets layouted (e.g if you set a view invisible or similar) so don't forget to remove this listener if you don't need it anymore with:

public void removeGlobalOnLayoutListener (ViewTreeObserver.OnGlobalLayoutListener victim) on SDK Lvl < 16

or

public void removeOnGlobalLayoutListener (ViewTreeObserver.OnGlobalLayoutListener victim) in SDK Lvl >= 16

push_back vs emplace_back

emplace_back conforming implementation will forward arguments to the vector<Object>::value_typeconstructor when added to the vector. I recall Visual Studio didn't support variadic templates, but with variadic templates will be supported in Visual Studio 2013 RC, so I guess a conforming signature will be added.

With emplace_back, if you forward the arguments directly to vector<Object>::value_type constructor, you don't need a type to be movable or copyable for emplace_back function, strictly speaking. In the vector<NonCopyableNonMovableObject> case, this is not useful, since vector<Object>::value_type needs a copyable or movable type to grow.

But note that this could be useful for std::map<Key, NonCopyableNonMovableObject>, since once you allocate an entry in the map, it doesn't need to be moved or copied ever anymore, unlike with vector, meaning that you can use std::map effectively with a mapped type that is neither copyable nor movable.

Open a new tab in the background?

I did exactly what you're looking for in a very simple way. It is perfectly smooth in Google Chrome and Opera, and almost perfect in Firefox and Safari. Not tested in IE.


function newTab(url)
{
    var tab=window.open("");
    tab.document.write("<!DOCTYPE html><html>"+document.getElementsByTagName("html")[0].innerHTML+"</html>");
    tab.document.close();
    window.location.href=url;
}

Fiddle : http://jsfiddle.net/tFCnA/show/

Explanations:
Let's say there is windows A1 and B1 and websites A2 and B2.
Instead of opening B2 in B1 and then return to A1, I open B2 in A1 and re-open A2 in B1.
(Another thing that makes it work is that I don't make the user re-download A2, see line 4)


The only thing you may doesn't like is that the new tab opens before the main page.

Best way to get whole number part of a Decimal number

By the way guys, (int)Decimal.MaxValue will overflow. You can't get the "int" part of a decimal because the decimal is too friggen big to put in the int box. Just checked... its even too big for a long (Int64).

If you want the bit of a Decimal value to the LEFT of the dot, you need to do this:

Math.Truncate(number)

and return the value as... A DECIMAL or a DOUBLE.

edit: Truncate is definitely the correct function!

How to grant remote access permissions to mysql server for user?

Ubuntu 18.04

Install and ensure mysqld us running..

Go into database and setup root user:

sudo mysql -u root
SELECT User,Host FROM mysql.user;
DROP USER 'root'@'localhost';
CREATE USER 'root'@'%' IDENTIFIED BY 'obamathelongleggedmacdaddy';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
exit;

Edit mysqld permissions and restart:

sudo vi /etc/mysql/mysql.conf.d/mysqld.cnf

# edit the line to be this:
bind-address=0.0.0.0

sudo systemctl stop mysql
sudo systemctl start mysql

From another machine, test.. Obvs port (3306) on mysqld machine must allow connection from test machine.

mysql -u root -p -h 123.456.789.666

All the additional "security" of MySql doesn't help security at all, it just complicates and obfuscates, it is now actually easier to screw it up than in the old days, where you just used a really long password.

How to change the sender's name or e-mail address in mutt?

One special case for this is if you have used a construction like the following in your ~/.muttrc:

# Reset From email to default
send-hook . "my_hdr From: Real Name <[email protected]>"

This send-hook will override either of these:

mutt -e "set [email protected]"
mutt -e "my_hdr From: Other Name <[email protected]>"

Your emails will still go out with the header:

From: Real Name <[email protected]>

In this case, the only command line solution I've found is actually overriding the send-hook itself:

mutt -e "send-hook . \"my_hdr From: Other Name <[email protected]>\""

Early exit from function?

If you are using jquery. This should stop the function from bubbling up to so the parent function calling this should stop as well.

  function myfunction(e)
  {
       e.stopImmediatePropagation();
       ................
  }

How to create war files

We use Maven (Ant's big brother) for all our java projects, and it has a very nifty WAR plugin. Tutorials and usage can be found there.

It's a lot easier than Ant, fully compatible with Eclipse (use maven eclipse:eclipse to create Eclipse projects) and easy to configure.

Maven's homepage

Maven WAR plugin

Sample Configuration:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.1-alpha-2</version>
    <configuration>
        <outputDirectory>${project.build.directory}/tmp/</outputDirectory>
        <workDirectory>${project.build.directory}/tmp/war/work</workDirectory>
        <webappDirectory>${project.build.webappDirectory}</webappDirectory>
        <cacheFile>${project.build.directory}/tmp/war/work/webapp-cache.xml</cacheFile>
        <nonFilteredFileExtensions>
            <nonFilteredFileExtension>pdf</nonFilteredFileExtension>
            <nonFilteredFileExtension>png</nonFilteredFileExtension>
            <nonFilteredFileExtension>gif</nonFilteredFileExtension>
            <nonFilteredFileExtension>jsp</nonFilteredFileExtension>
        </nonFilteredFileExtensions>
        <webResources>
            <resource>
                <directory>src/main/webapp/</directory>
                <targetPath>WEB-INF</targetPath>
                <filtering>true</filtering>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </webResources>
        <warName>Application</warName>
    </configuration>
</plugin>

Java: how do I get a class literal from a generic type?

Well as we all know that it gets erased. But it can be known under some circumstances where the type is explicitly mentioned in the class hierarchy:

import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

public abstract class CaptureType<T> {
    /**
     * {@link java.lang.reflect.Type} object of the corresponding generic type. This method is useful to obtain every kind of information (including annotations) of the generic type.
     *
     * @return Type object. null if type could not be obtained (This happens in case of generic type whose information cant be obtained using Reflection). Please refer documentation of {@link com.types.CaptureType}
     */
    public Type getTypeParam() {
        Class<?> bottom = getClass();
        Map<TypeVariable<?>, Type> reifyMap = new LinkedHashMap<>();

        for (; ; ) {
            Type genericSuper = bottom.getGenericSuperclass();
            if (!(genericSuper instanceof Class)) {
                ParameterizedType generic = (ParameterizedType) genericSuper;
                Class<?> actualClaz = (Class<?>) generic.getRawType();
                TypeVariable<? extends Class<?>>[] typeParameters = actualClaz.getTypeParameters();
                Type[] reified = generic.getActualTypeArguments();
                assert (typeParameters.length != 0);
                for (int i = 0; i < typeParameters.length; i++) {
                    reifyMap.put(typeParameters[i], reified[i]);
                }
            }

            if (bottom.getSuperclass().equals(CaptureType.class)) {
                bottom = bottom.getSuperclass();
                break;
            }
            bottom = bottom.getSuperclass();
        }

        TypeVariable<?> var = bottom.getTypeParameters()[0];
        while (true) {
            Type type = reifyMap.get(var);
            if (type instanceof TypeVariable) {
                var = (TypeVariable<?>) type;
            } else {
                return type;
            }
        }
    }

    /**
     * Returns the raw type of the generic type.
     * <p>For example in case of {@code CaptureType<String>}, it would return {@code Class<String>}</p>
     * For more comprehensive examples, go through javadocs of {@link com.types.CaptureType}
     *
     * @return Class object
     * @throws java.lang.RuntimeException If the type information cant be obtained. Refer documentation of {@link com.types.CaptureType}
     * @see com.types.CaptureType
     */
    public Class<T> getRawType() {
        Type typeParam = getTypeParam();
        if (typeParam != null)
            return getClass(typeParam);
        else throw new RuntimeException("Could not obtain type information");
    }


    /**
     * Gets the {@link java.lang.Class} object of the argument type.
     * <p>If the type is an {@link java.lang.reflect.ParameterizedType}, then it returns its {@link java.lang.reflect.ParameterizedType#getRawType()}</p>
     *
     * @param type The type
     * @param <A>  type of class object expected
     * @return The Class<A> object of the type
     * @throws java.lang.RuntimeException If the type is a {@link java.lang.reflect.TypeVariable}. In such cases, it is impossible to obtain the Class object
     */
    public static <A> Class<A> getClass(Type type) {
        if (type instanceof GenericArrayType) {
            Type componentType = ((GenericArrayType) type).getGenericComponentType();
            Class<?> componentClass = getClass(componentType);
            if (componentClass != null) {
                return (Class<A>) Array.newInstance(componentClass, 0).getClass();
            } else throw new UnsupportedOperationException("Unknown class: " + type.getClass());
        } else if (type instanceof Class) {
            Class claz = (Class) type;
            return claz;
        } else if (type instanceof ParameterizedType) {
            return getClass(((ParameterizedType) type).getRawType());
        } else if (type instanceof TypeVariable) {
            throw new RuntimeException("The type signature is erased. The type class cant be known by using reflection");
        } else throw new UnsupportedOperationException("Unknown class: " + type.getClass());
    }

    /**
     * This method is the preferred method of usage in case of complex generic types.
     * <p>It returns {@link com.types.TypeADT} object which contains nested information of the type parameters</p>
     *
     * @return TypeADT object
     * @throws java.lang.RuntimeException If the type information cant be obtained. Refer documentation of {@link com.types.CaptureType}
     */
    public TypeADT getParamADT() {
        return recursiveADT(getTypeParam());
    }

    private TypeADT recursiveADT(Type type) {
        if (type instanceof Class) {
            return new TypeADT((Class<?>) type, null);
        } else if (type instanceof ParameterizedType) {
            ArrayList<TypeADT> generic = new ArrayList<>();
            ParameterizedType type1 = (ParameterizedType) type;
            return new TypeADT((Class<?>) type1.getRawType(),
                    Arrays.stream(type1.getActualTypeArguments()).map(x -> recursiveADT(x)).collect(Collectors.toList()));
        } else throw new UnsupportedOperationException();
    }

}

public class TypeADT {
    private final Class<?> reify;
    private final List<TypeADT> parametrized;

    TypeADT(Class<?> reify, List<TypeADT> parametrized) {
        this.reify = reify;
        this.parametrized = parametrized;
    }

    public Class<?> getRawType() {
        return reify;
    }

    public List<TypeADT> getParameters() {
        return parametrized;
    }
}

And now you can do things like:

static void test1() {
        CaptureType<String> t1 = new CaptureType<String>() {
        };
        equals(t1.getRawType(), String.class);
    }

    static void test2() {
        CaptureType<List<String>> t1 = new CaptureType<List<String>>() {
        };
        equals(t1.getRawType(), List.class);
        equals(t1.getParamADT().getParameters().get(0).getRawType(), String.class);
    }


    private static void test3() {
            CaptureType<List<List<String>>> t1 = new CaptureType<List<List<String>>>() {
            };
            equals(t1.getParamADT().getRawType(), List.class);
        equals(t1.getParamADT().getParameters().get(0).getRawType(), List.class);
    }

    static class Test4 extends CaptureType<List<String>> {
    }

    static void test4() {
        Test4 test4 = new Test4();
        equals(test4.getParamADT().getRawType(), List.class);
    }

    static class PreTest5<S> extends CaptureType<Integer> {
    }

    static class Test5 extends PreTest5<Integer> {
    }

    static void test5() {
        Test5 test5 = new Test5();
        equals(test5.getTypeParam(), Integer.class);
    }

    static class PreTest6<S> extends CaptureType<S> {
    }

    static class Test6 extends PreTest6<Integer> {
    }

    static void test6() {
        Test6 test6 = new Test6();
        equals(test6.getTypeParam(), Integer.class);
    }



    class X<T> extends CaptureType<T> {
    }

    class Y<A, B> extends X<B> {
    }

    class Z<Q> extends Y<Q, Map<Integer, List<List<List<Integer>>>>> {
    }

    void test7(){
        Z<String> z = new Z<>();
        TypeADT param = z.getParamADT();
        equals(param.getRawType(), Map.class);
        List<TypeADT> parameters = param.getParameters();
        equals(parameters.get(0).getRawType(), Integer.class);
        equals(parameters.get(1).getRawType(), List.class);
        equals(parameters.get(1).getParameters().get(0).getRawType(), List.class);
        equals(parameters.get(1).getParameters().get(0).getParameters().get(0).getRawType(), List.class);
        equals(parameters.get(1).getParameters().get(0).getParameters().get(0).getParameters().get(0).getRawType(), Integer.class);
    }




    static void test8() throws IllegalAccessException, InstantiationException {
        CaptureType<int[]> type = new CaptureType<int[]>() {
        };
        equals(type.getRawType(), int[].class);
    }

    static void test9(){
        CaptureType<String[]> type = new CaptureType<String[]>() {
        };
        equals(type.getRawType(), String[].class);
    }

    static class SomeClass<T> extends CaptureType<T>{}
    static void test10(){
        SomeClass<String> claz = new SomeClass<>();
        try{
            claz.getRawType();
            throw new RuntimeException("Shouldnt come here");
        }catch (RuntimeException ex){

        }
    }

    static void equals(Object a, Object b) {
        if (!a.equals(b)) {
            throw new RuntimeException("Test failed. " + a + " != " + b);
        }
    }

More info here. But again, it is almost impossible to retrieve for:

class SomeClass<T> extends CaptureType<T>{}
SomeClass<String> claz = new SomeClass<>();

where it gets erased.

Beginner Python: AttributeError: 'list' object has no attribute

You need to pass the values of the dict into the Bike constructor before using like that. Or, see the namedtuple -- seems more in line with what you're trying to do.

Referring to a Column Alias in a WHERE Clause

You could refer to column alias but you need to define it using CROSS/OUTER APPLY:

SELECT s.logcount, s.logUserID, s.maxlogtm, c.daysdiff
FROM statslogsummary s
CROSS APPLY (SELECT DATEDIFF(day, s.maxlogtm, GETDATE()) AS daysdiff) c
WHERE c.daysdiff > 120;

DBFiddle Demo

Pros:

  • single definition of expression(easier to maintain/no need of copying-paste)
  • no need for wrapping entire query with CTE/outerquery
  • possibility to refer in WHERE/GROUP BY/ORDER BY
  • possible better performance(single execution)

Duplicate Symbols for Architecture arm64

If you are moving to Xcode 7 or 8 and are opening a really old project, I've encountered this problem:

in SomeConstFile.h

NSString * const kAConstant;

in SomeConstFile.m

NSString *const kAConstant = @"a constant";

Earlier versions of the compiler assumed that the definition in the header file was extern and so including SomeConstFile.h all over the place was fine.

Now you need to explicitly declare these consts as extern:

in SomeConstFile.h

extern NSString * const kAConstant;

PHP filesize MB/KB conversion

I think this is a better approach. Simple and straight forward.

public function sizeFilter( $bytes )
{
    $label = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB' );
    for( $i = 0; $bytes >= 1024 && $i < ( count( $label ) -1 ); $bytes /= 1024, $i++ );
    return( round( $bytes, 2 ) . " " . $label[$i] );
}

How to measure elapsed time in Python?

To get insight on every function calls recursively, do:

%load_ext snakeviz
%%snakeviz

It just takes those 2 lines of code in a Jupyter notebook, and it generates a nice interactive diagram. For example:

enter image description here

Here is the code. Again, the 2 lines starting with % are the only extra lines of code needed to use snakeviz:

# !pip install snakeviz
%load_ext snakeviz
import glob
import hashlib

%%snakeviz

files = glob.glob('*.txt')
def print_files_hashed(files):
    for file in files:
        with open(file) as f:
            print(hashlib.md5(f.read().encode('utf-8')).hexdigest())
print_files_hashed(files)

It also seems possible to run snakeviz outside notebooks. More info on the snakeviz website.

How to enumerate a range of numbers starting at 1

>>> list(enumerate(range(1999, 2005)))[1:]
[(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)]

sending email via php mail function goes to spam

Be careful with your tests. If you in your form you put the same email as the email address which must receive it will be directly in spam :)

Android fade in and fade out with ImageView

I wanted to achieve the same goal as you, so I wrote the following method which does exactly that if you pass it an ImageView and a list of references to image drawables.

ImageView demoImage = (ImageView) findViewById(R.id.DemoImage);
int imagesToShow[] = { R.drawable.image1, R.drawable.image2,R.drawable.image3 };

animate(demoImage, imagesToShow, 0,false);  



  private void animate(final ImageView imageView, final int images[], final int imageIndex, final boolean forever) {

  //imageView <-- The View which displays the images
  //images[] <-- Holds R references to the images to display
  //imageIndex <-- index of the first image to show in images[] 
  //forever <-- If equals true then after the last image it starts all over again with the first image resulting in an infinite loop. You have been warned.

    int fadeInDuration = 500; // Configure time values here
    int timeBetween = 3000;
    int fadeOutDuration = 1000;

    imageView.setVisibility(View.INVISIBLE);    //Visible or invisible by default - this will apply when the animation ends
    imageView.setImageResource(images[imageIndex]);

    Animation fadeIn = new AlphaAnimation(0, 1);
    fadeIn.setInterpolator(new DecelerateInterpolator()); // add this
    fadeIn.setDuration(fadeInDuration);

    Animation fadeOut = new AlphaAnimation(1, 0);
    fadeOut.setInterpolator(new AccelerateInterpolator()); // and this
    fadeOut.setStartOffset(fadeInDuration + timeBetween);
    fadeOut.setDuration(fadeOutDuration);

    AnimationSet animation = new AnimationSet(false); // change to false
    animation.addAnimation(fadeIn);
    animation.addAnimation(fadeOut);
    animation.setRepeatCount(1);
    imageView.setAnimation(animation);

    animation.setAnimationListener(new AnimationListener() {
        public void onAnimationEnd(Animation animation) {
            if (images.length - 1 > imageIndex) {
                animate(imageView, images, imageIndex + 1,forever); //Calls itself until it gets to the end of the array
            }
            else {
                if (forever){
                animate(imageView, images, 0,forever);  //Calls itself to start the animation all over again in a loop if forever = true
                }
            }
        }
        public void onAnimationRepeat(Animation animation) {
            // TODO Auto-generated method stub
        }
        public void onAnimationStart(Animation animation) {
            // TODO Auto-generated method stub
        }
    });
}

Listing only directories using ls in Bash?

To answer the original question, */ has nothing to do with ls per se; it is done by the shell/Bash, in a process known as globbing.

This is why echo */ and ls -d */ output the same elements. (The -d flag makes ls output the directory names and not contents of the directories.)

Eclipse error "Could not find or load main class"

A very simple fix coul’d be delete a commented error in the pom.xml.

I don’t now why, but the error coul’d persist in the pom, even if you comment it. In my case, it was an innecesary scope tag for mockit or whole dependency of mockit, all commented!!! It was sufficent delete the commented lines and save the pom.

Define a struct inside a class in C++

Something like:

class Tree {

 struct node {
   int data;
   node *llink;
   node *rlink;
 };
 .....
 .....
 .....
};

Export to CSV using MVC, C# and jQuery

From a button in view call .click(call some java script). From there call controller method by window.location.href = 'Controller/Method';

In controller either do the database call and get the datatable or call some method get the data from database table to a datatable and then do following,

using (DataTable dt = new DataTable())
                        {
                            sda.Fill(dt);
                            //Build the CSV file data as a Comma separated string.
                            string csv = string.Empty;
                            foreach (DataColumn column in dt.Columns)
                            {
                                //Add the Header row for CSV file.
                                csv += column.ColumnName + ',';
                            }
                            //Add new line.
                            csv += "\r\n";
                            foreach (DataRow row in dt.Rows)
                            {
                                foreach (DataColumn column in dt.Columns)
                                {
                                    //Add the Data rows.
                                    csv += row[column.ColumnName].ToString().Replace(",", ";") + ',';
                                }
                                //Add new line.
                                csv += "\r\n";
                             }
                             //Download the CSV file.
                             Response.Clear();
                             Response.Buffer = true;
                             Response.AddHeader("content-disposition", "attachment;filename=SqlExport"+DateTime.Now+".csv");
                             Response.Charset = "";
                             //Response.ContentType = "application/text";
                             Response.ContentType = "application/x-msexcel";
                             Response.Output.Write(csv);
                             Response.Flush();
                             Response.End();
                           }

How to resolve 'unrecognized selector sent to instance'?

For me, what caused this error was that I accidentally had the same message being sent twice to the same class member. When I right clicked on the button in the gui, I could see the method name twice, and I just deleted one. Newbie mistake in my case for sure, but wanted to get it out there for other newbies to consider.

AFNetworking Post Request

[SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];
[SVProgressHUD show];

NSDictionary *dictParam =@{@"user_id":@"31"};// Add perameter

NSString *URLString =@"your url string";

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
[manager.requestSerializer setValue:strGlobalLoginToken forHTTPHeaderField:@"Authorization"];//strGlobalLoginToken is your login token
//         [manager.requestSerializer setValue:setHeaderEnv forHTTPHeaderField:@"Env"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"application/rss+xml", nil];
[manager POST:URLString parameters:dictParam progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
 {

     NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];

     NSLog(@"Response DICT:%@",response);

     if ([[[[response objectForKey:@"response"] objectAtIndex:0] objectForKey:@"status"] isEqualToString:@"true"])
     {

         for (NSMutableDictionary *dicAll in [[[response objectForKey:@"response"]objectAtIndex:0]objectForKey:@"plans"])
         {
             [yourNsmutableArray addObject:[dicAll mutableCopy]];
         }
         //yourNsmutableArray Nsmutablearray  alloction in view didload

         NSLog(@"yourNsmutableArray  %@",yourNsmutableArray);
     }
     else
     {
         NSLog(@"False");
     }

     [SVProgressHUD dismiss];

 } failure:^(NSURLSessionDataTask  *_Nullable task, NSError  *_Nonnull error)
 {
     NSLog(@"RESPONSE STRING:%@",task.response);
     NSLog(@"error userInfo:%@",error.userInfo);

     NSString *errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
     NSLog(@"URLString :--->>   %@ Error********* %@",URLString,errResponse);

     [SVProgressHUD dismiss];

 }];

How to find the most recent file in a directory using .NET, and without looping?

If you want to search recursively, you can use this beautiful piece of code:

public static FileInfo GetNewestFile(DirectoryInfo directory) {
   return directory.GetFiles()
       .Union(directory.GetDirectories().Select(d => GetNewestFile(d)))
       .OrderByDescending(f => (f == null ? DateTime.MinValue : f.LastWriteTime))
       .FirstOrDefault();                        
}

Just call it the following way:

FileInfo newestFile = GetNewestFile(new DirectoryInfo(@"C:\directory\"));

and that's it. Returns a FileInfo instance or null if the directory is empty.

How to remove duplicate values from a multi-dimensional array in PHP

An alternative to serialize and unique

$test = [
    ['abc','def'],
    ['ghi','jkl'],
    ['mno','pql'],
    ['abc','def'],
    ['ghi','jkl'],
    ['mno','pql'],
];

$result = array_reduce(
    $test,
    function($carry,$item){
        if(!in_array($item,$carry)) {
            array_push($carry,$item);
        }
        return $carry;
    },
    []
);

var_dump($result);

/*
 php unique.php
array(3) {
    [0] =>
        array(2) {
            [0] =>
                string(3) "abc"
            [1] =>
                string(3) "def"
        }
    [1] =>
        array(2) {
            [0] =>
                string(3) "ghi"
            [1] =>
                string(3) "jkl"
        }
    [2] =>
        array(2) {
              [0] =>
                  string(3) "mno"
              [1] =>
                  string(3) "pql"
        }
}

*/

Get a list of all threads currently running in Java

To get a list of threads and their full states using the terminal, you can use the command below:

jstack -l <PID>

Which <PID> is the id of process running on your computer. To get the process id of your java process you can simply run the jps command.

Also, you can analyze your thread dump that produced by jstack in TDAs (Thread Dump Analyzer) such fastthread or spotify thread analyzer tool.

How to get difference between two rows for a column field?

SQL Server 2012 and up support LAG / LEAD functions to access the previous or subsequent row. SQL Server 2005 does not support this (in SQL2005 you need a join or something else).

A SQL 2012 example on this data

/* Prepare */
select * into #tmp
from
(
    select 2  as rowint,      23 as Value
    union select 3,       45
    union select 17,      10
    union select 9,       0
) x


/* The SQL 2012 query */
select rowInt, Value, LEAD(value) over (order by rowInt) - Value  
from #tmp

LEAD(value) will return the value of the next row in respect to the given order in "over" clause.