Programs & Examples On #Boto

boto is an open-source Python Interface to Amazon Web Services

How to upload a file to directory in S3 bucket using boto

I have something that seems to me has a bit more order:

import boto3
from pprint import pprint
from botocore.exceptions import NoCredentialsError


class S3(object):
    BUCKET = "test"
    connection = None

    def __init__(self):
        try:
            vars = get_s3_credentials("aws")
            self.connection = boto3.resource('s3', 'aws_access_key_id',
                                             'aws_secret_access_key')
        except(Exception) as error:
            print(error)
            self.connection = None


    def upload_file(self, file_to_upload_path, file_name):
        if file_to_upload is None or file_name is None: return False
        try:
            pprint(file_to_upload)
            file_name = "your-folder-inside-s3/{0}".format(file_name)
            self.connection.Bucket(self.BUCKET).upload_file(file_to_upload_path, 
                                                                      file_name)
            print("Upload Successful")
            return True

        except FileNotFoundError:
            print("The file was not found")
            return False

        except NoCredentialsError:
            print("Credentials not available")
            return False


There're three important variables here, the BUCKET const, the file_to_upload and the file_name

BUCKET: is the name of your S3 bucket

file_to_upload_path: must be the path from file you want to upload

file_name: is the resulting file and path in your bucket (this is where you add folders or what ever)

There's many ways but you can reuse this code in another script like this

import S3

def some_function():
    S3.S3().upload_file(path_to_file, final_file_name)

How do I install boto?

  1. If necessary, install pip:

    sudo apt-get install python-pip

  2. Then install boto:

    pip install -U boto

Open S3 object as a string with Boto3

This isn't in the boto3 documentation. This worked for me:

object.get()["Body"].read()

object being an s3 object: http://boto3.readthedocs.org/en/latest/reference/services/s3.html#object

Boto3 Error: botocore.exceptions.NoCredentialsError: Unable to locate credentials

I also had the same issue,it can be solved by creating a config and credential file in the home directory. Below show the steps I did to solve this issue.

Create a config file :

touch ~/.aws/config

And in that file I entered the region

[default]
region = us-west-2

Then create the credential file:

touch ~/.aws/credentials

Then enter your credentials

[Profile1]
aws_access_key_id = XXXXXXXXXXXXXXXXXXXX 
aws_secret_access_key = YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY

After set all these, then my python file to connect bucket. Run this file will list all the contents.

import boto3
import os

os.environ['AWS_PROFILE'] = "Profile1"
os.environ['AWS_DEFAULT_REGION'] = "us-west-2"

s3 = boto3.client('s3', region_name='us-west-2')
print("[INFO:] Connecting to cloud")

# Retrieves all regions/endpoints that work with S3

response = s3.list_buckets()
print('Regions:', response)

You can also refer below links:

How to handle errors with boto3?

You need to do something when it fails to handle the issue. Right now you are returning the actual exception. For example, if its not a problem that the user exists already and you want to use it as a get_or_create function maybe you handle the issue by returning the existing user object.

try:
    user = iam_conn.create_user(UserName=username)
    return user
except botocore.exceptions.ClientError as e:

    #this exception could actually be other things other than exists, so you want to evaluate it further in your real code.
    if e.message.startswith(
        'enough of the exception message to identify it as the one you want')

        print('that user already exists.')
        user = iam_conn.get_user(UserName=username)
        return user

    elif e.message.some_other_condition:

         #something else
    else:
         #unhandled ClientError
         raise(e)
except SomeOtherExceptionTypeYouCareAbout as e:
    #handle it

# any unhandled exception will raise here at this point.
# if you want a general handler

except Exception as e:
    #handle it.

That said, maybe it is a problem for your app, in which case you want to want to put the exception handler around the code that called your create user function and let the calling function determine how to deal with it, for example, by asking the user to input another username, or whatever makes sense for your application.

How to save S3 object to a file using boto3

For those of you who would like to simulate the set_contents_from_string like boto2 methods, you can try

import boto3
from cStringIO import StringIO

s3c = boto3.client('s3')
contents = 'My string to save to S3 object'
target_bucket = 'hello-world.by.vor'
target_file = 'data/hello.txt'
fake_handle = StringIO(contents)

# notice if you do fake_handle.read() it reads like a file handle
s3c.put_object(Bucket=target_bucket, Key=target_file, Body=fake_handle.read())

For Python3:

In python3 both StringIO and cStringIO are gone. Use the StringIO import like:

from io import StringIO

To support both version:

try:
   from StringIO import StringIO
except ImportError:
   from io import StringIO

How to write a file or data to an S3 object using boto3

You may use the below code to write, for example an image to S3 in 2019. To be able to connect to S3 you will have to install AWS CLI using command pip install awscli, then enter few credentials using command aws configure:

import urllib3
import uuid
from pathlib import Path
from io import BytesIO
from errors import custom_exceptions as cex

BUCKET_NAME = "xxx.yyy.zzz"
POSTERS_BASE_PATH = "assets/wallcontent"
CLOUDFRONT_BASE_URL = "https://xxx.cloudfront.net/"


class S3(object):
    def __init__(self):
        self.client = boto3.client('s3')
        self.bucket_name = BUCKET_NAME
        self.posters_base_path = POSTERS_BASE_PATH

    def __download_image(self, url):
        manager = urllib3.PoolManager()
        try:
            res = manager.request('GET', url)
        except Exception:
            print("Could not download the image from URL: ", url)
            raise cex.ImageDownloadFailed
        return BytesIO(res.data)  # any file-like object that implements read()

    def upload_image(self, url):
        try:
            image_file = self.__download_image(url)
        except cex.ImageDownloadFailed:
            raise cex.ImageUploadFailed

        extension = Path(url).suffix
        id = uuid.uuid1().hex + extension
        final_path = self.posters_base_path + "/" + id
        try:
            self.client.upload_fileobj(image_file,
                                       self.bucket_name,
                                       final_path
                                       )
        except Exception:
            print("Image Upload Error for URL: ", url)
            raise cex.ImageUploadFailed

        return CLOUDFRONT_BASE_URL + id

Amazon S3 boto - how to create a folder?

S3 doesn't have a folder structure, But there is something called as keys.

We can create /2013/11/xyz.xls and will be shown as folder's in the console. But the storage part of S3 will take that as the file name.

Even when retrieving we observe that we can see files in particular folder (or keys) by using the ListObjects method and using the Prefix parameter.

Listing contents of a bucket with boto3

With little modification to @Hephaeastus 's code in one of the above comments, wrote the below method to list down folders and objects (files) in a given path. Works similar to s3 ls command.

from boto3 import session

def s3_ls(profile=None, bucket_name=None, folder_path=None):
    folders=[]
    files=[]
    result=dict()
    bucket_name = bucket_name
    prefix= folder_path
    session = boto3.Session(profile_name=profile)
    s3_conn   = session.client('s3')
    s3_result =  s3_conn.list_objects_v2(Bucket=bucket_name, Delimiter = "/", Prefix=prefix)
    if 'Contents' not in s3_result and 'CommonPrefixes' not in s3_result:
        return []

    if s3_result.get('CommonPrefixes'):
        for folder in s3_result['CommonPrefixes']:
            folders.append(folder.get('Prefix'))

    if s3_result.get('Contents'):
        for key in s3_result['Contents']:
            files.append(key['Key'])

    while s3_result['IsTruncated']:
        continuation_key = s3_result['NextContinuationToken']
        s3_result = s3_conn.list_objects_v2(Bucket=bucket_name, Delimiter="/", ContinuationToken=continuation_key, Prefix=prefix)
        if s3_result.get('CommonPrefixes'):
            for folder in s3_result['CommonPrefixes']:
                folders.append(folder.get('Prefix'))
        if s3_result.get('Contents'):
            for key in s3_result['Contents']:
                files.append(key['Key'])

    if folders:
        result['folders']=sorted(folders)
    if files:
        result['files']=sorted(files)
    return result

This lists down all objects / folders in a given path. Folder_path can be left as None by default and method will list the immediate contents of the root of the bucket.

How do I install package.json dependencies in the current directory using npm

In my case I need to do

sudo npm install  

my project is inside /var/www so I also need to set proper permissions.

How do I code my submit button go to an email address

There are several ways to do an email from HTML. Typically you see people doing a mailto like so:

<a href="mailto:[email protected]">Click to email</a>

But if you are doing it from a button you may want to look into a javascript solution.

How to Set RadioButtonFor() in ASp.net MVC 2 as Checked by default

           @Html.RadioButton("Insured.GenderType", 1, (Model.Insured.GenderType == 1 ))
           @Web.Mvc.Claims.Resources.PartyResource.MaleLabel
           @Html.RadioButton("Insured.GenderType", 2, Model.Insured.GenderType == 2)
           @Web.Mvc.Claims.Resources.PartyResource.FemaleLabel

How to get last month/year in java?

The simplest & least error prone approach is... Use Calendar's roll() method. Like this:

    c.roll(Calendar.MONTH, false);

the roll method takes a boolean, which basically means roll the month up(true) or down(false)?

Android Crop Center of Bitmap

Probably the easiest solution so far:

public static Bitmap cropCenter(Bitmap bmp) {
    int dimension = Math.min(bmp.getWidth(), bmp.getHeight());
    return ThumbnailUtils.extractThumbnail(bmp, dimension, dimension);
}

imports:

import android.media.ThumbnailUtils;
import java.lang.Math;
import android.graphics.Bitmap;

tqdm in Jupyter Notebook prints new progress bars repeatedly

Most of the answers are outdated now. Better if you import tqdm correctly.

from tqdm import tqdm_notebook as tqdm

enter image description here

How to convert date to string and to date again?

tl;dr

How to convert date to string and to date again?

LocalDate.now().toString()

2017-01-23

…and…

LocalDate.parse( "2017-01-23" )

java.time

The Question uses troublesome old date-time classes bundled with the earliest versions of Java. Those classes are now legacy, supplanted by the java.time classes built into Java 8, Java 9, and later.

Determining today’s date requires a time zone. For any given moment the date varies around the globe by zone.

If not supplied by you, your JVM’s current default time zone is applied. That default can change at any moment during runtime, and so is unreliable. I suggest you always specify your desired/expected time zone.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate ld = LocalDate.now( z ) ;

ISO 8601

Your desired format of YYYY-MM-DD happens to comply with the ISO 8601 standard.

That standard happens to be used by default by the java.time classes when parsing/generating strings. So you can simply call LocalDate::parse and LocalDate::toString without specifying a formatting pattern.

String s = ld.toString() ;

To parse:

LocalDate ld = LocalDate.parse( s ) ;

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 do I change the default schema in sql developer?

Just create a new connection (hit the green plus sign) and enter the schema name and password of the new default schema your DBA suggested. You can switch between your old schema and the new schema with the pull down menu at the top right end of your window.

TypeError: a bytes-like object is required, not 'str'

This code is probably good for Python 2. But in Python 3, this will cause an issue, something related to bit encoding. I was trying to make a simple TCP server and encountered the same problem. Encoding worked for me. Try this with sendto command.

clientSocket.sendto(message.encode(),(serverName, serverPort))

Similarly you would use .decode() to receive the data on the UDP server side, if you want to print it exactly as it was sent.

In plain English, what does "git reset" do?

Remember that in git you have:

  • the HEAD pointer, which tells you what commit you're working on
  • the working tree, which represents the state of the files on your system
  • the staging area (also called the index), which "stages" changes so that they can later be committed together

Please include detailed explanations about:

--hard, --soft and --merge;

In increasing order of dangerous-ness:

  • --soft moves HEAD but doesn't touch the staging area or the working tree.
  • --mixed moves HEAD and updates the staging area, but not the working tree.
  • --merge moves HEAD, resets the staging area, and tries to move all the changes in your working tree into the new working tree.
  • --hard moves HEAD and adjusts your staging area and working tree to the new HEAD, throwing away everything.

concrete use cases and workflows;

  • Use --soft when you want to move to another commit and patch things up without "losing your place". It's pretty rare that you need this.

--

# git reset --soft example
touch foo                            // Add a file, make some changes.
git add foo                          // 
git commit -m "bad commit message"   // Commit... D'oh, that was a mistake!
git reset --soft HEAD^               // Go back one commit and fix things.
git commit -m "good commit"          // There, now it's right.

--

  • Use --mixed (which is the default) when you want to see what things look like at another commit, but you don't want to lose any changes you already have.

  • Use --merge when you want to move to a new spot but incorporate the changes you already have into that the working tree.

  • Use --hard to wipe everything out and start a fresh slate at the new commit.

How to Create a circular progressbar in Android which rotates on it?

Change

android:useLevel="false"

to

android:useLevel="true"

for second sahpe with id="@android:id/progress

hope it works

.NET data structures: ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary -- Speed, memory, and when to use each?

Off the top of my head:

  • Array* - represents an old-school memory array - kind of like a alias for a normal type[] array. Can enumerate. Can't grow automatically. I would assume very fast insert and retrival speed.

  • ArrayList - automatically growing array. Adds more overhead. Can enum., probably slower than a normal array but still pretty fast. These are used a lot in .NET

  • List - one of my favs - can be used with generics, so you can have a strongly typed array, e.g. List<string>. Other than that, acts very much like ArrayList

  • Hashtable - plain old hashtable. O(1) to O(n) worst case. Can enumerate the value and keys properties, and do key/val pairs

  • Dictionary - same as above only strongly typed via generics, such as Dictionary<string, string>

  • SortedList - a sorted generic list. Slowed on insertion since it has to figure out where to put things. Can enum., probably the same on retrieval since it doesn't have to resort, but deletion will be slower than a plain old list.

I tend to use List and Dictionary all the time - once you start using them strongly typed with generics, its really hard to go back to the standard non-generic ones.

There are lots of other data structures too - there's KeyValuePair which you can use to do some interesting things, there's a SortedDictionary which can be useful as well.

How can I decrease the size of Ratingbar?

The below snippet worked for me to resize the ratingBar

<RatingBar
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/ratingBar"
    style="?android:attr/ratingBarStyleIndicator"
    android:scaleX=".5"
    android:rating="3.5"
    android:scaleY=".5"
    android:transformPivotX="0dp"
    android:transformPivotY="0dp"
    android:max="5"/>

enter image description here

Dynamically load a function from a DLL

In addition to the already posted answer, I thought I should share a handy trick I use to load all the DLL functions into the program through function pointers, without writing a separate GetProcAddress call for each and every function. I also like to call the functions directly as attempted in the OP.

Start by defining a generic function pointer type:

typedef int (__stdcall* func_ptr_t)();

What types that are used aren't really important. Now create an array of that type, which corresponds to the amount of functions you have in the DLL:

func_ptr_t func_ptr [DLL_FUNCTIONS_N];

In this array we can store the actual function pointers that point into the DLL memory space.

Next problem is that GetProcAddress expects the function names as strings. So create a similar array consisting of the function names in the DLL:

const char* DLL_FUNCTION_NAMES [DLL_FUNCTIONS_N] = 
{
  "dll_add",
  "dll_subtract",
  "dll_do_stuff",
  ...
};

Now we can easily call GetProcAddress() in a loop and store each function inside that array:

