Programs & Examples On #Uitabview

UITabView is a common misrepresentation of UITabBarController, which is a specialized iOS view controller that manages a radio-style selection interface.

Connect to external server by using phpMyAdmin

using PhpMyAdmin version 4.5.4.1deb2ubuntu2, you can set the variables in /etc/phpmyadmin/config-db.php

so set $dbserver to your server name, e.g. $dbserver='mysql.example.com';

<?php
##
## database access settings in php format
## automatically generated from /etc/dbconfig-common/phpmyadmin.conf
## by /usr/sbin/dbconfig-generate-include
##
## by default this file is managed via ucf, so you shouldn't have to
## worry about manual changes being silently discarded.  *however*,
## you'll probably also want to edit the configuration file mentioned
## above too.
##
$dbuser='phpmyadmin';
$dbpass='P@55w0rd';
$basepath='';
$dbname='phpmyadmin';
$dbserver='localhost';
$dbport='';
$dbtype='mysql';

What is a Python equivalent of PHP's var_dump()?

The closest thing to PHP's var_dump() is pprint() with the getmembers() function in the built-in inspect module:

from inspect import getmembers
from pprint import pprint
pprint(getmembers(yourObj))

Installing PDO driver on MySQL Linux server

At first install necessary PDO parts by running the command

`sudo apt-get install php*-mysql` 

where * is a version name of php like 5.6, 7.0, 7.1, 7.2

After installation you need to mention these two statements

extension=pdo.so
extension=pdo_mysql.so

in your .ini file (uncomment if it is already there) and restart server by command

sudo service apache2 restart

Efficiently updating database using SQLAlchemy ORM

Withough testing, I'd try:

for c in session.query(Stuff).all():
     c.foo = c.foo+1
session.commit()

(IIRC, commit() works without flush()).

I've found that at times doing a large query and then iterating in python can be up to 2 orders of magnitude faster than lots of queries. I assume that iterating over the query object is less efficient than iterating over a list generated by the all() method of the query object.

[Please note comment below - this did not speed things up at all].

PHP cURL not working - WAMP on Windows 7 64 bit

I think cURL doesn't work with WAMP 2.2e. I tried all your solutions, but it still did not work. I got the previous version, (2.2d) and it works.

So just download the previous version :D

Replace tabs with spaces in vim

This got it working for me:

:set tabstop=2 shiftwidth=2 expandtab | retab

When should I use Memcache instead of Memcached?

When using Windows, the comparison is cut short: memcache appears to be the only client available.

Eclipse error: 'Failed to create the Java Virtual Machine'

In my case this problem occured after updating Java from 1.6 to 1.7.

To understand the error, run java.exe in the folder of eclipse.exe. Use parameters from eclipse.ini as it will show which parameter causes the failure.

For example:

F:\Mobile Class\adt-bundle-windows-x86\adt-bundle-windows-x86\eclipse>java -star
tup plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar --launcher.lib
rary plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.200.v20120522-1813
 -product com.android.ide.eclipse.adt.package.product --launcher.XXMaxPermSize 7
68m  -showsplash org.eclipse.platform --launcher.XXMaxPermSize 768m --launcher.d
efaultAction openFile -vm C:\Program Files\Java\jre7\bin\client\jvm.dll -vmargs
-Dosgi.requiredJavaVersion=1.6 -Declipse.buildId=v21.1.0-569685 -Xms40m -Xmx768m

Unrecognized option: -startup
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

So I changed 'startup' swith to 'jar' like below and problem fixed:

F:\Mobile Class\adt-bundle-windows-x86\adt-bundle-windows-x86\eclipse>java -jar
plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar --launcher.library
 plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.200.v20120522-1813 -pr
oduct com.android.ide.eclipse.adt.package.product --launcher.XXMaxPermSize 768m
-showsplash org.eclipse.platform --launcher.XXMaxPermSize 768m --launcher.defaul
tAction openFile -vm C:\Program Files\Java\jre7\bin\client\jvm.dll -vmargs -Dosg
i.requiredJavaVersion=1.6 -Declipse.buildId=v21.1.0-569685 -Xms40m -Xmx768m

How to add multiple values to a dictionary key in python?

How about

a["abc"] = [1, 2]

This will result in:

>>> a
{'abc': [1, 2]}

Is that what you were looking for?

.mp4 file not playing in chrome

After running into the same issue - here're some of my thoughts:

  • due to Chrome removing support for h264, on some machines, mp4 videos encoded with it will either not work (throwing an Parser error when viewing under Firebug/Network tab - consistent with issue submitted here), or crash the browser, depending upon the encoding settings
  • it isn't consistent - it entirely depends upon the codecs installed on the computer - while I didn't encounter this issue on my machine, we did have one in the office where the issue occurred (and thus we used this one for testing)
  • it might to do with Quicktime / divX settings (the machine in question had an older version of Quicktime than my native one - we didn't want to loose our testing pc though, so we didn't update it).

As it affects only Chrome (other browsers work fine with VideoForEverybody solution) the solution I've used is:

for every mp4 file, create a Theora encoded mp4 file (example.mp4 -> example_c.mp4) apply following js:

if (window.chrome)
    $("[type=video\\\/mp4]").each(function()
    {
        $(this).attr('src', $(this).attr('src').replace(".mp4", "_c.mp4"));
    });

Unfortunately it's a bad Chrome hack, but hey, at least it works.

Source: user: eithedog

This also can help: chrome could play html5 mp4 video but html5test said chrome did not support mp4 video codec

Also check your version of crome here: html5test

.NET - Get protocol, host, and port

Very similar to Holger's answer. If you need to grab the URL can do something like:

Uri uri = Context.Request.Url;         
var scheme = uri.Scheme // returns http, https
var scheme2 = uri.Scheme + Uri.SchemeDelimiter; // returns http://, https://
var host = uri.Host; // return www.mywebsite.com
var port = uri.Port; // returns port number

The Uri class provides a whole range of methods, many which I have not listed.

In my instance, I needed to grab LocalHost along with the Port Number, so this is what I did:

var Uri uri = Context.Request.Url;
var host = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port; 

Which successfully grabbed: http://localhost:12345

How can I round a number in JavaScript? .toFixed() returns a string?

It returns a string because 0.1, and powers thereof (which are used to display decimal fractions), are not representable (at least not with full accuracy) in binary floating-point systems.

For example, 0.1 is really 0.1000000000000000055511151231257827021181583404541015625, and 0.01 is really 0.01000000000000000020816681711721685132943093776702880859375. (Thanks to BigDecimal for proving my point. :-P)

Therefore (absent a decimal floating point or rational number type), outputting it as a string is the only way to get it trimmed to exactly the precision required for display.

Select count(*) from result query

This counts the rows of the inner query:

select count(*) from (
    select count(SID) 
    from Test 
    where Date = '2012-12-10' 
    group by SID
) t

However, in this case the effect of that is the same as this:

select count(distinct SID) from Test where Date = '2012-12-10'

Delete the last two characters of the String

You may use the following method to remove last n character -

public String removeLast(String s, int n) {
    if (null != s && !s.isEmpty()) {
        s = s.substring(0, s.length()-n);
    }
    return s;
}

Properties file with a list as the value for an individual key

There's probably a another way or better. But this is how I do this in Spring Boot.

My property file contains the following lines. "," is the delimiter in each line.

mml.pots=STDEP:DETY=LI3;,STDEP:DETY=LIMA;
mml.isdn.grunntengingar=STDEP:DETY=LIBAE;,STDEP:DETY=LIBAMA;
mml.isdn.stofntengingar=STDEP:DETY=LIPRAE;,STDEP:DETY=LIPRAM;,STDEP:DETY=LIPRAGS;,STDEP:DETY=LIPRVGS;

My server config

@Configuration
public class ServerConfig {

    @Inject
    private Environment env;

    @Bean
    public MMLProperties mmlProperties() {
        MMLProperties properties = new MMLProperties();
        properties.setMmmlPots(env.getProperty("mml.pots"));
        properties.setMmmlPots(env.getProperty("mml.isdn.grunntengingar"));
        properties.setMmmlPots(env.getProperty("mml.isdn.stofntengingar"));
        return properties;
    }
}

MMLProperties class.

public class MMLProperties {
    private String mmlPots;
    private String mmlIsdnGrunntengingar;
    private String mmlIsdnStofntengingar;

    public MMLProperties() {
        super();
    }

    public void setMmmlPots(String mmlPots) {
        this.mmlPots = mmlPots;
    }

    public void setMmlIsdnGrunntengingar(String mmlIsdnGrunntengingar) {
        this.mmlIsdnGrunntengingar = mmlIsdnGrunntengingar;
    }

    public void setMmlIsdnStofntengingar(String mmlIsdnStofntengingar) {
        this.mmlIsdnStofntengingar = mmlIsdnStofntengingar;
    }

    // These three public getXXX functions then take care of spliting the properties into List
    public List<String> getMmmlCommandForPotsAsList() {
        return getPropertieAsList(mmlPots);
    }

    public List<String> getMmlCommandsForIsdnGrunntengingarAsList() {
        return getPropertieAsList(mmlIsdnGrunntengingar);
    }

    public List<String> getMmlCommandsForIsdnStofntengingarAsList() {
        return getPropertieAsList(mmlIsdnStofntengingar);
    }

    private List<String> getPropertieAsList(String propertie) {
        return ((propertie != null) || (propertie.length() > 0))
        ? Arrays.asList(propertie.split("\\s*,\\s*"))
        : Collections.emptyList();
    }
}

Then in my Runner class I Autowire MMLProperties

@Component
public class Runner implements CommandLineRunner {

    @Autowired
    MMLProperties mmlProperties;

    @Override
    public void run(String... arg0) throws Exception {
        // Now I can call my getXXX function to retrieve the properties as List
        for (String command : mmlProperties.getMmmlCommandForPotsAsList()) {
            System.out.println(command);
        }
    }
}

Hope this helps

Drag and drop menuitems

jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div (or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.

SQL Server convert select a column and convert it to a string

You can do it like this:

Fiddle demo

declare @results varchar(500)

select @results = coalesce(@results + ',', '') +  convert(varchar(12),col)
from t
order by col

select @results as results

| RESULTS |
-----------
| 1,3,5,9 |

How to set a variable to be "Today's" date in Python/Pandas

You mention you are using Pandas (in your title). If so, there is no need to use an external library, you can just use to_datetime

>>> pandas.to_datetime('today').normalize()
Timestamp('2015-10-14 00:00:00')

This will always return today's date at midnight, irrespective of the actual time, and can be directly used in pandas to do comparisons etc. Pandas always includes 00:00:00 in its datetimes.

Replacing today with now would give you the date in UTC instead of local time; note that in neither case is the tzinfo (timezone) added.

In pandas versions prior to 0.23.x, normalize may not have been necessary to remove the non-midnight timestamp.

sql query distinct with Row_Number

This can be done very simple, you were pretty close already

SELECT distinct id, DENSE_RANK() OVER (ORDER BY  id) AS RowNum
FROM table
WHERE fid = 64

Page redirect with successful Ajax request

I posted the exact situation on a different thread. Re-post.

Excuse me, This is not an answer to the question posted above.

But brings an interesting topic --- WHEN to use AJAX and when NOT to use AJAX. In this case it's good not to use AJAX.

Let's take a simple example of login and password. If the login and/or password does not match it WOULD be nice to use AJAX to report back a simple message saying "Login Incorrect". But if the login and password IS correct, why would I have to callback an AJAX function to redirect to the user page?

In a case like, this I think it would be just nice to use a simple Form SUBMIT. And if the login fails, redirect to Relogin.php which looks same as the Login.php with a GET message in the url like Relogin.php?error=InvalidLogin... something like that...

Just my 2 cents. :)

Button Listener for button in fragment in android

Try this :

FragmentOne.java

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class FragmentOne extends Fragment{

    View rootView;        

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

        rootView = inflater.inflate(R.layout.fragment_one, container, false);


        Button button = (Button) rootView.findViewById(R.id.buttonSayHi);
        button.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                onButtonClicked(v);
            }
        });
        return rootView;
    }

  public void onButtonClicked(View view)
  {
          //do your stuff here..           
    final FragmentTransaction ft = getFragmentManager().beginTransaction(); 
    ft.replace(R.id.frameLayoutFragmentContainer, new FragmentTwo(), "NewFragmentTag"); 
    ft.commit(); 

    ft.addToBackStack(null);    
  }
}

check this : click here

Difference between 3NF and BCNF in simple terms (must be able to explain to an 8-year old)

All good answers. To put it in simple language [BCNF] No partial key can depend on a key.

i.e No partial subset ( i.e any non trivial subset except the full set ) of a candidate key can be functionally dependent on some candidate key.

Understanding implicit in Scala

I'll explain the main use cases of implicits below, but for more detail see the relevant chapter of Programming in Scala.

Implicit parameters

The final parameter list on a method can be marked implicit, which means the values will be taken from the context in which they are called. If there is no implicit value of the right type in scope, it will not compile. Since the implicit value must resolve to a single value and to avoid clashes, it's a good idea to make the type specific to its purpose, e.g. don't require your methods to find an implicit Int!

example:

  // probably in a library
class Prefixer(val prefix: String)
def addPrefix(s: String)(implicit p: Prefixer) = p.prefix + s

  // then probably in your application
implicit val myImplicitPrefixer = new Prefixer("***")
addPrefix("abc")  // returns "***abc"

Implicit conversions

When the compiler finds an expression of the wrong type for the context, it will look for an implicit Function value of a type that will allow it to typecheck. So if an A is required and it finds a B, it will look for an implicit value of type B => A in scope (it also checks some other places like in the B and A companion objects, if they exist). Since defs can be "eta-expanded" into Function objects, an implicit def xyz(arg: B): A will do as well.

So the difference between your methods is that the one marked implicit will be inserted for you by the compiler when a Double is found but an Int is required.

implicit def doubleToInt(d: Double) = d.toInt
val x: Int = 42.0

will work the same as

def doubleToInt(d: Double) = d.toInt
val x: Int = doubleToInt(42.0)

In the second we've inserted the conversion manually; in the first the compiler did the same automatically. The conversion is required because of the type annotation on the left hand side.


Regarding your first snippet from Play:

Actions are explained on this page from the Play documentation (see also API docs). You are using

apply(block: (Request[AnyContent]) ? Result): Action[AnyContent]

on the Action object (which is the companion to the trait of the same name).

So we need to supply a Function as the argument, which can be written as a literal in the form

request => ...

In a function literal, the part before the => is a value declaration, and can be marked implicit if you want, just like in any other val declaration. Here, request doesn't have to be marked implicit for this to type check, but by doing so it will be available as an implicit value for any methods that might need it within the function (and of course, it can be used explicitly as well). In this particular case, this has been done because the bindFromRequest method on the Form class requires an implicit Request argument.

Assign output of a program to a variable using a MS batch file

In addition to the answer, you can't directly use output redirection operators in the set part of for loop (e.g. if you wanna hide stderror output from a user and provide a nicer error message). Instead, you have to escape them with a caret character (^):

for /f %%O in ('some-erroring-command 2^> nul') do (echo %%O)

Reference: Redirect output of command in for loop of batch script

How to get values of selected items in CheckBoxList with foreach in ASP.NET C#?

Note that I prefer the code to be short.

List<ListItem> selected = CBLGold.Items.Cast<ListItem>()
    .Where(li => li.Selected)
    .ToList();

