Programs & Examples On #Credits

Tensorflow import error: No module named 'tensorflow'

The reason Python 3.5 environment is unable to import Tensorflow is that Anaconda does not store the tensorflow package in the same environment.

One solution is to create a new separate environment in Anaconda dedicated to TensorFlow with its own Spyder

conda create -n newenvt anaconda python=3.5
activate newenvt

and then install tensorflow into newenvt

I found this primer helpful

NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver

My system version: ubuntu 20.04 LTS.

  • I solved this by generate a new MOK and enroll it into shim.

  • Without disable of Secure Boot, although it also really works for me.

  • Simply execute this command and follow what it suggests:

    sudo update-secureboot-policy --enroll-key
    

According to ubuntu's wiki: How can I do non-automated signing of drivers

ImportError: No module named tensorflow

For Anaconda3, simply install in Anaconda Navigator: enter image description here

Moving Panel in Visual Studio Code to right side

"Wokbench.panel.defaultLocation": "right"

Open settings using CTRL+., search for terminal and you should see this setting at the top. From the drop down below the settings explanation, choose right. See the screenshot below.

enter image description here

pytest cannot import module while python can

Another special case:

I had the problem using tox. So my program ran fine, but unittests via tox kept complaining. After installing packages (needed for the program) you need to additionally specify the packages used in the unittests in the tox.ini

[testenv]
deps =
    package1
    package2 
...

How to run Pip commands from CMD

Firstly make sure that you have installed python 2.7 or higher

Open Command Prompt as administrator and change directory to python and then change directory to Scripts by typing cd Scripts then type pip.exe and now you can install modules Step by Step:

  • Open Cmd

  • type in "cd \" and then enter

  • type in "cd python2.7" and then enter

Note that my python version is 2.7 so my directory is that so use your python folder here...

  • type in "cd Scripts" and enter

  • Now enter this "pip.exe"

  • Now it prompts you to install modules

JavaScript Loading Screen while page loads

I would suggest adding class no-js to your html to nest your CSS selectors under it like:

.loading {
    display: none;
 }

.no-js .loading {
 display: block;
 //....
}

and when you finish loading your credit code remove it:

$('html').removeClass('no-js');

This will hide your loading spinner as there's no no-js class in html it means you already loaded your credit code

import error: 'No module named' *does* exist

I had the same issue. I solved it by running the command in a different python version. I tried python3 filename.py. Earlier i was using Python 2.7.

Another possibility is that the file from which something is imported may contain BOM (Byte Order Mark). It can be solved by opening the file in some editor which supports multiple encoding like VSCode (Notepad++) and saving in a different encoding statndard like ANSI, UTF-8(without BOM).

undefined reference to 'vtable for class' constructor

You're declaring a virtual function and not defining it:

virtual void calculateCredits();

Either define it or declare it as:

virtual void calculateCredits() = 0;

Or simply:

virtual void calculateCredits() { };

Read more about vftable: http://en.wikipedia.org/wiki/Virtual_method_table

Python DNS module import error

On Debian 7 Wheezy, I had to do:

pip install --upgrade dnspython

even if python-dns package was installed.

Subprocess changing directory

If you want to have cd functionality (assuming shell=True) and still want to change the directory in terms of the Python script, this code will allow 'cd' commands to work.

import subprocess
import os

def cd(cmd):
    #cmd is expected to be something like "cd [place]"
    cmd = cmd + " && pwd" # add the pwd command to run after, this will get our directory after running cd
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) # run our new command
    out = p.stdout.read()
    err = p.stderr.read()
    # read our output
    if out != "":
        print(out)
        os.chdir(out[0:len(out) - 1]) # if we did get a directory, go to there while ignoring the newline 
    if err != "":
        print(err) # if that directory doesn't exist, bash/sh/whatever env will complain for us, so we can just use that
    return

break statement in "if else" - java

The issue is that you are trying to have multiple statements in an if without using {}. What you currently have is interpreted like:

if( choice==5 )
{
    System.out.println( ... );
}
break;
else
{
    //...
}

You really want:

if( choice==5 )
{
    System.out.println( ... );
    break;
}
else
{
    //...
}

Also, as Farce has stated, it would be better to use else if for all the conditions instead of if because if choice==1, it will still go through and check if choice==5, which would fail, and it will still go into your else block.

if( choice==1 )
    //...
else if( choice==2 )
    //...
else if( choice==3 )
    //...
else if( choice==4 )
    //...
else if( choice==5 )
{
    //...
}
else
    //...

A more elegant solution would be using a switch statement. However, break only breaks from the most inner "block" unless you use labels. So you want to label your loop and break from that if the case is 5:

LOOP:
for(;;)
{
    System.out.println("---> Your choice: ");
    choice = input.nextInt();
    switch( choice )
    {
        case 1:
            playGame();
            break;
        case 2:
            loadGame();
            break;
        case 2:
            options();
            break;
        case 4:
            credits();
            break;
        case 5:
            System.out.println("End of Game\n Thank you for playing with us!");
            break LOOP;
        default:
            System.out.println( ... );
    }
}

Instead of labeling the loop, you could also use a flag to tell the loop to stop.

bool finished = false;
while( !finished )
{
    switch( choice )
    {
        // ...
        case 5:
            System.out.println( ... )
            finished = true;
            break;
        // ...
    }
}

NameError: name 'datetime' is not defined

You need to import the module datetime first:

>>> import datetime

After that it works:

>>> import datetime
>>> date = datetime.date.today()
>>> date
datetime.date(2013, 11, 12)

Two versions of python on linux. how to make 2.7 the default

Verify current version of python by:

$ python --version

then check python is symbolic link to which file.

  $ ll /usr/bin/python

Output Ex:

 lrwxrwxrwx 1 root root 9 Jun 16  2014 /usr/bin/python -> python2.7*

Check other available versions of python:

$ ls /usr/bin/python*

Output Ex:

/usr/bin/python     /usr/bin/python2.7-config  /usr/bin/python3.4         /usr/bin/python3.4m-config  /usr/bin/python3.6m         /usr/bin/python3m
/usr/bin/python2    /usr/bin/python2-config    /usr/bin/python3.4-config  /usr/bin/python3.6          /usr/bin/python3.6m-config  /usr/bin/python3m-config
/usr/bin/python2.7  /usr/bin/python3           /usr/bin/python3.4m        /usr/bin/python3.6-config   /usr/bin/python3-config     /usr/bin/python-config

If want to change current version of python to 3.6 version edit file ~/.bashrc:

vim ~/.bashrc

add below line in the end of file and save:

alias python=/usr/local/bin/python3.6

To install pip for python 3.6

$ sudo apt-get install python3.6 python3.6-dev
$ sudo curl https://bootstrap.pypa.io/ez_setup.py -o - | sudo python3.6
$ sudo easy_install pip

On Success, check current version of pip:

$ pip3 -V

Output Ex:

pip 1.5.4 from /usr/lib/python3/dist-packages (python 3.6)

MySQL : ERROR 1215 (HY000): Cannot add foreign key constraint

In my case charset, datatype every thing was correct. After investigation I found that in parent table there was no index on foreign key column. Once added problem got solved.

enter image description here

ImportError: No module named 'pygame'

I had the same problem and discovered that Pygame doesn't work for Python3 at least on the Mac OS, but I also have Tython2 installed in my computer as you probably do too, so when I use Pygame, I switch the path so that it uses python2 instead of python3. I use Sublime Text as my text editor so I just go to Tools > Build Systems > New Build System and enter the following:

{
    "cmd": ["/usr/local/bin/python", "-u", "$file"],    
}

instead of

{
    "cmd": ["/usr/local/bin/python3", "-u", "$file"],   
}

in my case. And when I'm not using pygame, I simply change the path back so that I can use Python3.

Install numpy on python3.3 - Install pip for python3

The normal way to install Python libraries is with pip. Your way of installing it for Python 3.2 works because it's the system Python, and that's the way to install things for system-provided Pythons on Debian-based systems.

If your Python 3.3 is system-provided, you should probably use a similar command. Otherwise you should probably use pip.

I took my Python 3.3 installation, created a virtualenv and run pip install in it, and that seems to have worked as expected:

$ virtualenv-3.3 testenv
$ cd testenv
$ bin/pip install numpy
blablabl

$ bin/python3
Python 3.3.2 (default, Jun 17 2013, 17:49:21) 
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> 

What is the right way to treat argparse.Namespace() as a dictionary?

Straight from the horse's mouth:

If you prefer to have dict-like view of the attributes, you can use the standard Python idiom, vars():

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> args = parser.parse_args(['--foo', 'BAR'])
>>> vars(args)
{'foo': 'BAR'}

— The Python Standard Library, 16.4.4.6. The Namespace object

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

Use decode:

print(curses.version.decode())
# 2.2

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

If you're using Angular's ng-repeat to populate the table hackel's jquery snippet will not work by placing it in the document load event. You'll need to run the snippet after angular has finished rendering the table.

To trigger an event after ng-repeat has rendered try this directive:

var app = angular.module('myapp', [])
.directive('onFinishRender', function ($timeout) {
return {
    restrict: 'A',
    link: function (scope, element, attr) {
        if (scope.$last === true) {
            $timeout(function () {
                scope.$emit('ngRepeatFinished');
            });
        }
    }
}
});

Complete example in angular: http://jsfiddle.net/ADukg/6880/

I got the directive from here: Use AngularJS just for routing purposes

How to get the PYTHONPATH in shell?

Python, at startup, loads a bunch of values into sys.path (which is "implemented" via a list of strings), including:

  • various hardcoded places
  • the value of $PYTHONPATH
  • probably some stuff from startup files (I'm not sure if Python has rcfiles)

$PYTHONPATH is only one part of the eventual value of sys.path.

If you're after the value of sys.path, the best way would be to ask Python (thanks @Codemonkey):

python -c "import sys; print sys.path"

Removing highcharts.com credits link

credits : null

also works to disable the credits

How to do left join in Doctrine?

If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user, picked from your example), then the syntax is quite simple:

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin('a.user', 'u')
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

Since you are applying a condition on the joined result here, using a LEFT JOIN or simply JOIN is the same.

If no association is available, then the query looks like following

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin(
            'User\Entity\User',
            'u',
            \Doctrine\ORM\Query\Expr\Join::WITH,
            'a.user = u.id'
        )
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

This will produce a resultset that looks like following:

array(
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    // ...
)

Unable to import a module that is definitely installed

The Python import mechanism works, really, so, either:

  1. Your PYTHONPATH is wrong,
  2. Your library is not installed where you think it is
  3. You have another library with the same name masking this one

How to fix Python Numpy/Pandas installation?

Don't know if you solved the problem but if anyone has this problem in future.

$python
>>import numpy
>>print(numpy)

Go to the location printed and delete the numpy installation found there. You can then use pip or easy_install

UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1

I was getting the same type of error, and I found that the console is not capable of displaying the string in another language. Hence I made the below code changes to set default_charset as UTF-8.

data_head = [('\x81\xa1\x8fo\x89\xef\x82\xa2\x95\xdb\x8f\xd8\x90\xa7\x93x\x81\xcb3\x8c\x8e\x8cp\x91\xb1\x92\x86(\x81\x86\x81\xde\x81\x85)\x81\xa1\x8f\x89\x89\xf1\x88\xc8\x8aO\x81A\x82\xa8\x8b\xe0\x82\xcc\x90S\x94z\x82\xcd\x88\xea\x90\xd8\x95s\x97v\x81\xa1\x83}\x83b\x83v\x82\xcc\x82\xa8\x8e\x8e\x82\xb5\x95\xdb\x8c\xaf\x82\xc5\x8fo\x89\xef\x82\xa2\x8am\x92\xe8\x81\xa1', 'shift_jis')]
default_charset = 'UTF-8' #can also try 'ascii' or other unicode type
print ''.join([ unicode(lin[0], lin[1] or default_charset) for lin in data_head ])

python list by value not by reference

Also, you can do:

b = list(a)

This will work for any sequence, even those that don't support indexers and slices...

SQL Server : trigger how to read value for Insert, Update, Delete

Here is the syntax to create a trigger:

CREATE TRIGGER trigger_name
ON { table | view }
[ WITH ENCRYPTION ]
{
    { { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
        [ WITH APPEND ]
        [ NOT FOR REPLICATION ]
        AS
        [ { IF UPDATE ( column )
            [ { AND | OR } UPDATE ( column ) ]
                [ ...n ]
        | IF ( COLUMNS_UPDATED ( ) { bitwise_operator } updated_bitmask )
                { comparison_operator } column_bitmask [ ...n ]
        } ]
        sql_statement [ ...n ]
    }
} 

If you want to use On Update you only can do it with the IF UPDATE ( column ) section. That's not possible to do what you are asking.

View's SELECT contains a subquery in the FROM clause

create view view_clients_credit_usage as
    select client_id, sum(credits_used) as credits_used 
    from credit_usage 
    group by client_id

create view view_credit_status as 
    select 
        credit_orders.client_id, 
        sum(credit_orders.number_of_credits) as purchased, 
        ifnull(t1.credits_used,0) as used 
    from credit_orders
    left outer join view_clients_credit_usage as t1 on t1.client_id = credit_orders.client_id
    where credit_orders.payment_status='Paid'
    group by credit_orders.client_id)

Vector of structs initialization

After looking on the accepted answer I realized that if know size of required vector then we have to use a loop to initialize every element

But I found new to do this using default_structure_element like following...

#include <bits/stdc++.h>
typedef long long ll;
using namespace std;

typedef struct subject {
  string name;
  int marks;
  int credits;
}subject;

int main(){
  subject default_subject;
  default_subject.name="NONE";
  default_subject.marks = 0;
  default_subject.credits = 0;

  vector <subject> sub(10,default_subject);         // default_subject to initialize

  //to check is it initialised
  for(ll i=0;i<sub.size();i++) {
    cout << sub[i].name << " " << sub[i].marks << " " << sub[i].credits << endl;
  } 
}

Then I think its good to way to initialize a vector of the struct, isn't it?

How to make an unaware datetime timezone aware in python

Python 3.9 adds the zoneinfo module so now only the standard library is needed!

from zoneinfo import ZoneInfo
from datetime import datetime
unaware = datetime(2020, 10, 31, 12)

Attach a timezone:

>>> unaware.replace(tzinfo=ZoneInfo('Asia/Tokyo'))
datetime.datetime(2020, 10, 31, 12, 0, tzinfo=zoneinfo.ZoneInfo(key='Asia/Tokyo'))
>>> str(_)
'2020-10-31 12:00:00+09:00'

Attach the system's local timezone:

>>> unaware.replace(tzinfo=ZoneInfo('localtime'))
datetime.datetime(2020, 10, 31, 12, 0, tzinfo=zoneinfo.ZoneInfo(key='localtime'))
>>> str(_)
'2020-10-31 12:00:00+01:00'

Subsequently it is properly converted to other timezones:

>>> unaware.replace(tzinfo=ZoneInfo('localtime')).astimezone(ZoneInfo('Asia/Tokyo'))
datetime.datetime(2020, 10, 31, 20, 0, tzinfo=backports.zoneinfo.ZoneInfo(key='Asia/Tokyo'))
>>> str(_)
'2020-10-31 20:00:00+09:00'

Wikipedia list of available time zones


Windows has no system time zone database, so here an extra package is needed:

pip install tzdata  

There is a backport to allow use of zoneinfo in Python 3.6 to 3.8:

pip install backports.zoneinfo

Then:

from backports.zoneinfo import ZoneInfo

The cast to value type 'Int32' failed because the materialized value is null

I was also facing the same problem and solved through making column as nullable using "?" operator.

Sequnce = db.mstquestionbanks.Where(x => x.IsDeleted == false && x.OrignalFormID == OriginalFormIDint).Select(x=><b>(int?)x.Sequence</b>).Max().ToString();

Sometimes null is returned.

Tkinter module not found on Ubuntu

sudo apt-get install python3-tk

Tkinter: "Python may not be configured for Tk"

So appearantly many seems to have had this issue (me including) and I found the fault to be that Tkinter wasn't installed on my system when python was compiled.