for(int i=0; i<DLL_FUNCTIONS_N; i++)
{
  func_ptr[i] = GetProcAddress(hinst_mydll, DLL_FUNCTION_NAMES[i]);

  if(func_ptr[i] == NULL)
  {
    // error handling, most likely you have to terminate the program here
  }
}

If the loop was successful, the only problem we have now is calling the functions. The function pointer typedef from earlier isn't helpful, because each function will have its own signature. This can be solved by creating a struct with all the function types:

typedef struct
{
  int  (__stdcall* dll_add_ptr)(int, int);
  int  (__stdcall* dll_subtract_ptr)(int, int);
  void (__stdcall* dll_do_stuff_ptr)(something);
  ...
} functions_struct;

And finally, to connect these to the array from before, create a union:

typedef union
{
  functions_struct  by_type;
  func_ptr_t        func_ptr [DLL_FUNCTIONS_N];
} functions_union;

Now you can load all the functions from the DLL with the convenient loop, but call them through the by_type union member.

But of course, it is a bit burdensome to type out something like

functions.by_type.dll_add_ptr(1, 1); whenever you want to call a function.

As it turns out, this is the reason why I added the "ptr" postfix to the names: I wanted to keep them different from the actual function names. We can now smooth out the icky struct syntax and get the desired names, by using some macros:

#define dll_add (functions.by_type.dll_add_ptr)
#define dll_subtract (functions.by_type.dll_subtract_ptr)
#define dll_do_stuff (functions.by_type.dll_do_stuff_ptr)

And voilà, you can now use the function names, with the correct type and parameters, as if they were statically linked to your project:

int result = dll_add(1, 1);

Disclaimer: Strictly speaking, conversions between different function pointers are not defined by the C standard and not safe. So formally, what I'm doing here is undefined behavior. However, in the Windows world, function pointers are always of the same size no matter their type and the conversions between them are predictable on any version of Windows I've used.

Also, there might in theory be padding inserted in the union/struct, which would cause everything to fail. However, pointers happen to be of the same size as the alignment requirement in Windows. A static_assert to ensure that the struct/union has no padding might be in order still.

How do I add a new column to a Spark DataFrame (using PySpark)?

To add new column with some custom value or dynamic value calculation which will be populated based on the existing columns.

e.g.

|ColumnA | ColumnB |
|--------|---------|
| 10     | 15      |
| 10     | 20      |
| 10     | 30      |

and new ColumnC as ColumnA+ColumnB

|ColumnA | ColumnB | ColumnC|
|--------|---------|--------|
| 10     | 15      | 25     |
| 10     | 20      | 30     |
| 10     | 30      | 40     |

using

#to add new column
def customColumnVal(row):
rd=row.asDict()
rd["ColumnC"]=row["ColumnA"] + row["ColumnB"]

new_row=Row(**rd)
return new_row
----------------------------
#convert DF to RDD
df_rdd= input_dataframe.rdd

#apply new fucntion to rdd
output_dataframe=df_rdd.map(customColumnVal).toDF()

input_dataframe is the dataframe which will get modified and customColumnVal function is having code to add new column.

CSS3 selector :first-of-type with class name?

This it not possible to use the CSS3 selector :first-of-type to select the first element with a given class name.

However, if the targeted element has a previous element sibling, you can combine the negation CSS pseudo-class and the adjacent sibling selectors to match an element that doesn't immediately have a previous element with the same class name :

:not(.myclass1) + .myclass1

Full working code example:

_x000D_
_x000D_
p:first-of-type {color:blue}_x000D_
p:not(.myclass1) + .myclass1 { color: red }_x000D_
p:not(.myclass2) + .myclass2 { color: green }
_x000D_
<div>_x000D_
  <div>This text should appear as normal</div>_x000D_
  <p>This text should be blue.</p>_x000D_
  <p class="myclass1">This text should appear red.</p>_x000D_
  <p class="myclass2">This text should appear green.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to Retrieve value from JTextField in Java Swing?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Swingtest extends JFrame implements ActionListener
{
    JTextField txtdata;
    JButton calbtn = new JButton("Calculate");

    public Swingtest()
    {
        JPanel myPanel = new JPanel();
        add(myPanel);
        myPanel.setLayout(new GridLayout(3, 2));
        myPanel.add(calbtn);
        calbtn.addActionListener(this);
        txtdata = new JTextField();
        myPanel.add(txtdata);
    }

    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource() == calbtn) {
            String data = txtdata.getText(); //perform your operation
            System.out.println(data);
        }
    }

    public static void main(String args[])
    {
        Swingtest g = new Swingtest();
        g.setLocation(10, 10);
        g.setSize(300, 300);
        g.setVisible(true);
    }
}

now its working

How to detect orientation change?

Swift 3 | UIDeviceOrientationDidChange Notification Observed Too Often

The following code prints "deviceDidRotate" every time your device changes orientation in 3D space - regardless of a change from portrait to landscape orientation. For example, if you hold your phone in portrait orientation and tilt it forward and backward - deviceDidRotate() is called repeatedly.

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(
        self, 
        selector:  #selector(deviceDidRotate), 
        name: .UIDeviceOrientationDidChange, 
        object: nil
    )
}

func deviceDidRotate() {
    print("deviceDidRotate")
}

To work around this you could hold the previous device orientation and check for a change in deviceDidRotate().

var previousDeviceOrientation: UIDeviceOrientation = UIDevice.current.orientation

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(
        self, 
        selector:  #selector(deviceDidRotate), 
        name: .UIDeviceOrientationDidChange, 
        object: nil
    )
}

func deviceDidRotate() {
    if UIDevice.current.orientation == previousDeviceOrientation { return }
    previousDeviceOrientation = UIDevice.current.orientation
    print("deviceDidRotate")
}

Or you can use a different notification that only gets called when the device changes from landscape to portrait. In this case you'd want to use the UIApplicationDidChangeStatusBarOrientation notification.

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(
        self, 
        selector:  #selector(deviceDidRotate), 
        name: .UIApplicationDidChangeStatusBarOrientation, 
        object: nil
    )
}

func deviceDidRotate() {
    print("deviceDidRotate")
}

Unresponsive KeyListener for JFrame

You could have custom JComponents set their parent JFrame focusable.

Just add a constructor and pass in the JFrame. Then make a call to setFocusable() in paintComponent.

This way the JFrame will always receive KeyEvents regardless of whether other components are pressed.

Setting max width for body using Bootstrap

Edit

A better way to do this is:

  1. Create your own less file as a main less file ( like bootstrap.less ).

  2. Import all bootstrap less files you need. (in this case, you just need to Import all responsive less files but responsive-1200px-min.less)

  3. If you need to modify anything in original bootstrap less file, you just need to write your own less to overwrite bootstrap's less code. (Just remember to put your less code/file after @import { /* bootstrap's less file */ };).

Original

I have the same problem. This is how I fixed it.

Find the media query:

@media (max-width:1200px) ...

Remove it. (I mean the whole thing , not just @media (max-width:1200px))

Since the default width of Bootstrap is 940px, you don't need to do anything.

If you want to have your own max-width, just modify the css rule in the media query that matches your desired width.

QComboBox - set selected item based on the item's data

You lookup the value of the data with findData() and then use setCurrentIndex()

QComboBox* combo = new QComboBox;
combo->addItem("100",100.0);    // 2nd parameter can be any Qt type
combo->addItem .....

float value=100.0;
int index = combo->findData(value);
if ( index != -1 ) { // -1 for not found
   combo->setCurrentIndex(index);
}

How can I mock requests and the response?

Here is a solution with requests Response class. It is cleaner IMHO.

from unittest.mock import patch
from requests.models import Response

def mocked_request_get(*args, **kwargs):
    response_content = None
    request_url = kwargs.get('url', None)
    if request_url == 'aurl':
        response_content = json.dumps('a response')
    elif request_url == 'burl':
        response_content = json.dumps('b response')
    elif request_url == 'curl':
        response_content = json.dumps('c response')
    response = Response()
    response.status_code = 200
    response._content = str.encode(response_content)
    return response

@mock.patch('requests.get', side_effect=mocked_requests_get)
def test_fetch(self, mock_get):
     response = call_your_view()
     assert ...

Make an image follow mouse pointer

Ok, here's a simple box that follows the cursor

Doing the rest is a simple case of remembering the last cursor position and applying a formula to get the box to move other than exactly where the cursor is. A timeout would also be handy if the box has a limited acceleration and must catch up to the cursor after it stops moving. Replacing the box with an image is simple CSS (which can replace most of the setup code for the box). I think the actual thinking code in the example is about 8 lines.

Select the right image (use a sprite) to orientate the rocket.

Yeah, annoying as hell. :-)

_x000D_
_x000D_
function getMouseCoords(e) {
  var e = e || window.event;
  document.getElementById('container').innerHTML = e.clientX + ', ' +
    e.clientY + '<br>' + e.screenX + ', ' + e.screenY;
}


var followCursor = (function() {
  var s = document.createElement('div');
  s.style.position = 'absolute';
  s.style.margin = '0';
  s.style.padding = '5px';
  s.style.border = '1px solid red';
  s.textContent = ""

  return {
    init: function() {
      document.body.appendChild(s);
    },

    run: function(e) {
      var e = e || window.event;
      s.style.left = (e.clientX - 5) + 'px';
      s.style.top = (e.clientY - 5) + 'px';
      getMouseCoords(e);
    }
  };
}());

window.onload = function() {
  followCursor.init();
  document.body.onmousemove = followCursor.run;
}
_x000D_
#container {
  width: 1000px;
  height: 1000px;
  border: 1px solid blue;
}
_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

Add / Change parameter of URL and redirect to the new URL

Some simple ideas to get you going:

In PHP you can do it like this:

if (!array_key_exists(explode('=', explode('&', $_GET))) {
  /* add the view-all bit here */
}

In javascript:

if(!location.search.match(/view\-all=/)) {
  location.href = location.href + '&view-all=Yes';
}

How to recover deleted rows from SQL server table?

It is possible using Apex Recovery Tool,i have successfully recovered my table rows which i accidentally deleted

if you download the trial version it will recover only 10th row

check here http://www.apexsql.com/sql_tools_log.aspx

Download large file in python with requests

Not exactly what OP was asking, but... it's ridiculously easy to do that with urllib:

from urllib.request import urlretrieve
url = 'http://mirror.pnl.gov/releases/16.04.2/ubuntu-16.04.2-desktop-amd64.iso'
dst = 'ubuntu-16.04.2-desktop-amd64.iso'
urlretrieve(url, dst)

Or this way, if you want to save it to a temporary file:

from urllib.request import urlopen
from shutil import copyfileobj
from tempfile import NamedTemporaryFile
url = 'http://mirror.pnl.gov/releases/16.04.2/ubuntu-16.04.2-desktop-amd64.iso'
with urlopen(url) as fsrc, NamedTemporaryFile(delete=False) as fdst:
    copyfileobj(fsrc, fdst)

I watched the process:

watch 'ps -p 18647 -o pid,ppid,pmem,rsz,vsz,comm,args; ls -al *.iso'

And I saw the file growing, but memory usage stayed at 17 MB. Am I missing something?

Search in all files in a project in Sublime Text 3

You can put <project> in "Where:" box to search from the current Sublime project from the Find in Files menu.

This is more useful than searching from the root folder for when your project is including or excluding particular folders or file extensions.

Powershell script to see currently logged in users (domain and machine) + status (active, idle, away)

In search of this same solution, I found what I needed under a different question in stackoverflow: Powershell-log-off-remote-session. The below one line will return a list of logged on users.

query user /server:$SERVER

Given URL is not allowed by the Application configuration Facebook application error

So... facebook distinguishes pretty harshly between http and https in your app. This is just another small thing to check if you run into trouble.

Plotting multiple curves same graph and same scale

points or lines comes handy if

  • y2 is generated later, or
  • the new data does not have the same x but still should go into the same coordinate system.

As your ys share the same x, you can also use matplot:

matplot (x, cbind (y1, y2), pch = 19)

matplot (x, cbind (y1, y2), pch = 19)

(without the pch matplopt will plot the column numbers of the y matrix instead of dots).

What is the best way to remove accents (normalize) in a Python unicode string?

perfplot

import unicodedata
from random import choice

import perfplot
import regex
import text_unidecode


def remove_accent_chars_regex(x: str):
    return regex.sub(r'\p{Mn}', '', unicodedata.normalize('NFKD', x))


def remove_accent_chars_join(x: str):
    # answer by MiniQuark
    # https://stackoverflow.com/a/517974/7966259
    return u"".join([c for c in unicodedata.normalize('NFKD', x) if not unicodedata.combining(c)])


perfplot.show(
    setup=lambda n: ''.join([choice('Málaga François Phút Hon ??') for i in range(n)]),
    kernels=[
        remove_accent_chars_regex,
        remove_accent_chars_join,
        text_unidecode.unidecode,
    ],
    labels=['regex', 'join', 'unidecode'],
    n_range=[2 ** k for k in range(22)],
    equality_check=None, relative_to=0, xlabel='str len'
)

Remove blank attributes from an Object in Javascript

With Lodash:

_.omitBy({a: 1, b: null}, (v) => !v)

Why is the use of alloca() not considered good practice?

All of the other answers are correct. However, if the thing you want to alloc using alloca() is reasonably small, I think that it's a good technique that's faster and more convenient than using malloc() or otherwise.

In other words, alloca( 0x00ffffff ) is dangerous and likely to cause overflow, exactly as much as char hugeArray[ 0x00ffffff ]; is. Be cautious and reasonable and you'll be fine.

Installing a local module using npm?

Missing the main property?

As previous people have answered npm --save ../location-of-your-packages-root-directory. The ../location-of-your-packages-root-directory however must have two things in order for it to work.

1) package.json in that directory pointed towards

2) main property in the package.json must be set and working i.g. "main": "src/index.js", if the entry file for ../location-of-your-packages-root-directory is ../location-of-your-packages-root-directory/src/index.js

Please run `npm cache clean`

This error can be due to many many things.

The key here seems the hint about error reading. I see you are working on a flash drive or something similar? Try to run the install on a local folder owned by your current user.

You could also try with sudo, that might solve a permission problem if that's the case.

Another reason why it cannot read could be because it has not downloaded correctly, or saved correctly. A little problem in your network could have caused that, and the cache clean would remove the files and force a refetch but that does not solve your problem. That means it would be more on the save part, maybe it didn't save because of permissions, maybe it didn't not save correctly because it was lacking disk space...

How to select the nth row in a SQL database table?

Oracle:

select * from (select foo from bar order by foo) where ROWNUM = x

Convert HH:MM:SS string to seconds only in javascript

Convert hh:mm:ss string to seconds in one line. Also allowed h:m:s format and mm:ss, m:s etc

'08:45:20'.split(':').reverse().reduce((prev, curr, i) => prev + curr*Math.pow(60, i), 0)

Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property