or with a simple foreach:

List<ListItem> selected = new List<ListItem>();
foreach (ListItem item in CBLGold.Items)
    if (item.Selected) selected.Add(item);

If you just want the ListItem.Value:

List<string> selectedValues = CBLGold.Items.Cast<ListItem>()
   .Where(li => li.Selected)
   .Select(li => li.Value)
   .ToList();

HTML Image not displaying, while the src url works

The simple solution is:

1.keep the image file and HTML file in the same folder.

2.code: <img src="Desert.png">// your image name.

3.keep the folder in D drive.

Keeping the folder on the desktop(which is c drive) you can face the issue of permission.

How to iterate through LinkedHashMap with lists as values

I'm assuming you have a typo in your get statement and that it should be test1.get(key). If so, I'm not sure why it is not returning an ArrayList unless you are not putting in the correct type in the map in the first place.

This should work:

// populate the map
Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>();
test1.put("key1", new ArrayList<String>());
test1.put("key2", new ArrayList<String>());

// loop over the set using an entry set
for( Map.Entry<String,List<String>> entry : test1.entrySet()){
  String key = entry.getKey();
  List<String>value = entry.getValue();
  // ...
}

or you can use

// second alternative - loop over the keys and get the value per key
for( String key : test1.keySet() ){
  List<String>value = test1.get(key);
  // ...
}

You should use the interface names when declaring your vars (and in your generic params) unless you have a very specific reason why you are defining using the implementation.

Where are Magento's log files located?

You can find the log within you Magento root directory under

var/log

there are two types of log files system.log and exception.log

you need to give the correct permission to var folder, then enable logging from your Magento admin by going to

System > Configuration> Developer > Log Settings > Enable = Yes

system.log is used for general debugging and catches almost all log entries from Magento, including warning, debug and errors messages from both native and custom modules.

exception.log is reserved for exceptions only, for example when you are using try-catch statement.

To output to either the default system.log or the exception.log see the following code examples:

Mage::log('My log entry');
Mage::log('My log message: '.$myVariable);
Mage::log($myArray);
Mage::log($myObject);
Mage::logException($e);

You can create your own log file for more debugging

Mage::log('My log entry', null, 'mylogfile.log');

Can I extend a class using more than 1 class in PHP?

There are plans for adding mix-ins soon, I believe.

But until then, go with the accepted answer. You can abstract that out a bit to make an "extendable" class:

class Extendable{
  private $extender=array();

  public function addExtender(Extender $obj){
    $this->extenders[] = $obj;
    $obj->setExtendee($this);
  }

  public function __call($name, $params){
    foreach($this->extenders as $extender){
       //do reflection to see if extender has this method with this argument count
       if (method_exists($extender, $name)){
          return call_user_func_array(array($extender, $name), $params);
       }
    }
  }
}


$foo = new Extendable();
$foo->addExtender(new OtherClass());
$foo->other_class_method();

Note that in this model "OtherClass" gets to 'know' about $foo. OtherClass needs to have a public function called "setExtendee" to set up this relationship. Then, if it's methods are invoked from $foo, it can access $foo internally. It will not, however, get access to any private/protected methods/variables like a real extended class would.

How to send parameters with jquery $.get()

This is what worked for me:

$.get({
    method: 'GET',
    url: 'api.php',
    headers: {
        'Content-Type': 'application/json',
    },
    // query parameters go under "data" as an Object
    data: {
        client: 'mikescafe'
    }
});

will make a REST/AJAX call - > GET http://localhost:3000/api.php?client=mikescafe

Good Luck.

Use URI builder in Android or create URL with variables

There is another way of using Uri and we can achieve the same goal

http://api.example.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7

To build the Uri you can use this:

final String FORECAST_BASE_URL = 
    "http://api.example.org/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";

You can declare all this the above way or even inside the Uri.parse() and appendQueryParameter()

Uri builtUri = Uri.parse(FORECAST_BASE_URL)
    .buildUpon()
    .appendQueryParameter(QUERY_PARAM, params[0])
    .appendQueryParameter(FORMAT_PARAM, "json")
    .appendQueryParameter(UNITS_PARAM, "metric")
    .appendQueryParameter(DAYS_PARAM, Integer.toString(7))
    .build();

At last

URL url = new URL(builtUri.toString());

Get the size of the screen, current web page and browser window

A non-jQuery way to get the available screen dimension. window.screen.width/height has already been put up, but for responsive webdesign and completeness sake I think its worth to mention those attributes:

alert(window.screen.availWidth);
alert(window.screen.availHeight);

http://www.quirksmode.org/dom/w3c_cssom.html#t10 :

availWidth and availHeight - The available width and height on the screen (excluding OS taskbars and such).

How to install 2 Anacondas (Python 2 and 3) on Mac OS

There is no need to install Anaconda again. Conda, the package manager for Anaconda, fully supports separated environments. The easiest way to create an environment for Python 2.7 is to do

conda create -n python2 python=2.7 anaconda

This will create an environment named python2 that contains the Python 2.7 version of Anaconda. You can activate this environment with

source activate python2

This will put that environment (typically ~/anaconda/envs/python2) in front in your PATH, so that when you type python at the terminal it will load the Python from that environment.

If you don't want all of Anaconda, you can replace anaconda in the command above with whatever packages you want. You can use conda to install packages in that environment later, either by using the -n python2 flag to conda, or by activating the environment.

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

You can also use Apache's ExceptionUtils.

Example:

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;


public class Test {

    static Logger logger = Logger.getLogger(Test.class);

    public static void main(String[] args) {

        try{
            String[] avengers = null;
            System.out.println("Size: "+avengers.length);
        } catch (NullPointerException e){
            logger.info(ExceptionUtils.getFullStackTrace(e));
        }
    }

}

Console output:

java.lang.NullPointerException
    at com.aimlessfist.avengers.ironman.Test.main(Test.java:11)

Getting parts of a URL (Regex)

Try the following:

^((ht|f)tp(s?)\:\/\/|~/|/)?([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+|/?)(\w+\.[\w]{3,4})?((\?\w+=\w+)?(&\w+=\w+)*)?

It supports HTTP / FTP, subdomains, folders, files etc.

I found it from a quick google search:

http://geekswithblogs.net/casualjim/archive/2005/12/01/61722.aspx

How to avoid "cannot load such file -- utils/popen" from homebrew on OSX

First, open a terminal session and run:

cd /usr/local/
git status

to see if Homebrew is clean.

If it's dirty, run:

git reset --hard && git clean -df

then

brew doctor
brew update

If it's still broken, try this in your session:

sudo rm /System/Library/Frameworks/Ruby.framework/Versions/Current
sudo ln -s /System/Library/Frameworks/Ruby.framework/Versions/1.8 /System/Library/Frameworks/Ruby.framework/Versions/Current

This will force Homebrew to use Ruby 1.8 from the system's installation.

How to programmatically send SMS on the iPhone?

Here is a tutorial which does exactly what you are looking for: the MFMessageComposeViewController.

http://blog.mugunthkumar.com/coding/iphone-tutorial-how-to-send-in-app-sms/

Essentially:

MFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];
if([MFMessageComposeViewController canSendText])
{
    controller.body = @"SMS message here";
    controller.recipients = [NSArray arrayWithObjects:@"1(234)567-8910", nil];
    controller.messageComposeDelegate = self;
    [self presentModalViewController:controller animated:YES];
}

And a link to the docs.

https://developer.apple.com/documentation/messageui/mfmessagecomposeviewcontroller

How to resolve "Waiting for Debugger" message?

disable you developer option in your phone.

Settings > Developer option > Disable

This worked for me, when i tried to use my application without debugging it.

Python: call a function from string name

You can use a dictionary too.

def install():
    print "In install"

methods = {'install': install}

method_name = 'install' # set by the command line options
if method_name in methods:
    methods[method_name]() # + argument list of course
else:
    raise Exception("Method %s not implemented" % method_name)

REST API - file (ie images) processing - best practices

OP here (I am answering this question after two years, the post made by Daniel Cerecedo was not bad at a time, but the web services are developing very fast)

After three years of full-time software development (with focus also on software architecture, project management and microservice architecture) I definitely choose the second way (but with one general endpoint) as the best one.

If you have a special endpoint for images, it gives you much more power over handling those images.

We have the same REST API (Node.js) for both - mobile apps (iOS/android) and frontend (using React). This is 2017, therefore you don't want to store images locally, you want to upload them to some cloud storage (Google cloud, s3, cloudinary, ...), therefore you want some general handling over them.

Our typical flow is, that as soon as you select an image, it starts uploading on background (usually POST on /images endpoint), returning you the ID after uploading. This is really user-friendly, because user choose an image and then typically proceed with some other fields (i.e. address, name, ...), therefore when he hits "send" button, the image is usually already uploaded. He does not wait and watching the screen saying "uploading...".

The same goes for getting images. Especially thanks to mobile phones and limited mobile data, you don't want to send original images, you want to send resized images, so they do not take that much bandwidth (and to make your mobile apps faster, you often don't want to resize it at all, you want the image that fits perfectly into your view). For this reason, good apps are using something like cloudinary (or we do have our own image server for resizing).

Also, if the data are not private, then you send back to app/frontend just URL and it downloads it from cloud storage directly, which is huge saving of bandwidth and processing time for your server. In our bigger apps there are a lot of terabytes downloaded every month, you don't want to handle that directly on each of your REST API server, which is focused on CRUD operation. You want to handle that at one place (our Imageserver, which have caching etc.) or let cloud services handle all of it.


Cons : The only "cons" which you should think of is "not assigned images". User select images and continue with filling other fields, but then he says "nah" and turn off the app or tab, but meanwhile you successfully uploaded the image. This means you have uploaded an image which is not assigned anywhere.

There are several ways of handling this. The most easiest one is "I don't care", which is a relevant one, if this is not happening very often or you even have desire to store every image user send you (for any reason) and you don't want any deletion.

Another one is easy too - you have CRON and i.e. every week and you delete all unassigned images older than one week.

What is "Signal 15 received"

This indicates the linux has delivered a SIGTERM to your process. This is usually at the request of some other process (via kill()) but could also be sent by your process to itself (using raise()). This signal requests an orderly shutdown of your process.

If you need a quick cheatsheet of signal numbers, open a bash shell and:

$ kill -l
 1) SIGHUP   2) SIGINT   3) SIGQUIT  4) SIGILL
 5) SIGTRAP  6) SIGABRT  7) SIGBUS   8) SIGFPE
 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG  24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM   27) SIGPROF 28) SIGWINCH
29) SIGIO   30) SIGPWR  31) SIGSYS  34) SIGRTMIN
35) SIGRTMIN+1  36) SIGRTMIN+2  37) SIGRTMIN+3  38) SIGRTMIN+4
39) SIGRTMIN+5  40) SIGRTMIN+6  41) SIGRTMIN+7  42) SIGRTMIN+8
43) SIGRTMIN+9  44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9  56) SIGRTMAX-8  57) SIGRTMAX-7  58) SIGRTMAX-6
59) SIGRTMAX-5  60) SIGRTMAX-4  61) SIGRTMAX-3  62) SIGRTMAX-2
63) SIGRTMAX-1  64) SIGRTMAX    

You can determine the sender by using an appropriate signal handler like:

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

void sigterm_handler(int signal, siginfo_t *info, void *_unused)
{
  fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
      info->si_pid);
  exit(0);
}

int main (void)
{
  struct sigaction action = {
    .sa_handler = NULL,
    .sa_sigaction = sigterm_handler,
    .sa_mask = 0,
    .sa_flags = SA_SIGINFO,
    .sa_restorer = NULL
  };

  sigaction(SIGTERM, &action, NULL);
  sleep(60);

  return 0;
}

Notice that the signal handler also includes a call to exit(). It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).

How to check the version before installing a package using apt-get?

on debian :

apt list --upgradable

gives the list with package, version to be upgraded, and actual version of the package.

result :

base-files/stable 8+deb8u8 amd64 [upgradable from: 8+deb8u7]
bind9-host/stable 1:9.9.5.dfsg-9+deb8u11 amd64 [upgradable from: 1:9.9.5.dfsg-9+deb8u9]
ca-certificates/stable 20141019+deb8u3 all [upgradable from: 20141019+deb8u2]
certbot/jessie-backports 0.10.2-1~bpo8+1 all [upgradable from: 0.8.1-2~bpo8+1]
dnsutils/stable 1:9.9.5.dfsg-9+deb8u11 amd64 [upgradable from: 1:9.9.5.dfsg-9+deb8u9]

How to tell if a connection is dead in python

It depends on what you mean by "dropped". For TCP sockets, if the other end closes the connection either through close() or the process terminating, you'll find out by reading an end of file, or getting a read error, usually the errno being set to whatever 'connection reset by peer' is by your operating system. For python, you'll read a zero length string, or a socket.error will be thrown when you try to read or write from the socket.

How do you concatenate Lists in C#?

Take a look at my implementation. It's safe from null lists.

 IList<string> all= new List<string>();

 if (letterForm.SecretaryPhone!=null)// first list may be null
     all=all.Concat(letterForm.SecretaryPhone).ToList();

 if (letterForm.EmployeePhone != null)// second list may be null
     all= all.Concat(letterForm.EmployeePhone).ToList(); 

 if (letterForm.DepartmentManagerName != null) // this is not list (its just string variable) so wrap it inside list then concat it 
     all = all.Concat(new []{letterForm.DepartmentManagerPhone}).ToList();

Unable to allocate array with shape and data type

Sometimes, this error pops up because of the kernel has reached its limit. Try to restart the kernel redo the necessary steps.

Add SUM of values of two LISTS into new LIST

Try the following code:

first = [1, 2, 3, 4]
second = [2, 3, 4, 5]
third = map(sum, zip(first, second))

password-check directive in angularjs

In order to achieve validation when both inputs change, I use the following code (which was a combination of all others other answers):

angular.module('app.directives')
.directive('passwordVerify', [function () {
    return {
        require: '?ngModel',
        restrict: 'A',
        scope: {
            origin: '=passwordVerify'
        },
        link: function (scope, element, attrs, ctrl) {
            if(!ctrl) {
                return;
            }

            function validate(value) {
                ctrl.$setValidity('passwordMatch', scope.origin === value);
                return value;
            }

            ctrl.$parsers.unshift(validate);

            scope.$watch('origin', function(value) {
                validate(ctrl.$viewValue);
            });
        }
    };
}]);

Java converting int to hex and back again

  • int to Hex :

    Integer.toHexString(intValue);
    
  • Hex to int :

    Integer.valueOf(hexString, 16).intValue();
    

You may also want to use long instead of int (if the value does not fit the int bounds):

  • Hex to long:

    Long.valueOf(hexString, 16).longValue()
    
  • long to Hex

    Long.toHexString(longValue)
    

Java FileOutputStream Create File if not exists

FileUtils from apache commons is a pretty good way to achieve this in a single line.

FileOutputStream s = FileUtils.openOutputStream(new File("/home/nikhil/somedir/file.txt"))

This will create parent folders if do not exist and create a file if not exists and throw a exception if file object is a directory or cannot be written to. This is equivalent to:

File file = new File("/home/nikhil/somedir/file.txt");
file.getParentFile().mkdirs(); // Will create parent directories if not exists
file.createNewFile();
FileOutputStream s = new FileOutputStream(file,false);

All the above operations will throw an exception if the current user is not permitted to do the operation.

error: unknown type name ‘bool’

C90 does not support the boolean data type.