This post describes how to solve the problem by:

  1. Removing the virtual environment/python distribution
  2. install Tkinter with sudo apt-get install tk-dev (for deb) or sudo pacman -S tk (for arch/manjaro)
  3. Then proceed to compile python again.

This worked wonders for me.

Generating matplotlib graphs without a running X server

You need to use the matplotlib API directly rather than going through the pylab interface. There's a good example here:

http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib_without_gui.html

Java default constructor

If a class doesn't have any constructor provided by programmer, then java compiler will add a default constructor with out parameters which will call super class constructor internally with super() call. This is called as default constructor.

In your case, there is no default constructor as you are adding them programmatically. If there are no constructors added by you, then compiler generated default constructor will look like this.

public Module()
{
   super();
}

Note: In side default constructor, it will add super() call also, to call super class constructor.

Purpose of adding default constructor:

Constructor's duty is to initialize instance variables, if there are no instance variables you could choose to remove constructor from your class. But when you are inheriting some class it is your class responsibility to call super class constructor to make sure that super class initializes all its instance variables properly.

That's why if there are no constructors, java compiler will add a default constructor and calls super class constructor.

How to repeat last command in python interpreter shell?

it is control + p in Mac os in python 3.4 IDEL

Reload chart data via JSON with Highcharts

If you are using push to push the data to the option.series dynamically .. just use

options.series = [];  

to clear it.

options.series = [];
$("#change").click(function(){
}

How to make links in a TextView clickable?

Add CDATA to your string resource

Strings.xml

<string name="txtCredits"><![CDATA[<a href=\"http://www.google.com\">Google</a>]]></string>

Java parsing XML document gives "Content not allowed in prolog." error

If you're able to control the xml file, try adding a bit more information to the beginning of the file:

<?xml version="1.0" encoding="UTF-16" standalone="no"?>

How do I install SciPy on 64 bit Windows?

Unofficial 64-bit installers for NumPy and SciPy are available at http://www.lfd.uci.edu/~gohlke/pythonlibs/

Make sure that you download & install the packages (aka. wheels) that match your CPython version and bitness (ie. cp35 = Python v3.5; win_amd64 = x86_64).

You'll want to install NumPy first; From a CMD prompt with administrator privileges for a system-wide (aka. Program Files) install:

C:\>pip install numpy-<version>+mkl-cp<ver-spec>-cp<ver-spec>m-<cpu-build>.whl

Or include the --user flag to install to the current user's application folder (Typically %APPDATA%\Python on Windows) from a non-admin CMD prompt:

C:\>pip install --user numpy-<version>+mkl-cp<ver-spec>-cp<ver-spec>m-<cpu-build>.whl

Then do the same for SciPy:

C:\>pip install [--user] scipy-<version>-cp<ver-spec>-cp<ver-spec>m-<cpu-build>.whl

Don't forget to replace <version>, <ver-spec>, and <cpu-build> appropriately if you copy & paste any of these examples. And also that you must use the numpy & scipy packages from the ifd.uci.edu link above (or else you will get errors if you try to mix & match incompatible packages -- uninstall any conflicting packages first [ie. pip list]).

Python integer division yields float

The accepted answer already mentions PEP 238. I just want to add a quick look behind the scenes for those interested in what's going on without reading the whole PEP.

Python maps operators like +, -, * and / to special functions, such that e.g. a + b is equivalent to

a.__add__(b)

Regarding division in Python 2, there is by default only / which maps to __div__ and the result is dependent on the input types (e.g. int, float).

Python 2.2 introduced the __future__ feature division, which changed the division semantics the following way (TL;DR of PEP 238):

  • / maps to __truediv__ which must "return a reasonable approximation of the mathematical result of the division" (quote from PEP 238)
  • // maps to __floordiv__, which should return the floored result of /

With Python 3.0, the changes of PEP 238 became the default behaviour and there is no more special method __div__ in Python's object model.

If you want to use the same code in Python 2 and Python 3 use

from __future__ import division

and stick to the PEP 238 semantics of / and //.

Can't import Numpy in Python

Have you installed it?

On debian/ubuntu:

aptitude install python-numpy

On windows:

http://sourceforge.net/projects/numpy/files/NumPy/

On other systems:

http://sourceforge.net/projects/numpy/files/NumPy/

$ tar xfz numpy-n.m.tar.gz
$ cd numpy-n.m
$ python setup.py install

No module named _sqlite3

my python is build from source, the cause is missing options when exec configure python version:3.7.4

./configure --enable-loadable-sqlite-extensions --enable-optimizations
make
make install

fixed

What does the Ellipsis object do?

Summing up what others have said, as of Python 3, Ellipsis is essentially another singleton constant similar to None, but without a particular intended use. Existing uses include:

  • In slice syntax to represent the full slice in remaining dimensions
  • In type hinting to indicate only part of a type(Callable[..., int] or Tuple[str, ...])
  • In type stub files to indicate there is a default value without specifying it

Possible uses could include:

  • As a default value for places where None is a valid option
  • As the content for a function you haven't implemented yet

JavaScript Adding an ID attribute to another created Element

You set an element's id by setting its corresponding property:

myPara.id = ID;

alert a variable value

If you're using greasemonkey, it's possible the page isn't ready for the javascript yet. You may need to use window.onReady.

var inputs;

function doThisWhenReady() {
    inputs = document.getElementsByTagName('input');

    //Other code here...
}

window.onReady = doThisWhenReady;

A server with the specified hostname could not be found

I got this error message when "/" from my URL is missing . Hope this help someone.

ex: actual URL is "https://www.myweb.com/login" .My URL which "https://www.myweb.comlogin" caused this error

android get real path by Uri.getPath()

Is it really necessary for you to get a physical path?
For example, ImageView.setImageURI() and ContentResolver.openInputStream() allow you to access the contents of a file without knowing its real path.

Run AVD Emulator without Android Studio

You can make a batch file, that will open your emulator directly without opening Android Studio. If you are using Windows:

  • Open Notepad

  • New file

  • Copy the next lines into your file:

     cd /d C:\Users\%username%\AppData\Local\Android\sdk\tools
     emulator @[YOUR_EMULATOR_DEVICE_NAME]
    

    Notes:

  • Replace [YOUR_EMULATOR_DEVICE_NAME] with the device name you created in emulator

  • To get the device name go to: C:\Users\%username%\AppData\Local\Android\sdk\tools

  • Run cmd and type: emulator -list-avds

  • Copy the device name and paste it in the batch file

  • Save the file as emulator.bat and close

  • Now double click on emulator.bat and you got the emulator running!

How do I output coloured text to a Linux terminal?

You can use ANSI colour codes.

use these functions.

enum c_color{BLACK=30,RED=31,GREEN=32,YELLOW=33,BLUE=34,MAGENTA=35,CYAN=36,WHITE=37};
enum c_decoration{NORMAL=0,BOLD=1,FAINT=2,ITALIC=3,UNDERLINE=4,RIVERCED=26,FRAMED=51};
void pr(const string str,c_color color,c_decoration decoration=c_decoration::NORMAL){
  cout<<"\033["<<decoration<<";"<<color<<"m"<<str<<"\033[0m";
}

void prl(const string str,c_color color,c_decoration decoration=c_decoration::NORMAL){
   cout<<"\033["<<decoration<<";"<<color<<"m"<<str<<"\033[0m"<<endl;
}

WPF Application that only has a tray icon

You have to use the NotifyIcon control from System.Windows.Forms, or alternatively you can use the Notify Icon API provided by Windows API. WPF Provides no such equivalent, and it has been requested on Microsoft Connect several times.

I have code on GitHub which uses System.Windows.Forms NotifyIcon Component from within a WPF application, the code can be viewed at https://github.com/wilson0x4d/Mubox/blob/master/Mubox.QuickLaunch/AppWindow.xaml.cs

Here are the summary bits:

Create a WPF Window with ShowInTaskbar=False, and which is loaded in a non-Visible State.

At class-level:

private System.Windows.Forms.NotifyIcon notifyIcon = null;

During OnInitialize():

notifyIcon = new System.Windows.Forms.NotifyIcon();
notifyIcon.Click += new EventHandler(notifyIcon_Click);
notifyIcon.DoubleClick += new EventHandler(notifyIcon_DoubleClick);
notifyIcon.Icon = IconHandles["QuickLaunch"];

During OnLoaded():

notifyIcon.Visible = true;

And for interaction (shown as notifyIcon.Click and DoubleClick above):

void notifyIcon_Click(object sender, EventArgs e)
{
    ShowQuickLaunchMenu();
}

From here you can resume the use of WPF Controls and APIs such as context menus, pop-up windows, etc.

It's that simple. You don't exactly need a WPF Window to host to the component, it's just the most convenient way to introduce one into a WPF App (as a Window is generally the default entry point defined via App.xaml), likewise, you don't need a WPF Wrapper or 3rd party control, as the SWF component is guaranteed present in any .NET Framework installation which also has WPF support since it's part of the .NET Framework (which all current and future .NET Framework versions build upon.) To date, there is no indication from Microsoft that SWF support will be dropped from the .NET Framework anytime soon.

Hope that helps.

It's a little cheese that you have to use a pre-3.0 Framework Component to get a tray-icon, but understandably as Microsoft has explained it, there is no concept of a System Tray within the scope of WPF. WPF is a presentation technology, and Notification Icons are an Operating System (not a "Presentation") concept.

How to convert a String into an ArrayList?

This is using Gson in Kotlin

 val listString = "[uno,dos,tres,cuatro,cinco]"
 val gson = Gson()
 val lista = gson.fromJson(listString , Array<String>::class.java).toList()
 Log.e("GSON", lista[0])

How can I use an ES6 import in Node.js?

You can also use npm package called esm which allows you to use ES6 modules in Node.js. It needs no configuration. With esm you will be able to use export/import in your JavaScript files.

Run the following command on your terminal

yarn add esm

or

npm install esm

After that, you need to require this package when starting your server with node. For example if your node server runs index.js file, you would use the command

node -r esm index.js

You can also add it in your package.json file like this

{
  "name": "My-app",
  "version": "1.0.0",
  "description": "Some Hack",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node -r esm index.js"
  },

}

Then run this command from the terminal to start your node server

npm start

Check this link for more details.

NULL value for int in Update statement

Assuming the column is set to support NULL as a value:

UPDATE YOUR_TABLE
   SET column = NULL

Be aware of the database NULL handling - by default in SQL Server, NULL is an INT. So if the column is a different data type you need to CAST/CONVERT NULL to the proper data type:

UPDATE YOUR_TABLE
   SET column = CAST(NULL AS DATETIME)

...assuming column is a DATETIME data type in the example above.

How to avoid Number Format Exception in java?

Just catch your exception and do proper exception handling:

if (cost !=null && !"".equals(cost) ){
        try {
           Integer intCost = Integer.parseInt(cost);
           List<Book> books = bookService . findBooksCheaperThan(intCost);  
        } catch (NumberFormatException e) {
           System.out.println("This is not a number");
           System.out.println(e.getMessage());
        }
    }

How to set order of repositories in Maven settings.xml

As far as I know, the order of the repositories in your pom.xml will also decide the order of the repository access.

As for configuring repositories in settings.xml, I've read that the order of repositories is interestingly enough the inverse order of how the repositories will be accessed.

Here a post where someone explains this curiosity:
http://community.jboss.org/message/576851

How to store JSON object in SQLite database

There is no data types for that.. You need to store it as VARCHAR or TEXT only.. jsonObject.toString();

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

Try this

SqlCommand cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID=@id", con);
cmd.Parameters.AddWithValue("id", id.Text);

How to downgrade tensorflow, multiple versions possible?

If you are using python3 on windows then you might do this as well

pip3 install tensorflow==1.4

you may select any version from "(from versions: 1.2.0rc2, 1.2.0, 1.2.1, 1.3.0rc0, 1.3.0rc1, 1.3.0rc2, 1.3.0, 1.4.0rc0, 1.4.0rc1, 1.4.0, 1.5.0rc0, 1.5.0rc1, 1.5.0, 1.5.1, 1.6.0rc0, 1.6.0rc1, 1.6.0, 1.7.0rc0, 1.7.0rc1, 1.7.0)"

I did this when I wanted to downgrade from 1.7 to 1.4

Java project in Eclipse: The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files

However trivial this might be, check your Java installation. For me, rt.jar was missing.

I found this after fiddling for half a day with Eclipse settings and getting nowhere. Desperate, I finally decided to try compiling the project from the command line. I wasn't expecting to see anything wrong since I thought it's an Eclipse issue but to my astonishment I saw this:

Error occurred during initialization of VM
java/lang/NoClassDefFoundError: java/lang/Object

I don't know what happened to my Java installation and where did rt.jar go. Anyway this comes as a reminder to go through the fail checklist and tick all the boxes no matter how unbelievable they are. It would have saved me a lot of time.

How to detect IE11?

I used the onscroll event at the element with the scrollbar. When triggered in IE, I added the following validation:

onscroll="if (document.activeElement==this) ignoreHideOptions()"

How to allow Cross domain request in apache2

I had a lot of trouble getting this to work. Dummy me, don't forget that old page - even for sub-requests - gets cached in your browser. Maybe obvious, but clear your browsers cache. After that, one can also use Header set Cache-Control "no-store" This was helpful to me while testing.

Create a user with all privileges in Oracle

My issue was, i am unable to create a view with my "scott" user in oracle 11g edition. So here is my solution for this

Error in my case

SQL>create view v1 as select * from books where id=10;

insufficient privileges.

Solution

1)open your cmd and change your directory to where you install your oracle database. in my case i was downloaded in E drive so my location is E:\app\B_Amar\product\11.2.0\dbhome_1\BIN> after reaching in the position you have to type sqlplus sys as sysdba

E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba

2) Enter password: here you have to type that password that you give at the time of installation of oracle software.

3) Here in this step if you want create a new user then you can create otherwise give all the privileges to existing user.

for creating new user

SQL> create user abc identified by xyz;

here abc is user and xyz is password.

giving all the privileges to abc user

SQL> grant all privileges to abc;

 grant succeeded. 

if you are seen this message then all the privileges are giving to the abc user.

4) Now exit from cmd, go to your SQL PLUS and connect to the user i.e enter your username & password.Now you can happily create view.

In My case

in cmd E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba

SQL> grant all privileges to SCOTT;

grant succeeded.

Now I can create views.

How can I get the current time in C#?

try this:

 string.Format("{0:HH:mm:ss tt}", DateTime.Now);

for further details you can check it out : How do you get the current time of day?

How to evaluate http response codes from bash/shell script?

Although the accepted response is a good answer, it overlooks failure scenarios. curl will return 000 if there is an error in the request or there is a connection failure.

url='http://localhost:8080/'
status=$(curl --head --location --connect-timeout 5 --write-out %{http_code} --silent --output /dev/null ${url})
[[ $status == 500 ]] || [[ $status == 000 ]] && echo restarting ${url} # do start/restart logic

Note: this goes a little beyond the requested 500 status check to also confirm that curl can even connect to the server (i.e. returns 000).

Create a function from it:

failureCode() {
    local url=${1:-http://localhost:8080}
    local code=${2:-500}
    local status=$(curl --head --location --connect-timeout 5 --write-out %{http_code} --silent --output /dev/null ${url})
    [[ $status == ${code} ]] || [[ $status == 000 ]]
}

Test getting a 500:

failureCode http://httpbin.org/status/500 && echo need to restart

Test getting error/connection failure (i.e. 000):

failureCode http://localhost:77777 && echo need to start

Test not getting a 500:

failureCode http://httpbin.org/status/400 || echo not a failure

Python set to list

s = set([1,2,3])
print [ x for x in iter(s) ]

Definition of a Balanced Tree

There are several ways to define "Balanced". The main goal is to keep the depths of all nodes to be O(log(n)).

It appears to me that the balance condition you were talking about is for AVL tree.
Here is the formal definition of AVL tree's balance condition:

For any node in AVL, the height of its left subtree differs by at most 1 from the height of its right subtree.

Next question, what is "height"?

The "height" of a node in a binary tree is the length of the longest path from that node to a leaf.

There is one weird but common case:

People define the height of an empty tree to be (-1).

For example, root's left child is null:

              A  (Height = 2)
           /     \
(height =-1)       B (Height = 1) <-- Unbalanced because 1-(-1)=2 >1
                    \
                     C (Height = 0)

Two more examples to determine:

Yes, A Balanced Tree Example:

        A (h=3)
     /     \
 B(h=1)     C (h=2)        
/          /   \
D (h=0)  E(h=0)  F (h=1)
               /
              G (h=0)

No, Not A Balanced Tree Example:

        A (h=3)
     /     \
 B(h=0)     C (h=2)        <-- Unbalanced: 2-0 =2 > 1
           /   \
        E(h=1)  F (h=0)
        /     \
      H (h=0)   G (h=0)      

Gradle sync failed: failed to find Build Tools revision 24.0.0 rc1

I had same problem and eventually found out that in file build.gradle the version does not match the version of buildTools in my installed sdk. (because I imported project done at home on different computed with updated sdk)

before:

  • build.gradle(app): buildToolsVersion "24.0.2"

  • Android\sdk\build-tools: file "25.0.1"

fixed: build.gradle(app): buildToolsVersion "25.0.1"

Then just sync your project with gradle files and it should work.

Error "The goal you specified requires a project to execute but there is no POM in this directory" after executing maven command

On Windows when you are using PowerShell you have to enclose all parameters with quotes.

So if you want to create a maven webapp archetype you would do as follows:

Prerequisites:

  1. Make sure you have maven installed and have it in your PATH environment variable.

Howto:

  1. Open windows powershell
  2. mkdir MyWebApp
  3. cd MyWebApp
  4. mvn archetype:generate "-DgroupId=com.javan.dev" "-DartifactId=MyWebApp" "-DarchetypeArtifactId=maven-archetype-webapp" "-DinteractiveMode=false"

enter image description here

Note: This is tested only on windows 10 powershell

Send response to all clients except sender

use this coding

io.sockets.on('connection', function (socket) {

    socket.on('mousemove', function (data) {

        socket.broadcast.emit('moving', data);
    });

this socket.broadcast.emit() will emit everthing in the function except to the server which is emitting

Reverse a string without using reversed() or [::-1]?

This is the simplest way in python 2.7 syntax

def reverse(text):

      rev = ""
      final = ""

      for a in range(0,len(text)):
            rev = text[len(text)-a-1]
            final = final + rev
return final

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object?

$resource("../rest/api"}).get();

returns an object.

$resource("../rest/api").query();

returns an array.

You must use :

return $resource('../rest/api.php?method=getTask&q=*').query();

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

More info

To find a compiler, you'll have 1 per .net version installed, type in a command prompt.

dir c:\Windows\Microsoft.NET\vbc.exe /a/s

Windows Forms

For a Windows Forms version (no console window and we don't get around to actually creating any forms - though you can if you want).

Compile line in a command prompt.

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe "%userprofile%\desktop\VBS2Exe.vb"

Text for VBS2EXE.vb

Imports System.Windows.Forms 

Partial Class MyForm : Inherits Form 

Private Sub InitializeComponent() 


End Sub

Public Sub New() 

InitializeComponent() 

End Sub

Public Shared Sub Main() 

Dim sc as object 
Dim Scrpt as string

sc = createObject("MSScriptControl.ScriptControl")

Scrpt = "msgbox " & chr(34) & "Hi there I'm a form" & chr(34)

With SC 
.Language = "VBScript" 
.UseSafeSubset = False 
.AllowUI = True 
End With


sc.addcode(Scrpt)


End Sub

End Class

Using these optional parameters gives you an icon and manifest. A manifest allows you to specify run as normal, run elevated if admin, only run elevated.

/win32icon: Specifies a Win32 icon file (.ico) for the default Win32 resources.

/win32manifest: The provided file is embedded in the manifest section of the output PE.

In theory, I have UAC off so can't test, but put this text file on the desktop and call it vbs2exe.manifest, save as UTF-8.

The command line

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe /win32manifest:"%userprofile%\desktop\VBS2Exe.manifest" "%userprofile%\desktop\VBS2Exe.vb"

The manifest

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
  <assembly xmlns="urn:schemas-microsoft-com:asm.v1" 
  manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" 
  processorArchitecture="*" name="VBS2EXE" type="win32" /> 
  <description>Script to Exe</description> 
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> 
  <security> <requestedPrivileges> 
  <requestedExecutionLevel level="requireAdministrator" 
  uiAccess="false" /> </requestedPrivileges> 
  </security> </trustInfo> </assembly>

Hopefully it will now ONLY run as admin.

Give Access To a Host's Objects

Here's an example giving the vbscript access to a .NET object.

Imports System.Windows.Forms 

Partial Class MyForm : Inherits Form 

Private Sub InitializeComponent() 


End Sub 

Public Sub New() 

InitializeComponent() 

End Sub 

Public Shared Sub Main() 

Dim sc as object
Dim Scrpt as string 

sc = createObject("MSScriptControl.ScriptControl") 

Scrpt = "msgbox " & chr(34) & "Hi there I'm a form" & chr(34) & ":msgbox meScript.state" 

With SC
.Language = "VBScript"
.UseSafeSubset = False
.AllowUI = True
.addobject("meScript", SC, true)
End With 


sc.addcode(Scrpt) 


End Sub 

End Class 

To Embed version info

Download vbs2exe.res file from https://skydrive.live.com/redir?resid=E2F0CE17A268A4FA!121 and put on desktop.

Download ResHacker from http://www.angusj.com/resourcehacker

Open vbs2exe.res file in ResHacker. Edit away. Click Compile button. Click File menu - Save.

Type

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:winexe /win32manifest:"%userprofile%\desktop\VBS2Exe.manifest" /win32resource:"%userprofile%\desktop\VBS2Exe.res" "%userprofile%\desktop\VBS2Exe.vb"

How to set HTTP headers (for cache-control)?

You can set the headers in PHP by using:

<?php
  //set headers to NOT cache a page
  header("Cache-Control: no-cache, must-revalidate"); //HTTP 1.1
  header("Pragma: no-cache"); //HTTP 1.0
  header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

  //or, if you DO want a file to cache, use:
  header("Cache-Control: max-age=2592000"); //30days (60sec * 60min * 24hours * 30days)

?>

Note that the exact headers used will depend on your needs (and if you need to support HTTP 1.0 and/or HTTP 1.1)

Django REST Framework: adding additional field to ModelSerializer

You can change your model method to property and use it in serializer with this approach.

class Foo(models.Model):
    . . .
    @property
    def my_field(self):
        return stuff
    . . .

class FooSerializer(ModelSerializer):
    my_field = serializers.ReadOnlyField(source='my_field')

    class Meta:
        model = Foo
        fields = ('my_field',)

Edit: With recent versions of rest framework (I tried 3.3.3), you don't need to change to property. Model method will just work fine.

Node.js check if file exists

  fs.statSync(path, function(err, stat){
      if(err == null) {
          console.log('File exists');
          //code when all ok
      }else if (err.code == "ENOENT") {
        //file doesn't exist
        console.log('not file');

      }
      else {
        console.log('Some other error: ', err.code);
      }
    });

Remove all files in a directory

Because the * is a shell construct. Python is literally looking for a file named "*" in the directory /home/me/test. Use listdir to get a list of the files first and then call remove on each one.

how to parse JSON file with GSON

In case you need to parse it from a file, I find the best solution to use a HashMap<String, String> to use it inside your java code for better manipultion.

Try out this code:

public HashMap<String, String> myMethodName() throws FileNotFoundException
{
    String path = "absolute path to your file";
    BufferedReader bufferedReader = new BufferedReader(new FileReader(path));

    Gson gson = new Gson();
    HashMap<String, String> json = gson.fromJson(bufferedReader, HashMap.class);
    return json;
}

Failed to load resource: the server responded with a status of 404 (Not Found)

Please install App Script for Ionic 3 Solution npm i -D -E @ionic/app-scripts

C++11 rvalues and move semantics confusion (return statement)

First example

std::vector<int> return_vector(void)
{
    std::vector<int> tmp {1,2,3,4,5};
    return tmp;
}

std::vector<int> &&rval_ref = return_vector();

The first example returns a temporary which is caught by rval_ref. That temporary will have its life extended beyond the rval_ref definition and you can use it as if you had caught it by value. This is very similar to the following:

const std::vector<int>& rval_ref = return_vector();

except that in my rewrite you obviously can't use rval_ref in a non-const manner.

Second example

std::vector<int>&& return_vector(void)
{
    std::vector<int> tmp {1,2,3,4,5};
    return std::move(tmp);
}

std::vector<int> &&rval_ref = return_vector();

In the second example you have created a run time error. rval_ref now holds a reference to the destructed tmp inside the function. With any luck, this code would immediately crash.

Third example

std::vector<int> return_vector(void)
{
    std::vector<int> tmp {1,2,3,4,5};
    return std::move(tmp);
}

std::vector<int> &&rval_ref = return_vector();

Your third example is roughly equivalent to your first. The std::move on tmp is unnecessary and can actually be a performance pessimization as it will inhibit return value optimization.

The best way to code what you're doing is:

Best practice

std::vector<int> return_vector(void)
{
    std::vector<int> tmp {1,2,3,4,5};
    return tmp;
}

std::vector<int> rval_ref = return_vector();

I.e. just as you would in C++03. tmp is implicitly treated as an rvalue in the return statement. It will either be returned via return-value-optimization (no copy, no move), or if the compiler decides it can not perform RVO, then it will use vector's move constructor to do the return. Only if RVO is not performed, and if the returned type did not have a move constructor would the copy constructor be used for the return.

Convert JavaScript String to be all lower case?

I payed attention that lots of people are looking for strtolower() in JavaScript. They are expecting the same function name as in other languages, that's why this post is here.

I would recommend using native Javascript function

"SomE StriNg".toLowerCase()

Here's the function that behaves exactly the same as PHP's one (for those who are porting PHP code into js)

function strToLower (str) {
    return String(str).toLowerCase();
}

How to disable the resize grabber of <textarea>?

Just use resize: none

textarea {
   resize: none;
}

You can also decide to resize your textareas only horizontal or vertical, this way:

textarea { resize: vertical; }

textarea { resize: horizontal; }

Finally, resize: both enables the resize grabber.

Change default text in input type="file"?

It is not possible. Otherwise you may need to use Silverlight or Flash upload control.

What exactly is Spring Framework for?

What is Spring for? I will answer that question shortly, but first, let's take another look at the example by victor hugo. It's not a great example because it doesn't justify the need for a new framework.

public class BaseView {
  protected UserLister userLister;

  public BaseView() {
    userLister = new UserListerDB(); // only line of code that needs changing
  }
}

public class SomeView extends BaseView {
  public SomeView() {
    super();
  }

  public void render() {
    List<User> users = userLister.getUsers();
    view.render(users);
  }
}

Done! So now even if you have hundreds or thousands of views, you still just need to change the one line of code, as in the Spring XML approach. But changing a line of code still requires recompiling as opposed to editing XML you say? Well my fussy friend, use Ant and script away!

So what is Spring for? It's for:

  1. Blind developers who follow the herd
  2. Employers who do not ever want to hire graduate programmers because they don't teach such frameworks at Uni
  3. Projects that started off with a bad design and need patchwork (as shown by victor hugo's example)

Further reading: http://discuss.joelonsoftware.com/?joel.3.219431.12

Proxy with express.js

To extend trigoman's answer (full credits to him) to work with POST (could also make work with PUT etc):

app.use('/api', function(req, res) {
  var url = 'YOUR_API_BASE_URL'+ req.url;
  var r = null;
  if(req.method === 'POST') {
     r = request.post({uri: url, json: req.body});
  } else {
     r = request(url);
  }

  req.pipe(r).pipe(res);
});

Which tool to build a simple web front-end to my database

The most rapid option is to hand out MS Access or SQL Sever Management Studio (there's a free express edition) along with a read only account.

PHP is simple and has a well earned reputation for getting stuff done. PHP is excellent for copying and pasting code, and you can iterate insanely fast in PHP. PHP can lead to hard-to-maintain applications, and it can be difficult to set up a visual debugger.

Given that you use SQL Server, ASP.NET is also a good option. This is somewhat harder to setup; you'll need an IIS server, with a configured application. Iterations are a bit slower. ASP.NET is easier to maintain and Visual Studio is the best visual debugger around.

Find string between two substrings

Here is a function I did to return a list with a string(s) inbetween string1 and string2 searched.

def GetListOfSubstrings(stringSubject,string1,string2):
    MyList = []
    intstart=0
    strlength=len(stringSubject)
    continueloop = 1

    while(intstart < strlength and continueloop == 1):
        intindex1=stringSubject.find(string1,intstart)
        if(intindex1 != -1): #The substring was found, lets proceed
            intindex1 = intindex1+len(string1)
            intindex2 = stringSubject.find(string2,intindex1)
            if(intindex2 != -1):
                subsequence=stringSubject[intindex1:intindex2]
                MyList.append(subsequence)
                intstart=intindex2+len(string2)
            else:
                continueloop=0
        else:
            continueloop=0
    return MyList


#Usage Example
mystring="s123y123o123pp123y6"
List = GetListOfSubstrings(mystring,"1","y68")
for x in range(0, len(List)):
               print(List[x])
output:


mystring="s123y123o123pp123y6"
List = GetListOfSubstrings(mystring,"1","3")
for x in range(0, len(List)):
              print(List[x])
output:
    2
    2
    2
    2

mystring="s123y123o123pp123y6"
List = GetListOfSubstrings(mystring,"1","y")
for x in range(0, len(List)):
               print(List[x])
output:
23
23o123pp123

How to install Intellij IDEA on Ubuntu?

Since Ubuntu 16.04 includes snapd by default.
So, the easiest way to install the stable version is

  • IntelliJ IDEA Community:
    $ sudo snap install intellij-idea-community --classic
  • IntelliJ IDEA Ultimate:
    $ sudo snap install intellij-idea-ultimate --classic

For the latest version use channel --edge
$ sudo snap install intellij-idea-community --classic --edge

Here is the list of all channels https://snapcraft.io/intellij-idea-ultimate (drop down 'All versions').

options

--classic

The --classic option is required because the IntelliJ IDEA snap requires full access to the system, like a traditionally packaged application.
[https://www.jetbrains.com/help/idea/install-and-set-up-product.html#install-on-linux-with-snaps]

--edge

--edge Install from the edge channel [http://manpages.ubuntu.com/manpages/bionic/man1/snap.1.html]

Note: Snap, also work a few major distributions: Arch, Debian, Fedora, openSUSE, Linux Mint,...

Concatenate chars to form String in java

If the size of the string is fixed, you might find easier to use an array of chars. If you have to do this a lot, it will be a tiny bit faster too.

char[] chars = new char[3];
chars[0] = 'i';
chars[1] = 'c';
chars[2] = 'e';
return new String(chars);

Also, I noticed in your original question, you use the Char class. If your chars are not nullable, it is better to use the lowercase char type.

number of values in a list greater than a certain number

Different way of counting by using bisect module:

>>> from bisect import bisect
>>> j = [4, 5, 6, 7, 1, 3, 7, 5]
>>> j.sort()
>>> b = 5
>>> index = bisect(j,b) #Find that index value
>>> print len(j)-index
3

Developing C# on Linux

Now Microsoft is migrating to open-source - see CoreFX (GitHub).

How to check Spark Version

According to the Cloudera documentation - What's New in CDH 5.7.0 it includes Spark 1.6.0.

gem install: Failed to build gem native extension (can't find header files)

This post helped me. Thanks a lot.

On Linux (Ubuntu 12.10) I needed to run

sudo apt-get install ruby
sudo apt-get install rubygems
sudo apt-get install ruby-dev

before I could succesfully run

sudo gem install jekyll

Difference between / and /* in servlet mapping url pattern

I'd like to supplement BalusC's answer with the mapping rules and an example.

Mapping rules from Servlet 2.5 specification:

  1. Map exact URL
  2. Map wildcard paths
  3. Map extensions
  4. Map to the default servlet

In our example, there're three servlets. / is the default servlet installed by us. Tomcat installs two servlets to serve jsp and jspx. So to map http://host:port/context/hello

  1. No exact URL servlets installed, next.
  2. No wildcard paths servlets installed, next.
  3. Doesn't match any extensions, next.
  4. Map to the default servlet, return.

To map http://host:port/context/hello.jsp

  1. No exact URL servlets installed, next.
  2. No wildcard paths servlets installed, next.
  3. Found extension servlet, return.

Does an HTTP Status code of 0 have any meaning?

Since iOS 9, you need to add "App Transport Security Settings" to your info.plist file and allow "Allow Arbitrary Loads" before making request to non-secure HTTP web service. I had this issue in one of my app.

Django 1.7 - makemigrations not detecting changes

Maybe this will help someone. I was using a nested app. project.appname and I actually had project and project.appname in INSTALLED_APPS. Removing project from INSTALLED_APPS allowed the changes to be detected.

check if directory exists and delete in one command unix

Here is another one liner:

[[ -d /tmp/test ]] && rm -r /tmp/test
  • && means execute the statement which follows only if the preceding statement executed successfully (returned exit code zero)

Why this "Implicit declaration of function 'X'"?

summation and your other functions are defined after they're used in main, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.

You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.

Either move the function bodies before main, or include method signatures before main, e.g.:

#include <stdio.h>

int summation(int *, int *, int *);

int main()
{
    // ...

Copy file remotely with PowerShell

Use net use or New-PSDrive to create a new drive:

New-PsDrive: create a new PsDrive only visible in PowerShell environment:

New-PSDrive -Name Y -PSProvider filesystem -Root \\ServerName\Share
Copy-Item BigFile Y:\BigFileCopy

Net use: create a new drive visible in all parts of the OS.

Net use y: \\ServerName\Share
Copy-Item BigFile Y:\BigFileCopy

Java for loop syntax: "for (T obj : objects)"

That's the for each loop syntax. It is looping through each object in the collection returned by objectListing.getObjectSummaries().

MySQL SELECT LIKE or REGEXP to match multiple words in one record

The correct solution is a FullText Search (if you can use it) https://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html

This nearly does what you want:

SELECT * FROM buckets WHERE bucketname RLIKE '(Stylus|2100)+.*(Stylus|2100)+';

SELECT * FROM buckets WHERE bucketname RLIKE '(Stylus|2100|photo)+.*(Stylus|2100|photo)+.*(Stylus|2100|photo)+.*';

But this will also match "210021002100" which is not great.

Changing SQL Server collation to case insensitive from case sensitive?

You basically need to run the installation again to rebuild the master database with the new collation. You cannot change the entire server's collation any other way.

See:

Update: if you want to change the collation of a database, you can get the current collation using this snippet of T-SQL:

SELECT name, collation_name 
FROM sys.databases
WHERE name = 'test2'   -- put your database name here

This will yield a value something like:

Latin1_General_CI_AS

The _CI means "case insensitive" - if you want case-sensitive, use _CS in its place:

Latin1_General_CS_AS

So your T-SQL command would be:

ALTER DATABASE test2 -- put your database name here
   COLLATE Latin1_General_CS_AS   -- replace with whatever collation you need

You can get a list of all available collations on the server using:

SELECT * FROM ::fn_helpcollations()

You can see the server's current collation using:

SELECT SERVERPROPERTY ('Collation')

How do you add an ActionListener onto a JButton in Java

I'm didn't totally follow, but to add an action listener, you just call addActionListener (from Abstract Button). If this doesn't totally answer your question, can you provide some more details?

Set Jackson Timezone for Date deserialization

I am using Jackson 1.9.7 and I found that doing the following does not solve my serialization/deserialization timezone issue:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
objectMapper.setDateFormat(dateFormat);

Instead of "2014-02-13T20:09:09.859Z" I get "2014-02-13T08:09:09.859+0000" in the JSON message which is obviously incorrect. I don't have time to step through the Jackson library source code to figure out why this occurs, however I found that if I just specify the Jackson provided ISO8601DateFormat class to the ObjectMapper.setDateFormat method the date is correct.

Except this doesn't put the milliseconds in the format which is what I want so I sub-classed the ISO8601DateFormat class and overrode the format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) method.

/**
 * Provides a ISO8601 date format implementation that includes milliseconds
 *
 */
public class ISO8601DateFormatWithMillis extends ISO8601DateFormat {

  /**
   * For serialization
   */
  private static final long serialVersionUID = 2672976499021731672L;


  @Override
  public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition)
  {
      String value = ISO8601Utils.format(date, true);
      toAppendTo.append(value);
      return toAppendTo;
  }
}

Assertion failure in dequeueReusableCellWithIdentifier:forIndexPath:

I give you the answer in both Objective C and Swift.Before that I want to say

If we use the dequeueReusableCellWithIdentifier:forIndexPath:,we must register a class or nib file using the registerNib:forCellReuseIdentifier: or registerClass:forCellReuseIdentifier: method before calling this method as Apple Documnetation Says

So we add registerNib:forCellReuseIdentifier: or registerClass:forCellReuseIdentifier:

Once we registered a class for the specified identifier and a new cell must be created, this method initializes the cell by calling its initWithStyle:reuseIdentifier: method. For nib-based cells, this method loads the cell object from the provided nib file. If an existing cell was available for reuse, this method calls the cell’s prepareForReuse method instead.

in viewDidLoad method we should register the cell

Objective C

OPTION 1:

[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];

OPTION 2:

[self.tableView registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil] forCellReuseIdentifier:@"cell"];

in above code nibWithNibName:@"CustomCell" give your nib name instead of my nib name CustomCell

SWIFT

OPTION 1:

tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

OPTION 2:

tableView.registerNib(UINib(nibName: "NameInput", bundle: nil), forCellReuseIdentifier: "Cell") 

in above code nibName:"NameInput" give your nib name

change values in array when doing foreach

Array: [1, 2, 3, 4]
Result: ["foo1", "foo2", "foo3", "foo4"]

Array.prototype.map() Keep original array

_x000D_
_x000D_
const originalArr = ["Iron", "Super", "Ant", "Aqua"];
const modifiedArr = originalArr.map(name => `${name}man`);

console.log( "Original: %s", originalArr );
console.log( "Modified: %s", modifiedArr );
_x000D_
_x000D_
_x000D_

Array.prototype.forEach() Override original array

_x000D_
_x000D_
const originalArr = ["Iron", "Super", "Ant", "Aqua"];
originalArr.forEach((name, index) => originalArr[index] = `${name}man`);

console.log( "Overridden: %s", originalArr );
_x000D_
_x000D_
_x000D_

Update query with PDO and MySQL

  1. Your UPDATE syntax is wrong
  2. You probably meant to update a row not all of them so you have to use WHERE clause to target your specific row

Change

UPDATE `access_users`   
      (`contact_first_name`,`contact_surname`,`contact_email`,`telephone`) 
      VALUES (:firstname, :surname, :telephone, :email)

to

UPDATE `access_users`   
   SET `contact_first_name` = :firstname,
       `contact_surname` = :surname,
       `contact_email` = :email,
       `telephone` = :telephone 
 WHERE `user_id` = :user_id -- you probably have some sort of id 

MySQL - Select the last inserted row easiest way

SELECT ID from bugs WHERE user=Me ORDER BY CREATED_STAMP DESC; BY CREATED_STAMP DESC fetches those data at index first which last created.

I hope it will resolve your problem

jquery fill dropdown with json data

This should do the trick:

$($.parseJSON(data.msg)).map(function () {
    return $('<option>').val(this.value).text(this.label);
}).appendTo('#combobox');

Here's the distinction between ajax and getJSON (from the jQuery documentation):

[getJSON] is a shorthand Ajax function, which is equivalent to:

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

EDIT: To be clear, part of the problem was that the server's response was returning a json object that looked like this:

{
    "msg": '[{"value":"1","label":"xyz"}, {"value":"2","label":"abc"}]'
}

...So that msg property needed to be parsed manually using $.parseJSON().

Instant run in Android Studio 2.0 (how to turn off)

Update August 2019

In Android Studio 3.5 Instant Run was replaced with Apply Changes. And it works in different way: APK is not modified on the fly anymore but instead runtime instrumentation is used to redefine classes on the fly (more info). So since Android Studio 3.5 instant run settings are replaced with Deployment (Settings -> Build, Execution, Deployment -> Deployment):enter image description here

REST URI convention - Singular or plural name of resource while creating it

I don't like to see the {id} part of the URLs overlap with sub-resources, as an id could theoretically be anything and there would be ambiguity. It is mixing different concepts (identifiers and sub-resource names).

Similar issues are often seen in enum constants or folder structures, where different concepts are mixed (for example, when you have folders Tigers, Lions and Cheetahs, and then also a folder called Animals at the same level -- this makes no sense as one is a subset of the other).

In general I think the last named part of an endpoint should be singular if it deals with a single entity at a time, and plural if it deals with a list of entities.

So endpoints that deal with a single user:

GET  /user             -> Not allowed, 400
GET  /user/{id}        -> Returns user with given id
POST /user             -> Creates a new user
PUT  /user/{id}        -> Updates user with given id
DELETE /user/{id}      -> Deletes user with given id

Then there is separate resource for doing queries on users, which generally return a list:

GET /users             -> Lists all users, optionally filtered by way of parameters
GET /users/new?since=x -> Gets all users that are new since a specific time
GET /users/top?max=x   -> Gets top X active users

And here some examples of a sub-resource that deals with a specific user:

GET /user/{id}/friends -> Returns a list of friends of given user

Make a friend (many to many link):

PUT /user/{id}/friend/{id}     -> Befriends two users
DELETE /user/{id}/friend/{id}  -> Unfriends two users
GET /user/{id}/friend/{id}     -> Gets status of friendship between two users

There is never any ambiguity, and the plural or singular naming of the resource is a hint to the user what they can expect (list or object). There are no restrictions on ids, theoretically making it possible to have a user with the id new without overlapping with a (potential future) sub-resource name.

Efficient way to Handle ResultSet in Java

RHT pretty much has it. Or you could use a RowSetDynaClass and let someone else do all the work :)

Find the similarity metric between two strings

Note, difflib.SequenceMatcher only finds the longest contiguous matching subsequence, this is often not what is desired, for example:

>>> a1 = "Apple"
>>> a2 = "Appel"
>>> a1 *= 50
>>> a2 *= 50
>>> SequenceMatcher(None, a1, a2).ratio()
0.012  # very low
>>> SequenceMatcher(None, a1, a2).get_matching_blocks()
[Match(a=0, b=0, size=3), Match(a=250, b=250, size=0)]  # only the first block is recorded

Finding the similarity between two strings is closely related to the concept of pairwise sequence alignment in bioinformatics. There are many dedicated libraries for this including biopython. This example implements the Needleman Wunsch algorithm:

>>> from Bio.Align import PairwiseAligner
>>> aligner = PairwiseAligner()
>>> aligner.score(a1, a2)
200.0
>>> aligner.algorithm
'Needleman-Wunsch'

Using biopython or another bioinformatics package is more flexible than any part of the python standard library since many different scoring schemes and algorithms are available. Also, you can actually get the matching sequences to visualise what is happening:

>>> alignment = next(aligner.align(a1, a2))
>>> alignment.score
200.0
>>> print(alignment)
Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-Apple-
|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-|||-|-
App-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-elApp-el

what innerHTML is doing in javascript?

innerHTML explanation with example:

The innerHTML manipulates the HTML content of an element(get or set). In the example below if you click on the Change Content link it's value will be updated by using innerHTML property of anchor link Change Content

Example:

_x000D_
_x000D_
<a id="example" onclick='testFunction()'>Change Content</a>_x000D_
_x000D_
<script>_x000D_
  function testFunction(){_x000D_
    // change the content using innerHTML_x000D_
    document.getElementById("example").innerHTML = "This is dummy content";_x000D_
_x000D_
    // get the content using innerHTML_x000D_
    alert(document.getElementById("example").innerHTML)_x000D_
_x000D_
  }_x000D_
</script>_x000D_
    
_x000D_
_x000D_
_x000D_

How to add results of two select commands in same query

UNION ALL once, aggregate once:

SELECT sum(hours) AS total_hours
FROM   (
   SELECT hours FROM resource
   UNION ALL
   SELECT hours FROM "projects-time" -- illegal name without quotes in most RDBMS
   ) x

Changing WPF title bar background color

You can also create a borderless window, and make the borders and title bar yourself

Scanner vs. BufferedReader

In currently latest JDK6 release/build (b27), the Scanner has a smaller buffer (1024 chars) as opposed to the BufferedReader (8192 chars), but it's more than sufficient.

As to the choice, use the Scanner if you want to parse the file, use the BufferedReader if you want to read the file line by line. Also see the introductory text of their aforelinked API documentations.

  • Parsing = interpreting the given input as tokens (parts). It's able to give back you specific parts directly as int, string, decimal, etc. See also all those nextXxx() methods in Scanner class.
  • Reading = dumb streaming. It keeps giving back you all characters, which you in turn have to manually inspect if you'd like to match or compose something useful. But if you don't need to do that anyway, then reading is sufficient.

what is <meta charset="utf-8">?

The characters you are reading on your screen now each have a numerical value. In the ASCII format, for example, the letter 'A' is 65, 'B' is 66, and so on. If you look at a table of characters available in ASCII you will see that it isn't much use for someone who wishes to write something in Mandarin, Arabic, or Japanese. For characters / words from those languages to be displayed we needed another system of encoding them to and from numbers stored in computer memory.

UTF-8 is just one of the encoding methods that were invented to implement this requirement. It lets you write text in all kinds of languages, so French accents will appear perfectly fine, as will text like this

???? ????? (Bzia zbasa), ???????, Ç'kemi, ???, and even right-to-left writing such as this ?????? ?????

If you copy and paste the above text into notepad and then try to save the file as ANSI (another format) you will receive a warning that saving in this format will lose some of the formatting. Accept it, then re-load the text file and you'll see something like this

???? ????? (Bzia zbasa), ???????, Ç'kemi, ???, and even right-to-left writing such as this ?????? ?????

Trouble setting up git with my GitHub Account error: could not lock config file

You can also try issuing the command while in your home directory.

How to add one day to a date?

U can try java.util.Date library like this way-

int no_of_day_to_add = 1;

Date today = new Date();
Date tomorrow = new Date( today.getYear(), today.getMonth(), today.getDate() + no_of_day_to_add );

Change value of no_of_day_to_add as you want.

I have set value of no_of_day_to_add to 1 because u wanted only one day to add.

More can be found in this documentation.

How to find unused/dead code in java projects

I'm suprised ProGuard hasn't been mentioned here. It's one of the most mature products around.

ProGuard is a free Java class file shrinker, optimizer, obfuscator, and preverifier. It detects and removes unused classes, fields, methods, and attributes. It optimizes bytecode and removes unused instructions. It renames the remaining classes, fields, and methods using short meaningless names. Finally, it preverifies the processed code for Java 6 or for Java Micro Edition.

Some uses of ProGuard are:

  • Creating more compact code, for smaller code archives, faster transfer across networks, faster loading, and smaller memory footprints.
  • Making programs and libraries harder to reverse-engineer.
  • Listing dead code, so it can be removed from the source code.
  • Retargeting and preverifying existing class files for Java 6 or higher, to take full advantage of their faster class loading.

Here example for list dead code: https://www.guardsquare.com/en/products/proguard/manual/examples#deadcode

How to install a private NPM module without my own registry?

Very simple -

npm config set registry https://path-to-your-registry/

It actually sets registry = "https://path-to-your-registry" this line to /Users/<ur-machine-user-name>/.npmrc

All the value you have set explicitly or have been set by default can be seen by - npm config list

How do you add a scroll bar to a div?

You need to add style="overflow-y:scroll;" to the div tag. (This will force a scrollbar on the vertical).

If you only want a scrollbar when needed, just do overflow-y:auto;

Efficiently replace all accented characters in a string?

Simply should be normalized chain and run a replacement codes:

var str = "Letras Á É Í Ó Ú Ñ - á é í ó ú ñ...";
console.log (str.normalize ("NFKD").replace (/[\u0300-\u036F]/g, ""));
// Letras A E I O U N - a e i o u n...

See normalize

Then you can use this function:

function noTilde (s) {
    if (s.normalize != undefined) {
        s = s.normalize ("NFKD");
    }
    return s.replace (/[\u0300-\u036F]/g, "");
}

Java - Find shortest path between 2 points in a distance weighted map

This maybe too late but No one provided a clear explanation of how the algorithm works

The idea of Dijkstra is simple, let me show this with the following pseudocode.

Dijkstra partitions all nodes into two distinct sets. Unsettled and settled. Initially all nodes are in the unsettled set, e.g. they must be still evaluated.

At first only the source node is put in the set of settledNodes. A specific node will be moved to the settled set if the shortest path from the source to a particular node has been found.

The algorithm runs until the unsettledNodes set is empty. In each iteration it selects the node with the lowest distance to the source node out of the unsettledNodes set. E.g. It reads all edges which are outgoing from the source and evaluates each destination node from these edges which are not yet settled.

If the known distance from the source to this node can be reduced when the selected edge is used, the distance is updated and the node is added to the nodes which need evaluation.

Please note that Dijkstra also determines the pre-successor of each node on its way to the source. I left that out of the pseudo code to simplify it.

Credits to Lars Vogel

WPF loading spinner

CircularProgressBarBlue.xaml

<UserControl 
x:Class="CircularProgressBarBlue"   
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Background="Transparent"
Name="progressBar">
<UserControl.Resources>
    <Storyboard x:Key="spinning" >
        <DoubleAnimation 
            Storyboard.TargetName="SpinnerRotate" 
            Storyboard.TargetProperty="(RotateTransform.Angle)"                 
            From="0" 
            To="360"                 
            RepeatBehavior="Forever"/>
    </Storyboard>
</UserControl.Resources>
<Grid 
    x:Name="LayoutRoot" 
    Background="Transparent" 
    HorizontalAlignment="Center" 
    VerticalAlignment="Center">
    <Image Source="C:\SpinnerImage\BlueSpinner.png" RenderTransformOrigin="0.5,0.5" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
        <Image.RenderTransform>
            <RotateTransform 
                x:Name="SpinnerRotate"
                Angle="0"/>
        </Image.RenderTransform>
    </Image>


</Grid>

CircularProgressBarBlue.xaml.cs

using System;

using System.Windows;

using System.Windows.Media.Animation;


        /// <summary>
    /// Interaction logic for CircularProgressBarBlue.xaml
    /// </summary>
    public partial class CircularProgressBarBlue
    {
        private Storyboard _sb;

        public CircularProgressBarBlue()
        {
            InitializeComponent();
            StartStoryBoard();
            IsVisibleChanged += CircularProgressBarBlueIsVisibleChanged;
        }

        void CircularProgressBarBlueIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (_sb == null) return;
            if (e != null && e.NewValue != null && (((bool)e.NewValue)))
            {
                _sb.Begin();
                _sb.Resume();
            }
            else
            {
                _sb.Stop();
            }
        }

        void StartStoryBoard()
        {
            try
            {
                _sb = (Storyboard)TryFindResource("spinning");
                if (_sb != null)
                    _sb.Begin();
            }
            catch
            { }
        }
    }

How to open .SQLite files

SQLite is database engine, .sqlite or .db should be a database. If you don't need to program anything, you can use a GUI like sqlitebrowser or anything like that to view the database contents.

There is also spatialite, https://www.gaia-gis.it/fossil/spatialite_gui/index

Multiple markers Google Map API v3 from array of addresses and avoid OVER_QUERY_LIMIT while geocoding on pageLoad

Regardless of your situation, heres a working demo that creates markers on the map based on an array of addresses.

http://jsfiddle.net/P2QhE/

Javascript code embedded aswell:

$(document).ready(function () {
    var map;
    var elevator;
    var myOptions = {
        zoom: 1,
        center: new google.maps.LatLng(0, 0),
        mapTypeId: 'terrain'
    };
    map = new google.maps.Map($('#map_canvas')[0], myOptions);

    var addresses = ['Norway', 'Africa', 'Asia','North America','South America'];

    for (var x = 0; x < addresses.length; x++) {
        $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
            var p = data.results[0].geometry.location
            var latlng = new google.maps.LatLng(p.lat, p.lng);
            new google.maps.Marker({
                position: latlng,
                map: map
            });

        });
    }

}); 

std::cin input with spaces?

You want to use the .getline function in cin.

#include <iostream>
using namespace std;

int main () {
  char name[256], title[256];

  cout << "Enter your name: ";
  cin.getline (name,256);

  cout << "Enter your favourite movie: ";
  cin.getline (title,256);

  cout << name << "'s favourite movie is " << title;

  return 0;
}

Took the example from here. Check it out for more info and examples.

I have created a table in hive, I would like to know which directory my table is created in?

All HIVE managed tables are stored in the below HDFS location.

hadoop fs -ls /user/hive/warehouse/databasename.db/tablename

How do I activate a virtualenv inside PyCharm's terminal?

If your Pycharm 2016.1.4v and higher you should use "default path" /K "<path-to-your-activate.bat>" don't forget quotes

How do I add a library path in cmake?

The simplest way of doing this would be to add

include_directories(${CMAKE_SOURCE_DIR}/inc)
link_directories(${CMAKE_SOURCE_DIR}/lib)

add_executable(foo ${FOO_SRCS})
target_link_libraries(foo bar) # libbar.so is found in ${CMAKE_SOURCE_DIR}/lib

The modern CMake version that doesn't add the -I and -L flags to every compiler invocation would be to use imported libraries:

add_library(bar SHARED IMPORTED) # or STATIC instead of SHARED
set_target_properties(bar PROPERTIES
  IMPORTED_LOCATION "${CMAKE_SOURCE_DIR}/lib/libbar.so"
  INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_SOURCE_DIR}/include/libbar"
)

set(FOO_SRCS "foo.cpp")
add_executable(foo ${FOO_SRCS})
target_link_libraries(foo bar) # also adds the required include path

If setting the INTERFACE_INCLUDE_DIRECTORIES doesn't add the path, older versions of CMake also allow you to use target_include_directories(bar PUBLIC /path/to/include). However, this no longer works with CMake 3.6 or newer.

HtmlSpecialChars equivalent in Javascript?

Here's a function to escape HTML:

function escapeHtml(str)
{
    var map =
    {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };
    return str.replace(/[&<>"']/g, function(m) {return map[m];});
}

And to decode:

function decodeHtml(str)
{
    var map =
    {
        '&amp;': '&',
        '&lt;': '<',
        '&gt;': '>',
        '&quot;': '"',
        '&#039;': "'"
    };
    return str.replace(/&amp;|&lt;|&gt;|&quot;|&#039;/g, function(m) {return map[m];});
}

Numeric for loop in Django templates

{% with ''|center:n as range %}
{% for _ in range %}
    {{ forloop.counter }}
{% endfor %}
{% endwith %}

What REST PUT/POST/DELETE calls should return by a convention?

Forgive the flippancy, but if you are doing REST over HTTP then RFC7231 describes exactly what behaviour is expected from GET, PUT, POST and DELETE.

Update (Jul 3 '14):
The HTTP spec intentionally does not define what is returned from POST or DELETE. The spec only defines what needs to be defined. The rest is left up to the implementer to choose.

Storing Form Data as a Session Variable

You can solve this problem using this code:

if(!empty($_GET['variable from which you get'])) 
{
$_SESSION['something']= $_GET['variable from which you get'];
}

So you get the variable from a GET form, you will store in the $_SESSION['whatever'] variable just once when $_GET['variable from which you get']is set and if it is empty $_SESSION['something'] will store the old parameter

Python - difference between two strings

What you are asking for is a specialized form of compression. xdelta3 was designed for this particular kind of compression, and there's a python binding for it, but you could probably get away with using zlib directly. You'd want to use zlib.compressobj and zlib.decompressobj with the zdict parameter set to your "base word", e.g. afrykanerskojezyczny.

Caveats are zdict is only supported in python 3.3 and higher, and it's easiest to code if you have the same "base word" for all your diffs, which may or may not be what you want.

Last Run Date on a Stored Procedure in SQL Server

sys.dm_exec_procedure_stats contains the information about the execution functions, constraints and Procedures etc. But the life time of the row has a limit, The moment the execution plan is removed from the cache the entry will disappear.

Use [yourDatabaseName]
GO
SELECT  
        SCHEMA_NAME(sysobject.schema_id),
        OBJECT_NAME(stats.object_id), 
        stats.last_execution_time
    FROM   
        sys.dm_exec_procedure_stats stats
        INNER JOIN sys.objects sysobject ON sysobject.object_id = stats.object_id 
    WHERE  
        sysobject.type = 'P'
    ORDER BY
           stats.last_execution_time DESC  

This will give you the list of the procedures recently executed.

If you want to check if a perticular stored procedure executed recently

SELECT  
    SCHEMA_NAME(sysobject.schema_id),
    OBJECT_NAME(stats.object_id), 
    stats.last_execution_time
FROM   
    sys.dm_exec_procedure_stats stats
    INNER JOIN sys.objects sysobject ON sysobject.object_id = stats.object_id 
WHERE  
    sysobject.type = 'P'
    and (sysobject.object_id = object_id('schemaname.procedurename') 
    OR sysobject.name = 'procedurename')
ORDER BY
       stats.last_execution_time DESC  

CodeIgniter Select Query

function news_get_by_id ( $news_id )
{

    $this->db->select('*');
    $this->db->select("DATE_FORMAT( date, '%d.%m.%Y' ) as date_human",  FALSE );
    $this->db->select("DATE_FORMAT( date, '%H:%i') as time_human",      FALSE );


    $this->db->from('news');

    $this->db->where('news_id', $news_id );


    $query = $this->db->get();

    if ( $query->num_rows() > 0 )
    {
        $row = $query->row_array();
        return $row;
    }

}   
This 

How can I draw vertical text with CSS cross-browser?

My solution that would work on Chrome, Firefox, IE9, IE10 (Change the degrees as per your requirement):

.rotate-text {
  -webkit-transform: rotate(270deg);
  -moz-transform: rotate(270deg);
  -ms-transform: rotate(270deg);
  -o-transform: rotate(270deg);
  transform: rotate(270deg);
  filter: none; /*Mandatory for IE9 to show the vertical text correctly*/      
}

How to rename a single column in a data.frame?

This is an old question, but it is worth noting that you can now use setnames from the data.table package.

library(data.table)

setnames(DF, "oldName", "newName")

# or since the data.frame in question is just one column: 
setnames(DF, "newName")

# And for reference's sake, in general (more than once column)
nms <- c("col1.name", "col2.name", etc...)
setnames(DF, nms)

How to use numpy.genfromtxt when first column is string and the remaining columns are numbers?

By default, np.genfromtxt uses dtype=float: that's why you string columns are converted to NaNs because, after all, they're Not A Number...

You can ask np.genfromtxt to try to guess the actual type of your columns by using dtype=None:

>>> from StringIO import StringIO
>>> test = "a,1,2\nb,3,4"
>>> a = np.genfromtxt(StringIO(test), delimiter=",", dtype=None)
>>> print a
array([('a',1,2),('b',3,4)], dtype=[('f0', '|S1'),('f1', '<i8'),('f2', '<i8')])

You can access the columns by using their name, like a['f0']...

Using dtype=None is a good trick if you don't know what your columns should be. If you already know what type they should have, you can give an explicit dtype. For example, in our test, we know that the first column is a string, the second an int, and we want the third to be a float. We would then use

>>> np.genfromtxt(StringIO(test), delimiter=",", dtype=("|S10", int, float))
array([('a', 1, 2.0), ('b', 3, 4.0)], 
      dtype=[('f0', '|S10'), ('f1', '<i8'), ('f2', '<f8')])

Using an explicit dtype is much more efficient than using dtype=None and is the recommended way.

In both cases (dtype=None or explicit, non-homogeneous dtype), you end up with a structured array.

[Note: With dtype=None, the input is parsed a second time and the type of each column is updated to match the larger type possible: first we try a bool, then an int, then a float, then a complex, then we keep a string if all else fails. The implementation is rather clunky, actually. There had been some attempts to make the type guessing more efficient (using regexp), but nothing that stuck so far]

php exec() is not executing the command

You might also try giving the full path to the binary you're trying to run. That solved my problem when trying to use ImageMagick.

Interface defining a constructor signature?

You can't.

Interfaces define contracts that other objects implement and therefore have no state that needs to be initialized.

If you have some state that needs to be initialized, you should consider using an abstract base class instead.

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
     ( 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

How to display (print) vector in Matlab?

To print a vector which possibly has complex numbers-

fprintf('Answer: %s\n', sprintf('%d ', num2str(x)));

Select N random elements from a List<T> in C#

Was thinking about comment by @JohnShedletsky on the accepted answer regarding (paraphrase):

you should be able to to this in O(subset.Length), rather than O(originalList.Length)

Basically, you should be able to generate subset random indices and then pluck them from the original list.

The Method

public static class EnumerableExtensions {

    public static Random randomizer = new Random(); // you'd ideally be able to replace this with whatever makes you comfortable

    public static IEnumerable<T> GetRandom<T>(this IEnumerable<T> list, int numItems) {
        return (list as T[] ?? list.ToArray()).GetRandom(numItems);

        // because ReSharper whined about duplicate enumeration...
        /*
        items.Add(list.ElementAt(randomizer.Next(list.Count()))) ) numItems--;
        */
    }

    // just because the parentheses were getting confusing
    public static IEnumerable<T> GetRandom<T>(this T[] list, int numItems) {
        var items = new HashSet<T>(); // don't want to add the same item twice; otherwise use a list
        while (numItems > 0 )
            // if we successfully added it, move on
            if( items.Add(list[randomizer.Next(list.Length)]) ) numItems--;

        return items;
    }

    // and because it's really fun; note -- you may get repetition
    public static IEnumerable<T> PluckRandomly<T>(this IEnumerable<T> list) {
        while( true )
            yield return list.ElementAt(randomizer.Next(list.Count()));
    }

}

If you wanted to be even more efficient, you would probably use a HashSet of the indices, not the actual list elements (in case you've got complex types or expensive comparisons);

The Unit Test

And to make sure we don't have any collisions, etc.

[TestClass]
public class RandomizingTests : UnitTestBase {
    [TestMethod]
    public void GetRandomFromList() {
        this.testGetRandomFromList((list, num) => list.GetRandom(num));
    }

    [TestMethod]
    public void PluckRandomly() {
        this.testGetRandomFromList((list, num) => list.PluckRandomly().Take(num), requireDistinct:false);
    }

    private void testGetRandomFromList(Func<IEnumerable<int>, int, IEnumerable<int>> methodToGetRandomItems, int numToTake = 10, int repetitions = 100000, bool requireDistinct = true) {
        var items = Enumerable.Range(0, 100);
        IEnumerable<int> randomItems = null;

        while( repetitions-- > 0 ) {
            randomItems = methodToGetRandomItems(items, numToTake);
            Assert.AreEqual(numToTake, randomItems.Count(),
                            "Did not get expected number of items {0}; failed at {1} repetition--", numToTake, repetitions);
            if(requireDistinct) Assert.AreEqual(numToTake, randomItems.Distinct().Count(),
                            "Collisions (non-unique values) found, failed at {0} repetition--", repetitions);
            Assert.IsTrue(randomItems.All(o => items.Contains(o)),
                        "Some unknown values found; failed at {0} repetition--", repetitions);
        }
    }
}

How to view .img files?

At first you should use file to identify the image:

file foo.img

How to make input type= file Should accept only pdf and xls

If you want the file upload control to Limit the types of files user can upload on a button click then this is the way..

<script type="text/JavaScript">
<!-- Begin
function TestFileType( fileName, fileTypes ) {
if (!fileName) return;

dots = fileName.split(".")
//get the part AFTER the LAST period.
fileType = "." + dots[dots.length-1];

return (fileTypes.join(".").indexOf(fileType) != -1) ?
alert('That file is OK!') : 
alert("Please only upload files that end in types: \n\n" + (fileTypes.join(" .")) + "\n\nPlease select a new file and try again.");
}
// -->
</script>

You can then call the function from an event like the onClick of the above button, which looks like:

onClick="TestFileType(this.form.uploadfile.value, ['gif', 'jpg', 'png', 'jpeg']);"

You can change this to: PDF and XLS

You can see it implemented over here: Demo

jQuery ui datepicker with Angularjs

onSelect doesn't work well in ng-repeat, so I made another version using event bind

html

<tr ng-repeat="product in products">
<td>
    <input type="text" ng-model="product.startDate" class="form-control date-picker" data-date-format="yyyy-mm-dd" datepicker/>
</td>
</tr>

script

angular.module('app', []).directive('datepicker', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModelCtrl) {
            element.datepicker();
            element.bind('blur keyup change', function(){
                var model = attrs.ngModel;
                if (model.indexOf(".") > -1) scope[model.replace(/\.[^.]*/, "")][model.replace(/[^.]*\./, "")] = element.val();
                else scope[model] = element.val();
            });
        }
    };
});

issue ORA-00001: unique constraint violated coming in INSERT/UPDATE

Oracle's error message should be somewhat longer. It usually looks like this:

ORA-00001: unique constraint (TABLE_UK1) violated

The name in parentheses is the constrait name. It tells you which constraint was violated.

How to asynchronously call a method in Java

I just discovered that there is a cleaner way to do your

new Thread(new Runnable() {
    public void run() {
        //Do whatever
    }
}).start();

(At least in Java 8), you can use a lambda expression to shorten it to:

new Thread(() -> {
    //Do whatever
}).start();

As simple as making a function in JS!

How to include css files in Vue 2

As you can see, the import command did work but is showing errors because it tried to locate the resources in vendor.css and couldn't find them

You should also upload your project structure and ensure that there aren't any path issues. Also, you could include the css file in the index.html or the Component template and webpack loader would extract it when built

Twitter API - Display all tweets with a certain hashtag?

This answer was written in 2010. The API it uses has since been retired. It is kept for historical interest only.


Search for it.

Make sure include_entities is set to true to get hashtag results. See Tweet Entities

Returns 5 mixed results with Twitter.com user IDs plus entities for the term "blue angels":

GET http://search.twitter.com/search.json?q=blue%20angels&rpp=5&include_entities=true&with_twitter_user_id=true&result_type=mixed

ImportError: No module named 'Tkinter'

check the python version you have installed by using command python --version

check for the Tk module installed correctly from following code

sudo apt-get install python3-tk 

Check if you are using open-source OS then

check the tkinter module in the following path /home/python/site-packages/tkinter change the path accordingly your system

Sorting an IList in C#

Found a good post on this and thought I'd share. Check it out HERE

Basically.

You can create the following class and IComparer Classes

public class Widget {
    public string Name = string.Empty;
    public int Size = 0;

    public Widget(string name, int size) {
    this.Name = name;
    this.Size = size;
}
}

public class WidgetNameSorter : IComparer<Widget> {
    public int Compare(Widget x, Widget y) {
        return x.Name.CompareTo(y.Name);
}
}

public class WidgetSizeSorter : IComparer<Widget> {
    public int Compare(Widget x, Widget y) {
    return x.Size.CompareTo(y.Size);
}
}

Then If you have an IList, you can sort it like this.

List<Widget> widgets = new List<Widget>();
widgets.Add(new Widget("Zeta", 6));
widgets.Add(new Widget("Beta", 3));
widgets.Add(new Widget("Alpha", 9));

widgets.Sort(new WidgetNameSorter());
widgets.Sort(new WidgetSizeSorter());

But Checkout this site for more information... Check it out HERE

How to manually deploy artifacts in Nexus Repository Manager OSS 3

My Team built a command line tool for uploading artifacts to nexus 3.x repository, Maybe it's will be helpful for you - Maven Artifacts Uploader

Start an Activity with a parameter

I like to do it with a static method in the second activity:

private static final String EXTRA_GAME_ID = "your.package.gameId";

public static void start(Context context, String gameId) {
    Intent intent = new Intent(context, SecondActivity.class);
    intent.putExtra(EXTRA_GAME_ID, gameId);
    context.startActivity(intent);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    ... 
    Intent intent = this.getIntent();
    String gameId = intent.getStringExtra(EXTRA_GAME_ID);
}

Then from your first activity (and for anywhere else), you just do:

SecondActivity.start(this, "the.game.id");

C# Wait until condition is true

At least you can change your loop from a busy-wait to a slow poll. For example:

    while (!isExcelInteractive())
    {
        Console.WriteLine("Excel is busy");
        await Task.Delay(25);
    }

Convert pyspark string to date format

Try this:

df = spark.createDataFrame([('2018-07-27 10:30:00',)], ['Date_col'])
df.select(from_unixtime(unix_timestamp(df.Date_col, 'yyyy-MM-dd HH:mm:ss')).alias('dt_col'))
df.show()
+-------------------+  
|           Date_col|  
+-------------------+  
|2018-07-27 10:30:00|  
+-------------------+  

Command line tool to dump Windows DLL version?

You can write a VBScript script to get the file version info:

VersionInfo.vbs

set args = WScript.Arguments
Set fso = CreateObject("Scripting.FileSystemObject")
WScript.Echo fso.GetFileVersion(args(0))
Wscript.Quit

You can call this from the command line like this:

cscript //nologo VersionInfo.vbs C:\Path\To\MyFile.dll

Difference between object and class in Scala

Scala class same as Java Class but scala not gives you any entry method in class, like main method in java. The main method associated with object keyword. You can think of the object keyword as creating a singleton object of a class that is defined implicitly.

more information check this article class and object keyword in scala programming

How to open a folder in Windows Explorer from VBA?

Here's an answer that gives the switch-or-launch behaviour of Start, without the Command Prompt window. It does have the drawback that it can be fooled by an Explorer window that has a folder of the same name elsewhere opened. I might fix that by diving into the child windows and looking for the actual path, I need to figure out how to navigate that.

Usage (requires "Windows Script Host Object Model" in your project's References):

Dim mShell As wshShell

mDocPath = whatever_path & "\" & lastfoldername
mExplorerPath = mShell.ExpandEnvironmentStrings("%SystemRoot%") & "\Explorer.exe"

If Not SwitchToFolder(lastfoldername) Then
    Shell PathName:=mExplorerPath & " """ & mDocPath & """", WindowStyle:=vbNormalFocus
End If

Module:

Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" _
(ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long
Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" _
(ByVal hWnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" _
(ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Private Declare Function BringWindowToTop Lib "user32" _
(ByVal lngHWnd As Long) As Long

Function SwitchToFolder(pFolder As String) As Boolean

Dim hWnd As Long
Dim mRet As Long
Dim mText As String
Dim mWinClass As String
Dim mWinTitle As String

    SwitchToFolder = False

    hWnd = FindWindowEx(0, 0&, vbNullString, vbNullString)
    While hWnd <> 0 And SwitchToFolder = False
        mText = String(100, Chr(0))
        mRet = GetClassName(hWnd, mText, 100)
        mWinClass = Left(mText, mRet)
        If mWinClass = "CabinetWClass" Then
            mText = String(100, Chr(0))
            mRet = GetWindowText(hWnd, mText, 100)
            If mRet > 0 Then
                mWinTitle = Left(mText, mRet)
                If UCase(mWinTitle) = UCase(pFolder) Or _
                   UCase(Right(mWinTitle, Len(pFolder) + 1)) = "\" & UCase(pFolder) Then
                    BringWindowToTop hWnd
                    SwitchToFolder = True
                End If
            End If
        End If
        hWnd = FindWindowEx(0, hWnd, vbNullString, vbNullString)
    Wend

End Function

SSLHandshakeException: No subject alternative names present

Unlike some browsers, Java follows the HTTPS specification strictly when it comes to the server identity verification (RFC 2818, Section 3.1) and IP addresses.

When using a host name, it's possible to fall back to the Common Name in the Subject DN of the server certificate, instead of using the Subject Alternative Name.

When using an IP address, there must be a Subject Alternative Name entry (of type IP address, not DNS name) in the certificate.

You'll find more details about the specification and how to generate such a certificate in this answer.

How to create a drop shadow only on one side of an element?

Just use the spread parameter to make the shadow smaller:

_x000D_
_x000D_
.shadow {_x000D_
  -webkit-box-shadow: 0 6px 4px -4px black;_x000D_
  -moz-box-shadow: 0 6px 4px -4px black;_x000D_
  box-shadow: 0 6px 4px -4px black;_x000D_
}
_x000D_
<div class="shadow">Some content</div>
_x000D_
_x000D_
_x000D_

Live demo: http://dabblet.com/gist/a8f8ba527f5cff607327

To not see any shadow on the sides, the (absolute value of the) spread radius (4th parameter) needs to be the same as the blur radius (3rd parameter).

Python sys.argv lists and indexes

let's say on the command-line you have:

C:\> C:\Documents and Settings\fred\My Documents\Downloads\google-python-exercises
\google-python-exercises\hello.py John

to make it easier to read, let's just shorten this to:

C:\> hello.py John

argv represents all the items that come along via the command-line input, but counting starts at zero (0) not one (1): in this case, "hello.py" is element 0, "John" is element 1

in other words, sys.argv[0] == 'hello.py' and sys.argv[1] == 'John' ... but look, how many elements is this? 2, right! so even though the numbers are 0 and 1, there are 2 elements here.

len(sys.argv) >= 2 just checks whether you entered at least two elements. in this case, we entered exactly 2.

now let's translate your code into English:

define main() function:
    if there are at least 2 elements on the cmd-line:
        set 'name' to the second element located at index 1, e.g., John
    otherwise there is only 1 element... the program name, e.g., hello.py:
        set 'name' to "World" (since we did not get any useful user input)
    display 'Hello' followed by whatever i assigned to 'name'

so what does this mean? it means that if you enter:

  • "hello.py", the code outputs "Hello World" because you didn't give a name
  • "hello.py John", the code outputs "Hello John" because you did
  • "hello.py John Paul", the code still outputs "Hello John" because it does not save nor use sys.argv[2], which was "Paul" -- can you see in this case that len(sys.argv) == 3 because there are 3 elements in the sys.argv list?

How to extend a class in python?

Use:

import color

class Color(color.Color):
    ...

If this were Python 2.x, you would also want to derive color.Color from object, to make it a new-style class:

class Color(object):
    ...

This is not necessary in Python 3.x.

How to use JQuery with ReactJS

Step 1:

npm install jquery

Step 2:

touch loader.js 

Somewhere in your project folder

Step 3:

//loader.js
window.$ = window.jQuery = require('jquery')

Step 4:

Import the loader into your root file before you import the files which require jQuery

//App.js
import '<pathToYourLoader>/loader.js'

Step 5:

Now use jQuery anywhere in your code:

//SomeReact.js
class SomeClass extends React.Compontent {

...

handleClick = () => {
   $('.accor > .head').on('click', function(){
      $('.accor > .body').slideUp();
      $(this).next().slideDown();
   });
}

...

export default SomeClass

How do I analyze a program's core dump file with GDB when it has command-line parameters?

Simple usage of GDB, to debug coredump files:

gdb <executable_path> <coredump_file_path>

A coredump file for a "process" gets created as a "core.pid" file.

After you get inside the GDB prompt (on execution of the above command), type:

...
(gdb) where

This will get you with the information, of the stack, where you can analayze the cause of the crash/fault. Other command, for the same purposes is:

...
(gdb) bt full

This is the same as above. By convention, it lists the whole stack information (which ultimately leads to the crash location).

Finding the id of a parent div using Jquery

1.

$(this).parent().attr("id");

2.

There must be a large number of ways! One could be to hide an element that contains the answer, e.g.

<div>
    Volume = <input type="text" />
    <button type="button">Check answer</button>
    <span style="display: hidden">3.93e-6&lt;/span>
    <div></div>
</div>

And then have similar jQuery code to the above to grab that:

$("button").click(function () 
{
    var correct = Number($(this).parent().children("span").text());
    validate ($(this).siblings("input").val(),correct);
    $(this).siblings("div").html(feedback);
});

bear in mind that if you put the answer in client code then they can see it :) The best way to do this is to validate it server-side, but for an app with limited scope this may not be a problem.

How to open a web server port on EC2 instance

You need to open TCP port 8787 in the ec2 Security Group. Also need to open the same port on the EC2 instance's firewall.

Visual Studio loading symbols

Visual Studio 2017 Debug symbol "speed-up" options, assuming you haven't gone crazy on option-customization already:

  1. At Tools -> Options -> Debugging -> Symbols
    a. Enable the "Microsoft Symbol Server" option
    b. Click "Empty Symbol Cache"
    c. Set your symbol cache to an easy to find spot, like C:\dbg_symbols or %USERPROFILE%\dbg_symbols
  2. After re-running Debug, let it load all the symbols once, from start-to-end, or as much as reasonably possible.

1A and 2 are the most important steps. 1B and 1C are just helpful changes to help you keep track of your symbols.

After your app has loaded all the symbols at least once and debugging didn't prematurely terminate, those symbols should be quickly loaded the next time debug runs.

I've noticed that if I cancel a debug-run, I have to reload those symbols, as I'm guessing they're "cleaned" up if newly introduced and suddenly cancelled. I understand the core rationale for that kind of flow, but in this case it seems poorly thought out.

How to restart Postgresql

Try this as root (maybe you can use sudo or su):

/etc/init.d/postgresql restart

Without any argument the script also gives you a hint on how to restart a specific version

[Uqbar@Feynman ~] /etc/init.d/postgresql
Usage: /etc/init.d/postgresql {start|stop|restart|reload|force-reload|status} [version ...]

Similarly, in case you have it, you can also use the service tool:

[Uqbar@Feynman ~] service postgresql
Usage: /etc/init.d/postgresql {start|stop|restart|reload|force reload|status} [version ...]

Please, pay attention to the optional [version ...] trailing argument. That's meant to allow you, the user, to act on a specific version, in case you were running multiple ones. So you can restart version X while keeping version Y and Z untouched and running.

Finally, in case you are running systemd, then you can use systemctl like this:

[support@Feynman ~] systemctl status postgresql
? postgresql.service - PostgreSQL database server
   Loaded: loaded (/usr/lib/systemd/system/postgresql.service; enabled; vendor preset: disabled)
   Active: active (running) since Wed 2017-11-14 12:33:35 CET; 7min ago
...

You can replace status with stop, start or restart as well as other actions. Please refer to the documentation for full details. In order to operate on multiple concurrent versions, the syntax is slightly different. For example to stop v12 and reload v13 you can run:

systemctl stop postgresql-12.service
systemctl reload postgresql-13.service

Thanks to @Jojo for pointing me to this very one. Finally Keep in mind that root permissions may be needed for non-informative tasks as in the other cases seen earlier.

What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs?

It is simple: if recv() returns 0 bytes; you will not receive any more data on this connection. Ever. You still might be able to send.

It means that your non-blocking socket have to raise an exception (it might be system-dependent) if no data is available but the connection is still alive (the other end may send).

Removing "NUL" characters

I tried to use the \x00 and it didn't work for me when using C# and Regex. I had success with the following:

//The hexidecimal 0x0 is the null character  
mystring.Contains(Convert.ToChar(0x0).ToString() );  

// This will replace the character
mystring = mystring.Replace(Convert.ToChar(0x0).ToString(), "");  

Visual Studio Code: Auto-refresh file changes

{
    "files.useExperimentalFileWatcher" : true
}

in Code -> Preferences -> Settings

Tested with Visual Studio Code Version 1.26.1 on mac and win

Still Reachable Leak detected by Valgrind

You don't appear to understand what still reachable means.

Anything still reachable is not a leak. You don't need to do anything about it.

HTML Button : Navigate to Other Page - Different Approaches

I make a link. A link is a link. A link navigates to another page. That is what links are for and everybody understands that. So Method 3 is the only correct method in my book.

I wouldn't want my link to look like a button at all, and when I do, I still think functionality is more important than looks.

Buttons are less accessible, not only due to the need of Javascript, but also because tools for the visually impaired may not understand this Javascript enhanced button well.

Method 4 would work as well, but it is more a trick than a real functionality. You abuse a form to post 'nothing' to this other page. It's not clean.

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

My complete code as below is working well:

package ripon.java.mail;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class SendEmail
{
public static void main(String [] args)
{    
    // Sender's email ID needs to be mentioned
     String from = "[email protected]";
     String pass ="test123";
    // Recipient's email ID needs to be mentioned.
   String to = "[email protected]";

   String host = "smtp.gmail.com";

   // Get system properties
   Properties properties = System.getProperties();
   // Setup mail server
   properties.put("mail.smtp.starttls.enable", "true");
   properties.put("mail.smtp.host", host);
   properties.put("mail.smtp.user", from);
   properties.put("mail.smtp.password", pass);
   properties.put("mail.smtp.port", "587");
   properties.put("mail.smtp.auth", "true");

   // Get the default Session object.
   Session session = Session.getDefaultInstance(properties);

   try{
      // Create a default MimeMessage object.
      MimeMessage message = new MimeMessage(session);

      // Set From: header field of the header.
      message.setFrom(new InternetAddress(from));

      // Set To: header field of the header.
      message.addRecipient(Message.RecipientType.TO,
                               new InternetAddress(to));

      // Set Subject: header field
      message.setSubject("This is the Subject Line!");

      // Now set the actual message
      message.setText("This is actual message");

      // Send message
      Transport transport = session.getTransport("smtp");
      transport.connect(host, from, pass);
      transport.sendMessage(message, message.getAllRecipients());
      transport.close();
      System.out.println("Sent message successfully....");
   }catch (MessagingException mex) {
      mex.printStackTrace();
   }
}
}

Jquery validation plugin - TypeError: $(...).validate is not a function

It looks like the JavaScript error your getting is probably being caused by

password: {
    required:true,
    rangelenght:[4.20]
},

As the [4.20] should be [4,20], which i'd guess is throwing off the validation code in additional-methods hence giving the type error's you posted.

Edit: As others have noted in the below comments rangelenght is also misspelled & jquery.validate.js library appears to be missing (assuming its not compiled in to one of your other assets)

JDBC ODBC Driver Connection

Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.

 import java.sql.*;  
 public class UserLogin
 {
     public static void main(String[] args)
     {
        try
        {    
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            // C:\\databaseFileName.accdb" - location of your database 
           String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";

            // specify url, username, pasword - make sure these are valid 
            Connection conn = DriverManager.getConnection(url, "username", "password");

            System.out.println("Connection Succesfull");
         } 
         catch (Exception e) 
         {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());

          }
      }
  }

How do I limit the number of rows returned by an Oracle query after ordering?

(untested) something like this may do the job

WITH
base AS
(
    select *                   -- get the table
    from sometable
    order by name              -- in the desired order
),
twenty AS
(
    select *                   -- get the first 30 rows
    from base
    where rownum < 30
    order by name              -- in the desired order
)
select *                       -- then get rows 21 .. 30
from twenty
where rownum > 20
order by name                  -- in the desired order

There is also the analytic function rank, that you can use to order by.

How to erase the file contents of text file in Python?

You have to overwrite the file. In C++:

#include <fstream>

std::ofstream("test.txt", std::ios::out).close();

Adding an arbitrary line to a matplotlib plot in ipython notebook

You can directly plot the lines you want by feeding the plot command with the corresponding data (boundaries of the segments):

plot([x1, x2], [y1, y2], color='k', linestyle='-', linewidth=2)

(of course you can choose the color, line width, line style, etc.)

From your example:

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")


# draw vertical line from (70,100) to (70, 250)
plt.plot([70, 70], [100, 250], 'k-', lw=2)

# draw diagonal line from (70, 90) to (90, 200)
plt.plot([70, 90], [90, 200], 'k-')

plt.show()

new chart

Rails: How can I set default values in ActiveRecord?

class Item < ActiveRecord::Base
  def status
    self[:status] or ACTIVE
  end

  before_save{ self.status ||= ACTIVE }
end

How to change background Opacity when bootstrap modal is open

Just in case someone is using Bootstrap 4. It seems we can no longer use .modal-backdrop.in, but must now use .modal-backdrop.show. Fade effect preserved.

.modal-backdrop.show {
    opacity: 0.7;
}

How do I style (css) radio buttons and labels?

This will get your buttons and labels next to each other, at least. I believe the second part can't be done in css alone, and will need javascript. I found a page that might help you with that part as well, but I don't have time right now to try it out: http://www.webmasterworld.com/forum83/6942.htm

<style type="text/css">
.input input {
  float: left;
}
.input label {
  margin: 5px;
}
</style>
<div class="input radio">
    <fieldset>
        <legend>What color is the sky?</legend>
        <input type="hidden" name="data[Submit][question]" value="" id="SubmitQuestion" />

        <input type="radio" name="data[Submit][question]" id="SubmitQuestion1" value="1"  />
        <label for="SubmitQuestion1">A strange radient green.</label>

        <input type="radio" name="data[Submit][question]" id="SubmitQuestion2" value="2"  />
        <label for="SubmitQuestion2">A dark gloomy orange</label>
        <input type="radio" name="data[Submit][question]" id="SubmitQuestion3" value="3"  />
        <label for="SubmitQuestion3">A perfect glittering blue</label>
    </fieldset>
</div>

C# "No suitable method found to override." -- but there is one

You cannot override a function with different parameters, only you are allowed to change the functionality of the overridden method.

//Compiler Microsoft (R) .NET Framework 4.5

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

//Overriding & overloading

namespace polymorpism
{
    public class Program
    {
        public static void Main(string[] args)
        {

            drowButn calobj = new drowButn();

            BtnOverride calobjOvrid = new BtnOverride();

            Console.WriteLine(calobj.btn(5.2, 6.6).ToString());

            //btn has compleately overrided inside this calobjOvrid object
            Console.WriteLine(calobjOvrid.btn(5.2, 6.6).ToString());
            //the overloaded function
            Console.WriteLine(calobjOvrid.btn(new double[] { 5.2, 6.6 }).ToString());

            Console.ReadKey();
        }
    }

    public class drowButn
    {

        //same add function overloading to add double type field inputs
        public virtual double btn(double num1, double num2)
        {

            return (num1 + num2);

        }


    }

    public class BtnOverride : drowButn
    {

        //same add function overrided and change its functionality 
        //(this will compleately replace the base class function
        public override double btn(double num1, double num2)
        {
            //do compleatly diffarant function then the base class
            return (num1 * num2);

        }

        //same function overloaded (no override keyword used) 
        // this will not effect the base class function

        public double btn(double[] num)
        {
            double cal = 0;

            foreach (double elmnt in num)
            {

                cal += elmnt;
            }
            return cal;

        }
    }
}

Bitbucket git credentials if signed up with Google

You can attach a "proper" Bitbucket account password to your account. Go to https://id.atlassian.com/manage/change-password (sign in using your Google account) and then enter a new password in both the old and new password boxes. Now you can use your email address and this new password to access your account on the command line.

Note: App passwords are the official way of doing this (per @Christian Tingino's answer), but IMO they don't work very nicely. No way of changing the password, and they are big unwieldly things to type into the command line.

Checking if a website is up via Python

my 2 cents

def getResponseCode(url):
conn = urllib.request.urlopen(url)
return conn.getcode()

if getResponseCode(url) != 200:
    print('Wrong URL')
else:
    print('Good URL')

How to iterate (keys, values) in JavaScript?

Try this:

var value;
for (var key in dictionary) {
    value = dictionary[key];
    // your code here...
}

How to run wget inside Ubuntu Docker image?

If you're running ubuntu container directly without a local Dockerfile you can ssh into the container and enable root control by entering su then apt-get install -y wget

Spring Data and Native Query with pagination

I could successfully integrate Pagination in

spring-data-jpa-2.1.6

as follows.

@Query(
 value = “SELECT * FROM Users”, 
 countQuery = “SELECT count(*) FROM Users”, 
 nativeQuery = true)
Page<User> findAllUsersWithPagination(Pageable pageable);

milliseconds to days

If you don't have another time interval bigger than days:

int days = (int) (milliseconds / (1000*60*60*24));

If you have weeks too:

int days = (int) ((milliseconds / (1000*60*60*24)) % 7);
int weeks = (int) (milliseconds / (1000*60*60*24*7));

It's probably best to avoid using months and years if possible, as they don't have a well-defined fixed length. Strictly speaking neither do days: daylight saving means that days can have a length that is not 24 hours.

What is parsing in terms that a new programmer would understand?

Have them try to write a program that can evaluate arbitrary simple arithmetic expressions. This is a simple problem to understand but as you start getting deeper into it a lot of basic parsing starts to make sense.

Copy data into another table

Insert Selected column with condition

INSERT INTO where_to_insert (col_1,col_2) SELECT col1, col2 FROM from_table WHERE condition;

Copy all data from one table to another with the same column name.

INSERT INTO where_to_insert 
SELECT * FROM from_table WHERE condition;

How do I check form validity with angularjs?

Example

<div ng-controller="ExampleController">
  <form name="myform">
   Name: <input type="text" ng-model="user.name" /><br>
   Email: <input type="email" ng-model="user.email" /><br>
  </form>
</div>

<script>
  angular.module('formExample', [])
    .controller('ExampleController', ['$scope', function($scope) {

     //if form is not valid then return the form.
     if(!$scope.myform.$valid) {
       return;
     }
  }]);
</script>

JavaScript alert not working in Android WebView

webView.setWebChromeClient(new WebChromeClient() {
    @Override
    public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
        return super.onJsAlert(view, url, message, result);
    }
});

Redirect in Spring MVC

Try this, it should work if you have configured your view resolver properly

 return "redirect:/index.html";

How to plot two columns of a pandas data frame using points?

You can specify the style of the plotted line when calling df.plot:

df.plot(x='col_name_1', y='col_name_2', style='o')

The style argument can also be a dict or list, e.g.:

import numpy as np
import pandas as pd

d = {'one' : np.random.rand(10),
     'two' : np.random.rand(10)}

df = pd.DataFrame(d)

df.plot(style=['o','rx'])

All the accepted style formats are listed in the documentation of matplotlib.pyplot.plot.

Output

How can I send emails through SSL SMTP with the .NET Framework?

For gmail these settings worked for me, the ServicePointManager.SecurityProtocol line was necessary. Because I has setup 2 step verification I needed get a App Password from google app password generator.

SmtpClient mailer = new SmtpClient();
mailer.Host = "smtp.gmail.com";
mailer.Port = 587;
mailer.EnableSsl = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

ActiveXObject creation error " Automation server can't create object"

This error is cause by security clutches between the web application and your java. To resolve it, look into your java setting under control panel. Move the security level to a medium.

Is there any native DLL export functions viewer?

If you don't have the source code and API documentation, the machine code is all there is, you need to disassemble the dll library using something like IDA Pro , another option is use the trial version of PE Explorer.

PE Explorer provides a Disassembler. There is only one way to figure out the parameters: run the disassembler and read the disassembly output. Unfortunately, this task of reverse engineering the interface cannot be automated.

PE Explorer comes bundled with descriptions for 39 various libraries, including the core Windows® operating system libraries (eg. KERNEL32, GDI32, USER32, SHELL32, WSOCK32), key graphics libraries (DDRAW, OPENGL32) and more.

alt text
(source: heaventools.com)

Filter spark DataFrame on string contains

In pyspark,SparkSql syntax:

where column_n like 'xyz%'

might not work.

Use:

where column_n RLIKE '^xyz' 

This works perfectly fine.

How to give spacing between buttons using bootstrap

Adding margins to a button makes it wider so that les buttons fit in the grid system. If only a visual effect is important, then give the button a white border with [style="margin:0px; border:solid white;"] This leaves the button width unaffected.

How do I auto-hide placeholder text upon focus using css or jquery?

$("input[placeholder]").focusin(function () {
    $(this).data('place-holder-text', $(this).attr('placeholder')).attr('placeholder', '');
})
.focusout(function () {
    $(this).attr('placeholder', $(this).data('place-holder-text'));
});

Why do we check up to the square root of a prime number to determine if it is prime?

Yes, as it was properly explained above, it's enough to iterate up to Math.floor of a number's square root to check its primality (because sqrt covers all possible cases of division; and Math.floor, because any integer above sqrt will already be beyond its range).

Here is a runnable JavaScript code snippet that represents a simple implementation of this approach – and its "runtime-friendliness" is good enough for handling pretty big numbers (I tried checking both prime and not prime numbers up to 10**12, i.e. 1 trillion, compared results with the online database of prime numbers and encountered no errors or lags even on my cheap phone):

_x000D_
_x000D_
function isPrime(num) {
  if (num % 2 === 0 || num < 3 || !Number.isInteger(num)) {
    return num === 2;
  } else {
    const sqrt = Math.floor(Math.sqrt(num));
    for (let i = 3; i <= sqrt; i += 2) {
      if (num % i === 0) {
        return false;
      }
    }
    return true;
  }
}
_x000D_
<label for="inp">Enter a number and click "Check!":</label><br>
<input type="number" id="inp"></input>
<button onclick="alert(isPrime(+document.getElementById('inp').value) ? 'Prime' : 'Not prime')" type="button">Check!</button>
_x000D_
_x000D_
_x000D_

How to return a value from a Form in C#?

Create some public Properties on your sub-form like so

public string ReturnValue1 {get;set;} 
public string ReturnValue2 {get;set;}

then set this inside your sub-form ok button click handler

private void btnOk_Click(object sender,EventArgs e)
{
    this.ReturnValue1 = "Something";
    this.ReturnValue2 = DateTime.Now.ToString(); //example
    this.DialogResult = DialogResult.OK;
    this.Close();
}

Then in your frmHireQuote form, when you open the sub-form

using (var form = new frmImportContact())
{
    var result = form.ShowDialog();
    if (result == DialogResult.OK)
    {
        string val = form.ReturnValue1;            //values preserved after close
        string dateString = form.ReturnValue2;
        //Do something here with these values

        //for example
        this.txtSomething.Text = val;
    }
}

Additionaly if you wish to cancel out of the sub-form you can just add a button to the form and set its DialogResult to Cancel and you can also set the CancelButton property of the form to said button - this will enable the escape key to cancel out of the form.

How to rebuild docker container in docker-compose.yml?

As @HarlemSquirrel posted, it is the best and I think the correct solution.

But, to answer the OP specific problem, it should be something like the following command, as he doesn't want to recreate ALL services in the docker-compose.yml file, but only the nginx one:

docker-compose up -d --force-recreate --no-deps --build nginx

Options description:

Options:
  -d                  Detached mode: Run containers in the background,
                      print new container names. Incompatible with
                      --abort-on-container-exit.
  --force-recreate    Recreate containers even if their configuration
                      and image haven't changed.
  --build             Build images before starting containers.
  --no-deps           Don't start linked services.

How should I escape strings in JSON?

Try this org.codehaus.jettison.json.JSONObject.quote("your string").

Download it here: http://mvnrepository.com/artifact/org.codehaus.jettison/jettison

Convert pandas dataframe to NumPy array

Just had a similar problem when exporting from dataframe to arcgis table and stumbled on a solution from usgs (https://my.usgs.gov/confluence/display/cdi/pandas.DataFrame+to+ArcGIS+Table). In short your problem has a similar solution:

df

      A    B    C
ID               
1   NaN  0.2  NaN
2   NaN  NaN  0.5
3   NaN  0.2  0.5
4   0.1  0.2  NaN
5   0.1  0.2  0.5
6   0.1  NaN  0.5
7   0.1  NaN  NaN

np_data = np.array(np.rec.fromrecords(df.values))
np_names = df.dtypes.index.tolist()
np_data.dtype.names = tuple([name.encode('UTF8') for name in np_names])

np_data

array([( nan,  0.2,  nan), ( nan,  nan,  0.5), ( nan,  0.2,  0.5),
       ( 0.1,  0.2,  nan), ( 0.1,  0.2,  0.5), ( 0.1,  nan,  0.5),
       ( 0.1,  nan,  nan)], 
      dtype=(numpy.record, [('A', '<f8'), ('B', '<f8'), ('C', '<f8')]))

How to convert string to boolean in typescript Angular 4

Define extension: String+Extension.ts

interface String {
  toBoolean(): boolean
}

String.prototype.toBoolean = function (): boolean {
  switch (this) {
    case 'true':
    case '1':
    case 'on':
    case 'yes':
      return true
    default:
      return false
  }
}

And import in any file where you want to use it '@/path/to/String+Extension'

Converting a generic list to a CSV string

Any solution work only if List a list(of string)

If you have a generic list of your own Objects like list(of car) where car has n properties, you must loop the PropertiesInfo of each car object.

Look at: http://www.csharptocsharp.com/generate-csv-from-generic-list

How to convert String into Hashmap in java

@Test
public void testToStringToMap() {
    Map<String,String> expected = new HashMap<>();
    expected.put("first_name", "naresh");
    expected.put("last_name", "kumar");
    expected.put("gender", "male");
    String mapString = expected.toString();
    Map<String, String> actual = Arrays.stream(mapString.replace("{", "").replace("}", "").split(","))
            .map(arrayData-> arrayData.split("="))
            .collect(Collectors.toMap(d-> ((String)d[0]).trim(), d-> (String)d[1]));

    expected.entrySet().stream().forEach(e->assertTrue(actual.get(e.getKey()).equals(e.getValue())));
}

Console.WriteLine does not show up in Output window

Try to uncheck the CheckBox “Use Managed Compatibility Mode” in

Tools => Options => Debugging => General

It worked for me.

alert() not working in Chrome

window.alert = null;
alert('test'); // fail
delete window.alert; // true
alert('test'); // win

window is an instance of DOMWindow, and by setting something to window.alert, the correct implementation is being "shadowed", i.e. when accessing alert it is first looking for it on the window object. Usually this is not found, and it then goes up the prototype chain to find the native implementation. However, when manually adding the alert property to window it finds it straight away and does not need to go up the prototype chain. Using delete window.alert you can remove the window own property and again expose the prototype implementation of alert. This may help explain:

window.hasOwnProperty('alert'); // false
window.alert = null;
window.hasOwnProperty('alert'); // true
delete window.alert;
window.hasOwnProperty('alert'); // false

Read XML Attribute using XmlDocument

You should look into XPath. Once you start using it, you'll find its a lot more efficient and easier to code than iterating through lists. It also lets you directly get the things you want.

Then the code would be something similar to

string attrVal = doc.SelectSingleNode("/MyConfiguration/@SuperNumber").Value;

Note that XPath 3.0 became a W3C Recommendation on April 8, 2014.

printf format specifiers for uint32_t and size_t

Sounds like you're expecting size_t to be the same as unsigned long (possibly 64 bits) when it's actually an unsigned int (32 bits). Try using %zu in both cases.

I'm not entirely certain though.

java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy

tl;dr

LocalDate.parse( 
    "01-23-2017" , 
    DateTimeFormatter.ofPattern( "MM-dd-uuuu" )
)

Details

I have a java.util.Date in the format yyyy-mm-dd

As other mentioned, the Date class has no format. It has a count of milliseconds since the start of 1970 in UTC. No strings attached.

java.time

The other Answers use troublesome old legacy date-time classes, now supplanted by the java.time classes.

If you have a java.util.Date, convert to a Instant object. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = myUtilDate.toInstant();

Time zone

The other Answers ignore the crucial issue of time zone. Determining a date requires a time zone. For any given moment, the date varies around the globe by zone. A few minutes after midnight in Paris France is a new day, while still “yesterday” in Montréal Québec.

Define the time zone by which you want context for your Instant.

ZoneId z = ZoneId.of( "America/Montreal" );

Apply the ZoneId to get a ZonedDateTime.

ZonedDateTime zdt = instant.atZone( z );

LocalDate

If you only care about the date without a time-of-day, extract a LocalDate.

LocalDate localDate = zdt.toLocalDate();

To generate a string in standard ISO 8601 format, YYYY-MM-DD, simply call toString. The java.time classes use the standard formats by default when generating/parsing strings.

String output = localDate.toString();

2017-01-23

If you want a MM-DD-YYYY format, define a formatting pattern.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu" );
String output = localDate.format( f );

Note that the formatting pattern codes are case-sensitive. The code in the Question incorrectly used mm (minute of hour) rather than MM (month of year).

Use the same DateTimeFormatter object for parsing. The java.time classes are thread-safe, so you can keep this object around and reuse it repeatedly even across threads.

LocalDate localDate = LocalDate.parse( "01-23-2017" , f );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to play YouTube video in my Android application?

You may use iframe as described in https://developers.google.com/youtube/iframe_api_reference

I am not following the google advises exactly but this is the code I am using and it is working fine

public class CWebVideoView {

    private String url;
    private Context context;
    private WebView webview;
    private static final String HTML_TEMPLATE = "webvideo.html";

    public CWebVideoView(Context context, WebView webview) {
        this.webview = webview;
        this.context = context;
        webview.setBackgroundColor(0);
        webview.getSettings().setJavaScriptEnabled(true);
    }

    public void load(String url){
        this.url = url;
        String data = readFromfile(HTML_TEMPLATE, context);
        data = data.replace("%1", url);
        webview.loadData(data, "text/html", "UTF-8");
    }

    public String readFromfile(String fileName, Context context) {
        StringBuilder returnString = new StringBuilder();
        InputStream fIn = null;
        InputStreamReader isr = null;
        BufferedReader input = null;
        try {
            fIn = context.getResources().getAssets().open(fileName, Context.MODE_WORLD_READABLE);
            isr = new InputStreamReader(fIn);
            input = new BufferedReader(isr);
            String line = "";
            while ((line = input.readLine()) != null) {
                returnString.append(line);
            }
        } catch (Exception e) {
            e.getMessage();
        } finally {
            try {
                if (isr != null)
                    isr.close();
                if (fIn != null)
                    fIn.close();
                if (input != null)
                    input.close();
            } catch (Exception e2) {
                e2.getMessage();
            }
        }
        return returnString.toString();
    }

    public void reload() {
        if (url!=null){
            load(url);
        }
    }
}

in /assets I have a file called webvideo.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <style>
            iframe   { border: 0; position:fixed; width:100%; height:100%; bgcolor="#000000"; }
            body     { margin: 0; bgcolor="#000000"; }
        </style>        
    </head>
    <body>
        <iframe src="%1" frameborder="0" allowfullscreen></iframe>
    </body>
</html>

and now I define a webview inside my main layout

<WebView
    android:id="@+id/video"
    android:visibility="gone"
    android:background="#000000"
    android:layout_centerInParent="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

and I use CWebVideoView inside my activity

videoView = (WebView) view.findViewById(R.id.video);
videoView.setVisibility(View.VISIBLE);
cWebVideoView = new CWebVideoView(context, videoView);
cWebVideoView.load(url);

How to add a TextView to LinearLayout in Android

You can add a TextView to your linear layout programmatically like this:

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.mylayout);
TextView txt1 = new TextView(MyClass.this);
linearLayout.setBackgroundColor(Color.TRANSPARENT);
linearLayout.addView(txt1);

Java Embedded Databases Comparison

I realize you mentioned SQL browsing, but everything else in your question makes me want to suggest you also consider DB4O, which is a great, simple object DB.

How to get the excel file name / path in VBA

   strScriptFullname = WScript.ScriptFullName 
   strScriptPath = Left(strScriptFullname, InStrRev(strScriptFullname,"\")) 

What is the difference between gravity and layout_gravity in Android?

Short Answer: use android:gravity or setGravity() to control gravity of all child views of a container; use android:layout_gravity or setLayoutParams() to control gravity of an individual view in a container.

Long story: to control gravity in a linear layout container such as LinearLayout or RadioGroup, there are two approaches:

1) To control the gravity of ALL child views of a LinearLayout container (as you did in your book), use android:gravity (not android:layout_gravity) in layout XML file or setGravity() method in code.

2) To control the gravity of a child view in its container, use android:layout_gravity XML attribute. In code, one needs to get the LinearLayout.LayoutParams of the view and set its gravity. Here is a code example that set a button to bottom in a horizontally oriented container:

import android.widget.LinearLayout.LayoutParams;
import android.view.Gravity;
...

Button button = (Button) findViewById(R.id.MyButtonId);
// need to cast to LinearLayout.LayoutParams to access the gravity field
LayoutParams params = (LayoutParams)button.getLayoutParams(); 
params.gravity = Gravity.BOTTOM;
button.setLayoutParams(params);

For horizontal LinearLayout container, the horizontal gravity of its child view is left-aligned one after another and cannot be changed. Setting android:layout_gravity to center_horizontal has no effect. The default vertical gravity is center (or center_vertical) and can be changed to top or bottom. Actually the default layout_gravity value is -1 but Android put it center vertically.

To change the horizontal positions of child views in a horizontal linear container, one can use layout_weight, margin and padding of the child view.

Similarly, for vertical View Group container, the vertical gravity of its child view is top-aligned one below another and cannot be changed. The default horizontal gravity is center (or center_horizontal) and can be changed to left or right.

Actually, a child view such as a button also has android:gravity XML attribute and the setGravity() method to control its child views -- the text in it. The Button.setGravity(int) is linked to this developer.android.com entry.

JavaScript DOM remove element

Seems I don't have enough rep to post a comment, so another answer will have to do.

When you unlink a node using removeChild() or by setting the innerHTML property on the parent, you also need to make sure that there is nothing else referencing it otherwise it won't actually be destroyed and will lead to a memory leak. There are lots of ways in which you could have taken a reference to the node before calling removeChild() and you have to make sure those references that have not gone out of scope are explicitly removed.

Doug Crockford writes here that event handlers are known a cause of circular references in IE and suggests removing them explicitly as follows before calling removeChild()

function purge(d) {
    var a = d.attributes, i, l, n;
    if (a) {
        for (i = a.length - 1; i >= 0; i -= 1) {
            n = a[i].name;
            if (typeof d[n] === 'function') {
                d[n] = null;
            }
        }
    }
    a = d.childNodes;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            purge(d.childNodes[i]);
        }
    }
}

And even if you take a lot of precautions you can still get memory leaks in IE as described by Jens-Ingo Farley here.

And finally, don't fall into the trap of thinking that Javascript delete is the answer. It seems to be suggested by many, but won't do the job. Here is a great reference on understanding delete by Kangax.

How do you detect/avoid Memory leaks in your (Unmanaged) code?

Working on Motorola cell phones operating system, we hijacked memory allocation library to observe all memory allocations. It helped to find a lot of problems with memory allocations. Since prevention is better then curing, I would recommend to use static analysis tool like Klockwork or PC-Lint

how to make a specific text on TextView BOLD

Here is my complete solution for dynamic String values with case check.

/**
 * Makes a portion of String formatted in BOLD.
 *
 * @param completeString       String from which a portion needs to be extracted and formatted.<br> eg. I am BOLD.
 * @param targetStringToFormat Target String value to format. <br>eg. BOLD
 * @param matchCase Match by target character case or not. If true, BOLD != bold
 * @return A string with a portion formatted in BOLD. <br> I am <b>BOLD</b>.
 */
public static SpannableStringBuilder formatAStringPortionInBold(String completeString, String targetStringToFormat, boolean matchCase) {
    //Null complete string return empty
    if (TextUtils.isEmpty(completeString)) {
        return new SpannableStringBuilder("");
    }

    SpannableStringBuilder str = new SpannableStringBuilder(completeString);
    int start_index = 0;

    //if matchCase is true, match exact string
    if (matchCase) {
        if (TextUtils.isEmpty(targetStringToFormat) || !completeString.contains(targetStringToFormat)) {
            return str;
        }

        start_index = str.toString().indexOf(targetStringToFormat);
    } else {
        //else find in lower cases
        if (TextUtils.isEmpty(targetStringToFormat) || !completeString.toLowerCase().contains(targetStringToFormat.toLowerCase())) {
            return str;
        }

        start_index = str.toString().toLowerCase().indexOf(targetStringToFormat.toLowerCase());
    }

    int end_index = start_index + targetStringToFormat.length();
    str.setSpan(new StyleSpan(BOLD), start_index, end_index, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return str;
}

Eg. completeString = "I am BOLD"

CASE I if *targetStringToFormat* = "bold" and *matchCase* = true

returns "I am BOLD" (since bold != BOLD)

CASE II if *targetStringToFormat* = "bold" and *matchCase* = false

returns "I am BOLD"

To Apply:

myTextView.setText(formatAStringPortionInBold("I am BOLD", "bold", false))

Hope that helps!

IOError: [Errno 13] Permission denied

I have a really stupid use case for why I got this error. Originally I was printing my data > file.txt

Then I changed my mind, and decided to use open("file.txt", "w") instead. But when I called python, I left > file.txt .....

How to Install gcc 5.3 with yum on CentOS 7.2?

You can use the centos-sclo-rh-testing repo to install GCC v7 without having to compile it forever, also enable V7 by default and let you switch between different versions if required.

sudo yum install -y yum-utils centos-release-scl;
sudo yum -y --enablerepo=centos-sclo-rh-testing install devtoolset-7-gcc;
echo "source /opt/rh/devtoolset-7/enable" | sudo tee -a /etc/profile;
source /opt/rh/devtoolset-7/enable;
gcc --version;

how to call scalar function in sql server 2008

For Scalar Function Syntax is

Select dbo.Function_Name(parameter_name)

Select dbo.Department_Employee_Count('HR')

JavaScript loop through json array?

There's a few problems in your code, first your json must look like :

var json = [{
"id" : "1", 
"msg"   : "hi",
"tid" : "2013-05-05 23:35",
"fromWho": "[email protected]"
},
{
"id" : "2", 
"msg"   : "there",
"tid" : "2013-05-05 23:45",
"fromWho": "[email protected]"
}];

Next, you can iterate like this :

for (var key in json) {
if (json.hasOwnProperty(key)) {
  alert(json[key].id);
  alert(json[key].msg);
}
}

And it gives perfect result.

See the fiddle here : http://jsfiddle.net/zrSmp/

From an array of objects, extract value of a property as array

If you want to also support array-like objects, use Array.from (ES2015):

Array.from(arrayLike, x => x.foo);

The advantage it has over Array.prototype.map() method is the input can also be a Set:

let arrayLike = new Set([{foo: 1}, {foo: 2}, {foo: 3}]);

Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute

How you deal with this at the moment depends on what model you are using Linq to SQL or EntityFramework?

In L2S you can add

public partial class NWDataContext
{
    partial void InsertCategory(Category instance)
    {
        if(Instance.Date == null)
            Instance.Data = DateTime.Now;

        ExecuteDynamicInsert(instance);
    }
}

EF is a little more complicated see http://msdn.microsoft.com/en-us/library/cc716714.aspx for more info on EF buisiness logic.

Changing the action of a form with JavaScript/jQuery

Use Java script to change action url dynamically Works for me well

function chgAction( action_name )
{

 {% for data in sidebar_menu_data %}

     if( action_name== "ABC"){ document.forms.action = "/ABC/";
     }
     else if( action_name== "XYZ"){ document.forms.action = "/XYZ/";
     }

}

<form name="forms" method="post" action="<put default url>" onSubmit="return checkForm(this);">{% csrf_token %} 

JavaScript global event mechanism

Does this help you:

<script type="text/javascript">
window.onerror = function() {
    alert("Error caught");
};

xxx();
</script>

I'm not sure how it handles Flash errors though...

Update: it doesn't work in Opera, but I'm hacking Dragonfly right now to see what it gets. Suggestion about hacking Dragonfly came from this question:

Mimic Window. onerror in Opera using javascript

Should I use the Reply-To header when sending emails as a service to others?

Here is worked for me:

Subject: SomeSubject
From:Company B (me)
Reply-to:Company A
To:Company A's customers

npm install won't install devDependencies

I had a similar problem. npm install --only=dev didn't work, and neither did npm rebuild. Ultimately, I had to delete node_modules and package-lock.json and run npm install again. That fixed it for me.

How to get JSON objects value if its name contains dots?

in javascript, object properties can be accessed with . operator or with associative array indexing using []. ie. object.property is equivalent to object["property"]

this should do the trick

var smth = mydata.list[0]["points.bean.pointsBase"][0].time;

Make a number a percentage

@xtrem's answer is good, but I think the toFixed and the makePercentage are common use. Define two functions, and we can use that at everywhere.

const R = require('ramda')
const RA = require('ramda-adjunct')

const fix = R.invoker(1, 'toFixed')(2)

const makePercentage = R.when(
  RA.isNotNil,
  R.compose(R.flip(R.concat)('%'), fix, R.multiply(100)),
)

let a = 0.9988
let b = null

makePercentage(b) // -> null
makePercentage(a) // -> ?????99.88%?????