In my case I have imported the RouterModule in App module but not imported in my feature module. After import the router module in my EventModule the error goes away.

    import {NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import {EventListComponent} from './EventList.Component';
    import {EventThumbnailComponent} from './EventThumbnail.Component';
    import { EventService } from './shared/Event.Service'
    import {ToastrService} from '../shared/toastr.service';
    import {EventDetailsComponent} from './event-details/event.details.component';
    import { RouterModule } from "@angular/router";
    @NgModule({
      imports:[BrowserModule,RouterModule],
      declarations:[EventThumbnailComponent,EventListComponent,EventDetailsComponent],
      exports: [EventThumbnailComponent,EventListComponent,EventDetailsComponent],
       providers: [EventService,ToastrService]
    })
    export class EventModule {
        
     }

Tab Escape Character?

Easy one! "\t"

Edit: In fact, here's something official: Escape Sequences

Git commit -a "untracked files"?

git commit -am "msg" is not same as git add file and git commit -m "msg"

If you have some files which were never added to git tracking you still need to do git add file

The “git commit -a” command is a shortcut to a two-step process. After you modify a file that is already known by the repo, you still have to tell the repo, “Hey! I want to add this to the staged files and eventually commit it to you.” That is done by issuing the “git add” command. “git commit -a” is staging the file and committing it in one step.

Source: "git commit -a" and "git add"

python-pandas and databases like mysql

The same syntax works for Ms SQL server using podbc also.

import pyodbc
import pandas.io.sql as psql

cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=servername;DATABASE=mydb;UID=username;PWD=password') 
cursor = cnxn.cursor()
sql = ("""select * from mytable""")

df = psql.frame_query(sql, cnxn)
cnxn.close()

Angular2 RC6: '<component> is not a known element'

If you have used the Webclipse automatically generated component definition you may find that the selector name has 'app-' prepended to it. Apparently this is a new convention when declaring sub-components of a main app component. Check how your selector has been defined in your component if you have used 'new' - 'component' to create it in Angular IDE. So instead of putting

<header-area></header-area>

you may need

<app-header-area></app-header-area>

Windows command to convert Unix line endings?

For convert UNIX(LF) to Windows(CR-LF) use next command

type file.txt > new_file.txt

Java client certificates over HTTPS/SSL

While not recommended, you can also disable SSL cert validation alltogether:

import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

public class SSLTool {

  public static void disableCertificateValidation() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { 
      new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() { 
          return new X509Certificate[0]; 
        }
        public void checkClientTrusted(X509Certificate[] certs, String authType) {}
        public void checkServerTrusted(X509Certificate[] certs, String authType) {}
    }};

    // Ignore differences between given hostname and certificate hostname
    HostnameVerifier hv = new HostnameVerifier() {
      public boolean verify(String hostname, SSLSession session) { return true; }
    };

    // Install the all-trusting trust manager
    try {
      SSLContext sc = SSLContext.getInstance("SSL");
      sc.init(null, trustAllCerts, new SecureRandom());
      HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
      HttpsURLConnection.setDefaultHostnameVerifier(hv);
    } catch (Exception e) {}
  }
}

from jquery $.ajax to angular $http

you can use $.param to assign data :

 $http({
  url: "http://example.appspot.com/rest/app",
  method: "POST",
  data: $.param({"foo":"bar"})
  }).success(function(data, status, headers, config) {
   $scope.data = data;
  }).error(function(data, status, headers, config) {
   $scope.status = status;
 });

look at this : AngularJS + ASP.NET Web API Cross-Domain Issue

What is the best (idiomatic) way to check the type of a Python variable?

I think I will go for the duck typing approach - "if it walks like a duck, it quacks like a duck, its a duck". This way you will need not worry about if the string is a unicode or ascii.

Here is what I will do:

In [53]: s='somestring'

In [54]: u=u'someunicodestring'

In [55]: d={}

In [56]: for each in s,u,d:
    if hasattr(each, 'keys'):
        print list(set(each.values()))
    elif hasattr(each, 'lower'):
        print [each]
    else:
        print "error"
   ....:         
   ....:         
['somestring']
[u'someunicodestring']
[]

The experts here are welcome to comment on this type of usage of ducktyping, I have been using it but got introduced to the exact concept behind it lately and am very excited about it. So I would like to know if thats an overkill to do.

Sort a single String in Java

str.chars().boxed().map(Character::toString).sorted().collect(Collectors.joining())

or

s.chars().mapToObj(Character::toString).sorted().collect(Collectors.joining())

or

Arrays.stream(str.split("")).sorted().collect(Collectors.joining())

Formula to convert date to number

If you change the format of the cells to General then this will show the date value of a cell as behind the scenes Excel saves a date as the number of days since 01/01/1900

Screenprint 1

Screenprint 2

If your date is text and you need to convert it then DATEVALUE will do this:

Datevalue function

How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)

NSData *data = [strChangetoJSON dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data
                                                             options:kNilOptions
                                                               error:&error];

For example you have a NSString with special characters in NSString strChangetoJSON. Then you can convert that string to JSON response using above code.

Prevent scrolling of parent element when inner element scroll position reaches top/bottom?

In case someone is still looking for a solution for this, the following plugin does the job http://mohammadyounes.github.io/jquery-scrollLock/

It fully addresses the issue of locking mouse wheel scroll inside a given container, preventing it from propagating to parent element.

It does not change wheel scrolling speed, user experience will not be affected. and you get the same behavior regardless of the OS mouse wheel vertical scrolling speed (On Windows it can be set to one screen or one line up to 100 lines per notch).

Demo: http://mohammadyounes.github.io/jquery-scrollLock/example/

Source: https://github.com/MohammadYounes/jquery-scrollLock

What is javax.inject.Named annotation supposed to be used for?

@Inject instead of Spring’s @Autowired to inject a bean.
@Named instead of Spring’s @Component to declare a bean.

Those JSR-330 standard annotations are scanned and retrieved the same way as Spring annotation (as long as the following jar is in your classpath)

Returning value from called function in a shell script

If it's just a true/false test, have your function return 0 for success, and return 1 for failure. The test would then be:

if function_name; then
  do something
else
  error condition
fi

Opening a SQL Server .bak file (Not restoring!)

The only workable solution is to restore the .bak file. The contents and the structure of those files are not documented and therefore, there's really no way (other than an awful hack) to get this to work - definitely not worth your time and the effort!

The only tool I'm aware of that can make sense of .bak files without restoring them is Red-Gate SQL Compare Professional (and the accompanying SQL Data Compare) which allow you to compare your database structure against the contents of a .bak file. Red-Gate tools are absolutely marvelous - highly recommended and well worth every penny they cost!

And I just checked their web site - it does seem that you can indeed restore a single table from out of a .bak file with SQL Compare Pro ! :-)

Passing multiple values for a single parameter in Reporting Services

What you also can do is add this code in your stored procedure:

set @s = char(39) + replace(@s, ',', char(39) + ',' + char(39)) + char(39)

(Assuming @s is a multi-valued string (like "A,B,C"))

Should I initialize variable within constructor or outside constructor

I have the practice (habit) of almost always initializing in the contructor for two reasons, one in my opinion it adds to readablitiy (cleaner), and two there is more logic control in the constructor than in one line. Even if initially the instance variable doesn't require logic, having it in the constructor gives more flexibility to add logic in the future if needed.

As to the concern mentioned above about multiple constructors, that's easily solved by having one no-arg constructor that initializes all the instance variables that are initilized the same for all constructors and then each constructor calls this() at the first line. That solves your reduncancy issues.

Pythonic way to print list items

Expanding @lucasg's answer (inspired by the comment it received):

To get a formatted list output, you can do something along these lines:

l = [1,2,5]
print ", ".join('%02d'%x for x in l)

01, 02, 05

Now the ", " provides the separator (only between items, not at the end) and the formatting string '02d'combined with %x gives a formatted string for each item x - in this case, formatted as an integer with two digits, left-filled with zeros.

Cross field validation with Hibernate Validator (JSR 303)

I made a small adaptation in Nicko's solution so that it is not necessary to use the Apache Commons BeanUtils library and replace it with the solution already available in spring, for those using it as I can be simpler:

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object> {

    private String firstFieldName;
    private String secondFieldName;

    @Override
    public void initialize(final FieldMatch constraintAnnotation) {
        firstFieldName = constraintAnnotation.first();
        secondFieldName = constraintAnnotation.second();
    }

    @Override
    public boolean isValid(final Object object, final ConstraintValidatorContext context) {

        BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(object);
        final Object firstObj = beanWrapper.getPropertyValue(firstFieldName);
        final Object secondObj = beanWrapper.getPropertyValue(secondFieldName);

        boolean isValid = firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);

        if (!isValid) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
                .addPropertyNode(firstFieldName)
                .addConstraintViolation();
        }

        return isValid;

    }
}

jQuery Scroll to Div

I ran into the same. Saw an example using this: https://github.com/flesler/jquery.scrollTo

I use it as follows:

$('#arrow_back').click(function () {
    $.scrollTo('#features_1', 1000, { easing: 'easeInOutExpo', offset: 0, 'axis': 'y' }); 
});

Clean solution. Works for me!

How do I start/stop IIS Express Server?

An excellent answer given by msigman. I just want to add that in windows 10 you can find IIS Express System Tray (32 bit) process under Visual Studio process:

enter image description here

How to pass multiple parameters in thread in VB

First of all: AddressOf just gets the delegate to a function - you cannot specify anything else (i.e. capture any variables).

Now, you can start up a thread in two possible ways.

  • Pass an Action in the constructor and just Start() the thread.
  • Pass a ParameterizedThreadStart and forward one extra object argument to the method pointed to when calling .Start(parameter)

I consider the latter option an anachronism from pre-generic, pre-lambda times - which have ended at the latest with VB10.

You could use that crude method and create a list or structure which you pass to your threading code as this single object parameter, but since we now have closures, you can just create the thread on an anonymous Sub that knows all necessary variables by itself (which is work performed for you by the compiler).

Soo ...

Dim Evaluator = New Thread(Sub() Me.TestThread(goodList, 1))

It's really just that ;)

How do I iterate through the files in a directory in Java?

I like to use Optional and streams to have a net and clear solution, i use the below code to iterate over a directory. the below cases are handled by the code:

  1. handle the case of empty directory
  2. Laziness

but as mentioned by others, you still have to pay attention for outOfMemory in case you have huge folders

    File directoryFile = new File("put your path here");
    Stream<File> files = Optional.ofNullable(directoryFile// directoryFile
                                                          .listFiles(File::isDirectory)) // filter only directories(change with null if you don't need to filter)
                                 .stream()
                                 .flatMap(Arrays::stream);// flatmap from Stream<File[]> to Stream<File>

How do I calculate a point on a circle’s circumference?

Here is my implementation in C#:

    public static PointF PointOnCircle(float radius, float angleInDegrees, PointF origin)
    {
        // Convert from degrees to radians via multiplication by PI/180        
        float x = (float)(radius * Math.Cos(angleInDegrees * Math.PI / 180F)) + origin.X;
        float y = (float)(radius * Math.Sin(angleInDegrees * Math.PI / 180F)) + origin.Y;

        return new PointF(x, y);
    }

String.equals() with multiple conditions (and one action on result)

If you develop for Android KitKat or newer, you could also use a switch statement (see: Android coding with switch (String)). e.g.

switch(yourString)
{
     case "john":
          //do something for john
     case "mary":
          //do something for mary
}

Remove spacing between table cells and rows

I had a similar problem. This helps me across main email clients. Add:

  • attributes cellpadding="0", cellspacing="0" and border="0" to tables
  • style border-collapse: collapse; to tables
  • styles padding: 0; margin: 0; to each element
  • and styles font-size: 0px; line-height: 0px; to each element which is empty

Spark: subtract two DataFrames

According to the api docs, doing:

dataFrame1.except(dataFrame2)

will return a new DataFrame containing rows in dataFrame1 but not in dataframe2.

Relational Database Design Patterns?

AskTom is probably the single most helpful resource on best practices on Oracle DBs. (I usually just type "asktom" as the first word of a google query on a particular topic)