C99 does include it with this include:

#include <stdbool.h>

Read int values from a text file in C

How about this?

fscanf(file,"%d %d %d %d %d %d %d",&line1_1,&line1_2, &line1_3, &line2_1, &line2_2, &line3_1, &line3_2); 

In this case spaces in fscanf match multiple occurrences of any whitespace until the next token in found.

How do you get the current text contents of a QComboBox?

Getting the Text of ComboBox when the item is changed

     self.ui.comboBox.activated.connect(self.pass_Net_Adap)

  def pass_Net_Adap(self):
      print str(self.ui.comboBox.currentText())

HTML email with Javascript

Here's what you CAN do:

You can attach (to the email) an html document that contains javascript.

Then, when the recipient opens the attachment, their web browser will facilitate the dynamic features you've implemented.

How to display a list of images in a ListView in Android?

I came up with a solution that I call “BatchImageDownloader” that has served well. Here’s a quick summary of how it is used:

  • Keep a global HashMap (ideally in your Application object) that serves as a cache of drawable objects

  • In the getView() method of your List Adapter, use the drawable from the cache for populating the ImageView in your list item.

  • Create an instance of BatchImageDownloader, passing in your ListView Adapter

  • Call addUrl() for each image that needs to be fetched/displayed

  • When done, call execute(). This fires an AsyncTask that fetches all images, and as each image is fetched and added to the cache, it refreshes your ListView (by calling notifyDataSetChanged())

The approach has the following advantages:

  • A single worker thread is used to fetch all images, rather than a separate thread for each image/view
  • Once an image is fetched, all list items that use it are instantly updated
  • The code does not access the Image View in your List Item directly – instead it triggers a listview refresh by calling notifyDataSetChanged() on your List Adapter, and the getView() implementation simply pulls the drawable from the cache and displays it. This avoids the problems associated with recycled View objects used in ListViews.

Here is the source code of BatchImageDownloader:

package com.mobrite.androidutils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.widget.BaseAdapter;

public class BatchImageDownloader extends AsyncTask<Void, Void, Void> {

    List<String> imgUrls = new ArrayList<String>();
    BaseAdapter adapter;
    HashMap<String, Drawable> imageCache;

    public BatchImageDownloader(BaseAdapter adapter,
            HashMap<String, Drawable> imageCache) {
        this.adapter = adapter;
        this.imageCache = imageCache;
    }

    public void addUrl(String url) {
        imgUrls.add(url);
    }

    @Override
    protected Void doInBackground(Void... params) {
        for (String url : imgUrls) {
            if (!imageCache.containsKey(url)) {
                Drawable bm = downloadImage(url);
                if (null != bm) {
                    imageCache.put(url, bm);
                    publishProgress();
                }
            }
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onPostExecute(Void result) {
        adapter.notifyDataSetChanged();
    }

    public Drawable downloadImage(String url) {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        try {
            HttpResponse response = httpClient.execute(request);
            InputStream stream = response.getEntity().getContent();
            Drawable drawable = Drawable.createFromStream(stream, "src");
            return drawable;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return null;
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

}

Invalid length parameter passed to the LEFT or SUBSTRING function

This is because the CHARINDEX-1 is returning a -ive value if the look-up for " " (space) is 0. The simplest solution would be to avoid '-ve' by adding

ABS(CHARINDEX(' ', PostCode ) -1))

which will return only +ive values for your length even if CHARINDEX(' ', PostCode ) -1) is a -ve value. Correct me if I'm wrong!

Shortcut to exit scale mode in VirtualBox

I arrived at this page looking to turn off scale mode for good, so I figured I would share what I found:

VBoxManage setextradata global GUI/Input/MachineShortcuts "ScaleMode=None"

Running this in my host's terminal worked like a charm for me.

Source: https://forums.virtualbox.org/viewtopic.php?f=8&t=47821

Redirect in Spring MVC

For completing the answers, Spring MVC uses viewResolver(for example, as axtavt metionned, InternalResourceViewResolver) to get the specific view. Therefore the first step is making sure that a viewResolver is configured.

Secondly, you should pay attention to the url of redirection(redirect or forward). A url starting with "/" means that it's a url absolute in the application. As Jigar says,

return "redirect:/index.html";  

should work. If your view locates in the root of the application, Spring can find it. If a url without a "/", such as that in your question, it means a url relative. It explains why it worked before and don't work now. If your page calling "redirect" locates in the root by chance, it works. If not, Spring can't find the view and it doesn't work.

Here is the source code of the method of RedirectView of Spring

protected void renderMergedOutputModel(  
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)  
throws IOException {  
  // Prepare target URL.  
  StringBuilder targetUrl = new StringBuilder();  
  if (this.contextRelative && getUrl().startsWith("/")) {  
    // Do not apply context path to relative URLs.  
    targetUrl.append(request.getContextPath());  
  }  
  targetUrl.append(getUrl());  

  // ...  

  sendRedirect(request, response, targetUrl.toString(), this.http10Compatible);  
}  

Creating a fixed sidebar alongside a centered Bootstrap 3 grid

As drew_w said, you can find a good example here.

HTML

<div id="wrapper">
    <div id="sidebar-wrapper">
        <ul class="sidebar-nav">
            <li class="sidebar-brand"><a href="#">Home</a></li>
            <li><a href="#">Another link</a></li>
            <li><a href="#">Next link</a></li>
            <li><a href="#">Last link</a></li>
        </ul>
    </div>
    <div id="page-content-wrapper">
        <div class="page-content">
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <!-- content of page -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

#wrapper {
  padding-left: 250px;
  transition: all 0.4s ease 0s;
}

#sidebar-wrapper {
  margin-left: -250px;
  left: 250px;
  width: 250px;
  background: #CCC;
  position: fixed;
  height: 100%;
  overflow-y: auto;
  z-index: 1000;
  transition: all 0.4s ease 0s;
}

#page-content-wrapper {
  width: 100%;
}

.sidebar-nav {
  position: absolute;
  top: 0;
  width: 250px;
  list-style: none;
  margin: 0;
  padding: 0;
}

@media (max-width:767px) {

    #wrapper {
      padding-left: 0;
    }

    #sidebar-wrapper {
      left: 0;
    }

    #wrapper.active {
      position: relative;
      left: 250px;
    }

    #wrapper.active #sidebar-wrapper {
      left: 250px;
      width: 250px;
      transition: all 0.4s ease 0s;
    }

}

JSFIDDLE

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

Running in a Docker container introduced a whole slew of additional problems for connecting so hopefully this helps someone. I ended up needed to add the following options which I'll explain below:

-Dcom.sun.management.jmxremote=true
-Dcom.sun.management.jmxremote.local.only=false
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
-Djava.rmi.server.hostname=${DOCKER_HOST_IP}
-Dcom.sun.management.jmxremote.port=9999
-Dcom.sun.management.jmxremote.rmi.port=9998

DOCKER_HOST_IP

Unlike using jconsole locally, you have to advertise a different IP than you'll probably see from within the container. You'll need to replace ${DOCKER_HOST_IP} with the externally resolvable IP (DNS Name) of your Docker host.

JMX Remote & RMI Ports

It looks like JMX also requires access to a remote management interface (jstat) that uses a different port to transfer some data when arbitrating the connection. I didn't see anywhere immediately obvious in jconsole to set this value. In the linked article the process was:

  • Try and connect from jconsole with logging enabled
  • Fail
  • Figure out which port jconsole attempted to use
  • Use iptables/firewall rules as necessary to allow that port to connect

While that works, it's certainly not an automatable solution. I opted for an upgrade from jconsole to VisualVM since it let's you to explicitly specify the port on which jstatd is running. In VisualVM, add a New Remote Host and update it with values that correlate to the ones specified above:

Add Remote Host

Then right-click the new Remote Host Connection and Add JMX Connection...

Add JMX Connection

Don't forget to check the checkbox for Do not require SSL connection. Hopefully, that should allow you to connect.

Fitting polynomial model to data in R

Regarding the question 'can R help me find the best fitting model', there is probably a function to do this, assuming you can state the set of models to test, but this would be a good first approach for the set of n-1 degree polynomials:

polyfit <- function(i) x <- AIC(lm(y~poly(x,i)))
as.integer(optimize(polyfit,interval = c(1,length(x)-1))$minimum)

Notes

  • The validity of this approach will depend on your objectives, the assumptions of optimize() and AIC() and if AIC is the criterion that you want to use,

  • polyfit() may not have a single minimum. check this with something like:

    for (i in 2:length(x)-1) print(polyfit(i))
    
  • I used the as.integer() function because it is not clear to me how I would interpret a non-integer polynomial.

  • for testing an arbitrary set of mathematical equations, consider the 'Eureqa' program reviewed by Andrew Gelman here

Update

Also see the stepAIC function (in the MASS package) to automate model selection.

How can I confirm a database is Oracle & what version it is using SQL?

Run this SQL:

select * from v$version;

And you'll get a result like:

BANNER
----------------------------------------------------------------
Oracle Database 10g Release 10.2.0.3.0 - 64bit Production
PL/SQL Release 10.2.0.3.0 - Production
CORE    10.2.0.3.0      Production
TNS for Solaris: Version 10.2.0.3.0 - Production
NLSRTL Version 10.2.0.3.0 - Production

Convert NSDate to NSString

I don't know how we all missed this: localizedStringFromDate:dateStyle:timeStyle:

NSString *dateString = [NSDateFormatter localizedStringFromDate:[NSDate date] 
                                                      dateStyle:NSDateFormatterShortStyle 
                                                      timeStyle:NSDateFormatterFullStyle];
NSLog(@"%@",dateString);

outputs '13/06/12 00:22:39 GMT+03:00'

How to increase the distance between table columns in HTML?

You can just use padding. Like so:

http://jsfiddle.net/davidja/KG8Kv/

HTML

   <table>
        <tr>
            <td>item1</td>
            <td>item2</td>
            <td>item2</td>
        </tr>
    </table>

CSS

 td {padding:10px 25px 10px 25px;}

OR

 tr td:first-child {padding-left:0px;}
 td {padding:10px 0px 10px 50px;}

How to remove the last element added into the List?

The direct answer to this question is:

if(rows.Any()) //prevent IndexOutOfRangeException for empty list
{
    rows.RemoveAt(rows.Count - 1);
}

However... in the specific case of this question, it makes more sense not to add the row in the first place:

Row row = new Row();
//...      

if (!row.cell[0].Equals("Something"))
{
    rows.Add(row);
}

TBH, I'd go a step further by testing "Something" against user."", and not even instantiating a Row unless the condition is satisfied, but seeing as user."" won't compile, I'll leave that as an exercise for the reader.

initialize a numpy array

Whenever you are in the following situation:

a = []
for i in range(5):
    a.append(i)

and you want something similar in numpy, several previous answers have pointed out ways to do it, but as @katrielalex pointed out these methods are not efficient. The efficient way to do this is to build a long list and then reshape it the way you want after you have a long list. For example, let's say I am reading some lines from a file and each row has a list of numbers and I want to build a numpy array of shape (number of lines read, length of vector in each row). Here is how I would do it more efficiently:

long_list = []
counter = 0
with open('filename', 'r') as f:
    for row in f:
        row_list = row.split()
        long_list.extend(row_list)
        counter++
#  now we have a long list and we are ready to reshape
result = np.array(long_list).reshape(counter, len(row_list)) #  desired numpy array

How to use ClassLoader.getResources() correctly?

The Spring Framework has a class which allows to recursively search through the classpath:

PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
resolver.getResources("classpath*:some/package/name/**/*.xml");

How do you round a floating point number in Perl?

loads of reading documentation on how to round numbers, many experts suggest writing your own rounding routines, as the 'canned' version provided with your language may not be precise enough, or contain errors. i imagine, however, they're talking many decimal places not just one, two, or three. with that in mind, here is my solution (although not EXACTLY as requested as my needs are to display dollars - the process is not much different, though).

sub asDollars($) {
  my ($cost) = @_;
  my $rv = 0;

  my $negative = 0;
  if ($cost =~ /^-/) {
    $negative = 1;
    $cost =~ s/^-//;
  }

  my @cost = split(/\./, $cost);

  # let's get the first 3 digits of $cost[1]
  my ($digit1, $digit2, $digit3) = split("", $cost[1]);
  # now, is $digit3 >= 5?
  # if yes, plus one to $digit2.
  # is $digit2 > 9 now?
  # if yes, $digit2 = 0, $digit1++
  # is $digit1 > 9 now??
  # if yes, $digit1 = 0, $cost[0]++
  if ($digit3 >= 5) {
    $digit3 = 0;
    $digit2++;
    if ($digit2 > 9) {
      $digit2 = 0;
      $digit1++;
      if ($digit1 > 9) {
        $digit1 = 0;
        $cost[0]++;
      }
    }
  }
  $cost[1] = $digit1 . $digit2;
  if ($digit1 ne "0" and $cost[1] < 10) { $cost[1] .= "0"; }

  # and pretty up the left of decimal
  if ($cost[0] > 999) { $cost[0] = commafied($cost[0]); }

  $rv = join(".", @cost);

  if ($negative) { $rv = "-" . $rv; }

  return $rv;
}

sub commafied($) {
  #*
  # to insert commas before every 3rd number (from the right)
  # positive or negative numbers
  #*
  my ($num) = @_; # the number to insert commas into!

  my $negative = 0;
  if ($num =~ /^-/) {
    $negative = 1;
    $num =~ s/^-//;
  }
  $num =~ s/^(0)*//; # strip LEADING zeros from given number!
  $num =~ s/0/-/g; # convert zeros to dashes because ... computers!

  if ($num) {
    my @digits = reverse split("", $num);
    $num = "";

    for (my $i = 0; $i < @digits; $i += 3) {
      $num .= $digits[$i];
      if ($digits[$i+1]) { $num .= $digits[$i+1]; }
      if ($digits[$i+2]) { $num .= $digits[$i+2]; }
      if ($i < (@digits - 3)) { $num .= ","; }
      if ($i >= @digits) { last; }
    }

    #$num =~ s/,$//;
    $num = join("", reverse split("", $num));
    $num =~ s/-/0/g;
  }

  if ($negative) { $num = "-" . $num; }

  return $num; # a number with commas added
  #usage: my $prettyNum = commafied(1234567890);
}

Count a list of cells with the same background color

Excel has no way of gathering that attribute with it's built-in functions. If you're willing to use some VB, all your color-related questions are answered here:

http://www.cpearson.com/excel/colors.aspx

Example form the site:

The SumColor function is a color-based analog of both the SUM and SUMIF function. It allows you to specify separate ranges for the range whose color indexes are to be examined and the range of cells whose values are to be summed. If these two ranges are the same, the function sums the cells whose color matches the specified value. For example, the following formula sums the values in B11:B17 whose fill color is red.

=SUMCOLOR(B11:B17,B11:B17,3,FALSE)

How to change indentation in Visual Studio Code?

To change the indentation based on programming language:

  1. Open the Command Palette (CtrlShiftP | macOS: ??P)

  2. Preferences: Configure language specific settings... (command id: workbench.action.configureLanguageBasedSettings)

  3. Select programming language (for example TypeScript)

  4. Add this code:

    "[typescript]": {
        "editor.tabSize": 2
    }
    

See also: VS Code Docs

How to display 3 buttons on the same line in css

Here is the Answer

CSS

#outer
{
    width:100%;
    text-align: center;
}
.inner
{
    display: inline-block;
}