I don't think it's really appropriate to speak of design patterns with relational databases. Relational databases are already the application of a "design pattern" to a problem (the problem being "how to represent, store and work with data while maintaining its integrity", and the design being the relational model). Other approches (generally considered obsolete) are the Navigational and Hierarchical models (and I'm nure many others exist).

Having said that, you might consider "Data Warehousing" as a somewhat separate "pattern" or approach in database design. In particular, you might be interested in reading about the Star schema.

java.math.BigInteger cannot be cast to java.lang.Integer

You can try this:

((BigDecimal) volume).intValue();

I use java.math.BigDecimal convert to int (primitive type).

It is worked for me.

IE11 prevents ActiveX from running

IE displays a active x warning and ask for permission if you allow it to run or not. To overcome this the only solution is to;

  1. Open Internet Explorer.
  2. Click the Tools menu, and then click Internet Options.
  3. On the Security tab, click the Custom level button.
  4. Scroll down the Security Settings list until you see ActiveX controls and plug-ins.
  5. For Automatic prompting for ActiveX controls, click Enable.
  6. Scroll down to Download signed ActiveX controls and click Enable or Prompt.
  7. Scroll down to Run ActiveX controls and plug-ins and click Enable or Prompt.
  8. Scroll down to Script ActiveX controls marked safe for scripting and click Enable or Prompt.
  9. Click OK, and then click OK again.

There is no way to overcome this issue except changing manually Internet explorer settings. Try checking if plugin works fine while changed settings. If its still not working or not showing any warning is display try checking console for other errors which are not related to active x. Good luck!

How to properly set Column Width upon creating Excel file? (Column properties)

Use this One

 ((Excel.Range)oSheet.Cells[1, 1]).EntireColumn.ColumnWidth = 10;

Select multiple columns in data.table by their numeric indices

@Tom, thank you very much for pointing out this solution. It works great for me.

I was looking for a way to just exclude one column from printing and from the example above. To exclude the second column you can do something like this

library(data.table)
dt <- data.table(a=1:2, b=2:3, c=3:4)
dt[,.SD,.SDcols=-2]
dt[,.SD,.SDcols=c(1,3)]

How do I remove the old history from a git repository?

Maybe it's too late to post a reply, but as this page is the first Google's result, it may still be helpful.

If you want to free some space in your git repo, but do not want to rebuild all your commits (rebase or graft), and still be able to push/pull/merge from people who has the full repo, you may use the git clone shallow clone (--depth parameter).

; Clone the original repo into limitedRepo
git clone file:///path_to/originalRepo limitedRepo --depth=10

; Remove the original repo, to free up some space
rm -rf originalRepo
cd limitedRepo
git remote rm origin

You may be able to shallow your existing repo, by following these steps:

; Shallow to last 5 commits
git rev-parse HEAD~5 > .git/shallow

; Manually remove all other branches, tags and remotes that refers to old commits

; Prune unreachable objects
git fsck --unreachable ; Will show you the list of what will be deleted
git gc --prune=now     ; Will actually delete your data

How to remove all git local tags?

Ps: Older versions of git didn't support clone/push/pull from/to shallow repos.

SELECT query with CASE condition and SUM()

Use an "Or"

Select SUM(CAmount) as PaymentAmount 
from TableOrderPayment 
where (CPaymentType='Check' Or CPaymentType='Cash')
   and CDate <= case CPaymentType When 'Check' Then SYSDATETIME() else CDate End
   and CStatus='" & "Active" & "'"

or an "IN"

Select SUM(CAmount) as PaymentAmount 
from TableOrderPayment 
where CPaymentType IN ('Check', 'Cash')
   and CDate <= case CPaymentType When 'Check' Then SYSDATETIME() else CDate End
   and CStatus='" & "Active" & "'"

How to install Intellij IDEA on Ubuntu?

TL;DR:

  1. Download IntelliJ IDEA from here.
  2. cd Downloads
  3. extract the downloaded file: sudo tar xf ideaIC-2017.2.5.tar.gz -C /opt/
  4. Switch to the bin directory: cd /opt/idea-IC-172.4343.14/bin
  5. Run idea.sh from the bin subdirectory.

HTML Upload MAX_FILE_SIZE does not appear to work

PHP.net explanation about MAX_FILE_SIZE hidden field.

The MAX_FILE_SIZE hidden field (measured in bytes) must precede the file input field, and its value is the maximum filesize accepted by PHP. This form element should always be used as it saves users the trouble of waiting for a big file being transferred only to find that it was too large and the transfer failed. Keep in mind: fooling this setting on the browser side is quite easy, so never rely on files with a greater size being blocked by this feature. It is merely a convenience feature for users on the client side of the application. The PHP settings (on the server side) for maximum-size, however, cannot be fooled.

http://php.net/manual/en/features.file-upload.post-method.php

Javascript reduce() on Object

If handled as an array is much easier

Return the total amount of fruits:

let fruits = [{ name: 'banana', id: 0, quantity: 9 }, { name: 'strawberry', id: 1, quantity: 1 }, { name: 'kiwi', id: 2, quantity: 2 }, { name: 'apple', id: 3, quantity: 4 }]

let total = fruits.reduce((sum, f) => sum + f.quantity, 0);

How to return a table from a Stored Procedure?

In SQL Server 2008 you can use

http://www.sommarskog.se/share_data.html#tableparam

or else simple and same as common execution

CREATE PROCEDURE OrderSummary @MaxQuantity INT OUTPUT AS

SELECT Ord.EmployeeID, SummSales = SUM(OrDet.UnitPrice * OrDet.Quantity)
FROM Orders AS Ord
     JOIN [Order Details] AS OrDet ON (Ord.OrderID = OrDet.OrderID)
GROUP BY Ord.EmployeeID
ORDER BY Ord.EmployeeID

SELECT @MaxQuantity = MAX(Quantity) FROM [Order Details]

RETURN (SELECT SUM(Quantity) FROM [Order Details])
GO

I hopes its help to you

How can I create a dropdown menu from a List in Tkinter?

To create a "drop down menu" you can use OptionMenu in tkinter

Example of a basic OptionMenu:

from Tkinter import *

master = Tk()

variable = StringVar(master)
variable.set("one") # default value

w = OptionMenu(master, variable, "one", "two", "three")
w.pack()

mainloop()

More information (including the script above) can be found here.


Creating an OptionMenu of the months from a list would be as simple as:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

mainloop()

In order to retrieve the value the user has selected you can simply use a .get() on the variable that we assigned to the widget, in the below case this is variable:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

def ok():
    print ("value is:" + variable.get())

button = Button(master, text="OK", command=ok)
button.pack()

mainloop()

I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.

Update multiple rows in same query using PostgreSQL

You can also use update ... from syntax and use a mapping table. If you want to update more than one column, it's much more generalizable:

update test as t set
    column_a = c.column_a
from (values
    ('123', 1),
    ('345', 2)  
) as c(column_b, column_a) 
where c.column_b = t.column_b;

You can add as many columns as you like:

update test as t set
    column_a = c.column_a,
    column_c = c.column_c
from (values
    ('123', 1, '---'),
    ('345', 2, '+++')  
) as c(column_b, column_a, column_c) 
where c.column_b = t.column_b;

sql fiddle demo

SQL: How to perform string does not equal

Your where clause will return all rows where tester does not match username AND where tester is not null.

If you want to include NULLs, try:

where tester <> 'username' or tester is null

If you are looking for strings that do not contain the word "username" as a substring, then like can be used:

where tester not like '%username%'

Auto increment in MongoDB to store sequence of Unique User ID

First Record should be add

"_id" = 1    in your db

$database = "demo";
$collections ="democollaction";
echo getnextid($database,$collections);

function getnextid($database,$collections){

     $m = new MongoClient();
    $db = $m->selectDB($database);
    $cursor = $collection->find()->sort(array("_id" => -1))->limit(1);
    $array = iterator_to_array($cursor);

    foreach($array as $value){



        return $value["_id"] + 1;

    }
 }

How to get height of entire document with JavaScript?

use blow code for compute height + scroll

var dif = document.documentElement.scrollHeight - document.documentElement.clientHeight;

var height = dif + document.documentElement.scrollHeight +"px";

Interface extends another interface but implements its methods

Why does it implement its methods? How can it implement its methods when an interface can't contain method body? How can it implement the methods when it extends the other interface and not implement it? What is the purpose of an interface implementing another interface?

Interface does not implement the methods of another interface but just extends them. One example where the interface extension is needed is: consider that you have a vehicle interface with two methods moveForward and moveBack but also you need to incorporate the Aircraft which is a vehicle but with some addition methods like moveUp, moveDown so in the end you have:

public interface IVehicle {
  bool moveForward(int x);
  bool moveBack(int x);
};

and airplane:

public interface IAirplane extends IVehicle {
  bool moveDown(int x);
  bool moveUp(int x);
};

PowerShell: Run command from script's directory

This would work fine.

Push-Location $PSScriptRoot

Write-Host CurrentDirectory $CurDir

docker run <IMAGE> <MULTIPLE COMMANDS>

Just to make a proper answer from the @Eddy Hernandez's comment and which is very correct since Alpine comes with ash not bash.

The question now referes to Starting a shell in the Docker Alpine container which implies using sh or ash or /bin/sh or /bin/ash/.

Based on the OP's question:

docker run image sh -c "cd /path/to/somewhere && python a.py"

What's the difference between ViewData and ViewBag?

ViewData: It requires type casting for complex data types and checks for null values to avoid errors.

ViewBag: It doesn’t require type casting for complex data types.

Consider the following example:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var emp = new Employee
        {
            EmpID=101,
            Name = "Deepak",
            Salary = 35000,
            Address = "Delhi"
        };

        ViewData["emp"] = emp;
        ViewBag.Employee = emp;

        return View(); 
    }
}

And the code for View is as follows:

@model MyProject.Models.EmpModel;
@{ 
 Layout = "~/Views/Shared/_Layout.cshtml"; 
 ViewBag.Title = "Welcome to Home Page";
 var viewDataEmployee = ViewData["emp"] as Employee; //need type casting
}

<h2>Welcome to Home Page</h2>
This Year Best Employee is!
<h4>@ViewBag.Employee.Name</h4>
<h3>@viewDataEmployee.Name</h3>

How can I get the content of CKEditor using JQuery?

you can retreive data like this :

<script>
var data = CKEDITOR.instances.editor1.getData();
// Your code to save "data", usually through Ajax.
</script>

reference : http://docs.ckeditor.com/#!/guide/dev_savedata

Could not find module "@angular-devkit/build-angular"

The following worked for me. Nothing else did, unfortunately.

npm uninstall @angular-devkit/build-angular
npm install @angular-devkit/build-angular
ng update --all --allow-dirty --force

How to get a value from a Pandas DataFrame and not the index and object type

df[df.Letters=='C'].Letters.item()

This returns the first element in the Index/Series returned from that selection. In this case, the value is always the first element.

EDIT:

Or you can run a loc() and access the first element that way. This was shorter and is the way I have implemented it in the past.

ES6 exporting/importing in index file

Nav.js comp inside components folder

export {Nav}

index.js in component folder

export {Nav} from './Nav';
export {Another} from './Another';

import anywhere

import {Nav, Another} from './components'

Javascript Iframe innerHTML

Conroy's answer was right. In the case you need only stuff from body tag, just use:

$('#my_iframe').contents().find('body').html();

Execution Failed for task :app:compileDebugJavaWithJavac in Android Studio

Changing anything in build.gradle file will re-sync everything again and the error will be gone.For me i changed the minSdkVersion and it worked. Don't worry this could happen if the system crashed or Android Studio was not shut properly.

favicon.png vs favicon.ico - why should I use PNG instead of ICO?

PNG has 2 advantages: it has smaller size and it's more widely used and supported (except in case favicons). As mentioned before ICO, can have multiple size icons, which is useful for desktop applications, but not too much for websites. I would recommend you to put a favicon.ico in the root of your application. An if you have access to the Head of your website pages use the tag to point to a png file. So older browser will show the favicon.ico and newer ones the png.

To create Png and Icon files I would recommend The Gimp.

Unicode via CSS :before

In CSS, FontAwesome unicode works only when the correct font family is declared (version 4 or less):

font-family: "FontAwesome";
content: "\f066";

Update - Version 5 has different names:

Free

font-family: "Font Awesome 5 Free"

Pro

font-family: "Font Awesome 5 Pro"

Brands

font-family: "Font Awesome 5 Brands"

See this related answer: https://stackoverflow.com/a/48004111/2575724

As per comment (BuddyZ) some more info here https://fontawesome.com/how-to-use/on-the-desktop/setup/getting-started

Prolog "or" operator, query

you can 'invoke' alternative bindings on Y this way:

...registered(X, Y), (Y=ct101; Y=ct102; Y=ct103).

Note the parenthesis are required to keep the correct execution control flow. The ;/2 it's the general or operator. For your restricted use you could as well choice the more idiomatic

...registered(X, Y), member(Y, [ct101,ct102,ct103]).

that on backtracking binds Y to each member of the list.

edit I understood with a delay your last requirement. If you want that Y match all 3 values the or is inappropriate, use instead

...registered(X, ct101), registered(X, ct102), registered(X, ct103).

or the more compact

...findall(Y, registered(X, Y), L), sort(L, [ct101,ct102,ct103]).

findall/3 build the list in the very same order that registered/2 succeeds. Then I use sort to ensure the matching.

...setof(Y, registered(X, Y), [ct101,ct102,ct103]).

setof/3 also sorts the result list

How Stuff and 'For Xml Path' work in SQL Server?

There is very new functionality in Azure SQL Database and SQL Server (starting with 2017) to handle this exact scenario. I believe this would serve as a native official method for what you are trying to accomplish with the XML/STUFF method. Example:

select id, STRING_AGG(name, ',') as abc
from temp1
group by id

STRING_AGG - https://msdn.microsoft.com/en-us/library/mt790580.aspx

EDIT: When I originally posted this I made mention of SQL Server 2016 as I thought I saw that on a potential feature that was to be included. Either I remembered that incorrectly or something changed, thanks for the suggested edit fixing the version. Also, pretty impressed and wasn't fully aware of the multi-step review process that just pulled me in for a final option.

URL encode sees “&” (ampersand) as “&amp;” HTML entity

Without seeing your code, it's hard to answer other than a stab in the dark. I would guess that the string you're passing to encodeURIComponent(), which is the correct method to use, is coming from the result of accessing the innerHTML property. The solution is to get the innerText/textContent property value instead:

var str, 
    el = document.getElementById("myUrl");

if ("textContent" in el)
    str = encodeURIComponent(el.textContent);
else
    str = encodeURIComponent(el.innerText);

If that isn't the case, you can use the replace() method to replace the HTML entity:

encodeURIComponent(str.replace(/&amp;/g, "&"));

INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server

In my case, I was inserting the values in the Child Table in the wrong order

For Table with 2 columns- Column1 and Column2, i got this error when I mistakenly entered:

Insert into Table values('value for column2''value for column1')

Error resolved when I used below format :-

Insert into Table (column1, column2) values('value for column2''value for column1')

Counting no of rows returned by a select query

SQL Server requires subqueries that you SELECT FROM or JOIN to have an alias.

Add an alias to your subquery (in this case x):

select COUNT(*) from
(
select m.Company_id
from Monitor as m
    inner join Monitor_Request as mr on mr.Company_ID=m.Company_id
    group by m.Company_id
    having COUNT(m.Monitor_id)>=5)  x

What is the use of the JavaScript 'bind' method?

Bind creates a new function that will force the this inside the function to be the parameter passed to bind().

Here's an example that shows how to use bind to pass a member method around that has the correct this:

var myButton = {
  content: 'OK',
  click() {
    console.log(this.content + ' clicked');
  }
};

myButton.click();

var looseClick = myButton.click;
looseClick(); // not bound, 'this' is not myButton - it is the globalThis

var boundClick = myButton.click.bind(myButton);
boundClick(); // bound, 'this' is myButton

Which prints out:

OK clicked
undefined clicked
OK clicked

You can also add extra parameters after the 1st (this) parameter and bind will pass in those values to the original function. Any additional parameters you later pass to the bound function will be passed in after the bound parameters:

// Example showing binding some parameters
var sum = function(a, b) {
  return a + b;
};

var add5 = sum.bind(null, 5);
console.log(add5(10));

Which prints out:

15

Check out JavaScript Function bind for more info and interactive examples.

Update: ECMAScript 2015 adds support for => functions. => functions are more compact and do not change the this pointer from their defining scope, so you may not need to use bind() as often. For example, if you wanted a function on Button from the first example to hook up the click callback to a DOM event, the following are all valid ways of doing that:

var myButton = {
  ... // As above
  hookEvent(element) {
    // Use bind() to ensure 'this' is the 'this' inside click()
    element.addEventListener('click', this.click.bind(this));
  }
};

Or:

var myButton = {
  ... // As above
  hookEvent(element) {
    // Use a new variable for 'this' since 'this' inside the function
    // will not be the 'this' inside hookEvent()
    var me = this;
    element.addEventListener('click', function() { me.click() });
  }
};    

Or:

var myButton = {
  ... // As above
  hookEvent(element) {
    // => functions do not change 'this', so you can use it directly
    element.addEventListener('click', () => this.click());
  }
};

Computed / calculated / virtual / derived columns in PostgreSQL

One way to do this is with a trigger!

CREATE TABLE computed(
    one SERIAL,
    two INT NOT NULL
);

CREATE OR REPLACE FUNCTION computed_two_trg()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
AS $BODY$
BEGIN
    NEW.two = NEW.one * 2;

    RETURN NEW;
END
$BODY$;

CREATE TRIGGER computed_500
BEFORE INSERT OR UPDATE
ON computed
FOR EACH ROW
EXECUTE PROCEDURE computed_two_trg();

The trigger is fired before the row is updated or inserted. It changes the field that we want to compute of NEW record and then it returns that record.

How to get data from observable in angular2

You need to subscribe to the observable and pass a callback that processes emitted values

this.myService.getConfig().subscribe(val => console.log(val));

How to get numeric value from a prompt box?

JavaScript will "convert" numeric string to integer, if you perform calculations on it (as JS is weakly typed). But you can convert it yourself using parseInt or parseFloat.

Just remember to put radix in parseInt!

In case of integer inputs:

var x = parseInt(prompt("Enter a Value", "0"), 10);
var y = parseInt(prompt("Enter a Value", "0"), 10);

In case of float:

var x = parseFloat(prompt("Enter a Value", "0"));
var y = parseFloat(prompt("Enter a Value", "0"));

Rendering HTML elements to <canvas>

Here is code to render arbitrary HTML into a canvas:

function render_html_to_canvas(html, ctx, x, y, width, height) {
    var xml = html_to_xml(html);
    xml = xml.replace(/\#/g, '%23');
    var data = "data:image/svg+xml;charset=utf-8,"+'<svg xmlns="http://www.w3.org/2000/svg" width="'+width+'" height="'+height+'">' +
                        '<foreignObject width="100%" height="100%">' +
                        xml+
                        '</foreignObject>' +
                        '</svg>';

    var img = new Image();
    img.onload = function () {
        ctx.drawImage(img, x, y);
    }
    img.src = data;
}

function html_to_xml(html) {
    var doc = document.implementation.createHTMLDocument('');
    doc.write(html);

    // You must manually set the xmlns if you intend to immediately serialize     
    // the HTML document to a string as opposed to appending it to a
    // <foreignObject> in the DOM
    doc.documentElement.setAttribute('xmlns', doc.documentElement.namespaceURI);

    // Get well-formed markup
    html = (new XMLSerializer).serializeToString(doc.body);
    return html;
}

example:

_x000D_
_x000D_
const ctx = document.querySelector('canvas').getContext('2d');
const html = `
<p>this
<p>is <span style="color:red; font-weight: bold;">not</span>
<p><i>xml</i>!
<p><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABWElEQVQ4jZ2Tu07DQBBFz9jjvEAQqAlQ0CHxERQ0/AItBV9Ew8dQUNBQIho6qCFE4Nhex4u85OHdWAKxzfWsx0d3HpazdGITA4kROjl0ckFrnYJmQlJrKsQZxFOIMyEqIMpADGhSZpikB1hAGsovdxABGuepC/4L0U7xRTG/riG3J8fuvdifPKnmasXp5c2TB1HNPl24gNTnpeqsgmj1eFgayoHvRDWbLBOKJbn9WLGYflCCpmM/2a4Au6/PTjdH+z9lCJQ9vyeq0w/ve2kA3vaOnI6k4Pz+0Y24yP3Gapy+Bw6qdfsCRZfWSWgclCCVXTZu5LZFXKJJ2sepW2KYNCENB3U5pw93zLoDjNK6E7rTFcgbkGYJtiLckxCiw4W1OURsxUE5BokQiQj3JIToVtKwlhsurq+YDYbMBjuU/W3KtT3xIbrpAD7E60lwQohuaMtP8ldI0uMbGfC1r1zyWPUAAAAASUVORK5CYII=">`;
render_html_to_canvas(html, ctx, 0, 0, 300, 150);


function render_html_to_canvas(html, ctx, x, y, width, height) {
  var data = "data:image/svg+xml;charset=utf-8," + '<svg xmlns="http://www.w3.org/2000/svg" width="' + width + '" height="' + height + '">' +
    '<foreignObject width="100%" height="100%">' +
    html_to_xml(html) +
    '</foreignObject>' +
    '</svg>';

  var img = new Image();
  img.onload = function() {
    ctx.drawImage(img, x, y);
  }
  img.src = data;
}

function html_to_xml(html) {
  var doc = document.implementation.createHTMLDocument('');
  doc.write(html);

  // You must manually set the xmlns if you intend to immediately serialize     
  // the HTML document to a string as opposed to appending it to a
  // <foreignObject> in the DOM
  doc.documentElement.setAttribute('xmlns', doc.documentElement.namespaceURI);

  // Get well-formed markup
  html = (new XMLSerializer).serializeToString(doc.body);
  return html;
}
_x000D_
<canvas></canvas>
_x000D_
_x000D_
_x000D_

jquery select element by xpath

If you are debugging or similar - In chrome developer tools, you can simply use

$x('/html/.//div[@id="text"]')

How to create a hex dump of file containing only the hex characters without spaces in bash?

Format strings can make hexdump behave exactly as you want it to (no whitespace at all, byte by byte):

hexdump -ve '1/1 "%.2x"'

1/1 means "each format is applied once and takes one byte", and "%.2x" is the actual format string, like in printf. In this case: 2-character hexadecimal number, leading zeros if shorter.

Creating a daemon in Linux

By calling fork() you've created a child process. If the fork is successful (fork returned a non-zero PID) execution will continue from this point from within the child process. In this case we want to gracefully exit the parent process and then continue our work in the child process.

Maybe this will help: http://www.netzmafia.de/skripten/unix/linux-daemon-howto.html

How do I print out the contents of a vector?

The problem is probably in the previous loop:

(x = 17; isalpha(firstsquare); x++)

This loop will run not at all (if firstsquare is non-alphabetic) or will run forever (if it is alphabetic). The reason is that firstsquare doesn't change as x is incremented.

How do I verify that a string only contains letters, numbers, underscores and dashes?

use a regex and see if it matches!

([a-z][A-Z][0-9]\_\-)*

Grep to find item in Perl array

This could be done using List::Util's first function:

use List::Util qw/first/;

my @array = qw/foo bar baz/;
print first { $_ eq 'bar' } @array;

Other functions from List::Util like max, min, sum also may be useful for you

iOS 10 - Changes in asking permissions of Camera, microphone and Photo Library causing application to crash

[UPDATED privacy keys list to iOS 13 - see below]

There is a list of all Cocoa Keys that you can specify in your Info.plist file:

https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html

(Xcode: Target -> Info -> Custom iOS Target Properties)

iOS already required permissions to access microphone, camera, and media library earlier (iOS 6, iOS 7), but since iOS 10 app will crash if you don't provide the description why you are asking for the permission (it can't be empty).

Privacy keys with example description: cheatsheet

Source

Alternatively, you can open Info.plist as source code: source code

Source

And add privacy keys like this:

<key>NSLocationAlwaysUsageDescription</key>
<string>${PRODUCT_NAME} always location use</string>

List of all privacy keys: [UPDATED to iOS 13]

NFCReaderUsageDescription
NSAppleMusicUsageDescription
NSBluetoothAlwaysUsageDescription
NSBluetoothPeripheralUsageDescription
NSCalendarsUsageDescription
NSCameraUsageDescription
NSContactsUsageDescription
NSFaceIDUsageDescription
NSHealthShareUsageDescription
NSHealthUpdateUsageDescription
NSHomeKitUsageDescription
NSLocationAlwaysUsageDescription
NSLocationUsageDescription
NSLocationWhenInUseUsageDescription
NSMicrophoneUsageDescription
NSMotionUsageDescription
NSPhotoLibraryAddUsageDescription
NSPhotoLibraryUsageDescription
NSRemindersUsageDescription
NSSiriUsageDescription
NSSpeechRecognitionUsageDescription
NSVideoSubscriberAccountUsageDescription

Update 2019:

In the last months, two of my apps were rejected during the review because the camera usage description wasn't specifying what I do with taken photos.

I had to change the description from ${PRODUCT_NAME} need access to the camera to take a photo to ${PRODUCT_NAME} need access to the camera to update your avatar even though the app context was obvious (user tapped on the avatar).

It seems that Apple is now paying even more attention to the privacy usage descriptions, and we should explain in details why we are asking for permission.

Best Regular Expression for Email Validation in C#

Email Validation Regex

^[a-z0-9][-a-z0-9._]+@([-a-z0-9]+.)+[a-z]{2,5}$

Or

^[a-z0-9][-a-z0-9._]+@([-a-z0-9]+[.])+[a-z]{2,5}$

Demo Link:

https://regex101.com/r/kN4nJ0/53

how to solve Error cannot add duplicate collection entry of type add with unique key attribute 'value' in iis 7

Just keep the following in mind.

In IIS if you have a folder for example called Pages with multiple websites in it. Website will inherit settings from the web.config file from the parent directory. So even if the folder page (in this example Pages) isn't a website but contains a web.config file, all websites listed inside of it will inherit the setting.

SQL Server 2008: how do I grant privileges to a username?

Like the following. It will make the user database owner.

EXEC sp_addrolemember N'db_owner', N'USerNAme'

What is the difference between attribute and property?

What is the difference between Attribute and Property?
What is the difference between Feature and Function? What is the difference between Characteristic and Character? What is the difference between Act and Behavior?

Its just a change in context.

Object,Product,Personality,Person

A Person Acts in a Behavior. A Personality has Characteristics of a given Character. A Product has Feature that derive Functionality. An Object had Attributes that give it Properties.

Passing properties by reference in C#

This is not possible. You could say

Client.WorkPhone = GetString(inputString, Client.WorkPhone);

where WorkPhone is a writeable string property and the definition of GetString is changed to

private string GetString(string input, string current) { 
    if (!string.IsNullOrEmpty(input)) {
        return input;
    }
    return current;
}

This will have the same semantics that you seem to be trying for.

This isn't possible because a property is really a pair of methods in disguise. Each property makes available getters and setters that are accessible via field-like syntax. When you attempt to call GetString as you've proposed, what you're passing in is a value and not a variable. The value that you are passing in is that returned from the getter get_WorkPhone.

How do you install and run Mocha, the Node.js testing module? Getting "mocha: command not found" after install

For windows :

Package.json

  "scripts": {
    "start": "nodemon app.js",
    "test": "mocha"
  },

then run the command

npm run test

How can I select item with class within a DIV?

Try this

$("#mydiv div.myclass")

How do I find the index of a character within a string in C?

What about:

char *string = "qwerty";
char *e = string;
int idx = 0;
while (*e++ != 'e') idx++;

copying to e to preserve the original string, I suppose if you don't care you could just operate over *string

How to access List elements

It's simple

y = [['vegas','London'],['US','UK']]

for x in y:
    for a in x:
        print(a)

Error QApplication: no such file or directory

For QT 5

Step1: .pro (in pro file, add these 2 lines)

QT       += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

Step2: In main.cpp replace code:

#include <QtGui/QApplication> 

with:

#include <QApplication>

What is the purpose of .PHONY in a Makefile?

The best explanation is the GNU make manual itself: 4.6 Phony Targets section.

.PHONY is one of make's Special Built-in Target Names. There are other targets that you may be interested in, so it's worth skimming through these references.

When it is time to consider a .PHONY target, make will run its recipe unconditionally, regardless of whether a file with that name exists or what its last-modification time is.

You may also be interested in make's Standard Targets such as all and clean.

Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

<p:commandXxx process> <p:ajax process> <f:ajax execute>

The process attribute is server side and can only affect UIComponents implementing EditableValueHolder (input fields) or ActionSource (command fields). The process attribute tells JSF, using a space-separated list of client IDs, which components exactly must be processed through the entire JSF lifecycle upon (partial) form submit.