HTML

<div id="outer">
  <div class="inner"><button type="submit" class="msgBtn" onClick="return false;" >Save</button></div>
  <div class="inner"><button type="submit" class="msgBtn2" onClick="return false;">Publish</button></div>
  <div class="inner"><button class="msgBtnBack">Back</button></div>
</div>

Fiddle

How to programmatically close a JFrame

 setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

Remove end of line characters from Java string

You can use unescapeJava from org.apache.commons.text.StringEscapeUtils like below

str = "hello\r\njava\r\nbook";
StringEscapeUtils.unescapeJava(str);

How to read value of a registry key c#

You need to first add using Microsoft.Win32; to your code page.

Then you can begin to use the Registry classes:

try
{
    using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))
    {
        if (key != null)
        {
            Object o = key.GetValue("Version");
            if (o != null)
            {
                Version version = new Version(o as String);  //"as" because it's REG_SZ...otherwise ToString() might be safe(r)
                //do what you like with version
            }
        }
    }
}
catch (Exception ex)  //just for demonstration...it's always best to handle specific exceptions
{
    //react appropriately
}

BEWARE: unless you have administrator access, you are unlikely to be able to do much in LOCAL_MACHINE. Sometimes even reading values can be a suspect operation without admin rights.

How to find top three highest salary in emp table in oracle?

Something like the following should do it.

SELECT  Name, Salary
FROM 
    (
    SELECT  Name, Salary
    FROM         emp 
    ORDER BY Salary desc
    )
WHERE rownum <= 3
ORDER BY Salary ;

Importing json file in TypeScript

Enable "resolveJsonModule": true in tsconfig.json file and implement as below code, it's work for me:

const config = require('./config.json');

What does map(&:name) mean in Ruby?

It is same as below:

def tag_names
  if @tag_names
    @tag_names
  else
    tags.map{ |t| t.name }.join(' ')
end

Adding an onclicklistener to listview (android)

The prestListView.getItemAtPosition(position); returns the UI widget: Text, Icon, ...

Try this instead:

Object o = prestationAdapterEco.getItemAtPosition(position);

or

Object o = arg0.getItemAtPosition(position);

Get the object from the adapter. Not from the list-view.

2. Object o is a prestationEco object. Not a String.

How do I set the rounded corner radius of a color drawable using xml?

mbaird's answer works fine. Just be aware that there seems to be a bug in Android (2.1 at least), that if you set any individual corner's radius to 0, it forces all the corners to 0 (at least that's the case with "dp" units; I didn't try it with any other units).

I needed a shape where the top corners were rounded and the bottom corners were square. I got achieved this by setting the corners I wanted to be square to a value slightly larger than 0: 0.1dp. This still renders as square corners, but it doesn't force the other corners to be 0 radius.

Github "Updates were rejected because the remote contains work that you do not have locally."

The error possibly comes because of the different structure of the code that you are committing and that present on GitHub. It creates conflicts which can be solved by

git pull

Merge conflicts resolving:

git push

If you confirm that your new code is all fine you can use:

git push -f origin master

Where -f stands for "force commit".

Return HTTP status code 201 in flask

You can read about it here.

return render_template('page.html'), 201

Connection to SQL Server Works Sometimes

I had this problem when I did a SharePoint 2010 to 2013 migration. I suspected that because the database server is on the other side of a firewall which does not route IP6 that it was trying then to use IP6 and failing when connecting to the database.

I think the issue is now solved. The errors seem to have stopped. What I did was I simply disabled IP6 (by unchecking it) for the network adapter on the SharePoint Servers.

"getaddrinfo failed", what does that mean?

May be this will help some one. I have my proxy setup in python script but keep getting the error mentioned in the question.

Below is the piece of block which will take my username and password as a constant in the beginning.

   if (use_proxy):
        proxy = req.ProxyHandler({'https': proxy_url})
        auth = req.HTTPBasicAuthHandler()
        opener = req.build_opener(proxy, auth, req.HTTPHandler)
        req.install_opener(opener)

If you are using corporate laptop and if you did not connect to Direct Access or office VPN then the above block will throw error. All you need to do is to connect to your org VPN and then execute your python script.

Thanks

Send string to stdin

You were close

/my/bash/script <<< 'This string will be sent to stdin.'

For multiline input, here-docs are suited:

/my/bash/script <<STDIN -o other --options
line 1
line 2
STDIN

Edit To the comments:

To achieve binary input, say

xxd -r -p <<BINARY | iconv -f UCS-4BE -t UTF-8 | /my/bash/script
0000 79c1 0000 306f 0000 3061 0000 3093 0000 3077 0000 3093 0000 304b 0000 3093 0000 3077 0000 3093 0000 306a 0000 8a71 0000 306b 0000 30ca 0000 30f3 0000 30bb
0000 30f3 0000 30b9 0000 3092 0000 7ffb 0000 8a33 0000 3059 0000 308b 0000 3053 0000 3068 0000 304c 0000 3067 0000 304d 0000 000a
BINARY

If you substitute cat for /my/bash/script (or indeed drop the last pipe), this prints:

????????????????????????????

Or, if you wanted something a little more geeky:

0000000: 0000 0000 bef9 0e3c 59f8 8e3c 0a71 d63c  .......<Y..<.q.<
0000010: c6f2 0e3d 3eaa 323d 3a5e 563d 090e 7a3d  ...=>.2=:^V=..z=
0000020: 7bdc 8e3d 2aaf a03d b67e b23d c74a c43d  {..=*..=.~.=.J.=
0000030: 0513 d63d 16d7 e73d a296 f93d a8a8 053e  ...=...=...=...>
0000040: 6583 0e3e 5a5b 173e 5b30 203e 3d02 293e  e..>Z[.>[0 >=.)>
0000050: d4d0 313e f39b 3a3e 6f63 433e 1c27 4c3e  ..1>..:>ocC>.'L>
0000060: cde6 543e 59a2 5d3e 9259 663e 4d0c 6f3e  ..T>Y.]>.Yf>M.o>
0000070: 60ba 773e cf31 803e ee83 843e 78d3 883e  `.w>.1.>...>x..>
0000080: 5720 8d3e 766a 913e beb1 953e 1cf6 993e  W .>vj.>...>...>
0000090: 7a37 9e3e c275 a23e dfb0 a63e bce8 aa3e  z7.>.u.>...>...>
00000a0: 441d af3e 624e b33e 017c b73e 0ca6 bb3e  D..>bN.>.|.>...>
00000b0: 6fcc bf3e 15ef c33e e90d c83e d728 cc3e  o..>...>...>.(.>
00000c0: c93f d03e ac52 d43e 6c61 d83e f36b dc3e  .?.>.R.>la.>.k.>
00000d0: 2f72 e03e 0a74 e43e 7171 e83e 506a ec3e  /r.>.t.>qq.>Pj.>
00000e0: 945e f03e 274e f43e f738 f83e f11e fc3e  .^.>'N.>.8.>...>
00000f0: 0000 003f 09ee 013f 89d9 033f 77c2 053f  ...?...?...?w..?
0000100: caa8 073f 788c 093f 776d 0b3f be4b 0d3f  ...?x..?wm.?.K.?
0000110: 4427 0f3f 0000 113f e8d5 123f f3a8 143f  D'.?...?...?...?
0000120: 1879 163f 4e46 183f 8d10 1a3f cad7 1b3f  .y.?NF.?...?...?
0000130: fe9b 1d3f 1f5d 1f3f 241b 213f 06d6 223f  ...?.].?$.!?.."?
0000140: bb8d 243f 3a42 263f 7cf3 273f 78a1 293f  ..$?:B&?|.'?x.)?
0000150: 254c 2b3f 7bf3 2c3f 7297 2e3f 0138 303f  %L+?{.,?r..?.80?
0000160: 22d5 313f ca6e 333f                      ".1?.n3?

Which is the sines of the first 90 degrees in 4byte binary floats

smooth scroll to top

theMaxx answer works in nuxt/vue, smooth scrolling is default behavior

<button @click=scrollToTop()>Jump to top of page

  methods: {
    scrollToTop() {
      window.scrollTo({ top: 0 });
    }
  }

NPM Install Error:Unexpected end of JSON input while parsing near '...nt-webpack-plugin":"0'

Even if npm cache clean --force

Try to execute the installing cmd in admin folder.
i.e C:\Users\admin
This worked out for me.

How can I make PHP display the error instead of giving me 500 Internal Server Error

Use "php -l <filename>" (that's an 'L') from the command line to output the syntax error that could be causing PHP to throw the status 500 error. It'll output something like:

PHP Parse error: syntax error, unexpected '}' in <filename> on line 18

Error creating bean with name 'entityManagerFactory

Adding dependencies didn't fix the issue at my end.

The issue was happening at my end because of "additional" fields that are part of the "@Entity" class and don't exist in the database.

I removed the additional fields from the @Entity class and it worked.

MySQL WHERE: how to write "!=" or "not equals"?

DELETE FROM konta WHERE taken <> '';

How to use callback with useState hook in react

_x000D_
_x000D_
function Parent() {_x000D_
  const [Name, setName] = useState("");_x000D_
  getChildChange = getChildChange.bind(this);_x000D_
  function getChildChange(value) {_x000D_
    setName(value);_x000D_
  }_x000D_
_x000D_
  return <div> {Name} :_x000D_
    <Child getChildChange={getChildChange} ></Child>_x000D_
  </div>_x000D_
}_x000D_
_x000D_
function Child(props) {_x000D_
  const [Name, setName] = useState("");_x000D_
  handleChange = handleChange.bind(this);_x000D_
  collectState = collectState.bind(this);_x000D_
  _x000D_
  function handleChange(ele) {_x000D_
    setName(ele.target.value);_x000D_
  }_x000D_
_x000D_
  function collectState() {_x000D_
    return Name;_x000D_
  }_x000D_
  _x000D_
   useEffect(() => {_x000D_
    props.getChildChange(collectState());_x000D_
   });_x000D_
_x000D_
  return (<div>_x000D_
    <input onChange={handleChange} value={Name}></input>_x000D_
  </div>);_x000D_
} 
_x000D_
_x000D_
_x000D_

useEffect act as componentDidMount, componentDidUpdate, so after updating state it will work

How to dynamically change header based on AngularJS partial view?

Simple and dirty way using $rootScope:

<html ng-app="project">
<head>
<title ng-bind="title">Placeholder title</title>

In your controllers, when you have the data necessary to create the title, do:

$rootScope.title = 'Page X'

Add resources, config files to your jar using gradle

Move the config files from src/main/java to src/main/resources.

Hive query output to file

This command will redirect the output to a text file of your choice:

$hive -e "select * from table where id > 10" > ~/sample_output.txt

Can you force a React component to rerender without calling setState?

There are a few ways to rerender your component:

The simplest solution is to use forceUpdate() method:

this.forceUpdate()

One more solution is to create not used key in the state(nonUsedKey) and call setState function with update of this nonUsedKey:

this.setState({ nonUsedKey: Date.now() } );

Or rewrite all current state:

this.setState(this.state);

Props changing also provides component rerender.

Installing Homebrew on OS X

It's on the top of the Homebrew homepage.

From a Terminal prompt:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

The command brew install wget is an example of how to use Homebrew to install another application (in this case, wget) after brew is already installed.

Edit:

Above command to install the Brew is migrated to:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

Disable submit button on form submit

Specifically if someone is facing problem in Chrome:

What you need to do to fix this is to use the onSubmit tag in the <form> element to set the submit button disabled. This will allow Chrome to disable the button immediately after it is pressed and the form submission will still go ahead...

<form name ="myform" method="POST" action="dosomething.php" onSubmit="document.getElementById('submit').disabled=true;"> 
     <input type="submit" name="submit" value="Submit" id="submit"> 
</form>

iloc giving 'IndexError: single positional indexer is out-of-bounds'

This happens when you index a row/column with a number that is larger than the dimensions of your dataframe. For instance, getting the eleventh column when you have only three.

import pandas as pd

df = pd.DataFrame({'Name': ['Mark', 'Laura', 'Adam', 'Roger', 'Anna'],
                   'City': ['Lisbon', 'Montreal', 'Lisbon', 'Berlin', 'Glasgow'],
                   'Car': ['Tesla', 'Audi', 'Porsche', 'Ford', 'Honda']})

You have 5 rows and three columns:

    Name      City      Car
0   Mark    Lisbon    Tesla
1  Laura  Montreal     Audi
2   Adam    Lisbon  Porsche
3  Roger    Berlin     Ford
4   Anna   Glasgow    Honda

Let's try to index the eleventh column (it doesn't exist):

df.iloc[:, 10] # there is obviously no 11th column

IndexError: single positional indexer is out-of-bounds

If you are a beginner with Python, remember that df.iloc[:, 10] would refer to the eleventh column.

Append text to input field

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <style type="text/css">
        *{
            font-family: arial;
            font-size: 15px;
        }
    </style>
</head>
<body>
    <button id="more">More</button><br/><br/>
    <div>
        User Name : <input type="text" class="users"/><br/><br/>
    </div>
    <button id="btn_data">Send Data</button>
    <script type="text/javascript">
        jQuery(document).ready(function($) {
            $('#more').on('click',function(x){
                var textMore = "User Name : <input type='text' class='users'/><br/><br/>";
                $("div").append(textMore);
            });

            $('#btn_data').on('click',function(x){
                var users=$(".users");
                $(users).each(function(i, e) {
                    console.log($(e).val());
                });
            })
        });
    </script>
</body>
</html>

Output enter image description here

NPM doesn't install module dependencies

I had very similar issue, removing entire node_modules folder and re-installing worked for me. Learned this trick from the IT Crowd show!

rm -rf node_modules
npm install

Passing multiple parameters with $.ajax url

why not just pass an data an object with your key/value pairs then you don't have to worry about encoding

$.ajax({
    type: "Post",
    url: "getdata.php",
    data:{
       timestamp: timestamp,
       uid: id,
       uname: name
    },
    async: true,
    cache: false,
    success: function(data) {


    };
}?);?

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

How to create an 2D ArrayList in java?

I want to create a 2D array that each cell is an ArrayList!

If you want to create a 2D array of ArrayList.Then you can do this :

ArrayList[][] table = new ArrayList[10][10];
table[0][0] = new ArrayList(); // add another ArrayList object to [0,0]
table[0][0].add(); // add object to that ArrayList

Application.WorksheetFunction.Match method

You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.

I used CountIf below, but there is lots of different ways to check existence of a value in a range.

Public Sub test()

Dim rng As Range
Dim aNumber As Long

aNumber = 666

Set rng = Sheet5.Range("B16:B615")

    If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then

        rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)

    Else
        MsgBox aNumber & " does not exist in range " & rng.Address
    End If

End Sub

ALTERNATIVE WAY

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Long

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    If Not IsError(Application.Match(aNumber, rng, 0)) Then
        rowNum = Application.Match(aNumber, rng, 0)
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

OR

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Variant

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    rowNum = Application.Match(aNumber, rng, 0)

    If Not IsError(rowNum) Then
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

Select a row from html table and send values onclick of a button

In my case $(document).ready(function() was missing. Try this.

$(document).ready(function(){   
("#table tr").click(function(){
       $(this).addClass('selected').siblings().removeClass('selected');    
       var value=$(this).find('td:first').html();
       alert(value);    
    });
    $('.ok').on('click', function(e){
        alert($("#table tr.selected td:first").html());
    });
});

Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4 (Year)

Added MSSQLSERVER full access to the folder, diskadmin and bulkadmin server roles.

In my c# application, when preparing for the bulk insert command,

string strsql = "BULK INSERT PWCR_Contractor_vw_TEST FROM '" + strFileName + "' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\\n')";

And I get this error - Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 8 (STATUS).

I looked at my logfile and found that the terminator becomes ' ' instead of '\n'. The OLE DB provider "BULK" for linked server "(null)" reported an error. The provider did not give any information about the error:

Cannot fetch a row from OLE DB provider "BULK" for linked server "(null)". Query :BULK INSERT PWCR_Contractor_vw_TEST FROM 'G:\NEWSTAGEWWW\CalAtlasToPWCR\Results\parsedRegistration.csv' WITH (FIELDTERMINATOR = ',', **ROWTERMINATOR = ''**)

So I added extra escape to the rowterminator - string strsql = "BULK INSERT PWCR_Contractor_vw_TEST FROM '" + strFileName + "' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\\n')";

And now it inserts successfully.

Bulk Insert SQL -   --->  BULK INSERT PWCR_Contractor_vw_TEST FROM 'G:\\NEWSTAGEWWW\\CalAtlasToPWCR\\Results\\parsedRegistration.csv' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n')
Bulk Insert to PWCR_Contractor_vw_TEST successful...  --->  clsDatase.PerformBulkInsert

Insert Data Into Temp Table with Query

Fastest way to do this is using "SELECT INTO" command e.g.

SELECT * INTO #TempTableName
FROM....

This will create a new table, you don't have to create it in advance.

The APK file does not exist on disk

My problem was including minutes in the file name - it looked for appname_debug_0.9.0.1_170214_2216.apk when the generated file was appname_debug_0.9.0.1_170214_2217.apk so the output filename code (nabbed from elsewhere) was clearly being called from two different points in the build.

applicationVariants.all { variant ->
        variant.outputs.each { output ->
            def project = "appname"
            def SEP = "_"
    //        def flavor = variant.productFlavors[0].name
            def buildType = variant.variantData.variantConfiguration.buildType.name
            def version = variant.versionName
            def date = new Date();
            def formattedDate = date.format('yyMMdd_HHmm')

            def newApkName = project + SEP + /*flavor + */ SEP + buildType + SEP + version + SEP + formattedDate + ".apk"

            output.outputFile = new File(output.outputFile.parent, newApkName)
        }
    }

fatal: git-write-tree: error building trees

This worked for me:

Do

$ git status

And check if you have Unmerged paths

# Unmerged paths:
#   (use "git reset HEAD <file>..." to unstage)
#   (use "git add <file>..." to mark resolution)
#
#   both modified:      app/assets/images/logo.png
#   both modified:      app/models/laundry.rb

Fix them with git add to each of them and try git stash again.

git add app/assets/images/logo.png

Apache won't run in xampp

Note that this problem usually occure for two reasons:

1-Port 80 is busy.

2-Port 443 is busy.

For number one as the others said, you can kill Skype and SQL Serever Reporter from

Windows Task Manager>"Services" Tab>"Services..." Button.

But if it dosen't worked, it's probably because of port 443, so try this one:

If you use VMware, go to

Windows Task Manager>"Services" Tab>"Services..." Button, and find "VMware Workstation Server" service, double click on it and press "Stop" button.

There is no need to stop other VMware's services.

Then again try to run Apache

how to fetch data from database in Hibernate

I know that it is very late to answer the question, but it may help someone like me who spent lots off time to fetch data using hql

So the thing is you just have to write a query

Query query = session.createQuery("from Employee");

it will give you all the data list but to fetch data from this you have to write this line.

List<Employee> fetchedData = query.list();

As simple as it looks.

Can an Android NFC phone act as an NFC tag?

Yes you can which is Peer-To-Peer Mode

Peer-To-Peer Mode


Bidirectional P2P connection to exchange data between devices

–Proximity triggered interactions

–Nexus S: Devices have to be placed back-to-back

Example of Applications

–Exchange of vCards

–Hand-over of Tickets & P2P Payment

–Web-page sharing, Youtube-video-sharing

–Application sharing

How to use order by with union all in sql?

SELECT  * 
FROM 
        (
            SELECT * FROM TABLE_A 
            UNION ALL 
            SELECT * FROM TABLE_B
        ) dum
-- ORDER BY .....

but if you want to have all records from Table_A on the top of the result list, the you can add user define value which you can use for ordering,

SELECT  * 
FROM 
        (
            SELECT *, 1 sortby FROM TABLE_A 
            UNION ALL 
            SELECT *, 2 sortby FROM TABLE_B
        ) dum
ORDER   BY sortby 

What does the "map" method do in Ruby?

Using ruby 2.4 you can do the same thing using transform_values, this feature extracted from rails to ruby.

h = {a: 1, b: 2, c: 3}

h.transform_values { |v| v * 10 }
 #=> {a: 10, b: 20, c: 30}

How to define constants in Visual C# like #define in C?

In C#, per MSDN library, we have the "const" keyword that does the work of the "#define" keyword in other languages.

"...when the compiler encounters a constant identifier in C# source code (for example, months), it substitutes the literal value directly into the intermediate language (IL) code that it produces." ( https://msdn.microsoft.com/en-us/library/ms173119.aspx )

Initialize constants at time of declaration since there is no changing them.

public const int cMonths = 12;

Comparing floating point number to zero

You are correct with your observation.

If x == 0.0, then abs(x) * epsilon is zero and you're testing whether abs(y) <= 0.0.

If y == 0.0 then you're testing abs(x) <= abs(x) * epsilon which means either epsilon >= 1 (it isn't) or x == 0.0.

So either is_equal(val, 0.0) or is_equal(0.0, val) would be pointless, and you could just say val == 0.0. If you want to only accept exactly +0.0 and -0.0.

The FAQ's recommendation in this case is of limited utility. There is no "one size fits all" floating-point comparison. You have to think about the semantics of your variables, the acceptable range of values, and the magnitude of error introduced by your computations. Even the FAQ mentions a caveat, saying this function is not usually a problem "when the magnitudes of x and y are significantly larger than epsilon, but your mileage may vary".

How to get first object out from List<Object> using Linq

Try this to get all the list at first, then your desired element (say the First in your case):

var desiredElementCompoundValueList = new List<YourType>();
dic.Values.ToList().ForEach( elem => 
{
   desiredElementCompoundValue.Add(elem.ComponentValue("Dep"));
});
var x = desiredElementCompoundValueList.FirstOrDefault();

To get directly the first element value without a lot of foreach iteration and variable assignment:

var desiredCompoundValue = dic.Values.ToList().Select( elem => elem.CompoundValue("Dep")).FirstOrDefault();

See the difference between the two approaches: in the first one you get the list through a ForEach, then your element. In the second you can get your value in a straight way.

Same result, different computation ;)

Generating Request/Response XML from a WSDL

Doing this yourself will give you insight into how a WSDL is structured and how it gets your job done. It is a good learning opportunity. This can be done using soapUI, if you only have the URL of the WSDL. (I'm using soapUI 5.2.1) If you actually have the complete WSDL as a file available to you, you don't even need soapUI. The title of the question says "Request & Response XML" while the question body says "Request & Response XML formats" which I interpret as the schema of the request and response. At any rate, the following will give you the schema which you can use on XSD2XML to generate sample XML.

  1. Start a "New Soap Project", enter a project name and WSDL location; choose to "Create Requests", unselect the other options and click OK.
  2. Under the "Project" tree on the left side, right-click an interface and choose "Show Interface Viewer".
  3. Select the "WSDL Content" tab.
  4. You should see the WSDL text on the right hand side; look for the block starting with "wsdl:types" below which are the schema for the input and output messages.
  5. Each schema definition starts with something like <s:element name="GetWeather"> and ends with </s:element>.
  6. Copy out the block into a text editor; above this block add: <?xml version="1.0" encoding="UTF-8"?> <s:schema xmlns:s="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
  7. Below the block of copied XML, add </s:schema>
  8. Decide if you need "UTF-16" instead of "UTF-8"
  9. The "s:" and the "xmlns:s" should match the block you copied (step 5)
  10. Save this file with ".xsd" extension; if you have "XML Copy Editor" or some such tool (XML Spy, may be) you should check that this is well-formed XML and valid schema.
  11. Repeat for all "element" items in the right hand pane of soapUI until you reach
  12. This way you'll get some type definitions you might not be interested in. If you want to pick and choose, use the following method: Look through the "wsdl:operation" items under "wsdl:portType" in the WSDL text below the type definitions. They will have "wsdl:input" and "wsdl:output". Take the message names from "wsdl:input" and "wsdl:output". Match them against "wsdl:message" names which will likely be above the "wsdl:portType" entries in the WSDL. Get the "wsdl:part" element name from "wsdl:message" item and look for that name as element name under "wsdl:types". Those will be the schema of interest to you.

You can try above procedure out using the WSDL at http://www.webservicex.com/globalweather.asmx?wsdl

Permutations in JavaScript?

Answer without the need for a exterior array or additional function

function permutator (arr) {
  var permutations = [];
  if (arr.length === 1) {
    return [ arr ];
  }

  for (var i = 0; i <  arr.length; i++) { 
    var subPerms = permutator(arr.slice(0, i).concat(arr.slice(i + 1)));
    for (var j = 0; j < subPerms.length; j++) {
      subPerms[j].unshift(arr[i]);
      permutations.push(subPerms[j]);
    }
  }
  return permutations;
}

Bootstrap's JavaScript requires jQuery version 1.9.1 or higher

If you are using CMS like Drupal or Wordpress - just install jQuery Update module and error no longer persists.

PHP function use variable from outside

Add second parameter

You need to pass additional parameter to your function:

function parts($site_url, $part) { 
    $structure = 'http://' . $site_url . 'content/'; 
    echo $structure . $part . '.php'; 
}

In case of closures

If you'd rather use closures then you can import variable to the current scope (the use keyword):

$parts = function($part) use ($site_url) { 
    $structure = 'http://' . $site_url . 'content/'; 
    echo $structure . $part . '.php'; 
};

global - a bad practice

This post is frequently read, so something needs to be clarified about global. Using it is considered a bad practice (refer to this and this).

For the completeness sake here is the solution using global:

function parts($part) { 
    global $site_url;
    $structure = 'http://' . $site_url . 'content/'; 
    echo($structure . $part . '.php'); 
}

It works because you have to tell interpreter that you want to use a global variable, now it thinks it's a local variable (within your function).

Suggested reading:

What's "P=NP?", and why is it such a famous question?

P stands for polynomial time. NP stands for non-deterministic polynomial time.

Definitions:

  • Polynomial time means that the complexity of the algorithm is O(n^k), where n is the size of your data (e. g. number of elements in a list to be sorted), and k is a constant.

  • Complexity is time measured in the number of operations it would take, as a function of the number of data items.

  • Operation is whatever makes sense as a basic operation for a particular task. For sorting, the basic operation is a comparison. For matrix multiplication, the basic operation is multiplication of two numbers.

Now the question is, what does deterministic vs. non-deterministic mean? There is an abstract computational model, an imaginary computer called a Turing machine (TM). This machine has a finite number of states, and an infinite tape, which has discrete cells into which a finite set of symbols can be written and read. At any given time, the TM is in one of its states, and it is looking at a particular cell on the tape. Depending on what it reads from that cell, it can write a new symbol into that cell, move the tape one cell forward or backward, and go into a different state. This is called a state transition. Amazingly enough, by carefully constructing states and transitions, you can design a TM, which is equivalent to any computer program that can be written. This is why it is used as a theoretical model for proving things about what computers can and cannot do.

There are two kinds of TM's that concern us here: deterministic and non-deterministic. A deterministic TM only has one transition from each state for each symbol that it is reading off the tape. A non-deterministic TM may have several such transition, i. e. it is able to check several possibilities simultaneously. This is sort of like spawning multiple threads. The difference is that a non-deterministic TM can spawn as many such "threads" as it wants, while on a real computer only a specific number of threads can be executed at a time (equal to the number of CPUs). In reality, computers are basically deterministic TMs with finite tapes. On the other hand, a non-deterministic TM cannot be physically realized, except maybe with a quantum computer.

It has been proven that any problem that can be solved by a non-deterministic TM can be solved by a deterministic TM. However, it is not clear how much time it will take. The statement P=NP means that if a problem takes polynomial time on a non-deterministic TM, then one can build a deterministic TM which would solve the same problem also in polynomial time. So far nobody has been able to show that it can be done, but nobody has been able to prove that it cannot be done, either.

NP-complete problem means an NP problem X, such that any NP problem Y can be reduced to X by a polynomial reduction. That implies that if anyone ever comes up with a polynomial-time solution to an NP-complete problem, that will also give a polynomial-time solution to any NP problem. Thus that would prove that P=NP. Conversely, if anyone were to prove that P!=NP, then we would be certain that there is no way to solve an NP problem in polynomial time on a conventional computer.

An example of an NP-complete problem is the problem of finding a truth assignment that would make a boolean expression containing n variables true.
For the moment in practice any problem that takes polynomial time on the non-deterministic TM can only be done in exponential time on a deterministic TM or on a conventional computer.
For example, the only way to solve the truth assignment problem is to try 2^n possibilities.

Count number of objects in list

You can also use unlist(), which is often useful for handling lists:

> mylist <- list(A = c(1:3), B = c(4:6), C = c(7:9))

> mylist
$A
[1] 1 2 3

$B
[1] 4 5 6

$C
[1] 7 8 9

> unlist(mylist)
A1 A2 A3 B1 B2 B3 C1 C2 C3 
 1  2  3  4  5  6  7  8  9 

> length(unlist(mylist))
[1] 9

unlist() is a simple way of executing other functions on lists as well, such as:

> sum(mylist)
Error in sum(mylist) : invalid 'type' (list) of argument

> sum(unlist(mylist))
[1] 45

Download files in laravel using Response::download

you can use simply inside your controller: return response()->download($filePath); Happy coding :)

jQuery if statement, syntax

You can wrap jQuery calls inside normal JavaScript code. So, for example:

$(document).ready(function() {
    if (someCondition && someOtherCondition) {
        // Make some jQuery call.
    }
});

How do I fill arrays in Java?

You can also do it as part of the declaration:

int[] a = new int[] {0, 0, 0, 0};

How can I align text in columns using Console.WriteLine?

Just to add to roya's answer. In c# 6.0 you can now use string interpolation:

Console.WriteLine($"{customer[DisplayPos],10}" +
                  $"{salesFigures[DisplayPos],10}" +
                  $"{feePayable[DisplayPos],10}" +
                  $"{seventyPercentValue,10}" +
                  $"{thirtyPercentValue,10}");

This can actually be one line without all the extra dollars, I just think it makes it a bit easier to read like this.

And you could also use a static import on System.Console, allowing you to do this:

using static System.Console;

WriteLine(/* write stuff */);

Java array assignment (multiple values)

    public class arrayFloats {
      public static void main (String [] args){
        float [] Values = new float[3];
        float Incre = 0.1f;
        int Count = 0;

        for (Count = 0;Count<3 ;Count++ ) {
          Values [Count] = Incre + 0.0f;
          Incre += 0.1f;
          System.out.println("Values [" + Count + "] : " + Values [Count]);
        }


      }
    }

//OUTPUT:
//Values [0] : 0.1
//Values [1] : 0.2
//Values [2] : 0.3

This isn't the all and be all of assigning values to a specific array. Since I've seen the sample was 0.1 - 0.3 you could do it this way. This method is very useful if you're designing charts and graphs. You can have the x-value incremented by 0.1 until nth time.

Or you want to design some grid of some sort.

How to set background color in jquery

$(this).css('background-color', 'red');

How to find out the MySQL root password

System:

  • CentOS Linux 7
  • mysql Ver 14.14 Distrib 5.7.25

Procedure:

  1. Open two shell sessions, logging in to one as the Linux root user and the other as a nonroot user with access to the mysql command.

  2. In your root session, stop the normal mysqld listener and start a listener which bypasses password authentication (note: this is a significant security risk as anyone with access to the mysql command may access your databases without a password. You may want to close active shell sessions and/or disable shell access before doing this):

    # systemctl stop mysqld
    # /usr/sbin/mysqld --skip-grant-tables -u mysql &

  3. In your nonroot session, log in to mysql and set the mysql root password:

    $ mysql
    mysql> flush privileges;
    Query OK, 0 rows affected (0.00 sec)

    mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPass');
    Query OK, 0 rows affected, 1 warning (0.01 sec)

    mysql> quit;

  4. In your root session, kill the passwordless instance of mysqld and restore the normal mysqld listener to service:

    # kill %1
    # systemctl start mysqld

  5. In your nonroot session, test the new root password you configured above:

    $ mysql -u root -p
    Enter password:
    Welcome to the MySQL monitor. Commands end with ; or \g.
    ...
    mysql>

Why must wait() always be in synchronized block

The problem it may cause if you do not synchronize before wait() is as follows:

  1. If the 1st thread goes into makeChangeOnX() and checks the while condition, and it is true (x.metCondition() returns false, means x.condition is false) so it will get inside it. Then just before the wait() method, another thread goes to setConditionToTrue() and sets the x.condition to true and notifyAll().
  2. Then only after that, the 1st thread will enter his wait() method (not affected by the notifyAll() that happened few moments before). In this case, the 1st thread will stay waiting for another thread to perform setConditionToTrue(), but that might not happen again.

But if you put synchronized before the methods that change the object state, this will not happen.

class A {

    private Object X;

    makeChangeOnX(){
        while (! x.getCondition()){
            wait();
            }
        // Do the change
    }

    setConditionToTrue(){
        x.condition = true; 
        notifyAll();

    }
    setConditionToFalse(){
        x.condition = false;
        notifyAll();
    }
    bool getCondition(){
        return x.condition;
    }
}

Floating Point Exception C++ Why and what is it?

Lots of reasons for a floating point exception. Looking at your code your for loop seems to be a bit "incorrect". Looks like a possible division by zero.

for (i>0; i--;){
c= input%i;

Thats division by zero at some point since you are decrementing i.

Finding the max value of an attribute in an array of objects

It's very simple

     const array1 = [
  {id: 1, val: 60},
  {id: 2, val: 2},
  {id: 3, val: 89},
  {id: 4, val: 78}
];
const array2 = [1,6,8,79,45,21,65,85,32,654];
const max = array1.reduce((acc, item) => acc = acc > item.val ? acc : item.val, 0);
const max2 = array2.reduce((acc, item) => acc = acc > item ? acc : item, 0);

console.log(max);
console.log(max2);

NPM clean modules

Try https://github.com/voidcosmos/npkill

npx npkill

it will find all node_modules and let you remove them.

npkill

LaTeX beamer: way to change the bullet indentation?

I use the package enumitem. You may then set such margins when you declare your lists (enumerate, description, itemize):

\begin{itemize}[leftmargin=0cm]
    \item Foo
    \item Bar
\end{itemize}

Naturally, the package provides lots of other nice customizations for lists (use 'label=' to change the bullet, use 'itemsep=' to change the spacing between items, etc...)

Wait until ActiveWorkbook.RefreshAll finishes - VBA

Here is a solution found at http://www.mrexcel.com/forum/excel-questions/510011-fails-activeworkbook-refreshall-backgroundquery-%3Dfalse.html:

Either have all the pivotcaches' backgroundquery properties set to False, or loop through all the workbook's pivotcaches:

Code:
    For Each pc In ActiveWorkbook.PivotCaches
       pc.BackgroundQuery = False
       pc.Refresh
    Next 

this will leave all pivotcaches backgroundquery properties as false. You could retain each one's settings with:

Code:

For Each pc In ActiveWorkbook.PivotCaches
  originalBGStatus = pc.BackgroundQuery
  pc.BackgroundQuery = False
  pc.Refresh
  pc.BackgroundQuery = originalBGStatus
Next

Django. Override save for model

You may supply extra argument for confirming a new image is posted.
Something like:

def save(self, new_image=False, *args, **kwargs):
    if new_image:
        small=rescale_image(self.image,width=100,height=100)
        self.image_small=SimpleUploadedFile(name,small_pic)
    super(Model, self).save(*args, **kwargs)

or pass request variable

def save(self, request=False, *args, **kwargs):
    if request and request.FILES.get('image',False):
        small=rescale_image(self.image,width=100,height=100)
        self.image_small=SimpleUploadedFile(name,small_pic)
    super(Model, self).save(*args, **kwargs)

I think these wont break your save when called simply.

You may put this in your admin.py so that this work with admin site too (for second of above solutions):

class ModelAdmin(admin.ModelAdmin):

    ....
    def save_model(self, request, obj, form, change): 
        instance = form.save(commit=False)
        instance.save(request=request)
        return instance

Generating random, unique values C#

Try this:

private void NewNumber()
  {
     Random a = new Random(Guid.newGuid().GetHashCode());
     MyNumber = a.Next(0, 10);
  }

Some Explnations:

Guid : base on here : Represents a globally unique identifier (GUID)

Guid.newGuid() produces a unique identifier like "936DA01F-9ABD-4d9d-80C7-02AF85C822A8"

and it will be unique in all over the universe base on here

Hash code here produce a unique integer from our unique identifier

so Guid.newGuid().GetHashCode() gives us a unique number and the random class will produce real random numbers throw this

Sample: https://rextester.com/ODOXS63244

generated ten random numbers with this approach with result of:

-1541116401
7
-1936409663
3
-804754459
8
1403945863
3
1287118327
1
2112146189
1
1461188435
9
-752742620
4
-175247185
4
1666734552
7

we got two 1s next to each other, but the hash codes do not same.

When to use IList and when to use List

Microsoft guidelines as checked by FxCop discourage use of List<T> in public APIs - prefer IList<T>.

Incidentally, I now almost always declare one-dimensional arrays as IList<T>, which means I can consistently use the IList<T>.Count property rather than Array.Length. For example:

public interface IMyApi
{
    IList<int> GetReadOnlyValues();
}

public class MyApiImplementation : IMyApi
{
    public IList<int> GetReadOnlyValues()
    {
        List<int> myList = new List<int>();
        ... populate list
        return myList.AsReadOnly();
    }
}
public class MyMockApiImplementationForUnitTests : IMyApi
{
    public IList<int> GetReadOnlyValues()
    {
        IList<int> testValues = new int[] { 1, 2, 3 };
        return testValues;
    }
}

Only variable references should be returned by reference - Codeigniter

this has been modified in codeigniter 2.2.1...usually not best practice to modify core files, I would always check for updates and 2.2.1 came out in Jan 2015

Is there a way to create xxhdpi, xhdpi, hdpi, mdpi and ldpi drawables from a large scale image?

The easiest way is to use Resource Manager

enter image description here

Then you can select each density

enter image description here

And after importing you can see the 6 different versions of this image

enter image description here

Adding Apostrophe in every field in particular column for excel

i use concantenate. works for me.

  1. fill j2-j14 with '(appostrophe)
  2. enter L2 with formula =concantenate(j2,k2)
  3. copy L2 to L3-L14

What is the difference between attribute and property?

Delphi used properties and they have found their way into .NET (because it has the same architect).

In Delphi they are often used in combination with runtime type information such that the integrated property editor can be used to set the property in designtime.

Properties are not always related to fields. They can be functions that possible have side effects (but of course that is very bad design).

Keyboard shortcut to comment lines in Sublime Text 2

By default on Linux/Windows for an English keyboard the shortcut is Ctrl+Shift+/ to toggle a block comment, and Ctrl+/ to toggle a line comment.

If you go into Preferences->Key Bindings - Default, you can find all the shortcuts, below are the lines for commenting.

{ "keys": ["ctrl+/"], "command": "toggle_comment", "args": { "block": false } },
{ "keys": ["ctrl+shift+/"], "command": "toggle_comment", "args": { "block": true } },

Git for beginners: The definitive practical guide

git status is your friend, use it often. Good for answering questions like:

  • What did that command just do?
  • What branch am I on?
  • What changes am I about to commit, and have I forgotten anything?
  • Was I in the middle of something last time I worked on this project (days, weeks, or perhaps months ago)?

Unlike, say svn status, git status runs nigh-instantly even on large projects. I often found it reassuring while learning git to use it frequently, to make sure my mental model of what was going on was accurate. Now I mostly just use it to remind myself what I've changed since my last commit.

Obviously, it's much more useful if your .gitignore is sanely configured.

jQuery validation plugin: accept only alphabetical characters?

Just a small addition to Nick's answer (which works great !) :

If you want to allow spaces in between letters, for example , you may restrict to enter only letters in full name, but it should allow space as well - just list the space as below with a comma. And in the same way if you need to allow any other specific character:

jQuery.validator.addMethod("lettersonly", function(value, element) 
{
return this.optional(element) || /^[a-z," "]+$/i.test(value);
}, "Letters and spaces only please");       

Which is preferred: Nullable<T>.HasValue or Nullable<T> != null?

I did some research on this by using different methods to assign values to a nullable int. Here is what happened when I did various things. Should clarify what's going on. Keep in mind: Nullable<something> or the shorthand something? is a struct for which the compiler seems to be doing a lot of work to let us use with null as if it were a class.
As you'll see below, SomeNullable == null and SomeNullable.HasValue will always return an expected true or false. Although not demonstrated below, SomeNullable == 3 is valid too (assuming SomeNullable is an int?).
While SomeNullable.Value gets us a runtime error if we assigned null to SomeNullable. This is in fact the only case where nullables could cause us a problem, thanks to a combination of overloaded operators, overloaded object.Equals(obj) method, and compiler optimization and monkey business.

Here is a description of some code I ran, and what output it produced in labels:

int? val = null;
lbl_Val.Text = val.ToString(); //Produced an empty string.
lbl_ValVal.Text = val.Value.ToString(); //Produced a runtime error. ("Nullable object must have a value.")
lbl_ValEqNull.Text = (val == null).ToString(); //Produced "True" (without the quotes)
lbl_ValNEqNull.Text = (val != null).ToString(); //Produced "False"
lbl_ValHasVal.Text = val.HasValue.ToString(); //Produced "False"
lbl_NValHasVal.Text = (!(val.HasValue)).ToString(); //Produced "True"
lbl_ValValEqNull.Text = (val.Value == null).ToString(); //Produced a runtime error. ("Nullable object must have a value.")
lbl_ValValNEqNull.Text = (val.Value != null).ToString(); //Produced a runtime error. ("Nullable object must have a value.")

Ok, lets try the next initialization method:

int? val = new int?();
lbl_Val.Text = val.ToString(); //Produced an empty string.
lbl_ValVal.Text = val.Value.ToString(); //Produced a runtime error. ("Nullable object must have a value.")
lbl_ValEqNull.Text = (val == null).ToString(); //Produced "True" (without the quotes)
lbl_ValNEqNull.Text = (val != null).ToString(); //Produced "False"
lbl_ValHasVal.Text = val.HasValue.ToString(); //Produced "False"
lbl_NValHasVal.Text = (!(val.HasValue)).ToString(); //Produced "True"
lbl_ValValEqNull.Text = (val.Value == null).ToString(); //Produced a runtime error. ("Nullable object must have a value.")
lbl_ValValNEqNull.Text = (val.Value != null).ToString(); //Produced a runtime error. ("Nullable object must have a value.")

All the same as before. Keep in mind that initializing with int? val = new int?(null);, with null passed to the constructor, would have produced a COMPILE time error, since the nullable object's VALUE is NOT nullable. It is only the wrapper object itself that can equal null.

Likewise, we would get a compile time error from:

int? val = new int?();
val.Value = null;

not to mention that val.Value is a read-only property anyway, meaning we can't even use something like:

val.Value = 3;

but again, polymorphous overloaded implicit conversion operators let us do:

val = 3;

No need to worry about polysomthing whatchamacallits though, so long as it works right? :)

Convert HTML to PDF in .NET

Quite likely most projects will wrap a C/C++ Engine rather than implementing a C# solution from scratch. Try Project Gotenberg.

To test it

docker run --rm -p 3000:3000 thecodingmachine/gotenberg:6

Curl sample

curl --request POST \
    --url http://localhost:3000/convert/url \
    --header 'Content-Type: multipart/form-data' \
    --form remoteURL=https://brave.com \
    --form marginTop=0 \
    --form marginBottom=0 \
    --form marginLeft=0 \
    --form marginRight=0 \
    -o result.pdf

C# sample.cs

using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;
using static System.Console;

namespace Gotenberg
{
    class Program
    {
        public static async Task Main(string[] args)
        {
            try
            {
                var client = new HttpClient();            
                var formContent = new MultipartFormDataContent
                    {
                        {new StringContent("https://brave.com/"), "remoteURL"},
                        {new StringContent("0"), "marginTop" }
                    };
                var result = await client.PostAsync(new Uri("http://localhost:3000/convert/url"), formContent);
                await File.WriteAllBytesAsync("duckduck.com.pdf", await result.Content.ReadAsByteArrayAsync());
            }
            catch (Exception ex)
            {
                WriteLine(ex);
            }
        }
    }
}

To compile

csc sample.cs -langversion:latest -reference:System.Net.Http.dll && mono ./sample.exe

Convert all data frame character columns to factors

I noticed "[" indexing columns fails to create levels when iterating:

for ( a_feature in convert.to.factors) {
feature.df[a_feature] <- factor(feature.df[a_feature]) }

It creates, e.g. for the "Status" column:

Status : Factor w/ 1 level "c(\"Success\", \"Fail\")" : NA NA NA ...

Which is remedied by using "[[" indexing:

for ( a_feature in convert.to.factors) {
feature.df[[a_feature]] <- factor(feature.df[[a_feature]]) }

Giving instead, as desired:

. Status : Factor w/ 2 levels "Success", "Fail" : 1 1 2 1 ...

How to force Chrome's script debugger to reload javascript?

For Google chrome it is not Ctrl+F5. It's Shift+F5 to clear the current cache! It works for me !

Adb install failure: INSTALL_CANCELED_BY_USER

1 Settings

2 Additional Settings

3 Developer Options

4 Developer options: Check the Install via USB option.

enter image description here

Stop mouse event propagation

This worked for me:

mycomponent.component.ts:

action(event): void {
  event.stopPropagation();
}

mycomponent.component.html:

<button mat-icon-button (click)="action($event);false">Click me !<button/>

Spring Boot - How to log all requests and responses with exceptions in single place?

If you are seeing only part of your request payload, you need to call the setMaxPayloadLength function as it defaults to showing only 50 characters in your request body. Also, setting setIncludeHeaders to false is a good idea if you don't want to log your auth headers!

@Bean
public CommonsRequestLoggingFilter requestLoggingFilter() {
    CommonsRequestLoggingFilter loggingFilter = new CommonsRequestLoggingFilter();
    loggingFilter.setIncludeClientInfo(false);
    loggingFilter.setIncludeQueryString(false);
    loggingFilter.setIncludePayload(true);
    loggingFilter.setIncludeHeaders(false);
    loggingFilter.setMaxPayloadLength(500);
    return loggingFilter;
}

How to generate UML diagrams (especially sequence diagrams) from Java code?

By far the best tool I have used for reverse engineering, and round tripping java -> UML is Borland's Together. It is based on Eclipse (not just a single plugin) and really works well.

Create <div> and append <div> dynamically

    while(i<10){
               $('#Postsoutput').prepend('<div id="first'+i+'">'+i+'</div>');
               /* get the dynamic Div*/
               $('#first'+i).hide(1000);
               $('#first'+i).show(1000);
                i++;
                }

Fitting empirical distribution to theoretical ones with Scipy (Python)?

The following code is the version of the general answer but with corrections and clarity.

import numpy as np
import pandas as pd
import scipy.stats as st
import statsmodels.api as sm
import matplotlib as mpl
import matplotlib.pyplot as plt
import math
import random

mpl.style.use("ggplot")

def danoes_formula(data):
    """
    DANOE'S FORMULA
    https://en.wikipedia.org/wiki/Histogram#Doane's_formula
    """
    N = len(data)
    skewness = st.skew(data)
    sigma_g1 = math.sqrt((6*(N-2))/((N+1)*(N+3)))
    num_bins = 1 + math.log(N,2) + math.log(1+abs(skewness)/sigma_g1,2)
    num_bins = round(num_bins)
    return num_bins

def plot_histogram(data, results, n):
    ## n first distribution of the ranking
    N_DISTRIBUTIONS = {k: results[k] for k in list(results)[:n]}

    ## Histogram of data
    plt.figure(figsize=(10, 5))
    plt.hist(data, density=True, ec='white', color=(63/235, 149/235, 170/235))
    plt.title('HISTOGRAM')
    plt.xlabel('Values')
    plt.ylabel('Frequencies')

    ## Plot n distributions
    for distribution, result in N_DISTRIBUTIONS.items():
        # print(i, distribution)
        sse = result[0]
        arg = result[1]
        loc = result[2]
        scale = result[3]
        x_plot = np.linspace(min(data), max(data), 1000)
        y_plot = distribution.pdf(x_plot, loc=loc, scale=scale, *arg)
        plt.plot(x_plot, y_plot, label=str(distribution)[32:-34] + ": " + str(sse)[0:6], color=(random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1)))
    
    plt.legend(title='DISTRIBUTIONS', bbox_to_anchor=(1.05, 1), loc='upper left')
    plt.show()

def fit_data(data):
    ## st.frechet_r,st.frechet_l: are disbled in current SciPy version
    ## st.levy_stable: a lot of time of estimation parameters
    ALL_DISTRIBUTIONS = [        
        st.alpha,st.anglit,st.arcsine,st.beta,st.betaprime,st.bradford,st.burr,st.cauchy,st.chi,st.chi2,st.cosine,
        st.dgamma,st.dweibull,st.erlang,st.expon,st.exponnorm,st.exponweib,st.exponpow,st.f,st.fatiguelife,st.fisk,
        st.foldcauchy,st.foldnorm, st.genlogistic,st.genpareto,st.gennorm,st.genexpon,
        st.genextreme,st.gausshyper,st.gamma,st.gengamma,st.genhalflogistic,st.gilbrat,st.gompertz,st.gumbel_r,
        st.gumbel_l,st.halfcauchy,st.halflogistic,st.halfnorm,st.halfgennorm,st.hypsecant,st.invgamma,st.invgauss,
        st.invweibull,st.johnsonsb,st.johnsonsu,st.ksone,st.kstwobign,st.laplace,st.levy,st.levy_l,
        st.logistic,st.loggamma,st.loglaplace,st.lognorm,st.lomax,st.maxwell,st.mielke,st.nakagami,st.ncx2,st.ncf,
        st.nct,st.norm,st.pareto,st.pearson3,st.powerlaw,st.powerlognorm,st.powernorm,st.rdist,st.reciprocal,
        st.rayleigh,st.rice,st.recipinvgauss,st.semicircular,st.t,st.triang,st.truncexpon,st.truncnorm,st.tukeylambda,
        st.uniform,st.vonmises,st.vonmises_line,st.wald,st.weibull_min,st.weibull_max,st.wrapcauchy
    ]
    
    MY_DISTRIBUTIONS = [st.beta, st.expon, st.norm, st.uniform, st.johnsonsb, st.gennorm, st.gausshyper]

    ## Calculae Histogram
    num_bins = danoes_formula(data)
    frequencies, bin_edges = np.histogram(data, num_bins, density=True)
    central_values = [(bin_edges[i] + bin_edges[i+1])/2 for i in range(len(bin_edges)-1)]

    results = {}
    for distribution in MY_DISTRIBUTIONS:
        ## Get parameters of distribution
        params = distribution.fit(data)
        
        ## Separate parts of parameters
        arg = params[:-2]
        loc = params[-2]
        scale = params[-1]
    
        ## Calculate fitted PDF and error with fit in distribution
        pdf_values = [distribution.pdf(c, loc=loc, scale=scale, *arg) for c in central_values]
        
        ## Calculate SSE (sum of squared estimate of errors)
        sse = np.sum(np.power(frequencies - pdf_values, 2.0))
        
        ## Build results and sort by sse
        results[distribution] = [sse, arg, loc, scale]
        
    results = {k: results[k] for k in sorted(results, key=results.get)}
    return results
        
def main():
    ## Import data
    data = pd.Series(sm.datasets.elnino.load_pandas().data.set_index('YEAR').values.ravel())
    results = fit_data(data)
    plot_histogram(data, results, 5)

if __name__ == "__main__":
    main()
    
    

enter image description here

How to declare and display a variable in Oracle

If using sqlplus you can define a variable thus:

define <varname>=<varvalue>

And you can display the value by:

define <varname>

And then use it in a query as, for example:

select *
from tab1
where col1 = '&varname';

How can I insert multiple rows into oracle with a sequence value?

This works:

insert into TABLE_NAME (COL1,COL2)
select my_seq.nextval, a
from
(SELECT 'SOME VALUE' as a FROM DUAL
 UNION ALL
 SELECT 'ANOTHER VALUE' FROM DUAL)

What is the best comment in source code you have ever encountered?

// woot, global var. I havent done this for a long time.

How to use onClick with divs in React.js

For future googlers (thousands have now googled this question):

To set your mind at ease, the onClick event does work with divs in react, so double-check your code syntax.

These are right:

<div onClick={doThis}>
<div onClick={() => doThis()}>

These are wrong:

<div onClick={doThis()}>
<div onClick={() => doThis}>

(and don't forget to close your tags... Watch for this:

<div onClick={doThis}

missing closing tag on the div)

Removing page title and date when printing web page (with CSS?)

A possible workaround for the page title:

  • Provide a print button,
  • catch the onclick event,
  • use javascript to change the page title,
  • then execute the print command via javascript as well.

document.title = "Print page title"; window.print();

This should work in every browser.

batch file to check 64bit or 32bit OS

If $SYSTEM_os_arch==x86 ( 
  Echo OS is 32bit
 ) else ( 
  ECHO OS is 64bit
)

WPF Check box: Check changed handling

A simple and proper way I've found to Handle Checked/Unchecked events using MVVM pattern is the Following, with Caliburn.Micro :

 <CheckBox IsChecked="{Binding IsCheckedBooleanProperty}" Content="{DynamicResource DisplayContent}" cal:Message.Attach="[Event Checked] = [Action CheckBoxClicked()]; [Event Unchecked] = [Action CheckBoxClicked()]" />

And implement a Method CheckBoxClicked() in the ViewModel, to do stuff you want.

How to convert integer into date object python?

import datetime

timestamp = datetime.datetime.fromtimestamp(1500000000)

print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))

This will give the output:

2017-07-14 08:10:00

Map and filter an array at the same time

I optimized the answers with the following points:

  1. Rewriting if (cond) { stmt; } as cond && stmt;
  2. Use ES6 Arrow Functions

I'll present two solutions, one using forEach, the other using reduce:

Solution 1: Using forEach

_x000D_
_x000D_
var options = [_x000D_
  { name: 'One', assigned: true }, _x000D_
  { name: 'Two', assigned: false }, _x000D_
  { name: 'Three', assigned: true }, _x000D_
];_x000D_
var reduced = []_x000D_
options.forEach(o => {_x000D_
  o.assigned && reduced.push( { name: o.name, newProperty: 'Foo' } );_x000D_
} );_x000D_
console.log(reduced);
_x000D_
_x000D_
_x000D_

Solution 2: Using reduce

_x000D_
_x000D_
var options = [_x000D_
  { name: 'One', assigned: true }, _x000D_
  { name: 'Two', assigned: false }, _x000D_
  { name: 'Three', assigned: true }, _x000D_
];_x000D_
var reduced = options.reduce((a, o) => {_x000D_
  o.assigned && a.push( { name: o.name, newProperty: 'Foo' } );_x000D_
  return a;_x000D_
}, [ ] );_x000D_
console.log(reduced);
_x000D_
_x000D_
_x000D_

I leave it up to you to decide which solution to go for.

Android studio doesn't list my phone under "Choose Device"

Have you installed drivers for the phone? http://developer.android.com/sdk/win-usb.html

It appears that the the sdk does not "install" the USB drivers. You can select that usb drivers in the sdk to see the file location, open that up, and right click to install the driver yourself.

  • File -> Settings -> Android SDK -> SDK Tools -> Google USB Driver -> Right click -> Install
    • Ensure that Google USB driver is checked.

If above doesn't work, @Abir Hasan appears to have another method in answers below.

PHP Get URL with Parameter

Here's probably what you are looking for: php-get-url-query-string. You can combine it with other suggested $_SERVER parameters.

A project with an Output Type of Class Library cannot be started directly

The strange part is that I don't see a main function anywhere.

That is exactly your problem. The project merely creates a DLL. It has no executable to run.

You will need to add a second project, which is an executable which references the other project, and calls something in it.

In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?

== Equality operator evaluates the arguments after converting them to numbers. So string zero "0" is converted to Number data type and boolean false is converted to Number 0. So

"0" == false // true

Same applies to `

false == "0" //true

=== Strict equality check evaluates the arguments with the original data type

"0" === false // false, because "0" is a string and false is boolean

Same applies to

false === "0" // false

In

if("0") console.log("ha");

The String "0" is not comparing with any arguments, and string is a true value until or unless it is compared with any arguments. It is exactly like

if(true) console.log("ha");

But

if (0) console.log("ha"); // empty console line, because 0 is false

`

Rails: Can't verify CSRF token authenticity when making a POST request

If you want to exclude the sample controller's sample action

class TestController < ApplicationController
  protect_from_forgery :except => [:sample]

  def sample
     render json: @hogehoge
  end
end

You can to process requests from outside without any problems.

How to switch position of two items in a Python list?

you can use for example:

>>> test_list = ['title', 'email', 'password2', 'password1', 'first_name',
                 'last_name', 'next', 'newsletter']
>>> reorder_func = lambda x: x.insert(x.index('password2'),  x.pop(x.index('password2')+1))
>>> reorder_func(test_list)
>>> test_list
... ['title', 'email', 'password1', 'password2', 'first_name', 'last_name', 'next', 'newsletter']

How to convert flat raw disk image to vmdk for virtualbox or vmplayer?

First, install QEMU. On Debian-based distributions like Ubuntu, run:

$ apt-get install qemu

Then run the following command:

$ qemu-img convert -O vmdk imagefile.dd vmdkname.vmdk

I’m assuming a flat disk image is a dd-style image. The convert operation also handles numerous other formats.

For more information about the qemu-img command, see the output of

$ qemu-img -h

How to reload / refresh model data from the server programmatically?

Before I show you how to reload / refresh model data from the server programmatically? I have to explain for you the concept of Data Binding. This is an extremely powerful concept that will truly revolutionize the way you develop. So may be you have to read about this concept from this link or this seconde link in order to unterstand how AngularjS work.

now I'll show you a sample example that exaplain how can you update your model from server.

HTML Code:

<div ng-controller="PersonListCtrl">
    <ul>
        <li ng-repeat="person in persons">
            Name: {{person.name}}, Age {{person.age}}
        </li>
    </ul>
   <button ng-click="updateData()">Refresh Data</button>
</div>

So our controller named: PersonListCtrl and our Model named: persons. go to your Controller js in order to develop the function named: updateData() that will be invoked when we are need to update and refresh our Model persons.

Javascript Code:

app.controller('adsController', function($log,$scope,...){

.....

$scope.updateData = function(){
$http.get('/persons').success(function(data) {
       $scope.persons = data;// Update Model-- Line X
     });
}

});

Now I explain for you how it work: when user click on button Refresh Data, the server will call to function updateData() and inside this function we will invoke our web service by the function $http.get() and when we have the result from our ws we will affect it to our model (Line X).Dice that affects the results for our model, our View of this list will be changed with new Data.

Markdown and image alignment

I have an alternative to the methods above that used the ALT tag and a CSS selector on the alt tag... Instead, add a URL hash like this:

First your Markdown image code:

![my image](/img/myImage.jpg#left)
![my image](/img/myImage.jpg#right)
![my image](/img/myImage.jpg#center)

Note the added URL hash #center.

Now add this rule in CSS using CSS 3 attribute selectors to select images with a certain path.

img[src*='#left'] {
    float: left;
}
img[src*='#right'] {
    float: right;
}
img[src*='#center'] {
    display: block;
    margin: auto;
}

You should be able to use a URL hash like this almost like defining a class name and it isn't a misuse of the ALT tag like some people had commented about for that solution. It also won't require any additional extensions. Do one for float right and left as well or any other styles you might want.

"installation of package 'FILE_PATH' had non-zero exit status" in R

For those of you who are using MacOS and like me perhaps have been circling the internet as to why some R packages do not install here is a possible help.

If you get a non-zero exit status first check to ensure all dependencies are installed as well. Read through the messaging. If that is checked off, then look for indications such as gfortran: No such a file or directory. That might be due to Apple OS compiler issues that some packages will not install unless you use their binary version. Look for binary zip file in the package cran.r-project.org page, download it and use the following command to get the package installed:

install.packages("/PATH/zip file ", repos = NULL, type="source")

Copying formula to the next row when inserting a new row

Private Sub Worksheet_Change(ByVal Target As Range)

'data starts on row 3 which has the formulas
'the sheet is protected - input cells not locked - formula cells locked
'this routine is triggered on change of any cell on the worksheet so first check if
' it's a cell that we're interested in - and the row doesn't already have formulas
If Target.Column = 3 And Target.Row > 3 _
And Range("M" & Target.Row).Formula = "" Then

    On Error GoTo ERROR_OCCURRED

    'unprotect the sheet - otherwise can't copy and paste
    ActiveSheet.Unprotect
    'disable events - this prevents this routine from triggering again when
    'copy and paste below changes the cell values
    Application.EnableEvents = False

    'copy col D (with validation list) from row above to new row (not locked)
    Range("D" & Target.Row - 1).Copy
    Range("D" & Target.Row).PasteSpecial

    'copy col M to P (with formulas) from row above to new row
    Range("M" & Target.Row - 1 & ":P" & Target.Row - 1).Copy
    Range("M" & Target.Row).PasteSpecial

'make sure if an error occurs (or not) events are re-enabled and sheet re-protected

ERROR_OCCURRED:

    If Err.Number <> 0 Then
        MsgBox "An error occurred. Formulas may not have been copied." & vbCrLf & vbCrLf & _
            Err.Number & " - " & Err.Description
    End If

    're-enable events
    Application.EnableEvents = True
    're-protect the sheet
    ActiveSheet.Protect

    'put focus back on the next cell after routine was triggered
    Range("D" & Target.Row).Select

End If

End Sub

How to multiply a BigDecimal by an integer in Java

First off, BigDecimal.multiply() returns a BigDecimal and you're trying to store that in an int.

Second, it takes another BigDecimal as the argument, not an int.

If you just use the BigDecimal for all variables involved in these calculations, it should work fine.

Command line to remove an environment variable from the OS level configuration

I agree with CupawnTae.

SET is not useful for changes to the master environment.

FYI: System variables are in HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment (a good deal longer than user vars).

The full command for a system var named FOOBAR therefore is:

REG delete "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /F /V FOOBAR

(Note the quotes required to handle the space.)

It is too bad the setx command doesn't support a delete syntax. :(

PS: Use responsibly - If you kill your path variable, don't blame me!

Exception Error c0000005 in VC++

Exception code c0000005 is the code for an access violation. That means that your program is accessing (either reading or writing) a memory address to which it does not have rights. Most commonly this is caused by:

  • Accessing a stale pointer. That is accessing memory that has already been deallocated. Note that such stale pointer accesses do not always result in access violations. Only if the memory manager has returned the memory to the system do you get an access violation.
  • Reading off the end of an array. This is when you have an array of length N and you access elements with index >=N.

To solve the problem you'll need to do some debugging. If you are not in a position to get the fault to occur under your debugger on your development machine you should get a crash dump file and load it into your debugger. This will allow you to see where in the code the problem occurred and hopefully lead you to the solution. You'll need to have the debugging symbols associated with the executable in order to see meaningful stack traces.

How to create exe of a console application

For .net core 2.1 console application, the following approaches worked for me:

1 - from CLI (after building the application and navigating to debug or release folders based on the build type specified):

dotnet appName.dll

2 - from Visual Studio

R.C solution and click publish
'Target location' -> 'configure' ->
   'Deployment Mode' = 'Self-Contained'
   'Target Runtime' = 'win-x64 or win-x86 depending on the OS'

References:

For an in depth explanation of all the deployment options available for .net core applications, checkout the following articles:

Converting datetime.date to UTC timestamp in Python

Considering you have a datetime object called d, use the following to get the timestamp in UTC:

d.strftime("%Y-%m-%dT%H:%M:%S.%fZ")

And for the opposite direction, use following :

d = datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%fZ")

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

You can use howfat which also displays dependency statistics:

npx howfat -r tree jasmine

screensot

How to find a string inside a entire database?

I usually use information_Schema.columns and information_schema.tables, although like @yuck said, sys.tables and sys.columns are shorter to type.

In a loop, concatenate these

@sql = @sql + 'select' + column_name + 
' from ' + table_name + 
' where ' + column_name ' like ''%''+value+''%' UNION

Then execute the resulting sql.

how to configure apache server to talk to HTTPS backend server?

Your server tells you exactly what you need : [Hint: SSLProxyEngine]

You need to add that directive to your VirtualHost before the Proxy directives :

SSLProxyEngine on
ProxyPass /primary/store https://localhost:9763/store/
ProxyPassReverse /primary/store https://localhost:9763/store/

See the doc for more detail.

How to parse the AndroidManifest.xml file inside an .apk package

Check this following WPF Project which decodes the properties correctly.

What is the use of static synchronized method in java?

Java VM contains a single class object per class. Each class may have some shared variables called static variables. If the critical section of the code plays with these variables in a concurrent environment, then we need to make that particular section as synchronized. When there is more than one static synchronized method only one of them will be executed at a time without preemption. That's what lock on class object does.

HTML Entity Decode

You could try something like:

_x000D_
_x000D_
var Title = $('<textarea />').html("Chris&apos; corner").text();_x000D_
console.log(Title);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

JS Fiddle.

A more interactive version:

_x000D_
_x000D_
$('form').submit(function() {_x000D_
  var theString = $('#string').val();_x000D_
  var varTitle = $('<textarea />').html(theString).text();_x000D_
  $('#output').text(varTitle);_x000D_
  return false;_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form action="#" method="post">_x000D_
  <fieldset>_x000D_
    <label for="string">Enter a html-encoded string to decode</label>_x000D_
    <input type="text" name="string" id="string" />_x000D_
  </fieldset>_x000D_
  <fieldset>_x000D_
    <input type="submit" value="decode" />_x000D_
  </fieldset>_x000D_
</form>_x000D_
_x000D_
<div id="output"></div>
_x000D_
_x000D_
_x000D_

JS Fiddle.

How to calculate the sentence similarity using word2vec model of gensim with python

You can just add the word vectors of one sentence together. Then count the Cosine similarity of two sentence vector as the similarity of two sentence. I think that's the most easy way.

How do I vertically align something inside a span tag?

The flexbox way:

.foo {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 50px;
}

CSS filter: make color image with transparency white

To my knowledge, there is sadly no CSS filter to colorise an element (perhaps with the use of some SVG filter magic, but I'm somewhat unfamiliar with that) and even if that wasn't the case, filters are basically only supported by webkit browsers.

With that said, you could still work around this and use a canvas to modify your image. Basically, you can draw an image element onto a canvas and then loop through the pixels, modifying the respective RGBA values to the colour you want.

However, canvases do come with some restrictions. Most importantly, you have to make sure that the image src comes from the same domain as the page. Otherwise the browser won't allow you to read or modify the pixel data of the canvas.

Here's a JSFiddle changing the colour of the JSFiddle logo.

_x000D_
_x000D_
//Base64 source, but any local source will work_x000D_
var src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC0AAAAgCAYAAACGhPFEAAAABGdBTUEAALGPC/xhBQAABzhJREFUWAnNWAtwXFUZ/v9zs4GUJJu+k7tb5DFAGWO1aal1sJUiY3FQQaWidqgPLAMqYzd9CB073VodhCa7KziiFgWhzvAYQCiCD5yK4gOTDnZK2ymdZoruppu0afbu0pBs7p7f7yy96W662aw2QO/Mzj2P//Gd/5z/+89dprfzubnTN332Re+xiKawllxWucm+9O4eCi9xT8ctn45yKd3AXX1BPsu3XIiuY+K5kDmrUA7jORb5m2baLm7uscNrJr9eOF9Je8JAz9ySnFHlq9nEpG6CYx+RdJDQDtKymxT1iWZLFDUy0/kkfDUxzYVzV0hvHZLs946Gph+uBLCRmRDQdjTVwmw9DZCNMPi4KzqWbPX/sxwIu71vlrKq10HnZizwTSFZngj5f1NOx5s7bdB2LHWDEusBOD487LrX9qyd8qpnvJL3zGjqAh+pR4W4RVhu715Vv2U8PTWeQLn5YHvms4qsR4TpH/ImLfhfARvbPaGGrrjTtwjH5hFFfHcgkv5SOZ9mbvxIgwGaZl+8ULGcJ8zOsJa9R1r9B2d8v2eGb1KNieqBhLNz8ekyAoV3VAX985+FvSXEenF8lf9lA7DUUxa0HUl/RTG1EfOUQmUwwCtggDewiHmc1R+Ir/MfKJz/f9tTwn31Nf7qVxlHLR6qXwg7cHXqU/p4hPdUB6Lp55TiXwDYTsrpG12dbdY5t0WLrCSRSVjIItG0dqIAG2jHwlPTmvQdsL3Ajjg3nAq3zIgdS98ZiGV0MJZeWVJs2WNWIJK5hcLh0osuqVTxIAdi6X3w/0LFGoa+AtFMzo5kflix0gQLBiLOZmAYro84RcfSc3NKpFAcliM9eYDdjZ7QO/1mRc+CTapqFX+4lO9TQEPoUpz//anQ5FQphXdizB1QXXk/moOl/JUC7aLMDpQSHj02PdxbG9xybM60u47UjZ4bq290Zm451ky3HSi6kxTKJ9fXHQVvZJm1XTjutYsozw53T1L+2ufBGPMTe/c30M/mD3uChW+c+6tQttthuBnbqMBLKGbydI54/eFQ3b5CWa/dGMl8xFJ0D/rvg1Pjdxil+2XK5b6ZWD15lyfnvYOxTBYs9TrY5NbuUENRUo5EGtGyVUNtBwBfDjA/IDtTkiNRsdYD8O+NcVN2KUfXo3UnukvA6Z3I+mWeY++NpNoAwDvAv1Uiss7oiNBmYD+XraoO0NvnPVnvrbUsA4CcYusPgajzY2/cvN+KtOFl/6w/IWrvdTV/Ktla92KhkNcOxpwPCqm/IgLbEvteW1m4E2/d8iY9AZOXQ/7WxKq6nxq9YNT5OLF6DmAfTHT13EL3XjTk2csXk4bqX2OXWiQ73Jz49tS4N5d/oxoHLr14EzPfAf1IIlS/2oznIx1omLURhL5Qa1oxFuC8EeHb8U6I88bXCwGbuZ61jb2Jgz1XYUHb0b0vEHNWmHE9lNsjWrcmnMhNhYDNnCkmNJSFHFdzte82M1b04HgC6HrYbAPw1pFdNOc4GE334wz9qkihRAdK/0HBub/E1MkhJBiq6V8gq7Htm05OjN2C/z/jCP1xbAlCwcnsAsbdkGHF/trPIcoNrtbjFRNmoama6EgZ42SimRG5FjLHWakNwWjmirLyZpLpKH7TysghZ00OUHNTxFmK2yDNQSKlx7u0Q0GQeLtQdy4rY5zMzqVb/ccoJ/OQMEmoPWW3988to4NY8DxYf6WMDCW6ktuRvFqxmqewgguhdLCcwsic0DMA8lE7kvrYyFhBw446X2B/nRNo739/YnX9azKUXYCg9CtlvdAUyywuEB1p4gh9AzbPZc0mF8Z+sINgn0MIwiVgKcAG6rGlT86AMdqw2n8ppR63o+mveQXCFAxzX2BWD0P6pcT+g3uNlmEDV3JX4iOh1xICdWU2gGXOMXN5HfRhK4IoPxlfXQfmKf+Ajh1I+MEeHMcKzqvoxoZsHsoOXgP+fEkxbw1e2JhB0h2q9tc4OL/fAVdsdd3jnyhklmRo8qGBQXchIvMMKPW7Pt85/SM66CNmDw1mh75cHu6JWZFZxNLNSJTPIM5PuJquKEt3o6zmqyJZH4LTC7CIfTonO5Jr/B2jxIq6jW3OZVYVX4edDSD6e1BAXqwgl/I2miKp+ZayOkT0CjaJww21/2bhznio7uoiL2dQB8HdhoV++ri4AdUdtgfw789mRHspzulXzyCcI1BMVQXgL5LodnP7zFfE+N9/9yOUyedxTn/SFHWWj0ifAY1ANHUleOJRlPqdCUmbO85J1jjxUfkUkgVCsg1/uGw0n/fvFm67LT2NLTLfi98Cke8dpMGl3r9QxVRnPuPrWzaIUmsAtgas0okd6ETh7AYt5d7+BeCbhfKVcQ6CtwgJjjoiP3fdgVbcbY57/otBnxidfndvo6/67BtxUf4kztJsbMg0CJaU9QxN2FskhePQBWr7La6wvzRFarTtyoBgB4hm5M//aAMT2+/Vlfzp81/vywLMWSBN1QAAAABJRU5ErkJggg==";_x000D_
var canvas = document.getElementById("theCanvas");_x000D_
var ctx = canvas.getContext("2d");_x000D_
var img = new Image;_x000D_
_x000D_
//wait for the image to load_x000D_
img.onload = function() {_x000D_
    //Draw the original image so that you can fetch the colour data_x000D_
    ctx.drawImage(img,0,0);_x000D_
    var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);_x000D_
    _x000D_
    /*_x000D_
    imgData.data is a one-dimensional array which contains _x000D_
    the respective RGBA values for every pixel _x000D_
    in the selected region of the context _x000D_
    (note i+=4 in the loop)_x000D_
    */_x000D_
    _x000D_
    for (var i = 0; i < imgData.data.length; i+=4) {_x000D_
   imgData.data[i] = 255; //Red, 0-255_x000D_
   imgData.data[i+1] = 255; //Green, 0-255_x000D_
   imgData.data[i+2] = 255; //Blue, 0-255_x000D_
   /* _x000D_
   imgData.data[i+3] contains the alpha value_x000D_
   which we are going to ignore and leave_x000D_
   alone with its original value_x000D_
   */_x000D_
    }_x000D_
    ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the original image_x000D_
    ctx.putImageData(imgData, 0, 0); //paint the new colorised image_x000D_
}_x000D_
_x000D_
//Load the image!_x000D_
img.src = src;
_x000D_
body {_x000D_
    background: green;_x000D_
}
_x000D_
<canvas id="theCanvas"></canvas>
_x000D_
_x000D_
_x000D_

Argument list too long error for rm, cp, mv commands

I ran into this problem a few times. Many of the solutions will run the rm command for each individual file that needs to be deleted. This is very inefficient:

find . -name "*.pdf" -print0 | xargs -0 rm -rf

I ended up writing a python script to delete the files based on the first 4 characters in the file-name:

import os
filedir = '/tmp/' #The directory you wish to run rm on 
filelist = (os.listdir(filedir)) #gets listing of all files in the specified dir
newlist = [] #Makes a blank list named newlist
for i in filelist: 
    if str((i)[:4]) not in newlist: #This makes sure that the elements are unique for newlist
        newlist.append((i)[:4]) #This takes only the first 4 charcters of the folder/filename and appends it to newlist
for i in newlist:
    if 'tmp' in i:  #If statment to look for tmp in the filename/dirname
        print ('Running command rm -rf '+str(filedir)+str(i)+'* : File Count: '+str(len(os.listdir(filedir)))) #Prints the command to be run and a total file count
        os.system('rm -rf '+str(filedir)+str(i)+'*') #Actual shell command
print ('DONE')

This worked very well for me. I was able to clear out over 2 million temp files in a folder in about 15 minutes. I commented the tar out of the little bit of code so anyone with minimal to no python knowledge can manipulate this code.

Permission denied for relation

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public to jerry;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public to jerry;
GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public to jerry;

How can I hide a checkbox in html?

input may have a hidden attribute:

_x000D_
_x000D_
input:checked + span::before {
  content: 'un';
}
_x000D_
<label>
  <input type='checkbox' hidden/>
  <span>check</span>
<label>
_x000D_
_x000D_
_x000D_

Setting default values for columns in JPA

You can't do this with the column annotation. I think the only way is to set the default value when a object is created. Maybe the default constructor would be the right place to do that.

typesafe select onChange event using reactjs and typescript

JSX:

<select value={ this.state.foo } onChange={this.handleFooChange}>
    <option value="A">A</option>
    <option value="B">B</option>
</select>

TypeScript:

private handleFooChange = (event: React.FormEvent<HTMLSelectElement>) => {
    const element = event.target as HTMLSelectElement;
    this.setState({ foo: element.value });
}