JSF will then apply the request values (finding HTTP request parameter based on component's own client ID and then either setting it as submitted value in case of EditableValueHolder components or queueing a new ActionEvent in case of ActionSource components), perform conversion, validation and updating the model values (EditableValueHolder components only) and finally invoke the queued ActionEvent (ActionSource components only). JSF will skip processing of all other components which are not covered by process attribute. Also, components whose rendered attribute evaluates to false during apply request values phase will also be skipped as part of safeguard against tampered requests.

Note that it's in case of ActionSource components (such as <p:commandButton>) very important that you also include the component itself in the process attribute, particularly if you intend to invoke the action associated with the component. So the below example which intends to process only certain input component(s) when a certain command component is invoked ain't gonna work:

<p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="foo" action="#{bean.action}" />

It would only process the #{bean.foo} and not the #{bean.action}. You'd need to include the command component itself as well:

<p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="@this foo" action="#{bean.action}" />

Or, as you apparently found out, using @parent if they happen to be the only components having a common parent:

<p:panel><!-- Type doesn't matter, as long as it's a common parent. -->
    <p:inputText id="foo" value="#{bean.foo}" />
    <p:commandButton process="@parent" action="#{bean.action}" />
</p:panel>

Or, if they both happen to be the only components of the parent UIForm component, then you can also use @form:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" />
    <p:commandButton process="@form" action="#{bean.action}" />
</h:form>

This is sometimes undesirable if the form contains more input components which you'd like to skip in processing, more than often in cases when you'd like to update another input component(s) or some UI section based on the current input component in an ajax listener method. You namely don't want that validation errors on other input components are preventing the ajax listener method from being executed.

Then there's the @all. This has no special effect in process attribute, but only in update attribute. A process="@all" behaves exactly the same as process="@form". HTML doesn't support submitting multiple forms at once anyway.

There's by the way also a @none which may be useful in case you absolutely don't need to process anything, but only want to update some specific parts via update, particularly those sections whose content doesn't depend on submitted values or action listeners.

Noted should be that the process attribute has no influence on the HTTP request payload (the amount of request parameters). Meaning, the default HTML behavior of sending "everything" contained within the HTML representation of the <h:form> will be not be affected. In case you have a large form, and want to reduce the HTTP request payload to only these absolutely necessary in processing, i.e. only these covered by process attribute, then you can set the partialSubmit attribute in PrimeFaces Ajax components as in <p:commandXxx ... partialSubmit="true"> or <p:ajax ... partialSubmit="true">. You can also configure this 'globally' by editing web.xml and add

<context-param>
    <param-name>primefaces.SUBMIT</param-name>
    <param-value>partial</param-value>
</context-param>

Alternatively, you can also use <o:form> of OmniFaces 3.0+ which defaults to this behavior.

The standard JSF equivalent to the PrimeFaces specific process is execute from <f:ajax execute>. It behaves exactly the same except that it doesn't support a comma-separated string while the PrimeFaces one does (although I personally recommend to just stick to space-separated convention), nor the @parent keyword. Also, it may be useful to know that <p:commandXxx process> defaults to @form while <p:ajax process> and <f:ajax execute> defaults to @this. Finally, it's also useful to know that process supports the so-called "PrimeFaces Selectors", see also How do PrimeFaces Selectors as in update="@(.myClass)" work?


<p:commandXxx update> <p:ajax update> <f:ajax render>

The update attribute is client side and can affect the HTML representation of all UIComponents. The update attribute tells JavaScript (the one responsible for handling the ajax request/response), using a space-separated list of client IDs, which parts in the HTML DOM tree need to be updated as response to the form submit.

JSF will then prepare the right ajax response for that, containing only the requested parts to update. JSF will skip all other components which are not covered by update attribute in the ajax response, hereby keeping the response payload small. Also, components whose rendered attribute evaluates to false during render response phase will be skipped. Note that even though it would return true, JavaScript cannot update it in the HTML DOM tree if it was initially false. You'd need to wrap it or update its parent instead. See also Ajax update/render does not work on a component which has rendered attribute.

Usually, you'd like to update only the components which really need to be "refreshed" in the client side upon (partial) form submit. The example below updates the entire parent form via @form:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" required="true" />
    <p:message id="foo_m" for="foo" />
    <p:inputText id="bar" value="#{bean.bar}" required="true" />
    <p:message id="bar_m" for="bar" />
    <p:commandButton action="#{bean.action}" update="@form" />
</h:form>

(note that process attribute is omitted as that defaults to @form already)

Whilst that may work fine, the update of input and command components is in this particular example unnecessary. Unless you change the model values foo and bar inside action method (which would in turn be unintuitive in UX perspective), there's no point of updating them. The message components are the only which really need to be updated:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" required="true" />
    <p:message id="foo_m" for="foo" />
    <p:inputText id="bar" value="#{bean.bar}" required="true" />
    <p:message id="bar_m" for="bar" />
    <p:commandButton action="#{bean.action}" update="foo_m bar_m" />
</h:form>

However, that gets tedious when you have many of them. That's one of the reasons why PrimeFaces Selectors exist. Those message components have in the generated HTML output a common style class of ui-message, so the following should also do:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" required="true" />
    <p:message id="foo_m" for="foo" />
    <p:inputText id="bar" value="#{bean.bar}" required="true" />
    <p:message id="bar_m" for="bar" />
    <p:commandButton action="#{bean.action}" update="@(.ui-message)" />
</h:form>

(note that you should keep the IDs on message components, otherwise @(...) won't work! Again, see How do PrimeFaces Selectors as in update="@(.myClass)" work? for detail)

The @parent updates only the parent component, which thus covers the current component and all siblings and their children. This is more useful if you have separated the form in sane groups with each its own responsibility. The @this updates, obviously, only the current component. Normally, this is only necessary when you need to change one of the component's own HTML attributes in the action method. E.g.

<p:commandButton action="#{bean.action}" update="@this" 
    oncomplete="doSomething('#{bean.value}')" />

Imagine that the oncomplete needs to work with the value which is changed in action, then this construct wouldn't have worked if the component isn't updated, for the simple reason that oncomplete is part of generated HTML output (and thus all EL expressions in there are evaluated during render response).

The @all updates the entire document, which should be used with care. Normally, you'd like to use a true GET request for this instead by either a plain link (<a> or <h:link>) or a redirect-after-POST by ?faces-redirect=true or ExternalContext#redirect(). In effects, process="@form" update="@all" has exactly the same effect as a non-ajax (non-partial) submit. In my entire JSF career, the only sensible use case I encountered for @all is to display an error page in its entirety in case an exception occurs during an ajax request. See also What is the correct way to deal with JSF 2.0 exceptions for AJAXified components?

The standard JSF equivalent to the PrimeFaces specific update is render from <f:ajax render>. It behaves exactly the same except that it doesn't support a comma-separated string while the PrimeFaces one does (although I personally recommend to just stick to space-separated convention), nor the @parent keyword. Both update and render defaults to @none (which is, "nothing").


See also:

HRESULT: 0x800A03EC on Worksheet.range

I encountered this issue.

Discovered that somewhere in my code I was asking it to count starting from 0 (as you would in a C# code).

Turns out Excel counting starts at 1.

How to align an input tag to the center without specifying the width?

You can use the following CSS for your input field:

.center-block {
  display: block;
  margin-right: auto;
  margin-left: auto;
}

Then,update your input field as following:

<input class="center-block" type="button" value="Some Button">

click command in selenium webdriver does not work

Please refer here https://code.google.com/p/selenium/issues/detail?id=6756 In crux

Please open the system display settings and ensure that font size is set to 100% It worked surprisingly

Installing OpenCV on Windows 7 for Python 2.7

I have posted a very simple method to install OpenCV 2.4 for Python in Windows here : Install OpenCV in Windows for Python

It is just as simple as copy and paste. Hope it will be useful for future viewers.

  1. Download Python, Numpy, OpenCV from their official sites.

  2. Extract OpenCV (will be extracted to a folder opencv)

  3. Copy ..\opencv\build\python\x86\2.7\cv2.pyd

  4. Paste it in C:\Python27\Lib\site-packages

  5. Open Python IDLE or terminal, and type

    >>> import cv2
    

If no errors shown, it is OK.

UPDATE (Thanks to dana for this info):

If you are using the VideoCapture feature, you must copy opencv_ffmpeg.dll into your path as well. See: https://stackoverflow.com/a/11703998/1134940

using jQuery .animate to animate a div from right to left?

This worked for me

$("div").css({"left":"2000px"}).animate({"left":"0px"}, "slow");

Select unique or distinct values from a list in UNIX shell script

With zsh you can do this:

% cat infile 
tar
more than one word
gz
java
gz
java
tar
class
class
zsh-5.0.0[t]% print -l "${(fu)$(<infile)}"
tar
more than one word
gz
java
class

Or you can use AWK:

% awk '!_[$0]++' infile    
tar
more than one word
gz
java
class

Share variables between files in Node.js?

Save any variable that want to be shared as one object. Then pass it to loaded module so it could access the variable through object reference..

// main.js
var myModule = require('./module.js');
var shares = {value:123};

// Initialize module and pass the shareable object
myModule.init(shares);

// The value was changed from init2 on the other file
console.log(shares.value); // 789

On the other file..

// module.js
var shared = null;

function init2(){
    console.log(shared.value); // 123
    shared.value = 789;
}

module.exports = {
    init:function(obj){
        // Save the shared object on current module
        shared = obj;

        // Call something outside
        init2();
    }
}

Twitter Bootstrap add active class to li

The solution is simple and there is no need for server side or ajax, you only need jQuery and Bootstrap. On every page add an id to the body tag. Use that id to find a tag that contains the page name (value of a tag).

Example:

page1.html

<body id="page1">
    <ul class="nav navbar-nav">
        <li><a href="page1.html">Page1</a></li>
        <li><a href="page2.html">Page2</a></li>
    </ul>
    <script src="script.js"></script>
</body>

page2.html

<body id="page2">
    <ul class="nav navbar-nav">
        <li><a href="page1.html">Page1</a></li>
        <li><a href="page2.html">Page2</a></li>
    </ul>
    <script src="script.js"></script>
</body>

script.js

<script>
    $(function () {
        $("#page1 a:contains('Page1')").parent().addClass('active');
        $("#page2 a:contains('Page2')").parent().addClass('active');
     });
</script>

Big thanks to Ben! YouTube

Returning multiple objects in an R function

One way to handle this is to put the information as an attribute on the primary one. I must stress, I really think this is the appropriate thing to do only when the two pieces of information are related such that one has information about the other.

For example, I sometimes stash the name of "crucial variables" or variables that have been significantly modified by storing a list of variable names as an attribute on the data frame:

attr(my.DF, 'Modified.Variables') <- DVs.For.Analysis$Names.of.Modified.Vars
return(my.DF)

This allows me to store a list of variable names with the data frame itself.

How to reload or re-render the entire page using AngularJS

If you want to refresh the controller while refreshing any services you are using, you can use this solution:

  • Inject $state

i.e.

app.controller('myCtrl',['$scope','MyService','$state', function($scope,MyService,$state) {

    //At the point where you want to refresh the controller including MyServices

    $state.reload();

    //OR:

    $state.go($state.current, {}, {reload: true});
}

This will refresh the controller and the HTML as well you can call it Refresh or Re-Render.

Validate SSL certificates with Python

M2Crypto can do the validation. You can also use M2Crypto with Twisted if you like. The Chandler desktop client uses Twisted for networking and M2Crypto for SSL, including certificate validation.

Based on Glyphs comment it seems like M2Crypto does better certificate verification by default than what you can do with pyOpenSSL currently, because M2Crypto checks subjectAltName field too.

I've also blogged on how to get the certificates Mozilla Firefox ships with in Python and usable with Python SSL solutions.

Storing and Retrieving ArrayList values from hashmap

Fetch all at once =

List<Integer> list = null;

if(map!= null) 
{ 
  list = new ArrayList<Integer>(map.values()); 
}

For Storing =

if(map!= null) 
{ 
  list = map.get(keyString); 
   if(list == null)
    {
         list = new ArrayList<Integer>();
    }
  list.add(value);
  map.put(keyString,list);
}

Why can't I make a vector of references?

By their very nature, references can only be set at the time they are created; i.e., the following two lines have very different effects:

int & A = B;   // makes A an alias for B
A = C;         // assigns value of C to B.

Futher, this is illegal:

int & D;       // must be set to a int variable.

However, when you create a vector, there is no way to assign values to it's items at creation. You are essentially just making a whole bunch of the last example.

JavaScript code for getting the selected value from a combo box

I use this

var e = document.getElementById('ticket_category_clone').value;

Notice that you don't need the '#' character in javascript.

    function check () {

    var str = document.getElementById('ticket_category_clone').value;

      if (str==="Hardware")
      {
        SPICEWORKS.utils.addStyle('#ticket_c_hardware_clone{display: none !important;}');
      }

    }

SPICEWORKS.app.helpdesk.ready(check);?

How can I convert a file pointer ( FILE* fp ) to a file descriptor (int fd)?

The proper function is int fileno(FILE *stream). It can be found in <stdio.h>, and is a POSIX standard but not standard C.

How to upload file using Selenium WebDriver in Java

driver.findElement(By.id("urid")).sendKeys("drive:\\path\\filename.extension");

Reading JSON from a file?

This works for me.

json.load() accepts file object, parses the JSON data, populates a Python dictionary with the data and returns it back to you.

Suppose JSON file is like this:

{
   "emp_details":[
                 {
                "emp_name":"John",
                "emp_emailId":"[email protected]"  
                  },
                {
                 "emp_name":"Aditya",
                 "emp_emailId":"[email protected]"
                }
              ] 
}


import json 

# Opening JSON file 
f = open('data.json',) 

# returns JSON object as  
# a dictionary 
data = json.load(f) 

# Iterating through the json 
# list 
for i in data['emp_details']: 
    print(i) 

# Closing file 
f.close()

#Output:
{'emp_name':'John','emp_emailId':'[email protected]'}
{'emp_name':'Aditya','emp_emailId':'[email protected]'}

Setting a backgroundImage With React Inline Styles

  1. Copy the image to the React Component's folder where you want to see it.
  2. Copy the following code:
<div className="welcomer" style={{ backgroundImage: url(${myImage}) }}></div>
  1. Give a height to your .welcomer using CSS so that you can see your image in the desired size.

How to logout and redirect to login page using Laravel 5.4?

if you are looking to do it via code on specific conditions, here is the solution worked for me. I have used in middleware to block certain users: these lines from below is the actual code to logout:

$auth = new LoginController();
$auth->logout($request);

Complete File:

namespace App\Http\Middleware;
use Closure;
use Auth;
use App\Http\Controllers\Auth\LoginController;
class ExcludeCustomers{
    public function handle($request, Closure $next){
        $user = Auth::guard()->user();
        if( $user->role == 3 ) {
            $auth = new LoginController();
            $auth->logout($request);
            header("Location: https://google.com");
            die();
        } 
        return $next($request);
    }
}

Change the "From:" address in Unix "mail"

On CentOS 5.5, the easiest way I've found to set the default from domain is to modify the hosts file. If your hosts file contains your WAN/public IP address, simply modify the first hostname listed for it. For example, your hosts file may look like:

...
11.22.33.44 localhost default-domain whatever-else.com
...

To make it send from whatever-else.com, simply modify it so that whatever-else.com is listed first, for example:

...
11.22.33.44 whatever-else.com localhost default-domain
...

I can't speak for any other distro (or even version of CentOS) but in my particular case, the above works perfectly.

200 PORT command successful. Consider using PASV. 425 Failed to establish connection

What worked for me was just typing the command passive and ftp went into passive mode from active mode.

Python Script Uploading files via FTP

I just answered a similar question here IMHO, if your FTP server is able to communicate with Fabric please us Fabric. It is far better than doing raw ftp.

I have an FTP account from dotgeek.com so I am not sure if this will work for other FTP accounts.

#!/usr/bin/python

from fabric.api import run, env, sudo, put

env.user = 'username'
env.hosts = ['ftp_host_name',]     # such as ftp.google.com

def copy():
    # assuming i have wong_8066.zip in the same directory as this script
    put('wong_8066.zip', '/www/public/wong_8066.zip')

save the file as fabfile.py and run fab copy locally.

yeukhon@yeukhon-P5E-VM-DO:~$ fab copy2
[1.ai] Executing task 'copy2'
[1.ai] Login password: 
[1.ai] put: wong_8066.zip -> /www/public/wong_8066.zip

Done.
Disconnecting from 1.ai... done.

Once again, if you don't want to input password all the time, just add

env.password = 'my_password'

How to get domain root url in Laravel 4?

My hint:

  1. FIND IF EXISTS in .env:

    APP_URL=http://yourhost.dev

  2. REPLACE TO (OR ADD)

    APP_DOMAIN=yourhost.dev

  3. FIND in config/app.php:

    'url' => env('APP_URL'),

  4. REPLACE TO

    'domain' => env('APP_DOMAIN'),

    'url' => 'http://' . env('APP_DOMAIN'),

  5. USE:

    Config::get('app.domain'); // yourhost.dev

    Config::get('app.url') // http://yourhost.dev

  6. Do your magic!

What should every programmer know about security?

I suggest reviewing CWE/SANS TOP 25 Most Dangerous Programming Errors. It was updated for 2010 with the promise of regular updates in the future. The 2009 revision is available as well.

From http://cwe.mitre.org/top25/index.html

The 2010 CWE/SANS Top 25 Most Dangerous Programming Errors is a list of the most widespread and critical programming errors that can lead to serious software vulnerabilities. They are often easy to find, and easy to exploit. They are dangerous because they will frequently allow attackers to completely take over the software, steal data, or prevent the software from working at all.

The Top 25 list is a tool for education and awareness to help programmers to prevent the kinds of vulnerabilities that plague the software industry, by identifying and avoiding all-too-common mistakes that occur before software is even shipped. Software customers can use the same list to help them to ask for more secure software. Researchers in software security can use the Top 25 to focus on a narrow but important subset of all known security weaknesses. Finally, software managers and CIOs can use the Top 25 list as a measuring stick of progress in their efforts to secure their software.

Could not load file or assembly ... The parameter is incorrect

I had users of Siemens Teamcenter 10 Client for Microsoft Office getting the same error about a different DLL. None of the other answers worked. The solution was to delete the folders in

C:\Users\%username%\AppData\Local\assembly\

Print string to text file

text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()

If you use a context manager, the file is closed automatically for you

with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: %s" % TotalAmount)

If you're using Python2.6 or higher, it's preferred to use str.format()

with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: {0}".format(TotalAmount))

For python2.7 and higher you can use {} instead of {0}

In Python3, there is an optional file parameter to the print function

with open("Output.txt", "w") as text_file:
    print("Purchase Amount: {}".format(TotalAmount), file=text_file)

Python3.6 introduced f-strings for another alternative

with open("Output.txt", "w") as text_file:
    print(f"Purchase Amount: {TotalAmount}", file=text_file)

How to pass the id of an element that triggers an `onclick` event to the event handling function

Here's a non-standard but cross-browser method that may be useful if you don't want to pass any arguments:-

Html:

<div onclick=myHandler() id="my element's id">&rarr; Click Here! &larr;</div>

Script:

function myHandler(){
    alert(myHandler.caller.arguments[0].target.id)
}

Demo: http://codepen.io/mrmoje/pen/ouJtk

Make text wrap in a cell with FPDF?

Text Wrap:

The MultiCell is used for print text with multiple lines. It has the same atributes of Cell except for ln and link.

$pdf->MultiCell( 200, 40, $reportSubtitle, 1);

Line Height:

What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).

MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])

You can read the full documentation here.

How to dismiss the dialog with click on outside of the dialog?

This code is use for when use click on dialogbox that time hidesoftinput and when user click outer side of dialogbox that time both softinput and dialogbox are close.

dialog = new Dialog(act) {
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // Tap anywhere to close dialog.
        Rect dialogBounds = new Rect();
        getWindow().getDecorView().getHitRect(dialogBounds);
        if (!dialogBounds.contains((int) event.getX(),
                (int) event.getY())) {
            // You have clicked the grey area
            InputMethodManager inputMethodManager = (InputMethodManager) act
                    .getSystemService(act.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(dialog
                    .getCurrentFocus().getWindowToken(), 0);
            dialog.dismiss();
            // stop activity closing
        } else {
            InputMethodManager inputMethodManager = (InputMethodManager) act
                    .getSystemService(act.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(dialog
                    .getCurrentFocus().getWindowToken(), 0);
        }

        return true;
    }
};

Correct way to write loops for promise.

Bergi's suggested function is really nice:

var promiseWhile = Promise.method(function(condition, action) {
      if (!condition()) return;
    return action().then(promiseWhile.bind(null, condition, action));
});

Still I want to make a tiny addition, which makes sense, when using promises:

var promiseWhile = Promise.method(function(condition, action, lastValue) {
  if (!condition()) return lastValue;
  return action().then(promiseWhile.bind(null, condition, action));
});

This way the while loop can be embedded into a promise chain and resolves with lastValue (also if the action() is never run). See example:

var count = 10;
util.promiseWhile(
  function condition() {
    return count > 0;
  },
  function action() {
    return new Promise(function(resolve, reject) {
      count = count - 1;
      resolve(count)
    })
  },
  count)

Spring Security with roles and permissions

ACL was overkill for my requirements also.
I ended up creating a library similar to @Alexander's to inject a GrantedAuthority list for Role->Permissions based on the role membership of a user.

For example, using a DB to hold the relationships -

@Autowired 
RolePermissionsRepository repository;

public void setup(){
  String roleName = "ROLE_ADMIN";
  List<String> permissions = new ArrayList<String>();
  permissions.add("CREATE");
  permissions.add("READ");
  permissions.add("UPDATE");
  permissions.add("DELETE");
  repository.save(new RolePermissions(roleName, permissions));
}

When an Authentication object is injected in the current security session, it will have the original roles/granted authorities.

This library provides 2 built-in integration points for Spring Security. When the integration point is reached, the PermissionProvider is called to get the effective permissions for each role the user is a member of.
The distinct list of permissions are added as GrantedAuthority items in the Authentication object.

You can also implement a custom PermissionProvider to store the relationships in config for example.

A more complete explanation here - https://stackoverflow.com/a/60251931/1308685

And the source code is here - https://github.com/savantly-net/spring-role-permissions

How to delete migration files in Rails 3

Sometimes I found myself deleting the migration file and then deleting the corresponding entry on the table schema_migrations from the database. Not pretty but it works.

How to get HttpClient returning status code and response body?

BasicResponseHandler throws if the status is not 2xx. See its javadoc.

Here is how I would do it:

HttpResponse response = client.execute( get );
int code = response.getStatusLine().getStatusCode();
InputStream body = response.getEntity().getContent();
// Read the body stream

Or you can also write a ResponseHandler starting from BasicResponseHandler source that don't throw when the status is not 2xx.

dplyr mutate with conditional values

Try this:

myfile %>% mutate(V5 = (V1 == 1 & V2 != 4) + 2 * (V2 == 4 & V3 != 1))

giving:

  V1 V2 V3 V4 V5
1  1  2  3  5  1
2  2  4  4  1  2
3  1  4  1  1  0
4  4  5  1  3  0
5  5  5  5  4  0

or this:

myfile %>% mutate(V5 = ifelse(V1 == 1 & V2 != 4, 1, ifelse(V2 == 4 & V3 != 1, 2, 0)))

giving:

  V1 V2 V3 V4 V5
1  1  2  3  5  1
2  2  4  4  1  2
3  1  4  1  1  0
4  4  5  1  3  0
5  5  5  5  4  0

Note

Suggest you get a better name for your data frame. myfile makes it seem as if it holds a file name.

Above used this input:

myfile <- 
structure(list(V1 = c(1L, 2L, 1L, 4L, 5L), V2 = c(2L, 4L, 4L, 
5L, 5L), V3 = c(3L, 4L, 1L, 1L, 5L), V4 = c(5L, 1L, 1L, 3L, 4L
)), .Names = c("V1", "V2", "V3", "V4"), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5"))

Update 1 Since originally posted dplyr has changed %.% to %>% so have modified answer accordingly.

Update 2 dplyr now has case_when which provides another solution:

myfile %>% 
       mutate(V5 = case_when(V1 == 1 & V2 != 4 ~ 1, 
                             V2 == 4 & V3 != 1 ~ 2,
                             TRUE ~ 0))

How do you clear Apache Maven's cache?

Have you checked/changed the updatePolicy settings for your repositories in your settings.xml.

This element specifies how often updates should attempt to occur. Maven will compare the local POM's timestamp (stored in a repository's maven-metadata file) to the remote. The choices are: always, daily (default), interval:X (where X is an integer in minutes) or never.

Try to set it to always.

CASE WHEN statement for ORDER BY clause

declare @OrderByCmd  nvarchar(2000)
declare @OrderByName nvarchar(100)
declare @OrderByCity nvarchar(100)
set @OrderByName='Name'    
set @OrderByCity='city'
set @OrderByCmd= 'select * from customer Order By '+@OrderByName+','+@OrderByCity+''
EXECUTE sp_executesql @OrderByCmd 

Why doesn't the height of a container element increase if it contains floated elements?

you can use overflow property to the container div if you don't have any div to show over the container eg:

<div class="cointainer">
    <div class="one">Content One</div>
    <div class="two">Content Two</div>
</div>

Here is the following css:

.container{
    width:100%;/* As per your requirment */
    height:auto;
    float:left;
    overflow:hidden;
}
.one{
    width:200px;/* As per your requirment */
    height:auto;
    float:left;
}

.two{
    width:200px;/* As per your requirment */
    height:auto;
    float:left;
}

-----------------------OR------------------------------

    <div class="cointainer">
        <div class="one">Content One</div>
        <div class="two">Content Two</div>
        <div class="clearfix"></div>
    </div>

Here is the following css:

    .container{
        width:100%;/* As per your requirment */
        height:auto;
        float:left;
        overflow:hidden;
    }
    .one{
        width:200px;/* As per your requirment */
        height:auto;
        float:left;
    }

    .two{
        width:200px;/* As per your requirment */
        height:auto;
        float:left;
    }
    .clearfix:before,
    .clearfix:after{
        display: table;
        content: " ";
    }
    .clearfix:after{
        clear: both;
    }

Is there a standard sign function (signum, sgn) in C/C++?

Is there a standard sign function (signum, sgn) in C/C++?

Yes, depending on definition.

C99 and later has the signbit() macro in <math.h>

int signbit(real-floating x);
The signbit macro returns a nonzero value if and only if the sign of its argument value is negative. C11 §7.12.3.6


Yet OP wants something a little different.

I want a function that returns -1 for negative numbers and +1 for positive numbers. ... a function working on floats.

#define signbit_p1_or_n1(x)  ((signbit(x) ?  -1 : 1)

Deeper:

The post is not specific in the following cases: x = 0.0, -0.0, +NaN, -NaN.

A classic signum() returns +1 on x>0, -1 on x<0 and 0 on x==0.

Many answers have already covered that, but do not address x = -0.0, +NaN, -NaN. Many are geared for an integer point-of-view that usually lacks Not-a-Numbers (NaN) and -0.0.

Typical answers function like signnum_typical() On -0.0, +NaN, -NaN, they return 0.0, 0.0, 0.0.

int signnum_typical(double x) {
  if (x > 0.0) return 1;
  if (x < 0.0) return -1;
  return 0;
}

Instead, I propose this functionality: On -0.0, +NaN, -NaN, it returns -0.0, +NaN, -NaN.

double signnum_c(double x) {
  if (x > 0.0) return 1.0;
  if (x < 0.0) return -1.0;
  return x;
}

Displaying a message in iOS which has the same functionality as Toast in Android

For me this solution works fine: https://github.com/cruffenach/CRToast

enter image description here

Example how use it:

    NSDictionary *options = @{
                          kCRToastTextKey : @"Hello World!",
                          kCRToastTextAlignmentKey : @(NSTextAlignmentCenter),
                          kCRToastBackgroundColorKey : [UIColor redColor],
                          kCRToastAnimationInTypeKey : @(CRToastAnimationTypeGravity),
                          kCRToastAnimationOutTypeKey : @(CRToastAnimationTypeGravity),
                          kCRToastAnimationInDirectionKey : @(CRToastAnimationDirectionLeft),
                          kCRToastAnimationOutDirectionKey : @(CRToastAnimationDirectionRight)
                          };
[CRToastManager showNotificationWithOptions:options
                            completionBlock:^{
                                NSLog(@"Completed");
                            }];

How to move or copy files listed by 'find' command in unix?

Actually, you can process the find command output in a copy command in two ways:

  1. If the find command's output doesn't contain any space, i.e if the filename doesn't contain a space in it, then you can use:

    Syntax:
        find <Path> <Conditions> | xargs cp -t <copy file path>
    Example:
        find -mtime -1 -type f | xargs cp -t inner/
    
  2. But our production data files might contain spaces, so most of time this command is effective:

    Syntax:
       find <path> <condition> -exec cp '{}' <copy path> \;
    
    Example 
       find -mtime -1 -type f -exec cp '{}' inner/ \;
    

In the second example, the last part, the semi-colon is also considered as part of the find command, and should be escaped before pressing Enter. Otherwise you will get an error something like:

find: missing argument to `-exec'

How to access site running apache server over lan without internet connection

* Don't change anything to Listen : keep it as it is..

1) Open httpd.conf of Apache server (backup first) Look for the the following :

<Directory />
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    Allow from all
    #Deny from all
</Directory>

and also this

<Directory "cgi-bin">
    AllowOverride None
    Options None
    Order allow,deny
    Allow from all
</Directory>

2) Now From taskbar :

Click on wamp icon > Apache > Apache modules > apache_rewrite (enable this module)

And Ya Also Activate "Put Online" From same taskbar icon

You need to allow port request from windows firewall setting.

(Windows 7)

Go to control panel > windows firewall > advance setting (on left sidebar)

then

Right click on inbound rules -> add new rule -> port -> TCP (Specific port 80 - if your localhost wok on this port) -> Allow the connections -> Give a profile name -> ok

Now Restart all the services of Apache server & you are done..

Is there a way to check for both `null` and `undefined`?

If you want to pass tslint without setting strict-boolean-expressions to allow-null-union or allow-undefined-union, you need to use isNullOrUndefined from node's util module or roll your own:

// tslint:disable:no-null-keyword
export const isNullOrUndefined =
  <T>(obj: T | null | undefined): obj is null | undefined => {
    return typeof obj === "undefined" || obj === null;
  };
// tslint:enable:no-null-keyword

Not exactly syntactic sugar but useful when your tslint rules are strict.

Forbidden :You don't have permission to access /phpmyadmin on this server

Centos 7 php install comes with the ModSecurity package installed and enabled which prevents web access to phpMyAdmin. At the end of phpMyAdmin.conf, you should find

# This configuration prevents mod_security at phpMyAdmin directories from
# filtering SQL etc.  This may break your mod_security implementation.
#
#<IfModule mod_security.c>
#    <Directory /usr/share/phpMyAdmin/>
#        SecRuleInheritance Off
#    </Directory>
#</IfModule>

which gives you the answer to the problem. By adding

    SecRuleEngine Off

in the block "Directory /usr/share/phpMyAdmin/", you can solve the 'denied access' to phpmyadmin, but you may create security issues.

How do I create a new user in a SQL Azure database?

You can simply create a contained user in SQL DB V12.

Create user containeduser with password = 'Password'

Contained user login is more efficient than login to the database using the login created by master. You can find more details @ http://www.sqlindepth.com/contained-users-in-sql-azure-db-v12/

LINQ Group By and select collection

I think you want:

items.GroupBy(item => item.Order.Customer)
     .Select(group => new { Customer = group.Key, Items = group.ToList() })
     .ToList() 

If you want to continue use the overload of GroupBy you are currently using, you can do:

items.GroupBy(item => item.Order.Customer, 
              (key, group) =>  new { Customer = key, Items = group.ToList() })
     .ToList() 

...but I personally find that less clear.

Where am I? - Get country

/**
 * Get ISO 3166-1 alpha-2 country code for this device (or null if not available)
 * @param context Context reference to get the TelephonyManager instance from
 * @return country code or null
 */
public static String getUserCountry(Context context) {
    try {
        final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        final String simCountry = tm.getSimCountryIso();
        if (simCountry != null && simCountry.length() == 2) { // SIM country code is available
            return simCountry.toLowerCase(Locale.US);
        }
        else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { // device is not 3G (would be unreliable)
            String networkCountry = tm.getNetworkCountryIso();
            if (networkCountry != null && networkCountry.length() == 2) { // network country code is available
                return networkCountry.toLowerCase(Locale.US);
            }
        }
    }
    catch (Exception e) { }
    return null;
}

Live-stream video from one android phone to another over WiFi

If you do not need the recording and playback functionality in your app, using off-the-shelf streaming app and player is a reasonable choice.

If you do need them to be in your app, however, you will have to look into MediaRecorder API (for the server/camera app) and MediaPlayer (for client/player app).

Quick sample code for the server:

// this is your network socket
ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(socket);
mCamera = getCameraInstance();
mMediaRecorder = new MediaRecorder();
mCamera.unlock();
mMediaRecorder.setCamera(mCamera);
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
// this is the unofficially supported MPEG2TS format, suitable for streaming (Android 3.0+)
mMediaRecorder.setOutputFormat(8);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
mediaRecorder.setOutputFile(pfd.getFileDescriptor());
mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());
mMediaRecorder.prepare();
mMediaRecorder.start();

On the player side it is a bit tricky, you could try this:

// this is your network socket, connected to the server
ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(socket);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(pfd.getFileDescriptor());
mMediaPlayer.prepare();
mMediaPlayer.start();

Unfortunately mediaplayer tends to not like this, so you have a couple of options: either (a) save data from socket to file and (after you have a bit of data) play with mediaplayer from file, or (b) make a tiny http proxy that runs locally and can accept mediaplayer's GET request, reply with HTTP headers, and then copy data from the remote server to it. For (a) you would create the mediaplayer with a file path or file url, for (b) give it a http url pointing to your proxy.

See also:

Stream live video from phone to phone using socket fd

MediaPlayer stutters at start of mp3 playback

How do I get sed to read from standard input?

  1. Open the file using vi myfile.csv
  2. Press Escape
  3. Type :%s/replaceme/withthis/
  4. Type :wq and press Enter

Now you will have the new pattern in your file.

convert string into array of integers

The point against parseInt-approach:

There's no need to use lambdas and/or give radix parameter to parseInt, just use parseFloat or Number instead.


Reasons:

  1. It's working:

    var src = "1,2,5,4,3";
    var ids = src.split(',').map(parseFloat); // [1, 2, 5, 4, 3]
    
    var obj = {1: ..., 3: ..., 4: ..., 7: ...};
    var keys= Object.keys(obj); // ["1", "3", "4", "7"]
    var ids = keys.map(parseFloat); // [1, 3, 4, 7]
    
    var arr = ["1", 5, "7", 11];
    var ints= arr.map(parseFloat); // [1, 5, 7, 11]
    ints[1] === "5" // false
    ints[1] === 5   // true
    ints[2] === "7" // false
    ints[2] === 7   // true
    
  2. It's shorter.

  3. It's a tiny bit quickier and takes advantage of cache, when parseInt-approach - doesn't:

      // execution time measure function
      // keep it simple, yeah?
    > var f = (function (arr, c, n, m) {
          var i,t,m,s=n();
          for(i=0;i++<c;)t=arr.map(m);
          return n()-s
      }).bind(null, "2,4,6,8,0,9,7,5,3,1".split(','), 1000000, Date.now);
    
    > f(Number) // first launch, just warming-up cache
    > 3971 // nice =)
    
    > f(Number)
    > 3964 // still the same
    
    > f(function(e){return+e})
    > 5132 // yup, just little bit slower
    
    > f(function(e){return+e})
    > 5112 // second run... and ok.
    
    > f(parseFloat)
    > 3727 // little bit quicker than .map(Number)
    
    > f(parseFloat)
    > 3737 // all ok
    
    > f(function(e){return parseInt(e,10)})
    > 21852 // awww, how adorable...
    
    > f(function(e){return parseInt(e)})
    > 22928 // maybe, without '10'?.. nope.
    
    > f(function(e){return parseInt(e)})
    > 22769 // second run... and nothing changes.
    
    > f(Number)
    > 3873 // and again
    > f(parseFloat)
    > 3583 // and again
    > f(function(e){return+e})
    > 4967 // and again
    
    > f(function(e){return parseInt(e,10)})
    > 21649 // dammit 'parseInt'! >_<
    

Notice: In Firefox parseInt works about 4 times faster, but still slower than others. In total: +e < Number < parseFloat < parseInt

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'

I also had same issue. I investigated and found missing {action} attribute from route template.

Before code (Having Issue):

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

After Fix(Working code):

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

How to hide Soft Keyboard when activity starts

To hide the softkeyboard at the time of New Activity start or onCreate(),onStart() etc. you can use the code below:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

Using Jquery AJAX function with datatype HTML

var datos = $("#id_formulario").serialize();
$.ajax({         
    url: "url.php",      
    type: "POST",                   
    dataType: "html",                 
    data: datos,                 
    success: function (prueba) { 
        alert("funciona!");
    }//FIN SUCCES

});//FIN  AJAX

Generating random numbers with Swift

This is how I get a random number between 2 int's!

func randomNumber(MIN: Int, MAX: Int)-> Int{
    var list : [Int] = []
    for i in MIN...MAX {
        list.append(i)
    }
    return list[Int(arc4random_uniform(UInt32(list.count)))]
}

usage:

print("My Random Number is: \(randomNumber(MIN:-10,MAX:10))")

pandas: find percentile stats of a given column

You can use the pandas.DataFrame.quantile() function, as shown below.

import pandas as pd
import random

A = [ random.randint(0,100) for i in range(10) ]
B = [ random.randint(0,100) for i in range(10) ]

df = pd.DataFrame({ 'field_A': A, 'field_B': B })
df
#    field_A  field_B
# 0       90       72
# 1       63       84
# 2       11       74
# 3       61       66
# 4       78       80
# 5       67       75
# 6       89       47
# 7       12       22
# 8       43        5
# 9       30       64

df.field_A.mean()   # Same as df['field_A'].mean()
# 54.399999999999999

df.field_A.median() 
# 62.0

# You can call `quantile(i)` to get the i'th quantile,
# where `i` should be a fractional number.

df.field_A.quantile(0.1) # 10th percentile
# 11.9

df.field_A.quantile(0.5) # same as median
# 62.0

df.field_A.quantile(0.9) # 90th percentile
# 89.10000000000001

Check if a string contains a substring in SQL Server 2005, using a stored procedure

CHARINDEX() searches for a substring within a larger string, and returns the position of the match, or 0 if no match is found

if CHARINDEX('ME',@mainString) > 0
begin
    --do something
end

Edit or from daniels answer, if you're wanting to find a word (and not subcomponents of words), your CHARINDEX call would look like:

CHARINDEX(' ME ',' ' + REPLACE(REPLACE(@mainString,',',' '),'.',' ') + ' ')

(Add more recursive REPLACE() calls for any other punctuation that may occur)

Nullable type as a generic parameter possible?

Just had to do something incredible similar to this. My code:

public T IsNull<T>(this object value, T nullAlterative)
{
    if(value != DBNull.Value)
    {
        Type type = typeof(T);
        if (type.IsGenericType && 
            type.GetGenericTypeDefinition() == typeof(Nullable<>).GetGenericTypeDefinition())
        {
            type = Nullable.GetUnderlyingType(type);
        }

        return (T)(type.IsEnum ? Enum.ToObject(type, Convert.ToInt32(value)) :
            Convert.ChangeType(value, type));
    }
    else 
        return nullAlternative;
}

check if a std::vector contains a certain object?

If searching for an element is important, I'd recommend std::set instead of std::vector. Using this:

std::find(vec.begin(), vec.end(), x) runs in O(n) time, but std::set has its own find() member (ie. myset.find(x)) which runs in O(log n) time - that's much more efficient with large numbers of elements

std::set also guarantees all the added elements are unique, which saves you from having to do anything like if not contained then push_back()....

Best Practice: Software Versioning

We use a.b.c.d where

  • a - major (incremented on delivery to client)
  • b - minor (incremented on delivery to client)
  • c - revision (incremented on internal releases)
  • d - build (incremented by cruise control)

Error: unmappable character for encoding UTF8 during maven compilation

When i inspect the console i found that the version of maven compiler is 2.5.1 but in other side i try to build my project with maven 3.2.2.So after writting the exact version in pom.xml, it works good. Here is the full tag:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>3.2</version>
  <configuration>
   ....
  <configuration>
</plugin>

Backporting Python 3 open(encoding="utf-8") to Python 2

I think

from io import open

should do.

ADB No Devices Found

I have found a solution for my case.

  1. Go to Tools->Layout Inspector.
  2. Press Restart button a few times.

I have no idea how it connect with ADB but it works.

multiple where condition codeigniter

$wherecond = "( ( ( username ='" . $username . "' OR status='" . $status . "') AND (id='" . $id . "') ) )"; $this->db->where($wherecond);

If you want to add AND and OR conditions at a time. this will work.

How to make a input field readonly with JavaScript?

You can get the input element and then set its readOnly property to true as follows:

document.getElementById('InputFieldID').readOnly = true;

Specifically, this is what you want:

<script type="text/javascript">
  function onLoadBody() {
    document.getElementById('control_EMAIL').readOnly = true;
  } 
</script>

Call this onLoadBody() function on body tag like:

<body onload="onLoadBody">

View Demo: jsfiddle.

How to solve "Kernel panic - not syncing - Attempted to kill init" -- without erasing any user data

I just came across this problem when I replaced a failing disk. I had copied over the system files to the new disk, and was good about replacing the old disk's UUID entry with the new disk's UUID in fstab.

However I had not replaced the UUID in the grub.conf (sometimes menu.lst) file in /boot/grub. So check your grub.conf file, and if the "kernel" line has something like

kernel ... root=UUID=906eaa97-f66a-4d39-a39d-5091c7095987 

it likely has the old disk's UUID. Replace it with the new disk's UUID and run grub-install (if you're in a live CD rescue you may need to chroot or specify the grub directory).

Defining a `required` field in Bootstrap

If wont work in case you have something like : novalidate="novalidate" attached to your form.

Creating a blurring overlay view

enter image description here

From Xcode you can do it easily. Follow the steps from xcode. Drage visual effect view on your uiview or imageview.

Happy Coding :)

Explain ExtJS 4 event handling

Firing application wide events

How to make controllers talk to each other ...

In addition to the very great answer above I want to mention application wide events which can be very useful in an MVC setup to enable communication between controllers. (extjs4.1)

Lets say we have a controller Station (Sencha MVC examples) with a select box:

Ext.define('Pandora.controller.Station', {
    extend: 'Ext.app.Controller',
    ...

    init: function() {
        this.control({
            'stationslist': {
                selectionchange: this.onStationSelect
            },
            ...
        });
    },

    ...

    onStationSelect: function(selModel, selection) {
        this.application.fireEvent('stationstart', selection[0]);
    },    
   ...
});

When the select box triggers a change event, the function onStationSelect is fired.

Within that function we see:

this.application.fireEvent('stationstart', selection[0]);

This creates and fires an application wide event that we can listen to from any other controller.

Thus in another controller we can now know when the station select box has been changed. This is done through listening to this.application.on as follows:

Ext.define('Pandora.controller.Song', {
    extend: 'Ext.app.Controller', 
    ...
    init: function() {
        this.control({
            'recentlyplayedscroller': {
                selectionchange: this.onSongSelect
            }
        });

        // Listen for an application wide event
        this.application.on({
            stationstart: this.onStationStart, 
                scope: this
        });
    },
    ....
    onStationStart: function(station) {
        console.info('I called to inform you that the Station controller select box just has been changed');
        console.info('Now what do you want to do next?');
    },
}

If the selectbox has been changed we now fire the function onStationStart in the controller Song also ...

From the Sencha docs:

Application events are extremely useful for events that have many controllers. Instead of listening for the same view event in each of these controllers, only one controller listens for the view event and fires an application-wide event that the others can listen for. This also allows controllers to communicate with one another without knowing about or depending on each other’s existence.

In my case: Clicking on a tree node to update data in a grid panel.

Update 2016 thanks to @gm2008 from the comments below:

In terms of firing application-wide custom events, there is a new method now after ExtJS V5.1 is published, which is using Ext.GlobalEvents.

When you fire events, you can call: Ext.GlobalEvents.fireEvent('custom_event');

When you register a handler of the event, you call: Ext.GlobalEvents.on('custom_event', function(arguments){/* handler codes*/}, scope);

This method is not limited to controllers. Any component can handle a custom event through putting the component object as the input parameter scope.

Found in Sencha Docs: MVC Part 2

How can I initialise a static Map?

Here is the code by AbacusUtil

Map<Integer, String> map = N.asMap(1, "one", 2, "two");
// Or for Immutable map 
ImmutableMap<Integer, String> = ImmutableMap.of(1, "one", 2, "two");

Declaration: I'm the developer of AbacusUtil.

versionCode vs versionName in Android Manifest

versionCode

A positive integer used as an internal version number. This number is used only to determine whether one version is more recent than another, with higher numbers indicating more recent versions. This is not the version number shown to users; that number is set by the versionName setting, below. The Android system uses the versionCode value to protect against downgrades by preventing users from installing an APK with a lower versionCode than the version currently installed on their device.

The value is a positive integer so that other apps can programmatically evaluate it, for example to check an upgrade or downgrade relationship. You can set the value to any positive integer you want, however you should make sure that each successive release of your app uses a greater value. You cannot upload an APK to the Play Store with a versionCode you have already used for a previous version.

versionName

A string used as the version number shown to users. This setting can be specified as a raw string or as a reference to a string resource.

The value is a string so that you can describe the app version as a .. string, or as any other type of absolute or relative version identifier. The versionName has no purpose other than to be displayed to users.

Url decode UTF-8 in Python

The data is UTF-8 encoded bytes escaped with URL quoting, so you want to decode, with urllib.parse.unquote(), which handles decoding from percent-encoded data to UTF-8 bytes and then to text, transparently:

from urllib.parse import unquote

url = unquote(url)

Demo:

>>> from urllib.parse import unquote
>>> url = 'example.com?title=%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%B2%D0%B0%D1%8F+%D0%B7%D0%B0%D1%89%D0%B8%D1%82%D0%B0'
>>> unquote(url)
'example.com?title=????????+??????'

The Python 2 equivalent is urllib.unquote(), but this returns a bytestring, so you'd have to decode manually:

from urllib import unquote

url = unquote(url).decode('utf8')

Decreasing height of bootstrap 3.0 navbar

If you guys are generating your stylesheets with LESS/SASS and are importing Bootstrap there, I've found that overriding the @navbar-height variable lets your set the height of the navbar, which is originally defined in the variables.less file.

enter image description here

git with development, staging and production branches

The thought process here is that you spend most of your time in development. When in development, you create a feature branch (off of development), complete the feature, and then merge back into development. This can then be added to the final production version by merging into production.

See A Successful Git Branching Model for more detail on this approach.

How to view Plugin Manager in Notepad++

Notepad v7.6 includes a Plugin Admin and from this you can install Plugin Manager(note1) but it doesn't work fine with npp v7.6(note2)

On the other hand Plugin Admin is only available on NPP "Setup version" and after following conditions

  • on Custom installation, "Plugin Admin" checkbox is enabled
  • on Choose Components "Don't use %APPDATA%" checkbox is disabled

Plugin Admin will place plugins at C:\ProgramData\Notepad++\plugins

(note1)Installation from Plugin Admin is not complete and \updater\gpup.exe is missing (note2) Plugin manager is not using new plugins path and folder structure; from version 7.6 npp Plugins will be stored in individual folders (having same name than file.dll)

If you want to use npp7.6 portable, you can copy updater folder from Setup version, copy plugins from Setup version, or copy Plugins from npp v<7.6 and place each one in a individual folder.

![Plugin Admin feature Installation npp76 Install Plugin manager from Plugin Admin

difference between css height : 100% vs height : auto

height:100% works if the parent container has a specified height property else, it won't work

Pick any kind of file via an Intent in Android

Samsung file explorer needs not only custom action (com.sec.android.app.myfiles.PICK_DATA), but also category part (Intent.CATEGORY_DEFAULT) and mime-type should be passed as extra.

Intent intent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
intent.putExtra("CONTENT_TYPE", "*/*");
intent.addCategory(Intent.CATEGORY_DEFAULT);

You can also use this action for opening multiple files: com.sec.android.app.myfiles.PICK_DATA_MULTIPLE Anyway here is my solution which works on Samsung and other devices:

public void openFile(String mimeType) {

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType(mimeType);
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        // special intent for Samsung file manager
        Intent sIntent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
         // if you want any file type, you can skip next line 
        sIntent.putExtra("CONTENT_TYPE", mimeType); 
        sIntent.addCategory(Intent.CATEGORY_DEFAULT);

        Intent chooserIntent;
        if (getPackageManager().resolveActivity(sIntent, 0) != null){
            // it is device with Samsung file manager
            chooserIntent = Intent.createChooser(sIntent, "Open file");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { intent});
        } else {
            chooserIntent = Intent.createChooser(intent, "Open file");
        }

        try {
            startActivityForResult(chooserIntent, CHOOSE_FILE_REQUESTCODE);
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(getApplicationContext(), "No suitable File Manager was found.", Toast.LENGTH_SHORT).show();
        }
    }

This solution works well for me, and maybe will be useful for someone else.

Install a module using pip for specific python version

If you have both 2.7 and 3.x versions of python installed, then just rename the python exe file of python 3.x version to something like - "python.exe" to "python3.exe". Now you can use pip for both versions individually. If you normally type "pip install " it will consider the 2.7 version by default. If you want to install it on the 3.x version you need to call the command as "python3 -m pip install ".