Programs & Examples On #Grouping

The process of grouping entities into collections of associated elements.

Group a list of objects by an attribute

You can sort like this:

    Collections.sort(studlist, new Comparator<Student>() {

        @Override
        public int compare(Student o1, Student o2) {
            return o1.getStud_location().compareTo(o2.getStud_location());
        }
    });

Assuming you also have the getter for location on your Student class.

SVG Positioning

Everything in the g element is positioned relative to the current transform matrix.

To move the content, just put the transformation in the g element:

<g transform="translate(20,2.5) rotate(10)">
    <rect x="0" y="0" width="60" height="10"/>
</g>

Links: Example from the SVG 1.1 spec

How to group an array of objects by key

There is absolutely no reason to download a 3rd party library to achieve this simple problem, like the above solutions suggest.

The one line version to group a list of objects by a certain key in es6:

const groupByKey = (list, key) => list.reduce((hash, obj) => ({...hash, [obj[key]]:( hash[obj[key]] || [] ).concat(obj)}), {})

The longer version that filters out the objects without the key:

_x000D_
_x000D_
function groupByKey(array, key) {
   return array
     .reduce((hash, obj) => {
       if(obj[key] === undefined) return hash; 
       return Object.assign(hash, { [obj[key]]:( hash[obj[key]] || [] ).concat(obj)})
     }, {})
}


var cars = [{'make':'audi','model':'r8','year':'2012'},{'make':'audi','model':'rs5','year':'2013'},{'make':'ford','model':'mustang','year':'2012'},{'make':'ford','model':'fusion','year':'2015'},{'make':'kia','model':'optima','year':'2012'}];

console.log(groupByKey(cars, 'make'))
_x000D_
_x000D_
_x000D_

NOTE: It appear the original question asks how to group cars by make, but omit the make in each group. So the short answer, without 3rd party libraries, would look like this:

_x000D_
_x000D_
const groupByKey = (list, key, {omitKey=false}) => list.reduce((hash, {[key]:value, ...rest}) => ({...hash, [value]:( hash[value] || [] ).concat(omitKey ? {...rest} : {[key]:value, ...rest})} ), {})

var cars = [{'make':'audi','model':'r8','year':'2012'},{'make':'audi','model':'rs5','year':'2013'},{'make':'ford','model':'mustang','year':'2012'},{'make':'ford','model':'fusion','year':'2015'},{'make':'kia','model':'optima','year':'2012'}];

console.log(groupByKey(cars, 'make', {omitKey:true}))
_x000D_
_x000D_
_x000D_

How to group subarrays by a column value?

for($i = 0 ; $i < count($arr)  ; $i++ )
{
    $tmpArr[$arr[$i]['id']] = $arr[$i]['id'];
}
$vmpArr = array_keys($tmpArr);
print_r($vmpArr);

How to select the first row for each group in MySQL?

When I write

SELECT AnotherColumn
FROM Table
GROUP BY SomeColumn
;

It works. IIRC in other RDBMS such statement is impossible, because a column that doesn't belongs to the grouping key is being referenced without any sort of aggregation.

This "quirk" behaves very closely to what I want. So I used it to get the result I wanted:

SELECT * FROM 
(
 SELECT * FROM `table`
 ORDER BY AnotherColumn
) t1
GROUP BY SomeColumn
;

How can I group data with an Angular filter?

First do a loop using a filter that will return only unique teams, and then a nested loop that returns all players per current team:

http://jsfiddle.net/plantface/L6cQN/

html:

<div ng-app ng-controller="Main">
    <div ng-repeat="playerPerTeam in playersToFilter() | filter:filterTeams">
        <b>{{playerPerTeam.team}}</b>
        <li ng-repeat="player in players | filter:{team: playerPerTeam.team}">{{player.name}}</li>        
    </div>
</div>

script:

function Main($scope) {
    $scope.players = [{name: 'Gene', team: 'team alpha'},
                    {name: 'George', team: 'team beta'},
                    {name: 'Steve', team: 'team gamma'},
                    {name: 'Paula', team: 'team beta'},
                    {name: 'Scruath of the 5th sector', team: 'team gamma'}];

    var indexedTeams = [];

    // this will reset the list of indexed teams each time the list is rendered again
    $scope.playersToFilter = function() {
        indexedTeams = [];
        return $scope.players;
    }

    $scope.filterTeams = function(player) {
        var teamIsNew = indexedTeams.indexOf(player.team) == -1;
        if (teamIsNew) {
            indexedTeams.push(player.team);
        }
        return teamIsNew;
    }
}

Group list by values

Howard's answer is concise and elegant, but it's also O(n^2) in the worst case. For large lists with large numbers of grouping key values, you'll want to sort the list first and then use itertools.groupby:

>>> from itertools import groupby
>>> from operator import itemgetter
>>> seq = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]]
>>> seq.sort(key = itemgetter(1))
>>> groups = groupby(seq, itemgetter(1))
>>> [[item[0] for item in data] for (key, data) in groups]
[['A', 'C'], ['B'], ['D', 'E']]

Edit:

I changed this after seeing eyequem's answer: itemgetter(1) is nicer than lambda x: x[1].

Spark difference between reduceByKey vs groupByKey vs aggregateByKey vs combineByKey

ReduceByKey reduceByKey(func, [numTasks])-

Data is combined so that at each partition there should be at least one value for each key. And then shuffle happens and it is sent over the network to some particular executor for some action such as reduce.

GroupByKey - groupByKey([numTasks])

It doesn't merge the values for the key but directly the shuffle process happens and here lot of data gets sent to each partition, almost same as the initial data.

And the merging of values for each key is done after the shuffle. Here lot of data stored on final worker node so resulting in out of memory issue.

AggregateByKey - aggregateByKey(zeroValue)(seqOp, combOp, [numTasks]) It is similar to reduceByKey but you can provide initial values when performing aggregation.

Use of reduceByKey

  • reduceByKey can be used when we run on large data set.

  • reduceByKey when the input and output value types are of same type over aggregateByKey

Moreover it recommended not to use groupByKey and prefer reduceByKey. For details you can refer here.

You can also refer this question to understand in more detail how reduceByKey and aggregateByKey.

using lodash .groupBy. how to add your own keys for grouped output?

another way

_.chain(data)
    .groupBy('color')
    .map((users, color) => ({ users, color }))
    .value();

Newtonsoft JSON Deserialize

A much easier solution: Using a dynamic type

As of Json.NET 4.0 Release 1, there is native dynamic support. You don't need to declare a class, just use dynamic :

dynamic jsonDe = JsonConvert.DeserializeObject(json);

All the fields will be available:

foreach (string typeStr in jsonDe.Type[0])
{
    // Do something with typeStr
} 

string t = jsonDe.t;
bool a = jsonDe.a;
object[] data = jsonDe.data;
string[][] type = jsonDe.Type;

With dynamic you don't need to create a specific class to hold your data.

SSH to Elastic Beanstalk instance

I also ran into the same problem awhile ago. I wanted to use the key file, but Amazon says somewhere that you cannot add a key file to an existing EC2 server. For the first Beanstalk application, Amazon preconfigures the application for you. You need to create a new application, and you can configure the EC2 server that runs the Beanstalk app to use an old pem file (ppk if using Putty), or you can create a new one. Now you should be able to SSH.

enter image description here

Then configure, then delete your old app.

Could not load file or assembly 'xxx' or one of its dependencies. An attempt was made to load a program with an incorrect format

Sounds like one part of the project is being built for x86-only while the rest is being built for any CPU/x64. This bit me, too. Are you running an x64 (or uh... IA64)?

Check the project properties and make sure everything is being built for "Any CPU". f you're in Visual Studio, you can check for everything by going to the "x86" or "Any CPU" menu (next to the "Debug"/"Release" menu) on the toolbar at the top of the screen and clicking "Configuration Manager..."

How to bind list to dataGridView?

Instead of create the new Container class you can use a dataTable.

DataTable dt = new DataTable();
dt.Columns.Add("My first column Name");

dt.Rows.Add(new object[] { "Item 1" });
dt.Rows.Add(new object[] { "Item number 2" });
dt.Rows.Add(new object[] { "Item number three" });

myDataGridView.DataSource = dt;

More about this problem you can find here: http://psworld.pl/Programming/BindingListOfString

How to split a single column values to multiple column values?

An alternative to Martin's

select LEFT(name, CHARINDEX(' ', name + ' ') -1),
       STUFF(name, 1, Len(Name) +1- CHARINDEX(' ',Reverse(name)), '')
from somenames

Sample table

create table somenames (Name varchar(100))
insert somenames select 'abcd efgh'
insert somenames select 'ijk lmn opq'
insert somenames select 'asd j. asdjja'
insert somenames select 'asb (asdfas) asd'
insert somenames select 'asd'
insert somenames select ''
insert somenames select null

What is HEAD in Git?

A branch is actually a pointer that holds a commit ID such as 17a5. HEAD is a pointer to a branch the user is currently working on.

HEAD has a reference filw which looks like this:

ref:

You can check these files by accessing .git/HEAD .git/refs that are in the repository you are working in.

Does svn have a `revert-all` command?

Use the recursive switch --recursive (-R)

svn revert -R .

Getting attribute using XPath

If you are using PostgreSQL, this is the right way to get it. This is just an assumption where as you have a book table TITLE and PRICE column with populated data. Here's the query

SELECT xpath('/bookstore/book/title/@lang', xmlforest(book.title AS title, book.price AS price), ARRAY[ARRAY[]::TEXT[]]) FROM book LIMIT 1;

Disable scrolling when touch moving certain element

Set the touch-action CSS property to none, which works even with passive event listeners:

touch-action: none;

Applying this property to an element will not trigger the default (scroll) behavior when the event is originating from that element.

What's the difference between map() and flatMap() methods in Java 8?

The function you pass to stream.map has to return one object. That means each object in the input stream results in exactly one object in the output stream.

The function you pass to stream.flatMap returns a stream for each object. That means the function can return any number of objects for each input object (including none). The resulting streams are then concatenated to one output stream.

How to determine if binary tree is balanced?

An empty tree is height-balanced. A non-empty binary tree T is balanced if:

1) Left subtree of T is balanced

2) Right subtree of T is balanced

3) The difference between heights of left subtree and right subtree is not more than 1.

/* program to check if a tree is height-balanced or not */
#include<stdio.h>
#include<stdlib.h>
#define bool int

/* A binary tree node has data, pointer to left child
   and a pointer to right child */
struct node
{
  int data;
  struct node* left;
  struct node* right;
};

/* The function returns true if root is balanced else false
   The second parameter is to store the height of tree.  
   Initially, we need to pass a pointer to a location with value 
   as 0. We can also write a wrapper over this function */
bool isBalanced(struct node *root, int* height)
{
  /* lh --> Height of left subtree 
     rh --> Height of right subtree */   
  int lh = 0, rh = 0;  

  /* l will be true if left subtree is balanced 
    and r will be true if right subtree is balanced */
  int l = 0, r = 0;

  if(root == NULL)
  {
    *height = 0;
     return 1;
  }

  /* Get the heights of left and right subtrees in lh and rh 
    And store the returned values in l and r */   
  l = isBalanced(root->left, &lh);
  r = isBalanced(root->right,&rh);

  /* Height of current node is max of heights of left and 
     right subtrees plus 1*/   
  *height = (lh > rh? lh: rh) + 1;

  /* If difference between heights of left and right 
     subtrees is more than 2 then this node is not balanced
     so return 0 */
  if((lh - rh >= 2) || (rh - lh >= 2))
    return 0;

  /* If this node is balanced and left and right subtrees 
    are balanced then return true */
  else return l&&r;
}


/* UTILITY FUNCTIONS TO TEST isBalanced() FUNCTION */

/* Helper function that allocates a new node with the
   given data and NULL left and right pointers. */
struct node* newNode(int data)
{
    struct node* node = (struct node*)
                                malloc(sizeof(struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;

    return(node);
}

int main()
{
  int height = 0;

  /* Constructed binary tree is
             1
           /   \
         2      3
       /  \    /
     4     5  6
    /
   7
  */   
  struct node *root = newNode(1);  
  root->left = newNode(2);
  root->right = newNode(3);
  root->left->left = newNode(4);
  root->left->right = newNode(5);
  root->right->left = newNode(6);
  root->left->left->left = newNode(7);

  if(isBalanced(root, &height))
    printf("Tree is balanced");
  else
    printf("Tree is not balanced");    

  getchar();
  return 0;
}

Time Complexity: O(n)

Does a valid XML file require an XML declaration?

In XML 1.0, the XML Declaration is optional. See section 2.8 of the XML 1.0 Recommendation, where it says it "should" be used -- which means it is recommended, but not mandatory. In XML 1.1, however, the declaration is mandatory. See section 2.8 of the XML 1.1 Recommendation, where it says "MUST" be used. It even goes on to state that if the declaration is absent, that automatically implies the document is an XML 1.0 document.

Note that in an XML Declaration the encoding and standalone are both optional. Only the version is mandatory. Also, these are not attributes, so if they are present they must be in that order: version, followed by any encoding, followed by any standalone.

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

If you don't specify the encoding in this way, XML parsers try to guess what encoding is being used. The XML 1.0 Recommendation describes one possible way character encoding can be autodetected. In practice, this is not much of a problem if the input is encoded as UTF-8, UTF-16 or US-ASCII. Autodetection doesn't work when it encounters 8-bit encodings that use characters outside the US-ASCII range (e.g. ISO 8859-1) -- avoid creating these if you can.

The standalone indicates whether the XML document can be correctly processed without the DTD or not. People rarely use it. These days, it is a bad to design an XML format that is missing information without its DTD.

Update:

A "prolog error/invalid utf-8 encoding" error indicates that the actual data the parser found inside the file did not match the encoding that the XML declaration says it is. Or in some cases the data inside the file did not match the autodetected encoding.

Since your file contains a byte-order-mark (BOM) it should be in UTF-16 encoding. I suspect that your declaration says <?xml version="1.0" encoding="UTF-8"?> which is obviously incorrect when the file has been changed into UTF-16 by NotePad. The simple solution is to remove the encoding and simply say <?xml version="1.0"?>. You could also edit it to say encoding="UTF-16" but that would be wrong for the original file (which wasn't in UTF-16) or if the file somehow gets changed back to UTF-8 or some other encoding.

Don't bother trying to remove the BOM -- that's not the cause of the problem. Using NotePad or WordPad to edit XML is the real problem!

How can I specify a display?

Please do NOT try to set $DISPLAY manually when connecting over SSH.
If you connect via SSH -X and $DISPLAY stays empty, this usually means that no encrypted channel could be established.

Most likely you are missing the package xauth or xorg-x11-xauth. Try to install it on the remote machine using:

sudo apt-get install xauth

or

sudo apt-get install xorg-x11-xauth

After that end and restart your SSH connection. Don't forget to use SSH -X so that X Window output is forwarded to your local machine.

Now try echo $DISPLAYagain to see if $DISPLAY has been set automatically by the SSH demon. It should show you a line with an IP address and a port.

How to start a stopped Docker container with a different command?

Add a check to the top of your Entrypoint script

Docker really needs to implement this as a new feature, but here's another workaround option for situations in which you have an Entrypoint that terminates after success or failure, which can make it difficult to debug.

If you don't already have an Entrypoint script, create one that runs whatever command(s) you need for your container. Then, at the top of this file, add these lines to entrypoint.sh:

# Run once, hold otherwise
if [ -f "already_ran" ]; then
    echo "Already ran the Entrypoint once. Holding indefinitely for debugging."
    cat
fi
touch already_ran

# Do your main things down here

To ensure that cat holds the connection, you may need to provide a TTY. I'm running the container with my Entrypoint script like so:

docker run -t --entrypoint entrypoint.sh image_name

This will cause the script to run once, creating a file that indicates it has already run (in the container's virtual filesystem). You can then restart the container to perform debugging:

docker start container_name

When you restart the container, the already_ran file will be found, causing the Entrypoint script to stall with cat (which just waits forever for input that will never come, but keeps the container alive). You can then execute a debugging bash session:

docker exec -i container_name bash

While the container is running, you can also remove already_ran and manually execute the entrypoint.sh script to rerun it, if you need to debug that way.

How to configure heroku application DNS to Godaddy Domain?

You can't use the naked domain of your-domain.com if it is not redirected to the www.your-domain.com. Heroku use the www.yourdomain.com which act here as a subdomain. So when you follow the default instruction to use your-domain.com then you will need to assign both of them.

We can actually assign only the naked domain without the www.your-domain.com. Use only your-domain.com when the domain's dns provider (NameServers) support ALIAS or ANAME for the @ Record to example.herokuapp.com without CNAME www.your-domain.com to it.

It will let you to point www.your-domain.com to other hosting separately (independent).

How to convert An NSInteger to an int?

Ta da:

NSInteger myInteger = 42;
int myInt = (int) myInteger;

NSInteger is nothing more than a 32/64 bit int. (it will use the appropriate size based on what OS/platform you're running)

Setting environment variables for accessing in PHP when using Apache

If your server is Ubuntu and Apache version is 2.4

Server version: Apache/2.4.29 (Ubuntu)

Then you export variables in "/etc/apache2/envvars" location.

Just like this below line, you need to add an extra line in "/etc/apache2/envvars" export GOROOT=/usr/local/go

iOS 7 status bar back to iOS 6 default style in iPhone app?

This might be too late to share, but I have something to contribute which might help someone, I was trying to sub-class the UINavigationBar and wanted to make it look like ios 6 with black status bar and status bar text in white.

Here is what I found working for that

        self.navigationController?.navigationBar.clipsToBounds = true
        self.navigationController?.navigationBar.translucent = false
        self.navigationController?.navigationBar.barStyle = .Black
        self.navigationController?.navigationBar.barTintColor = UIColor.whiteColor()

It made my status bar background black, status bar text white and navigation bar's color white.

iOS 9.3, XCode 7.3.1

How to enable cURL in PHP / XAMPP

Basic tip: After enabling the CURL in php.ini file, you need to restart the web server to make it work (my experience says).

HTML input field hint

I think for your situation, the easy and simple for your html input , you can probably add the attribute title

<input name="Username" value="Enter username.." type="text" size="20" maxlength="20" title="enter username">

JQuery .hasClass for multiple values in an if statement

var classes = $('html')[0].className;

if (classes.indexOf('m320') != -1 || classes.indexOf('m768') != -1) {
    //do something
}

What is the difference between find(), findOrFail(), first(), firstOrFail(), get(), list(), toArray()

  1. find($id) takes an id and returns a single model. If no matching model exist, it returns null.

  2. findOrFail($id) takes an id and returns a single model. If no matching model exist, it throws an error1.

  3. first() returns the first record found in the database. If no matching model exist, it returns null.

  4. firstOrFail() returns the first record found in the database. If no matching model exist, it throws an error1.

  5. get() returns a collection of models matching the query.

  6. pluck($column) returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists.

  7. toArray() converts the model/collection into a simple PHP array.


Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.

Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach loop is ok, put passing it to array_map is not. Similarly, if you type-hint an argument as array, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable typehint, which can be used to accept both arrays and collections.

If you ever want to get a plain array from a collection, call its all() method.


1 The error thrown by the findOrFail and firstOrFail methods is a ModelNotFoundException. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.

Increase max execution time for php

This is old question, but if somebody finds it today chances are php will be run via php-fpm and mod_fastcgi. In that case nothing here will help with extending execution time because Apache will terminate connection to a process which does not output anything for 30 seconds. Only way to extend it is to change -idle-timeout in apache (module/site/vhost) config.

FastCgiExternalServer /usr/lib/cgi-bin/php7-fcgi -socket /run/php/php7.0-fpm.sock -idle-timeout 900 -pass-header Authorization

More details - Increase PHP-FPM idle timeout setting

Concatenate text files with Windows command line, dropping leading lines

I use this, and it works well for me:

TYPE \\Server\Share\Folder\*.csv >> C:\Folder\ConcatenatedFile.csv

Of course, before every run, you have to DELETE C:\Folder\ConcatenatedFile.csv

The only issue is that if all files have headers, then it will be repeated in all files.

How to open Atom editor from command line in OS X?

When Atom installs it automatically creates a symlink in your /usr/local/bin. However in case it hasn't, you can create it yourself on your Mac

ln -s /Applications/Atom.app/Contents/Resources/app/atom.sh /usr/local/bin/atom

Now you can use atom folder_name to open a folder and atom file_name to open a file.

How to check if memcache or memcached is installed for PHP?

I combined, minified and extended (some more checks) the answers from @Bijay Rungta and @J.C. Inacio

<?php
if(!extension_loaded('Memcache'))
{
    die("Memcache extension is not loaded");
}

if (!class_exists('Memcache')) 
{
    die('Memcache class not available');
}

$memcacheObj = new Memcache;
if(!$memcacheObj)
{
    die('Could not create memcache object');
}

if (!$memcacheObj->connect('localhost')) 
{
    die('Could not connect to memcache server');
}

// testdata to store in memcache
$testData = array(
    'the' => 'cake',
    'is' => 'a lie',
);

// set data (if not present)
$aData = $memcacheObj->get('data');
if (!$aData) 
{
    if(!$memcacheObj->set('data', $testData, 0, 300))
    {
        die('Memcache could not set the data');
    }
}

// try to fetch data
$aData = $memcacheObj->get('data');
if (!$aData) 
{
    die('Memcache is not responding with data');
}

if($aData !== $testData)
{
    die('Memcache is responding but with wrong data');
}

die('Memcache is working fine');

How to verify Facebook access token?

You can simply request https://graph.facebook.com/me?access_token=xxxxxxxxxxxxxxxxx if you get an error, the token is invalid. If you get a JSON object with an id property then it is valid.

Unfortunately this will only tell you if your token is valid, not if it came from your app.

MySQL: update a field only if condition is met

found the solution with AND condition:

  $trainstrength = "UPDATE user_character SET strength_trains = strength_trains + 1, trained_strength = trained_strength +1, character_gold = character_gold - $gold_to_next_strength WHERE ID = $currentUser AND character_gold > $gold_to_next_strength";

Embed image in a <button> element

The simplest way to put an image into a button:

<button onclick="myFunction()"><img src="your image name here.png"></button>

This will automatically resize the button to the size of the image.

What is wrong with my SQL here? #1089 - Incorrect prefix key

There is a simple way of doing it. This may not be the expert answer and it may not work for everyone but it did for me.

Uncheck all primary and unique check boxes, jut create a plain simple table.

When phpmyadmin (or other) shows you the table structure, make the column primary by the given button.

Then click on change and edit the settings of that or other colums like 'unique' etc.

VSCode: How to Split Editor Vertically

By default, editor groups are laid out in vertical columns (e.g. when you split an editor to open it to the side). You can easily arrange editor groups in any layout you like, both vertically and horizontally:

To support flexible layouts, you can create empty editor groups. By default, closing the last editor of an editor group will also close the group itself, but you can change this behavior with the new setting workbench.editor.closeEmptyGroups: false:

enter image description here

There are a predefined set of editor layouts in the new View > Editor Layout menu:

enter image description here

Editors that open to the side (for example by clicking the editor toolbar Split Editor action) will by default open to the right hand side of the active editor. If you prefer to open editors below the active one, configure the new setting workbench.editor.openSideBySideDirection: down.

There are many keyboard commands for adjusting the editor layout with the keyboard alone, but if you prefer to use the mouse, drag and drop is a fast way to split the editor into any direction:

enter image description here

Keyboard shortcuts# Here are some handy keyboard shortcuts to quickly navigate between editors and editor groups.

If you'd like to modify the default keyboard shortcuts, see Key Bindings for details.

??? go to the right editor.
??? go to the left editor.
^Tab open the next editor in the editor group MRU list.
^?Tab open the previous editor in the editor group MRU list.
?1 go to the leftmost editor group.
?2 go to the center editor group.
?3 go to the rightmost editor group.
unassigned go to the previous editor group.
unassigned go to the next editor group.
?W close the active editor.
?K W close all editors in the editor group.
?K ?W close all editors.

Add a new item to recyclerview programmatically?

First add your item to mItems and then use:

mAdapter.notifyItemInserted(mItems.size() - 1);

this method is better than using:

mAdapter.notifyDataSetChanged();

in performance.

iOS 7's blurred overlay effect using CSS?

You made me want to try, so I did, check out the example here:

http://codepen.io/Edo_B/pen/cLbrt

Using:

  1. HW Accelerated CSS filters
  2. JS for class assigning and arrow key events
  3. Images CSS Clip property

that's it.

I also believe this could be done dynamically for any screen if using canvas to copy the current dom and blurring it.

How is returning the output of a function different from printing it?

Unfortunately, there is a character limit so this will be in many parts. First thing to note is that return and print are statements, not functions, but that is just semantics.

I’ll start with a basic explanation. print just shows the human user a string representing what is going on inside the computer. The computer cannot make use of that printing. return is how a function gives back a value. This value is often unseen by the human user, but it can be used by the computer in further functions.

On a more expansive note, print will not in any way affect a function. It is simply there for the human user’s benefit. It is very useful for understanding how a program works and can be used in debugging to check various values in a program without interrupting the program.

return is the main way that a function returns a value. All functions will return a value, and if there is no return statement (or yield but don’t worry about that yet), it will return None. The value that is returned by a function can then be further used as an argument passed to another function, stored as a variable, or just printed for the benefit of the human user. Consider these two programs:

def function_that_prints():
    print "I printed"

def function_that_returns():
    return "I returned"

f1 = function_that_prints()
f2 = function_that_returns()

print "Now let us see what the values of f1 and f2 are"

print f1 --->None

print f2---->"I returned"

When function_that_prints ran, it automatically printed to the console "I printed". However, the value stored in f1 is None because that function had no return statement.

When function_that_returns ran, it did not print anything to the console. However, it did return a value, and that value was stored in f2. When we printed f2 at the end of the code, we saw "I returned"

How can I throw CHECKED exceptions from inside Java 8 streams?

The simple answer to your question is: You can't, at least not directly. And it's not your fault. Oracle messed it up. They cling on the concept of checked exceptions, but inconsistently forgot to take care of checked exceptions when designing the functional interfaces, streams, lambda etc. That's all grist to the mill of experts like Robert C. Martin who call checked exceptions a failed experiment.

In my opinion, this is a huge bug in the API and a minor bug in the language specification.

The bug in the API is that it provides no facility for forwarding checked exceptions where this actually would make an awful lot of sense for functional programming. As I will demonstrate below, such a facility would've been easily possible.

The bug in the language specification is that it does not allow a type parameter to infer a list of types instead of a single type as long as the type parameter is only used in situations where a list of types is permissable (throws clause).

Our expectation as Java programmers is that the following code should compile:

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

public class CheckedStream {
    // List variant to demonstrate what we actually had before refactoring.
    public List<Class> getClasses(final List<String> names) throws ClassNotFoundException {
        final List<Class> classes = new ArrayList<>();
        for (final String name : names)
            classes.add(Class.forName(name));
        return classes;
    }

    // The Stream function which we want to compile.
    public Stream<Class> getClasses(final Stream<String> names) throws ClassNotFoundException {
        return names.map(Class::forName);
    }
}

However, it gives:

cher@armor1:~/playground/Java/checkedStream$ javac CheckedStream.java 
CheckedStream.java:13: error: incompatible thrown types ClassNotFoundException in method reference
        return names.map(Class::forName);
                         ^
1 error

The way in which the functional interfaces are defined currently prevents the Compiler from forwarding the exception - there is no declaration which would tell Stream.map() that if Function.apply() throws E, Stream.map() throws E as well.

What's missing is a declaration of a type parameter for passing through checked exceptions. The following code shows how such a pass-through type parameter actually could have been declared with the current syntax. Except for the special case in the marked line, which is a limit discussed below, this code compiles and behaves as expected.

import java.io.IOException;
interface Function<T, R, E extends Throwable> {
    // Declare you throw E, whatever that is.
    R apply(T t) throws E;
}   

interface Stream<T> {
    // Pass through E, whatever mapper defined for E.
    <R, E extends Throwable> Stream<R> map(Function<? super T, ? extends R, E> mapper) throws E;
}   

class Main {
    public static void main(final String... args) throws ClassNotFoundException {
        final Stream<String> s = null;

        // Works: E is ClassNotFoundException.
        s.map(Class::forName);

        // Works: E is RuntimeException (probably).
        s.map(Main::convertClass);

        // Works: E is ClassNotFoundException.
        s.map(Main::throwSome);

        // Doesn't work: E is Exception.
        s.map(Main::throwSomeMore);  // error: unreported exception Exception; must be caught or declared to be thrown
    }   

    public static Class convertClass(final String s) {
        return Main.class;
    }   

    static class FooException extends ClassNotFoundException {}

    static class BarException extends ClassNotFoundException {}

    public static Class throwSome(final String s) throws FooException, BarException {
        throw new FooException();
    }   

    public static Class throwSomeMore(final String s) throws ClassNotFoundException, IOException  {
        throw new FooException();
    }   
}   

In the case of throwSomeMore we would like to see IOException being missed, but it actually misses Exception.

This is not perfect because type inference seems to be looking for a single type, even in the case of exceptions. Because the type inference needs a single type, E needs to resolve to a common super of ClassNotFoundException and IOException, which is Exception.

A tweak to the definition of type inference is needed so that the compiler would look for multiple types if the type parameter is used where a list of types is permissible (throws clause). Then the exception type reported by the compiler would be as specific as the original throws declaration of the checked exceptions of the referenced method, not a single catch-all super type.

The bad news is that this means that Oracle messed it up. Certainly they won't break user-land code, but introducing exception type parameters to the existing functional interfaces would break compilation of all user-land code that uses these interfaces explicitly. They'll have to invent some new syntax sugar to fix this.

The even worse news is that this topic was already discussed by Brian Goetz in 2010 https://blogs.oracle.com/briangoetz/entry/exception_transparency_in_java (new link: http://mail.openjdk.java.net/pipermail/lambda-dev/2010-June/001484.html) but I'm informed that this investigation ultimately did not pan out, and that there is no current work at Oracle that I know of to mitigate the interactions between checked exceptions and lambdas.

What is the shortest function for reading a cookie by name in JavaScript?

How about this one?

function getCookie(k){var v=document.cookie.match('(^|;) ?'+k+'=([^;]*)(;|$)');return v?v[2]:null}

Counted 89 bytes without the function name.

How to execute a remote command over ssh with arguments?

Do it this way instead:

function mycommand {
    ssh [email protected] "cd testdir;./test.sh \"$1\""
}

You still have to pass the whole command as a single string, yet in that single string you need to have $1 expanded before it is sent to ssh so you need to use "" for it.

Update

Another proper way to do this actually is to use printf %q to properly quote the argument. This would make the argument safe to parse even if it has spaces, single quotes, double quotes, or any other character that may have a special meaning to the shell:

function mycommand {
    printf -v __ %q "$1"
    ssh [email protected] "cd testdir;./test.sh $__"
}
  • When declaring a function with function, () is not necessary.
  • Don't comment back about it just because you're a POSIXist.

How to change the background color on a input checkbox with css?

I always use pseudo elements :before and :after for changing the appearance of checkboxes and radio buttons. it's works like a charm.

Refer this link for more info

CODEPEN

Steps

  1. Hide the default checkbox using css rules like visibility:hidden or opacity:0 or position:absolute;left:-9999px etc.
  2. Create a fake checkbox using :before element and pass either an empty or a non-breaking space '\00a0';
  3. When the checkbox is in :checked state, pass the unicode content: "\2713", which is a checkmark;
  4. Add :focus style to make the checkbox accessible.
  5. Done

Here is how I did it.

_x000D_
_x000D_
.box {_x000D_
  background: #666666;_x000D_
  color: #ffffff;_x000D_
  width: 250px;_x000D_
  padding: 10px;_x000D_
  margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
  margin: 1.5em 0;_x000D_
  padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
  visibility: hidden;_x000D_
}_x000D_
label {_x000D_
  cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
  border: 1px solid #333;_x000D_
  content: "\00a0";_x000D_
  display: inline-block;_x000D_
  font: 16px/1em sans-serif;_x000D_
  height: 16px;_x000D_
  margin: 0 .25em 0 0;_x000D_
  padding: 0;_x000D_
  vertical-align: top;_x000D_
  width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
  background: #fff;_x000D_
  color: #333;_x000D_
  content: "\2713";_x000D_
  text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
    outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
  <div class="box">_x000D_
    <p>_x000D_
      <input type="checkbox" id="c1" name="cb">_x000D_
      <label for="c1">Option 01</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c2" name="cb">_x000D_
      <label for="c2">Option 02</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c3" name="cb">_x000D_
      <label for="c3">Option 03</label>_x000D_
    </p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Much more stylish using :before and :after

_x000D_
_x000D_
body{_x000D_
  font-family: sans-serif;  _x000D_
}_x000D_
_x000D_
.container {_x000D_
    margin-top: 50px;_x000D_
    margin-left: 20px;_x000D_
    margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
    width: 100%;_x000D_
    margin: 15px auto;_x000D_
    position: relative;_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
    width: auto;_x000D_
    opacity: 0.00000001;_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
    position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    top: 0;_x000D_
    margin: 4px;_x000D_
    width: 22px;_x000D_
    height: 22px;_x000D_
    transition: transform 0.28s ease;_x000D_
    border-radius: 3px;_x000D_
    border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
  content: '';_x000D_
    display: block;_x000D_
    width: 10px;_x000D_
    height: 5px;_x000D_
    border-bottom: 2px solid #7bbe72;_x000D_
    border-left: 2px solid #7bbe72;_x000D_
    -webkit-transform: rotate(-45deg) scale(0);_x000D_
    transform: rotate(-45deg) scale(0);_x000D_
    transition: transform ease 0.25s;_x000D_
    will-change: transform;_x000D_
    position: absolute;_x000D_
    top: 12px;_x000D_
    left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
    color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
    -webkit-transform: rotate(-45deg) scale(1);_x000D_
    transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
    min-height: 34px;_x000D_
    display: block;_x000D_
    padding-left: 40px;_x000D_
    margin-bottom: 0;_x000D_
    font-weight: normal;_x000D_
    cursor: pointer;_x000D_
    vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    -webkit-transform: translateY(-50%);_x000D_
    transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
    outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox" name="" value="">_x000D_
     <label for="checkbox"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
_x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox2" name="" value="">_x000D_
     <label for="checkbox2"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to open this .DB file?

You can use a tool like the TrIDNet - File Identifier to look for the Magic Number and other telltales, if the file format is in it's database it may tell you what it is for.

However searching the definitions did not turn up anything for the string "FLDB", but it checks more than magic numbers so it is worth a try.

If you are using Linux File is a command that will do a similar task.

The other thing to try is if you have access to the program that generated this file, there may be DLL's or EXE's from the database software that may contain meta information about the dll's creator which could give you a starting point for looking for software that can read the file outside of the program that originally created the .db file.

How to pass in parameters when use resource service?

I think I see your problem, you need to use the @ syntax to define parameters you will pass in this way, also I'm not sure what loginID or password are doing you don't seem to define them anywhere and they are not being used as URL parameters so are they being sent as query parameters?

This is what I can suggest based on what I see so far:

.factory('MagComments', function ($resource) {
    return $resource('http://localhost/dooleystand/ci/api/magCommenct/:id', {
      loginID : organEntity,
      password : organCommpassword,
      id : '@magId'
    });
  })

The @magId string will tell the resource to replace :id with the property magId on the object you pass it as parameters.

I'd suggest reading over the documentation here (I know it's a bit opaque) very carefully and looking at the examples towards the end, this should help a lot.

Variable name as a string in Javascript

Typically, you would use a hash table for a situation where you want to map a name to some value, and be able to retrieve both.

_x000D_
_x000D_
var obj = { myFirstName: 'John' };_x000D_
obj.foo = 'Another name';_x000D_
for(key in obj)_x000D_
    console.log(key + ': ' + obj[key]);
_x000D_
_x000D_
_x000D_

Update ViewPager dynamically?

I had a similar problem but don't want to trust on the existing solutions (hard coded tag names etc.) and I couldn't make M-WaJeEh's solution work for me. Here is my solution:

I keep references to the fragments created in getItem in an array. This works fine as long as the activity is not destroyed due to configurationChange or lack of memory or whatever (--> when coming back to the activity, fragments return to their last state without 'getItem' being called again and thus without updating the array).

To avoid this problem I implemented instantiateItem(ViewGroup, int) and update my array there, like this:

        @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Object o = super.instantiateItem(container, position);
        if(o instanceof FragmentX){
            myFragments[0] = (FragmentX)o;
        }else if(o instanceof FragmentY){
            myFragments[1] = (FragmentY)o;
        }else if(o instanceof FragmentZ){
            myFragments[2] = (FragmentZ)o;
        }
        return o;
    }

So, on the one hand I'm happy that I found a solution that works for me and wanted to share it with you, but I also wanted to ask whether somebody else tried something similar and whether there is any reason why I shouldn't do it like that? So far it works very good for me...

Monitor network activity in Android Phones

Without root, you can use debug proxies like Charlesproxy&Co.

Django: Model Form "object has no attribute 'cleaned_data'"

For some reason, you're re-instantiating the form after you check is_valid(). Forms only get a cleaned_data attribute when is_valid() has been called, and you haven't called it on this new, second instance.

Just get rid of the second form = SearchForm(request.POST) and all should be well.

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

I'd use pathos.multiprocesssing, instead of multiprocessing. pathos.multiprocessing is a fork of multiprocessing that uses dill. dill can serialize almost anything in python, so you are able to send a lot more around in parallel. The pathos fork also has the ability to work directly with multiple argument functions, as you need for class methods.

>>> from pathos.multiprocessing import ProcessingPool as Pool
>>> p = Pool(4)
>>> class Test(object):
...   def plus(self, x, y): 
...     return x+y
... 
>>> t = Test()
>>> p.map(t.plus, x, y)
[4, 6, 8, 10]
>>> 
>>> class Foo(object):
...   @staticmethod
...   def work(self, x):
...     return x+1
... 
>>> f = Foo()
>>> p.apipe(f.work, f, 100)
<processing.pool.ApplyResult object at 0x10504f8d0>
>>> res = _
>>> res.get()
101

Get pathos (and if you like, dill) here: https://github.com/uqfoundation

Form Google Maps URL that searches for a specific places near specific coordinates

You can use the new URL for Google Maps: https://www.google.com/maps/@39.774769,-74.86084,18z equivalent to http://maps.google.com/?ll=39.774769,-74.86084.

39.774769 is the latitude and -74.86084 is longitude and 18z is 18 zoom level.

How do you force a CIFS connection to unmount

umount -f -t cifs -l /mnt &

Be careful of &, let umount run in background. umount will detach filesystem first, so you will find nothing abount /mnt. If you run df command, then it will umount /mnt forcibly.

how to remove key+value from hash in javascript

Another option may be this John Resig remove method. can better fit what you need. if you know the index in the array.

SQL Query NOT Between Two Dates

What you are currently doing is checking whether neither the start_date nor the end_date fall within the range of the dates given.

I guess what you are really looking for is a record which does not fit in the date range given. If so, use the query below.

SELECT * 
    FROM `test_table` 
    WHERE  CAST('2009-12-15' AS DATE) > start_date  AND  CAST('2010-01-02' AS DATE) < end_date

Set the maximum character length of a UITextField in Swift

If you have multiple textField that have various length checks on one page I've found an easy and short solution.

class MultipleTextField: UIViewController {

    let MAX_LENGTH_TEXTFIELD_A = 10
    let MAX_LENGTH_TEXTFIELD_B = 11

    lazy var textFieldA: UITextField = {
        let textField = UITextField()
        textField.tag = MAX_LENGTH_TEXTFIELD_A
        textField.delegate = self
        return textField
    }()
    lazy var textFieldB: UITextField = {
        let textField = UITextField()
        textField.tag = MAX_LENGTH_TEXTFIELD_B
        textField.delegate = self
        return textField
    }()
}

extension MultipleTextField: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        return (range.location < textField.tag) && (string.count < textField.tag)
    }
}

Search for a string in all tables, rows and columns of a DB

I think this can be an easiest way to find a string in all rows of your database -without using cursors and FOR XML-.

CREATE PROCEDURE SPFindAll (@find VARCHAR(max) = '')
AS
BEGIN
    SET NOCOUNT ON;
    --
    DECLARE @query VARCHAR(max) = ''

    SELECT  @query = @query + 
            CASE 
                WHEN @query = '' THEN '' 
                ELSE ' UNION ALL '
            END +
            'SELECT ''' + s.name + ''' As schemaName, ''' + t.name + ''' As tableName, ''' + c.name + ''' As ColumnName, [' + c.name + '] COLLATE DATABASE_DEFAULT As [Data] FROM [' + s.name + '].[' + t.name + '] WHERE [' + c.name + '] Like ''%' + @find + '%'''
    FROM 
        sys.schemas s
        INNER JOIN
        sys.tables t ON s.[schema_id] = t.[schema_id]
        INNER JOIN 
        sys.columns c ON t.[object_id] = c.[object_id]
        INNER JOIN
        sys.types ty ON c.user_type_id = ty.user_type_id
    WHERE
        ty.name LIKE '%char'

    EXEC(@query)
END

By creating this stored procedure you can run it for any string you want to find like this:

EXEC SPFindAll 'Hello World'

The result will be like this:

schemaName | tableName | columnName | Data
-----------+-----------+------------+-----------------------
schema1    | Table1    | Column1    | Hello World
schema1    | Table1    | Column1    | Hello World!
schema1    | Table2    | Column1    | I say "Hello World".
schema1    | Table2    | Column2    | Hello World

when exactly are we supposed to use "public static final String"?

You do not have to use final, but the final is making clear to everyone else - including the compiler - that this is a constant, and that's the good practice in it.

Why people doe that even if the constant will be used only in one place and only in the same class: Because in many cases it still makes sense. If you for example know it will be final during program run, but you intend to change the value later and recompile (easier to find), and also might use it more often later-on. It is also informing other programmers about the core values in the program flow at a prominent and combined place.

An aspect the other answers are missing out unfortunately, is that using the combination of public final needs to be done very carefully, especially if other classes or packages will use your class (which can be assumed because it is public).

Here's why:

  1. Because it is declared as final, the compiler will inline this field during compile time into any compilation unit reading this field. So far, so good.
  2. What people tend to forget is, because the field is also declared public, the compiler will also inline this value into any other compile unit. That means other classes using this field.

What are the consequences?

Imagine you have this:

class Foo {
  public static final String VERSION = "1.0";
}

class Bar {
  public static void main(String[] args) {
    System.out.println("I am using version " + Foo.VERSION);
  }
}

After compiling and running Bar, you'll get:

I am using version 1.0

Now, you improve Foo and change the version to "1.1". After recompiling Foo, you run Bar and get this wrong output:

I am using version 1.0

This happens, because VERSION is declared final, so the actual value of it was already in-lined in Bar during the first compile run. As a consequence, to let the example of a public static final ... field propagate properly after actually changing what was declared final (you lied!;), you'd need to recompile every class using it.

I've seen this a couple of times and it is really hard to debug.

If by final you mean a constant that might change in later versions of your program, a better solution would be this:

class Foo {
  private static String version = "1.0";
  public static final String getVersion() {
    return version;
  }
}

The performance penalty of this is negligible, since JIT code generator will inline it at run-time.

Calling a class function inside of __init__

If I'm not wrong, both functions are part of your class, you should use it like this:

class MyClass():
    def __init__(self, filename):
        self.filename = filename 

        self.stat1 = None
        self.stat2 = None
        self.stat3 = None
        self.stat4 = None
        self.stat5 = None
        self.parse_file()

    def parse_file(self):
        #do some parsing
        self.stat1 = result_from_parse1
        self.stat2 = result_from_parse2
        self.stat3 = result_from_parse3
        self.stat4 = result_from_parse4
        self.stat5 = result_from_parse5

replace your line:

parse_file() 

with:

self.parse_file()

How to check if a map contains a key in Go?

have a look at this snippet of code

    nameMap := make(map[string]int)
    nameMap["river"] = 33
    v ,exist := nameMap["river"]
    if exist {
        fmt.Println("exist ",v)
    }

jQuery: Check if div with certain class name exists

You can simplify this by checking the first object that is returned from JQuery like so:

if ($(".mydivclass")[0]){
    // Do something if class exists
} else {
    // Do something if class does not exist
}

In this case if there is a truthy value at the first ([0]) index, then assume class exists.

Edit 04/10/2013: I've created a jsperf test case here.

Get push notification while App in foreground iOS

As @Danial Martine said iOS won't show a notification banner/alert. That's by design. But if really have to do it then there is one way . I have also achieve this by same.

1.Download the parse frame work from Parse FrameWork

2.Import #import <Parse/Parse.h>

3.Add following code to your didReceiveRemoteNotification Method

 - (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    [PFPush handlePush:userInfo];
}

PFPush will take care how to handle the remote notification . If App is in foreground this shows the alert otherwise it shows the notification at the top.

Creating a .p12 file

The openssl documentation says that file supplied as the -in argument must be in PEM format.

Turns out that, contrary to the CA's manual, the certificate returned by the CA which I stored in myCert.cer is not PEM format rather it is PKCS7.

In order to create my .p12, I had to first convert the certificate to PEM:

openssl pkcs7 -in myCert.cer -print_certs -out certs.pem

and then execute

openssl pkcs12 -export -out keyStore.p12 -inkey myKey.pem -in certs.pem

Binding value to style

Try [attr.style]="changeBackground()"

How to insert new row to database with AUTO_INCREMENT column without specifying column names?

Even better, use DEFAULT instead of NULL. You want to store the default value, not a NULL that might trigger a default value.

But you'd better name all columns, with a piece of SQL you can create all the INSERT, UPDATE and DELETE's you need. Just check the information_schema and construct the queries you need. There is no need to do it all by hand, SQL can help you out.

What's the difference between an Angular component and module

Components control views (html). They also communicate with other components and services to bring functionality to your app.

Modules consist of one or more components. They do not control any html. Your modules declare which components can be used by components belonging to other modules, which classes will be injected by the dependency injector and which component gets bootstrapped. Modules allow you to manage your components to bring modularity to your app.

How to submit a form on enter when the textarea has focus?

You can't do this without JavaScript. Stackoverflow is using the jQuery JavaScript library which attachs functions to HTML elements on page load.

Here's how you could do it with vanilla JavaScript:

<textarea onkeydown="if (event.keyCode == 13) { this.form.submit(); return false; }"></textarea>

Keycode 13 is the enter key.

Here's how you could do it with jQuery like as Stackoverflow does:

<textarea class="commentarea"></textarea>

with

$(document).ready(function() {
    $('.commentarea').keydown(function(event) {
        if (event.which == 13) {
            this.form.submit();
            event.preventDefault();
         }
    });
});

Delete all data rows from an Excel table (apart from the first)

This is how I clear the data:

Sub Macro3()
    With Sheet1.ListObjects("Table1")
        If Not .DataBodyRange Is Nothing Then
            .DataBodyRange.Delete
        End If
    End With
End Sub

How do I escape ampersands in batch files?

& is used to separate commands. Therefore you can use ^ to escape the &.

How do I capture the output of a script if it is being ran by the task scheduler?

Try this as the command string in Task Scheduler:

cmd /c yourscript.cmd > logall.txt

Convert Python program to C/C++ code?

I know this is an older thread but I wanted to give what I think to be helpful information.

I personally use PyPy which is really easy to install using pip. I interchangeably use Python/PyPy interpreter, you don't need to change your code at all and I've found it to be roughly 40x faster than the standard python interpreter (Either Python 2x or 3x). I use pyCharm Community Edition to manage my code and I love it.

I like writing code in python as I think it lets you focus more on the task than the language, which is a huge plus for me. And if you need it to be even faster, you can always compile to a binary for Windows, Linux, or Mac (not straight forward but possible with other tools). From my experience, I get about 3.5x speedup over PyPy when compiling, meaning 140x faster than python. PyPy is available for Python 3x and 2x code and again if you use an IDE like PyCharm you can interchange between say PyPy, Cython, and Python very easily (takes a little of initial learning and setup though).

Some people may argue with me on this one, but I find PyPy to be faster than Cython. But they're both great choices though.

Edit: I'd like to make another quick note about compiling: when you compile, the resulting binary is much bigger than your python script as it builds all dependencies into it, etc. But then you get a few distinct benefits: speed!, now the app will work on any machine (depending on which OS you compiled for, if not all. lol) without Python or libraries, it also obfuscates your code and is technically 'production' ready (to a degree). Some compilers also generate C code, which I haven't really looked at or seen if it's useful or just gibberish. Good luck.

Hope that helps.

How to check if a table contains an element in Lua?

Given your representation, your function is as efficient as can be done. Of course, as noted by others (and as practiced in languages older than Lua), the solution to your real problem is to change representation. When you have tables and you want sets, you turn tables into sets by using the set element as the key and true as the value. +1 to interjay.

Gradle Sync failed could not find constraint-layout:1.0.0-alpha2

Just to make sure that in studio version 2.3 you won't see a dropdown near constraint-layout in sdk tools, it will by default install the latest version

To get the desired version check the box saying show package details and boom you can now choose the desired version you want to install

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

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

How to write URLs in Latex?

Here is all the information you need in order to format clickable hyperlinks in LaTeX:

http://en.wikibooks.org/wiki/LaTeX/Hyperlinks

Essentially, you use the hyperref package and use the \url or \href tag depending on what you're trying to achieve.

How to remove square brackets from list in Python?

Yes, there are several ways to do it. For instance, you can convert the list to a string and then remove the first and last characters:

l = ['a', 2, 'c']
print str(l)[1:-1]
'a', 2, 'c'

If your list contains only strings and you want remove the quotes too then you can use the join method as has already been said.

Entity Framework The underlying provider failed on Open

I get this exception often while running on my development machine, especially after I make a code change, rebuild the code, then execute an associated web page(s). However, the problem goes away for me if I bump up the CommandTimeout parameter to 120 seconds or more (e.g., set context.Database.CommandTimeout = 120 before the LINQ statement). While this was originally asked 3 years ago, it may help someone looking for an answer. My theory is VisualStudio takes time to convert the built binary libraries to machine code, and times out when attempting to connect to SQL Server following that just-in-time compile.

How to Identify Microsoft Edge browser via CSS?

/* Microsoft Edge Browser 12-18 (All versions before Chromium) */

This one should work:

@supports (-ms-ime-align:auto) {
    .selector {
        property: value;
    }
}

For more see: Browser Strangeness

Pass array to where in Codeigniter Active Record

From the Active Record docs:

$this->db->where_in();

Generates a WHERE field IN ('item', 'item') SQL query joined with AND if appropriate

$names = array('Frank', 'Todd', 'James');
$this->db->where_in('username', $names);
// Produces: WHERE username IN ('Frank', 'Todd', 'James')

PowerShell: how to grep command output?

If you truly want to "grep" the formatted output (display strings) then go with Mike's approach. There are definitely times where this comes in handy. However if you want to try embracing PowerShell's object pipeline nature, then try this. First, check out the properties on the objects flowing down the pipeline:

PS> alias | Get-Member


   TypeName: System.Management.Automation.AliasInfo

Name                MemberType     Definition
----                ----------     ----------
Equals              Method         bool Equals(System.Object obj)
GetHashCode         Method         int GetHashCode()
GetType             Method         type GetType()
ToString            Method         string ToString()
<snip>
*Definition*        Property       System.String Definition {get;}
<snip>

Note the Definition property which is a header you see when you display the output of Get-Alias (alias) e.g.:

PS> alias

CommandType     Name           *Definition*
-----------     ----           ----------
Alias           %              ForEach-Object
<snip>

Usually the header title matches the property name but not always. That is where using Get-Member comes in handy. It shows you what you need to "script" against. Now if what you want to "grep" is the Definition property contents then consider this. Rather than just grepping that one property's value, you can instead filter each AliasInfo object in the pipepline by the contents of this property and you can use a regex to do it e.g.:

PS> alias | Where-Object {$_.Definition -match 'alias'}

CommandType     Name                   Definition
-----------     ----                   ----------
Alias           epal                   Export-Alias
Alias           gal                    Get-Alias
Alias           ipal                   Import-Alias
Alias           nal                    New-Alias
Alias           sal                    Set-Alias

In this example I use the Where-Object cmdlet to filter objects based on some arbitrary script. In this case, I filter by the Defintion property matched against the regex 'alias'. Only those objects that return true for that filter are allowed to propagate down the pipeline and get formatted for display on the host.

BTW if you're typing this, then you can use one of two aliases for Where-Object - 'Where' or '?'. For example:

PS> gal | ?{$_.Definition -match '-Item*'}

Convert a number to 2 decimal places in Java

try this new DecimalFormat("#.00");

update:

    double angle = 20.3034;

    DecimalFormat df = new DecimalFormat("#.00");
    String angleFormated = df.format(angle);
    System.out.println(angleFormated); //output 20.30

Your code wasn't using the decimalformat correctly

The 0 in the pattern means an obligatory digit, the # means optional digit.

update 2: check bellow answer

If you want 0.2677 formatted as 0.27 you should use new DecimalFormat("0.00"); otherwise it will be .27

Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running?

I installed docker from snap repository. So I also had to start from snap (running Ubuntu).

sudo snap start docker

Otherwise you can also install it from their repositories.

How to search file text for a pattern and replace it with a given value

If you need to do substitutions across line boundaries, then using ruby -pi -e won't work because the p processes one line at a time. Instead, I recommend the following, although it could fail with a multi-GB file:

ruby -e "file='translation.ja.yml'; IO.write(file, (IO.read(file).gsub(/\s+'$/, %q('))))"

The is looking for white space (potentially including new lines) following by a quote, in which case it gets rid of the whitespace. The %q(')is just a fancy way of quoting the quote character.

How to unmount, unrender or remove a component, from itself in a React/Redux/Typescript notification message

In most cases, it is enough just to hide the element, for example in this way:

export default class ErrorBoxComponent extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            isHidden: false
        }
    }

    dismiss() {
        this.setState({
            isHidden: true
        })
    }

    render() {
        if (!this.props.error) {
            return null;
        }

        return (
            <div data-alert className={ "alert-box error-box " + (this.state.isHidden ? 'DISPLAY-NONE-CLASS' : '') }>
                { this.props.error }
                <a href="#" className="close" onClick={ this.dismiss.bind(this) }>&times;</a>
            </div>
        );
    }
}

Or you may render/rerender/not render via parent component like this

export default class ParentComponent extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            isErrorShown: true
        }
    }

    dismiss() {
        this.setState({
            isErrorShown: false
        })
    }

    showError() {
        if (this.state.isErrorShown) {
            return <ErrorBox 
                error={ this.state.error }
                dismiss={ this.dismiss.bind(this) }
            />
        }

        return null;
    }

    render() {

        return (
            <div>
                { this.showError() }
            </div>
        );
    }
}

export default class ErrorBoxComponent extends React.Component {
    dismiss() {
        this.props.dismiss();
    }

    render() {
        if (!this.props.error) {
            return null;
        }

        return (
            <div data-alert className="alert-box error-box">
                { this.props.error }
                <a href="#" className="close" onClick={ this.dismiss.bind(this) }>&times;</a>
            </div>
        );
    }
}

Finally, there is a way to remove html node, but i really dont know is it a good idea. Maybe someone who knows React from internal will say something about this.

export default class ErrorBoxComponent extends React.Component {
    dismiss() {
        this.el.remove();
    }

    render() {
        if (!this.props.error) {
            return null;
        }

        return (
            <div data-alert className="alert-box error-box" ref={ (el) => { this.el = el} }>
                { this.props.error }
                <a href="#" className="close" onClick={ this.dismiss.bind(this) }>&times;</a>
            </div>
        );
    }
}

What does 'foo' really mean?

In my opinion every programmer has his or her own "words" that is used every time you need an arbitrary word when programming. For some people it's the first words from a childs song, for other it's names and for other its something completely different. Now for the programmer community there are these "words" as well, and these words are 'foo' and 'bar'. The use of this is that if you have to communicate publicly about programming you don't have to say that you would use arbitratry words, you would simply write 'foo' or 'bar' and every programmer knows that this is just arbitrary words.

jQuery keypress() event not firing?

With jQuery, I've done it this way:

function checkKey(e){
     switch (e.keyCode) {
        case 40:
            alert('down');
            break;
        case 38:
            alert('up');
            break;
        case 37:
            alert('left');
            break;
        case 39:
            alert('right');
            break;
        default:
            alert('???');  
            }      
}

if ($.browser.mozilla) {
    $(document).keypress (checkKey);
} else {
    $(document).keydown (checkKey);
}

Also, try these plugins, which looks like they do all that work for you:

http://www.openjs.com/scripts/events/keyboard_shortcuts

http://www.webappers.com/2008/07/31/bind-a-hot-key-combination-with-jquery-hotkeys/

How to copy file from HDFS to the local file system

In Hadoop 2.0,

hdfs dfs -copyToLocal <hdfs_input_file_path> <output_path>

where,

  • hdfs_input_file_path maybe obtained from http://<<name_node_ip>>:50070/explorer.html

  • output_path is the local path of the file, where the file is to be copied to.

  • you may also use get in place of copyToLocal.

Is it possible to have a multi-line comments in R?

Put the following into your ~/.Rprofile file:

exclude <-  function(blah) {
    "excluded block"
}

Now, you can exclude blocks like follows:

stuffiwant

exclude({
    stuffidontwant
    morestuffidontwant
})

How to show Alert Message like "successfully Inserted" after inserting to DB using ASp.net MVC3

Little Edit

Try adding

return new JavascriptResult() { Script = "alert('Successfully registered');" };

in place of

return RedirectToAction("Index");

AngularJS app.run() documentation?

Here's the calling order:

  1. app.config()
  2. app.run()
  3. directive's compile functions (if they are found in the dom)
  4. app.controller()
  5. directive's link functions (again, if found)

Here's a simple demo where you can watch each one executing (and experiment if you'd like).

From Angular's module docs:

Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.

Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the services have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.

One situation where run blocks are used is during authentications.

Pause in Python

If you type

input("")

It will wait for them to press any button then it will continue. Also you can put text between the quotes.

Laravel Request getting current path with query string

$request->fullUrl() will also work if you are injecting Illumitate\Http\Request.

round value to 2 decimals javascript

Just multiply the number by 100, round, and divide the resulting number by 100.

Get total of Pandas column

As other option, you can do something like below

Group   Valuation   amount
    0   BKB Tube    156
    1   BKB Tube    143
    2   BKB Tube    67
    3   BAC Tube    176
    4   BAC Tube    39
    5   JDK Tube    75
    6   JDK Tube    35
    7   JDK Tube    155
    8   ETH Tube    38
    9   ETH Tube    56

Below script, you can use for above data

import pandas as pd    
data = pd.read_csv("daata1.csv")
bytreatment = data.groupby('Group')
bytreatment['amount'].sum()

SQL Server stored procedure creating temp table and inserting value

A SELECT INTO statement creates the table for you. There is no need for the CREATE TABLE statement before hand.

What is happening is that you create #ivmy_cash_temp1 in your CREATE statement, then the DB tries to create it for you when you do a SELECT INTO. This causes an error as it is trying to create a table that you have already created.

Either eliminate the CREATE TABLE statement or alter your query that fills it to use INSERT INTO SELECT format.

If you need a unique ID added to your new row then it's best to use SELECT INTO... since IDENTITY() only works with this syntax.

What's your favorite "programmer" cartoon?

Estimation

XKCD hits the button every time.

how to print a string to console in c++

All you have to do is add:

#include <string>
using namespace std;

at the top. (BTW I know this was posted in 2013 but I just wanted to answer)

Where does Hive store files in HDFS?

Summarize few points posted earlier, in hive-site.xml, property hive.metastore.warehouse.dir specifies where the files located under hadoop HDFS

<property>
   <name>hive.metastore.warehouse.dir</name>
   <value>/user/hive/warehouse</value>
</property>

To view files, use this command:

hadoop fs -ls /user/hive/warehouse

or

http://localhost:50070
Utilities > Browse the file system
or
http://localhost:50070/explorer.html#/

tested under hadoop-2.7.3, hive-2.1.1

Login to Microsoft SQL Server Error: 18456

Before opening, right-click and choose 'Run as Administrator'. This solved the problem for me.

How do I use the ternary operator ( ? : ) in PHP as a shorthand for "if / else"?

The ternary operator is just a shorthand for and if/else block. Your working code does not have an else condition, so is not suitable for this.

The following example will work:

echo empty($address['street2']) ? 'empty' : 'not empty';

Running bash script from within python

Adding an answer because I was directed here after asking how to run a bash script from python. You receive an error OSError: [Errno 2] file not found if your script takes in parameters. Lets say for instance your script took in a sleep time parameter: subprocess.call("sleep.sh 10") will not work, you must pass it as an array: subprocess.call(["sleep.sh", 10])

GitHub - error: failed to push some refs to '[email protected]:myrepo.git'

In windows, you need to use double quotes "". So the command would be

git commit -m "t"

Exit single-user mode

  1. Right click your database in databases section
  2. Select "Properties"
  3. Select "Options" page
  4. Scroll down "Other options" and alter "Restrict access" field

screenshot of options page of sql server

a tag as a submit button?

Supposing the form is the direct parent you can do:

<a href='#' onclick='this.parentNode.submit(); return false;'>submit</a>

If not you can access through the forms name attribute like this:

<a href='#' onclick='document.forms["myform"].submit(); return false;'>submit</a>

See both examples here: http://jsfiddle.net/WEZDC/1/

Selecting specific rows and columns from NumPy array

Fancy indexing requires you to provide all indices for each dimension. You are providing 3 indices for the first one, and only 2 for the second one, hence the error. You want to do something like this:

>>> a[[[0, 0], [1, 1], [3, 3]], [[0,2], [0,2], [0, 2]]]
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

That is of course a pain to write, so you can let broadcasting help you:

>>> a[[[0], [1], [3]], [0, 2]]
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

This is much simpler to do if you index with arrays, not lists:

>>> row_idx = np.array([0, 1, 3])
>>> col_idx = np.array([0, 2])
>>> a[row_idx[:, None], col_idx]
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

How to declare an array of strings in C++?

Declare an array of strings in C++ like this : char array_of_strings[][]

For example : char array_of_strings[200][8192];

will hold 200 strings, each string having the size 8kb or 8192 bytes.

use strcpy(line[i],tempBuffer); to put data in the array of strings.

How to install bcmath module?

If still anyone is not getting how to install bcmath as it has lots of other dependant modules to install like php7.2-common, etc.

Try using synaptic application, to install the same. fire command.\

sudo apt-get install synaptic

Open the synaptic application and then click on search tab.

search for bcmath

search results will show all the packages depends on php.

Install as per your convenience.

and install with all auto populated dependancies it required to install.

That's it.

Debug message "Resource interpreted as other but transferred with MIME type application/javascript"

I don't think it is a bug, Try adding the MIME type to your .htaccess file For instance, put or add the following content to your .htaccess file (which should be in the same place of your .js or above folders)

#JavaScript
AddType application/x-javascript .js

This solved my tree "Resource interpreted as other but transfered ... " warnings. Everytime you have that kind of warning it means you don't have enough info in your .htaccess file.

BTW1: Since you are modifying .htaccess file, make sure you restart your server.

BTW2: I also could clear same warnings for GIF files in Safari 4 with this:

#GIF
AddType image/gif .gif

BTW3: For other file types: see w3schools list or htaccess-guide

NSRange from Swift Range?

Swift 3 Extension Variant that preserves existing attributes.

extension UILabel {
  func setLineHeight(lineHeight: CGFloat) {
    guard self.text != nil && self.attributedText != nil else { return }
    var attributedString = NSMutableAttributedString()

    if let attributedText = self.attributedText {
      attributedString = NSMutableAttributedString(attributedString: attributedText)
    } else if let text = self.text {
      attributedString = NSMutableAttributedString(string: text)
    }

    let style = NSMutableParagraphStyle()
    style.lineSpacing = lineHeight
    style.alignment = self.textAlignment
    let str = NSString(string: attributedString.string)

    attributedString.addAttribute(NSParagraphStyleAttributeName,
                                  value: style,
                                  range: str.range(of: str as String))
    self.attributedText = attributedString
  }
}

How to convert numbers to words without using num2word library?

This Did the job for me(Python 2.x)

nums = {1:"One", 2:"Two", 3:"Three" ,4:"Four", 5:"Five", 6:"Six", 7:"Seven", 8:"Eight",\
        9:"Nine", 0:"Zero", 10:"Ten", 11:"Eleven", 12:"Tweleve" , 13:"Thirteen", 14:"Fourteen", \
        15: "Fifteen", 16:"Sixteen", 17:"Seventeen", 18:"Eighteen", 19:"Nineteen", 20:"Twenty", 30:"Thirty", 40:"Forty", 50:"Fifty",\
        60:"Sixty", 70:"Seventy", 80:"Eighty", 90:"Ninety"}
num = input("Enter a number: ")
# To convert three digit number into words 
if 100 <= num < 1000:
    a = num / 100
    b = num % 100
    c = b / 10
    d = b % 10
    if c == 1 :
        print nums[a] + "hundred" , nums[b]
    elif c == 0:
        print nums[a] + "hundred" , nums[d]
    else:
        c *= 10
        if d == 0:
            print nums[a] + "hundred", nums[c]
        else:
            print nums[a] + "hundred" , nums[c], nums[d]
# to convert two digit number into words            
elif 0 <= num < 100:
    a = num / 10
    b = num % 10
    if a == 1:
        print nums[num]
    else:
        a *= 10
        print nums[a], nums[b]

R define dimensions of empty data frame

You can do something like:

N <- 10
collect1 <- data.frame(id   = integer(N),
                       max1 = numeric(N),
                       min1 = numeric(N))

Now be careful that in the rest of your code, you forgot to use the row index for filling the data.frame row by row. It should be:

for(i in seq_len(N)){
   collect1$id[i] <- i
   ss1 <- subset(df1, df1$id == i)
   collect1$max1[i] <- max(ss1$value)
   collect1$min1[i] <- min(ss1$value)
}

Finally, I would say that there are many alternatives for doing what you are trying to accomplish, some would be much more efficient and use a lot less typing. You could for example look at the aggregate function, or ddply from the plyr package.

CentOS 7 and Puppet unable to install nc

You can use a case in this case, to separate versions one example is using FACT os (which returns the version etc of your system... the command facter will return the details:

root@sytem# facter -p os
{"name"=>"CentOS", "family"=>"RedHat", "release"=>{"major"=>"7", "minor"=>"0", "full"=>"7.0.1406"}}

#we capture release hash
$curr_os = $os['release']

case $curr_os['major'] {
  '7': { .... something }
  *: {something}
}

That is an fast example, Might have typos, or not exactly working. But using system facts you can see what happens.

The OS fact provides you 3 main variables: name, family, release... Under release you have a small dictionary with more information about your os! combining these you can create cases to meet your targets.

Mysql: Setup the format of DATETIME to 'DD-MM-YYYY HH:MM:SS' when creating a table

This cannot be done for the table; besides, you even cannot change this default value at all.

The answer is a server variable datetime_format, it is unused.

How do I read the file content from the Internal storage - Android App

Read a file as a string full version (handling exceptions, using UTF-8, handling new line):

// Calling:
/* 
    Context context = getApplicationContext();
    String filename = "log.txt";
    String str = read_file(context, filename);
*/  
public String read_file(Context context, String filename) {
        try {
            FileInputStream fis = context.openFileInput(filename);
            InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            return sb.toString();
        } catch (FileNotFoundException e) {
            return "";
        } catch (UnsupportedEncodingException e) {
            return "";
        } catch (IOException e) {
            return "";
        }
    }

Note: you don't need to bother about file path only with file name.

how to do bitwise exclusive or of two strings in python?

Do you mean something like this:

s1 = '00000001'
s2 = '11111110'
int(s1,2) ^ int(s2,2)

Add new column in Pandas DataFrame Python

The easiest way that I found for adding a column to a DataFrame was to use the "add" function. Here's a snippet of code, also with the output to a CSV file. Note that including the "columns" argument allows you to set the name of the column (which happens to be the same as the name of the np.array that I used as the source of the data).

#  now to create a PANDAS data frame
df = pd.DataFrame(data = FF_maxRSSBasal, columns=['FF_maxRSSBasal'])
# from here on, we use the trick of creating a new dataframe and then "add"ing it
df2 = pd.DataFrame(data = FF_maxRSSPrism, columns=['FF_maxRSSPrism'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = FF_maxRSSPyramidal, columns=['FF_maxRSSPyramidal'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_strainE22, columns=['deltaFF_strainE22'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = scaled, columns=['scaled'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_orientation, columns=['deltaFF_orientation'])
df = df.add( df2, fill_value=0 )
#print(df)
df.to_csv('FF_data_frame.csv')

Java 8 Filter Array Using Lambda

even simpler, adding up to String[],

use built-in filter filter(StringUtils::isNotEmpty) of org.apache.commons.lang3

import org.apache.commons.lang3.StringUtils;

    String test = "a\nb\n\nc\n";
    String[] lines = test.split("\\n", -1);


    String[]  result = Arrays.stream(lines).filter(StringUtils::isNotEmpty).toArray(String[]::new);
    System.out.println(Arrays.toString(lines));
    System.out.println(Arrays.toString(result));

and output: [a, b, , c, ] [a, b, c]

What's the maximum value for an int in PHP?

(a little bit late, but could be useful)

Only trust PHP_INT_MAX and PHP_INT_SIZE, this value vary on your arch (32/64 bits) and your OS...

Any other "guess" or "hint" can be false.

What is a void pointer in C++?

A void* can point to anything (it's a raw pointer without any type info).

Multiple maven repositories in one gradle file

you have to do like this in your project level gradle file

allprojects {
    repositories {
        jcenter()
        maven { url "http://dl.appnext.com/" }
        maven { url "https://maven.google.com" }
    }
}

Android: How to stretch an image to the screen width while maintaining aspect ratio?

You are setting the ScaleType to ScaleType.FIT_XY. According to the javadocs, this will stretch the image to fit the whole area, changing the aspect ratio if necessary. That would explain the behavior you are seeing.

To get the behavior you want... FIT_CENTER, FIT_START, or FIT_END are close, but if the image is narrower than it is tall, it will not start to fill the width. You could look at how those are implemented though, and you should probably be able to figure out how to adjust it for your purpose.

Get the key corresponding to the minimum value within a dictionary

If you are not sure that you have not multiple minimum values, I would suggest:

d = {320:1, 321:0, 322:3, 323:0}
print ', '.join(str(key) for min_value in (min(d.values()),) for key in d if d[key]==min_value)

"""Output:
321, 323
"""

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

foreach uses iterators under the hood anyway. It really is just syntactic sugar.

Consider the following program:

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

public class Whatever {
    private final List<Integer> list = new ArrayList<>();
    public void main() {
        for(Integer i : list) {
        }
    }
}

Let's compile it with javac Whatever.java,
And read the disassembled bytecode of main(), using javap -c Whatever:

public void main();
  Code:
     0: aload_0
     1: getfield      #4                  // Field list:Ljava/util/List;
     4: invokeinterface #5,  1            // InterfaceMethod java/util/List.iterator:()Ljava/util/Iterator;
     9: astore_1
    10: aload_1
    11: invokeinterface #6,  1            // InterfaceMethod java/util/Iterator.hasNext:()Z
    16: ifeq          32
    19: aload_1
    20: invokeinterface #7,  1            // InterfaceMethod java/util/Iterator.next:()Ljava/lang/Object;
    25: checkcast     #8                  // class java/lang/Integer
    28: astore_2
    29: goto          10
    32: return

We can see that foreach compiles down to a program which:

  • Creates iterator using List.iterator()
  • If Iterator.hasNext(): invokes Iterator.next() and continues loop

As for "why doesn't this useless loop get optimized out of the compiled code? we can see that it doesn't do anything with the list item": well, it's possible for you to code your iterable such that .iterator() has side-effects, or so that .hasNext() has side-effects or meaningful consequences.

You could easily imagine that an iterable representing a scrollable query from a database might do something dramatic on .hasNext() (like contacting the database, or closing a cursor because you've reached the end of the result set).

So, even though we can prove that nothing happens in the loop body… it is more expensive (intractable?) to prove that nothing meaningful/consequential happens when we iterate. The compiler has to leave this empty loop body in the program.

The best we could hope for would be a compiler warning. It's interesting that javac -Xlint:all Whatever.java does not warn us about this empty loop body. IntelliJ IDEA does though. Admittedly I have configured IntelliJ to use Eclipse Compiler, but that may not be the reason why.

enter image description here

Bootstrap 3.0 Popovers and tooltips

For some reason the only way I was able to get my code to work is by switching couple of things. If nothing worked for you so far, please give a whirl to this:

$('body').popover({ 
    selector: '[data-toggle="popover"]', 
    trigger: 'hover',
    placement: 'right'
});

Assign keyboard shortcut to run procedure

For assigning a keyboard key to button on the sheet you can use this code, just copy this code to the sheet which contain the button.

Here Return specifies the key and get_detail is the procedure name.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Application.OnKey "{RETURN}", "get_detail"

End Sub

Now within this sheet whenever you press Enter button the assigned macro will be called.

How to set column header text for specific column in Datagridview C#

If you work with visual studio designer, you will probably have defined fields for each columns in the YourForm.Designer.cs file e.g.:

private System.Windows.Forms.DataGridViewCheckBoxColumn dataGridViewCheckBoxColumn1;    
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2; 

If you give them useful names, you can set the HeaderText easily:

usefulNameForDataGridViewTextBoxColumn.HeaderText = "Useful Header Text";

What is "android:allowBackup"?

This is not explicitly mentioned, but based on the following docs, I think it is implied that an app needs to declare and implement a BackupAgent in order for data backup to work, even in the case when allowBackup is set to true (which is the default value).

http://developer.android.com/reference/android/R.attr.html#allowBackup http://developer.android.com/reference/android/app/backup/BackupManager.html http://developer.android.com/guide/topics/data/backup.html

Array.push() and unique items

Your logic is saying, "if this item exists already, then add it." It should be the opposite of that.

Change it to...

if (this.items.indexOf(item) == -1) {
    this.items.push(item);
}

Set focus to field in dynamically loaded DIV

This runs on page load.

<script type="text/javascript">
    $(function () {
        $("#header").focus();
    });
</script>

SQL subquery with COUNT help

Do you want to get the number of rows?

SELECT columnName, COUNT(*) AS row_count
FROM eventsTable
WHERE columnName = 'Business'
GROUP BY columnName

Integrate ZXing in Android Studio

Anybody facing the same issues, follow the simple steps:

Import the project android from downloaded zxing-master zip file using option Import project (Eclipse ADT, Gradle, etc.) and add the dollowing 2 lines of codes in your app level build.gradle file and and you are ready to run.

So simple, yahh...

dependencies {
        // https://mvnrepository.com/artifact/com.google.zxing/core
        compile group: 'com.google.zxing', name: 'core', version: '3.2.1'
        // https://mvnrepository.com/artifact/com.google.zxing/android-core
        compile group: 'com.google.zxing', name: 'android-core', version: '3.2.0'

    }

You can always find latest version core and android core from below links:

https://mvnrepository.com/artifact/com.google.zxing/core/3.2.1 https://mvnrepository.com/artifact/com.google.zxing/android-core/3.2.0

UPDATE (29.05.2019)

Add these dependencies instead:

dependencies {
    implementation 'com.google.zxing:core:3.4.0'
    implementation 'com.google.zxing:android-core:3.3.0'
}

Show a message box from a class in c#?

System.Windows.MessageBox.Show("Hello world"); //WPF
System.Windows.Forms.MessageBox.Show("Hello world"); //WinForms

Fully custom validation error message with Rails

One solution might be to change the i18n default error format:

en:
  errors:
    format: "%{message}"

Default is format: %{attribute} %{message}

Postgres and Indexes on Foreign Keys and Primary Keys

I love how this is explained in the article Cool performance features of EclipseLink 2.5

Indexing Foreign Keys

The first feature is auto indexing of foreign keys. Most people incorrectly assume that databases index foreign keys by default. Well, they don't. Primary keys are auto indexed, but foreign keys are not. This means any query based on the foreign key will be doing full table scans. This is any OneToMany, ManyToMany or ElementCollection relationship, as well as many OneToOne relationships, and most queries on any relationship involving joins or object comparisons. This can be a major perform issue, and you should always index your foreign keys fields.

composer laravel create project

composer create-project laravel/laravel ProjectName 

Check if a string is palindrome

Just compare the string with itself reversed:

string input;

cout << "Please enter a string: ";
cin >> input;

if (input == string(input.rbegin(), input.rend())) {
    cout << input << " is a palindrome";
}

This constructor of string takes a beginning and ending iterator and creates the string from the characters between those two iterators. Since rbegin() is the end of the string and incrementing it goes backwards through the string, the string we create will have the characters of input added to it in reverse, reversing the string.

Then you just compare it to input and if they are equal, it is a palindrome.

This does not take into account capitalisation or spaces, so you'll have to improve on it yourself.

convert array into DataFrame in Python

In general you can use pandas rename function here. Given your dataframe you could change to a new name like this. If you had more columns you could also rename those in the dictionary. The 0 is the current name of your column

import pandas as pd    
import numpy as np   
e = np.random.normal(size=100)  
e_dataframe = pd.DataFrame(e)      

e_dataframe.rename(index=str, columns={0:'new_column_name'})

Create a directory if it does not exist and then create the files in that directory as well

This code checks for the existence of the directory first and creates it if not, and creates the file afterwards. Please note that I couldn't verify some of your method calls as I don't have your complete code, so I'm assuming the calls to things like getTimeStamp() and getClassName() will work. You should also do something with the possible IOException that can be thrown when using any of the java.io.* classes - either your function that writes the files should throw this exception (and it be handled elsewhere), or you should do it in the method directly. Also, I assumed that id is of type String - I don't know as your code doesn't explicitly define it. If it is something else like an int, you should probably cast it to a String before using it in the fileName as I have done here.

Also, I replaced your append calls with concat or + as I saw appropriate.

public void writeFile(String value){
    String PATH = "/remote/dir/server/";
    String directoryName = PATH.concat(this.getClassName());
    String fileName = id + getTimeStamp() + ".txt";

    File directory = new File(directoryName);
    if (! directory.exists()){
        directory.mkdir();
        // If you require it to make the entire directory path including parents,
        // use directory.mkdirs(); here instead.
    }

    File file = new File(directoryName + "/" + fileName);
    try{
        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(value);
        bw.close();
    }
    catch (IOException e){
        e.printStackTrace();
        System.exit(-1);
    }
}

You should probably not use bare path names like this if you want to run the code on Microsoft Windows - I'm not sure what it will do with the / in the filenames. For full portability, you should probably use something like File.separator to construct your paths.

Edit: According to a comment by JosefScript below, it's not necessary to test for directory existence. The directory.mkdir() call will return true if it created a directory, and false if it didn't, including the case when the directory already existed.

Compiler error: "class, interface, or enum expected"

Look at your function s definition. If you forget using "()" after function declaration somewhere, you ll get plenty of errors with the same format:

 ... ??: class, interface, or enum expected ...

And also you have forgot closing bracket after your class or function definition ends. But note that these missing bracket, is not the only reason for this type of error.

Android Stop Emulator from Command Line

I can close it with:

adb shell reboot -p

How to open a folder in Windows Explorer from VBA?

Thanks to PhilHibbs comment (on VBwhatnow's answer) I was finally able to find a solution that both reuses existing windows and avoids flashing a CMD-window at the user:

Dim path As String
path = CurrentProject.path & "\"
Shell "cmd /C start """" /max """ & path & """", vbHide

where 'path' is the folder you want to open.

(In this example I open the folder where the current workbook is saved.)

Pros:

  • Avoids opening new explorer instances (only sets focus if window exists).
  • The cmd-window is never visible thanks to vbHide.
  • Relatively simple (does not need to reference win32 libraries).

Cons:

  • Window maximization (or minimization) is mandatory.

Explanation:

At first I tried using only vbHide. This works nicely... unless there is already such a folder opened, in which case the existing folder window becomes hidden and disappears! You now have a ghost window floating around in memory and any subsequent attempt to open the folder after that will reuse the hidden window - seemingly having no effect.

In other words when the 'start'-command finds an existing window the specified vbAppWinStyle gets applied to both the CMD-window and the reused explorer window. (So luckily we can use this to un-hide our ghost-window by calling the same command again with a different vbAppWinStyle argument.)

However by specifying the /max or /min flag when calling 'start' it prevents the vbAppWinStyle set on the CMD window from being applied recursively. (Or overrides it? I don't know what the technical details are and I'm curious to know exactly what the chain of events is here.)

Binary Data in JSON String. Something better than Base64

Refer: http://snia.org/sites/default/files/Multi-part%20MIME%20Extension%20v1.0g.pdf

It describes a way to transfer binary data between a CDMI client and server using 'CDMI content type' operations without requiring base64 conversion of the binary data.

If you can use 'Non-CDMI content type' operation, it is ideal to transfer 'data' to/from a object. Metadata can then later be added/retrieved to/from the object as a subsequent 'CDMI content type' operation.

Get to UIViewController from UIView?

Swift 4 version

extension UIView {
var parentViewController: UIViewController? {
    var parentResponder: UIResponder? = self
    while parentResponder != nil {
        parentResponder = parentResponder!.next
        if let viewController = parentResponder as? UIViewController {
            return viewController
        }
    }
    return nil
}

Usage example

 if let parent = self.view.parentViewController{

 }

Determining whether an object is a member of a collection in VBA

Not exactly elegant, but the best (and quickest) solution i could find was using OnError. This will be significantly faster than iteration for any medium to large collection.

Public Function InCollection(col As Collection, key As String) As Boolean
  Dim var As Variant
  Dim errNumber As Long

  InCollection = False
  Set var = Nothing

  Err.Clear
  On Error Resume Next
    var = col.Item(key)
    errNumber = CLng(Err.Number)
  On Error GoTo 0

  '5 is not in, 0 and 438 represent incollection
  If errNumber = 5 Then ' it is 5 if not in collection
    InCollection = False
  Else
    InCollection = True
  End If

End Function

How do I do a simple 'Find and Replace" in MsSQL?

This pointed me in the right direction, but I have a DB that originated in MSSQL 2000 and is still using the ntext data type for the column I was replacing on. When you try to run REPLACE on that type you get this error:

Argument data type ntext is invalid for argument 1 of replace function.

The simplest fix, if your column data fits within nvarchar, is to cast the column during replace. Borrowing the code from the accepted answer:

UPDATE YourTable
SET Column1 = REPLACE(cast(Column1 as nvarchar(max)),'a','b')
WHERE Column1 LIKE '%a%'

This worked perfectly for me. Thanks to this forum post I found for the fix. Hopefully this helps someone else!

PHP CSV string to array

If you have carriage return/line feeds within columns, str_getcsv will not work.

Try https://github.com/synappnz/php-csv

Use:

include "csv.php";
$csv = new csv(file_get_contents("filename.csv"));
$rows = $csv->rows();
foreach ($rows as $row)
{
  // do something with $row
}

How To Add An "a href" Link To A "div"?

In this case, it doesn't matter as there is no content between the two divs.

Either one will get the browser to scroll down to it.

The a element will look like:

<a href="mypageName.html#buttonOne">buttonOne</a>

Or:

<a href="mypageName.html#linkedinB">linkedinB</a>

What is the optimal way to compare dates in Microsoft SQL server?

Get items when the date is between fromdate and toDate.

where convert(date, fromdate, 103 ) <= '2016-07-26' and convert(date, toDate, 103) >= '2016-07-26'

Groovy Shell warning "Could not open/create prefs root node ..."

I was able to resolve the problem by manually creating the following registry key:

HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs

Changing the cursor in WPF sometimes works, sometimes doesn't

If your application uses async stuff and you're fiddling with Mouse's cursor, you probably want to do it only in main UI thread. You can use app's Dispatcher thread for that:

Application.Current.Dispatcher.Invoke(() =>
{
    // The check is required to prevent cursor flickering
    if (Mouse.OverrideCursor != cursor)
        Mouse.OverrideCursor = cursor;
});

Does MS Access support "CASE WHEN" clause if connect with ODBC?

Since you are using Access to compose the query, you have to stick to Access's version of SQL.

To choose between several different return values, use the switch() function. So to translate and extend your example a bit:

select switch(
  age > 40, 4,
  age > 25, 3,
  age > 20, 2,
  age > 10, 1,
  true, 0
) from demo

The 'true' case is the default one. If you don't have it and none of the other cases match, the function will return null.

The Office website has documentation on this but their example syntax is VBA and it's also wrong. I've given them feedback on this but you should be fine following the above example.

What does the CSS rule "clear: both" do?

The clear property indicates that the left, right or both sides of an element can not be adjacent to earlier floated elements within the same block formatting context. Cleared elements are pushed below the corresponding floated elements. Examples:

clear: none; Element remains adjacent to floated elements

_x000D_
_x000D_
body {_x000D_
  font-family: monospace;_x000D_
  background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
  float: left;_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
  float: right;_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.clear-none {_x000D_
  clear: none;_x000D_
  background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-none">clear: none;</div>
_x000D_
_x000D_
_x000D_

clear: left; Element pushed below left floated elements

_x000D_
_x000D_
body {_x000D_
  font-family: monospace;_x000D_
  background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
  float: left;_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
  float: right;_x000D_
  width: 60px;_x000D_
  height: 120px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.clear-left {_x000D_
  clear: left;_x000D_
  background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-left">clear: left;</div>
_x000D_
_x000D_
_x000D_

clear: right; Element pushed below right floated elements

_x000D_
_x000D_
body {_x000D_
  font-family: monospace;_x000D_
  background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
  float: left;_x000D_
  width: 60px;_x000D_
  height: 120px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
  float: right;_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.clear-right {_x000D_
  clear: right;_x000D_
  background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-right">clear: right;</div>
_x000D_
_x000D_
_x000D_

clear: both; Element pushed below all floated elements

_x000D_
_x000D_
body {_x000D_
  font-family: monospace;_x000D_
  background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
  float: left;_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
  float: right;_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.clear-both {_x000D_
  clear: both;_x000D_
  background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-both">clear: both;</div>
_x000D_
_x000D_
_x000D_

clear does not affect floats outside the current block formatting context

_x000D_
_x000D_
body {_x000D_
  font-family: monospace;_x000D_
  background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
  float: left;_x000D_
  width: 60px;_x000D_
  height: 120px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.inline-block {_x000D_
  display: inline-block;_x000D_
  background: #BDF;_x000D_
}_x000D_
.inline-block .float-left {_x000D_
  height: 60px;_x000D_
}_x000D_
.clear-both {_x000D_
  clear: both;_x000D_
  background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="inline-block">_x000D_
  <div>display: inline-block;</div>_x000D_
  <div class="float-left">float: left;</div>_x000D_
  <div class="clear-both">clear: both;</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Can't change z-index with JQuery

$(this).parent().css('z-index',3000);

Javascript callback when IFRAME is finished loading?

I had a similar problem as you. What I did is that I use something called jQuery. What you then do in the javascript code is this:

$(function(){ //this is regular jQuery code. It waits for the dom to load fully the first time you open the page.

    $("#myIframeId").load(function(){
       callback($("#myIframeId").html());
       $("#myIframeId").remove();

    });

});

It seems as you delete you iFrame before you grab the html from it. Now, I do see a problem with that :p

Hope this helps :).

Unresolved Import Issues with PyDev and Eclipse

I had some issues importing additional libraries, after trying to resolve the problem, by understanding PYTHONPATH, Interpreter, and Grammar I found that I did everything write but the problems continue. After that, I just add a new empty line in the files that had the import errors and saved them and the error was resolved.

upstream sent too big header while reading response header from upstream

If nginx is running as a proxy / reverse proxy

that is, for users of ngx_http_proxy_module

In addition to fastcgi, the proxy module also saves the request header in a temporary buffer.

So you may need also to increase the proxy_buffer_size and the proxy_buffers, or disable it totally (Please read the nginx documentation).

Example of proxy buffering configuration

http {
  proxy_buffer_size   128k;
  proxy_buffers   4 256k;
  proxy_busy_buffers_size   256k;
}

Example of disabling your proxy buffer (recommended for long polling servers)

http {
  proxy_buffering off;
}

For more information: Nginx proxy module documentation

What exactly is RESTful programming?

Old question, newish way of answering. There's a lot of misconception out there about this concept. I always try to remember:

  1. Structured URLs and Http Methods/Verbs are not the definition of restful programming.
  2. JSON is not restful programming
  3. RESTful programming is not for APIs

I define restful programming as

An application is restful if it provides resources (being the combination of data + state transitions controls) in a media type the client understands

To be a restful programmer you must be trying to build applications that allow actors to do things. Not just exposing the database.

State transition controls only make sense if the client and server agree upon a media type representation of the resource. Otherwise there's no way to know what's a control and what isn't and how to execute a control. IE if browsers didn't know <form> tags in html then there'd be nothing for you to submit to transition state in your browser.

I'm not looking to self promote, but i expand on these ideas to great depth in my talk http://techblog.bodybuilding.com/2016/01/video-what-is-restful-200.html .

An excerpt from my talk is about the often referred to richardson maturity model, i don't believe in the levels, you either are RESTful (level 3) or you are not, but what i like to call out about it is what each level does for you on your way to RESTful

annotated richardson maturity model

How to drop SQL default constraint without knowing its name?

I found that this works and uses no joins:

DECLARE @ObjectName NVARCHAR(100)
SELECT @ObjectName = OBJECT_NAME([default_object_id]) FROM SYS.COLUMNS
WHERE [object_id] = OBJECT_ID('[tableSchema].[tableName]') AND [name] = 'columnName';
EXEC('ALTER TABLE [tableSchema].[tableName] DROP CONSTRAINT ' + @ObjectName)

Just make sure that columnName does not have brackets around it because the query is looking for an exact match and will return nothing if it is [columnName].

libxml/tree.h no such file or directory

Ray Wenderlich has a blog post about using gdata that solves this problem. Basically these simple steps:

In XCode, click Project\Edit Project Settings and make sure “All Configurations” are checked.

Find the Search Paths\Header Search Paths setting and add /usr/include/libxml2 to the list.

Finally, find the Linking\Other Linker Flags section and add -lxml2 to the list.

original post: read and write xml documents with gdataxml

counting the number of lines in a text file

In C if you implement count line it will never fail. Yes you can get one extra line if there is stray "ENTER KEY" generally at the end of the file.

File might look some thing like this:

"hello 1
"Hello 2

"

Code below

#include <stdio.h>
#include <stdlib.h>
#define FILE_NAME "file1.txt"

int main() {

    FILE *fd = NULL;
    int cnt, ch;

    fd = fopen(FILE_NAME,"r");
    if (fd == NULL) {
            perror(FILE_NAME);
            exit(-1);
    }

    while(EOF != (ch = fgetc(fd))) {
    /*
     * int fgetc(FILE *) returns unsigned char cast to int
     * Because it has to return EOF or error also.
     */
            if (ch == '\n')
                    ++cnt;
    }

    printf("cnt line in %s is %d\n", FILE_NAME, cnt);

    fclose(fd);
    return 0;
}

Laravel 5 How to switch from Production mode

In Laravel the default environment is always production.

What you need to do is to specify correct hostname in bootstrap/start.php for your enviroments eg.:

/*
|--------------------------------------------------------------------------
| Detect The Application Environment
|--------------------------------------------------------------------------
|
| Laravel takes a dead simple approach to your application environments
| so you can just specify a machine name for the host that matches a
| given environment, then we will automatically detect it for you.
|
*/

$env = $app->detectEnvironment(array(
    'local' => array('homestead'),
    'profile_1' => array('hostname_for_profile_1')
));

The differences between initialize, define, declare a variable

Declaration says "this thing exists somewhere":

int foo();       // function
extern int bar;  // variable
struct T
{
   static int baz;  // static member variable
};

Definition says "this thing exists here; make memory for it":

int foo() {}     // function
int bar;         // variable
int T::baz;      // static member variable

Initialisation is optional at the point of definition for objects, and says "here is the initial value for this thing":

int bar = 0;     // variable
int T::baz = 42; // static member variable

Sometimes it's possible at the point of declaration instead:

struct T
{
   static int baz = 42;
};

…but that's getting into more complex features.

How to convert a DataFrame back to normal RDD in pyspark?

Answer given by kennyut/Kistian works very well but to get exact RDD like output when RDD consist of list of attributes e.g. [1,2,3,4] we can use flatmap command as below,

rdd = df.rdd.flatMap(list)
or 
rdd = df.rdd.flatmap(lambda x: list(x))

How do I set the default value for an optional argument in Javascript?

If str is null, undefined or 0, this code will set it to "hai"

function(nodeBox, str) {
  str = str || "hai";
.
.
.

If you also need to pass 0, you can use:

function(nodeBox, str) {
  if (typeof str === "undefined" || str === null) { 
    str = "hai"; 
  }
.
.
.

TSQL CASE with if comparison in SELECT statement

Should be:

SELECT registrationDate, 
       (SELECT CASE
        WHEN COUNT(*)< 2 THEN 'Ama'
        WHEN COUNT(*)< 5 THEN 'SemiAma' 
        WHEN COUNT(*)< 7 THEN 'Good'  
        WHEN COUNT(*)< 9 THEN 'Better' 
        WHEN COUNT(*)< 12 THEN 'Best'
        ELSE 'Outstanding'
        END as a FROM Articles 
        WHERE Articles.userId = Users.userId) as ranking,
        (SELECT COUNT(*) 
        FROM Articles 
        WHERE userId = Users.userId) as articleNumber,
hobbies, etc...
FROM USERS

Force IE10 to run in IE10 Compatibility View?

See here:

https://softwareengineering.stackexchange.com/questions/194687/how-the-compatibility-view-in-ie-works-behind-the-scenes

Use

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE10">

I just tried it and it showed IE10 compatibility mode in the debug window.

javascript windows alert with redirect function

If you would like to redirect the user after the alert, do this:

echo ("<script LANGUAGE='JavaScript'>
          window.alert('Succesfully Updated');
          window.location.href='<URL to redirect to>';
       </script>");

Is it possible to change the speed of HTML's <marquee> tag?

_x000D_
_x000D_
<marquee behavior=scroll direction="left" scrollamount="5">Your message here</marquee>
_x000D_
_x000D_
_x000D_

scrollamount controls the speed of text: higher the value higher is the scrolling speed

How to reload current page?

It will work 100%. The following lines of code are responsible for page reload in my project.

load(val) {
if (val == this.router.url) {
  this.spinnerService.show();
  this.router.routeReuseStrategy.shouldReuseRoute = function () {
    return false;
  };
 }
}

Just use the following part in your code.

this.router.routeReuseStrategy.shouldReuseRoute = function () {
    return false;
  };

Modifying the "Path to executable" of a windows service

It involves editing the registry, but service information can be found in HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services. Find the service you want to redirect, locate the ImagePath subkey and change that value.

How to add a ListView to a Column in Flutter?

You can use Flex and Flexible widgets. for example:

Flex(
direction: Axis.vertical,
children: <Widget>[
    ... other widgets ...
    Flexible(
        flex: 1,
        child: ListView.builder(
        itemCount: ...,
        itemBuilder: (context, index) {
            ...
        },
        ),
    ),
],

);

Find and replace words/lines in a file

Any decent text editor has a search&replace facility that supports regular expressions.

If however, you have reason to reinvent the wheel in Java, you can do:

Path path = Paths.get("test.txt");
Charset charset = StandardCharsets.UTF_8;

String content = new String(Files.readAllBytes(path), charset);
content = content.replaceAll("foo", "bar");
Files.write(path, content.getBytes(charset));

This only works for Java 7 or newer. If you are stuck on an older Java, you can do:

String content = IOUtils.toString(new FileInputStream(myfile), myencoding);
content = content.replaceAll(myPattern, myReplacement);
IOUtils.write(content, new FileOutputStream(myfile), myencoding);

In this case, you'll need to add error handling and close the streams after you are done with them.

IOUtils is documented at http://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/IOUtils.html

How to fix "set SameSite cookie to none" warning?

For those can not create PHP session and working with live domain at local. You should delete live sites secure cookie first.

Full answer ; https://stackoverflow.com/a/64073275/1067434

How to use Tomcat 8 in Eclipse?

UPDATE: Eclipse Mars EE and later have native support for Tomcat8. Use this only if you have an earlier version of eclipse.


The latest version of Eclipse still does not support Tomcat 8, but you can add the new version of WTP and Tomcat 8 support will be added natively. To do this:

  • Download the latest version of Eclipse for Java EE
  • Go to the WTP downloads page, select the latest version (currently 3.6), and download the zip (under Traditional Zip Files...Web App Developers). Here's the current link.
  • Copy the all of the files in features and plugins directories of the downloaded WTP into the corresponding Eclipse directories in your Eclipse folder (overwriting the existing files).

Start Eclipse and you should have a Tomcat 8 option available when you go to deploy. enter image description here

Xcode "Device Locked" When iPhone is unlocked

Lots of answers, but the one that worked for me (El Capitan, Xcode 8.2) was to close iTunes. If that has a connection to the IOS device then although Xcode can load the app components it will still fail to run it.

Free c# QR-Code generator

Generate QR Code Image in ASP.NET Using Google Chart API

Google Chart API returns an image in response to a URL GET or POST request. All the data required to create the graphic is included in the URL, including the image type and size.

var url = string.Format("http://chart.apis.google.com/chart?cht=qr&chs={1}x{2}&chl={0}", txtCode.Text, txtWidth.Text, txtHeight.Text);
                WebResponse response = default(WebResponse);
                Stream remoteStream = default(Stream);
                StreamReader readStream = default(StreamReader);
                WebRequest request = WebRequest.Create(url);
                response = request.GetResponse();
                remoteStream = response.GetResponseStream();
                readStream = new StreamReader(remoteStream);
                System.Drawing.Image img = System.Drawing.Image.FromStream(remoteStream);
                img.Save("D:/QRCode/" + txtCode.Text + ".png");
                response.Close();
                remoteStream.Close();
                readStream.Close();
                txtCode.Text = string.Empty;
                txtWidth.Text = string.Empty;
                txtHeight.Text = string.Empty;
                lblMsg.Text = "The QR Code generated successfully";

Click here for complete source code to download

Demo of application for free QR Code generator using C#

enter image description here

Trigger a Travis-CI rebuild without pushing a commit?

Log in to Travis and go to the build page. You will see a "Restart Build" button on the top-right corner, next to the gear icon:

screengrab

Note: you need to have write access to the linked GitHub repo for this to work.

PHP substring extraction. Get the string before the first '/' or the whole string

One-line version of the accepted answer:

$out=explode("/", $mystring, 2)[0];

Should work in php 5.4+

Android refresh current activity

You may try this

finish();
startActivity(getIntent());

This question was asked before: How do I restart an Android Activity

Changing factor levels with dplyr mutate

With the forcats package from the tidyverse this is easy, too.

mutate(dat, x = fct_recode(x, "B" = "A"))

Convert a space delimited string to list

try

states.split()

it returns the list

['Alaska',
 'Alabama',
 'Arkansas',
 'American',
 'Samoa',
 'Arizona',
 'California',
 'Colorado']

and this returns the random element of the list

import random
random.choice(states.split())

split statement parses the string and returns the list, by default it's divided into the list by spaces, if you specify the string it's divided by this string, so for example

states.split('Ari')

returns

['Alaska Alabama Arkansas American Samoa ', 'zona California Colorado']

Btw, list is in python interpretated with [] brackets instead of {} brackets, {} brackets are used for dictionaries, you can read more on this here

I see you are probably new to python, so I'd give you some advice how to use python's great documentation

Almost everything you need can be found here You can use also python included documentation, open python console and write help() If you don't know what to do with some object, I'd install ipython, write statement and press Tab, great tool which helps you with interacting with the language

I just wrote this here to show that python is great tool also because it's great documentation and it's really powerful to know this

How to get selected option using Selenium WebDriver with Java

You should be able to get the text using getText() (for the option element you got using getFirstSelectedOption()):

Select select = new Select(driver.findElement(By.xpath("//select")));
WebElement option = select.getFirstSelectedOption();
String defaultItem = option.getText();
System.out.println(defaultItem );

Set selected option of select box

I had a problem where the value was not set because of a syntax error before the call.

$("#someId").value(33); //script bailed here without showing any errors Note: .value instead of .val
$("#gate").val('Gateway 2'); //this line didn't work.

Check for syntax errors before the call.

How to use orderby with 2 fields in linq?

Use ThenByDescending:

var hold = MyList.OrderBy(x => x.StartDate)
                 .ThenByDescending(x => x.EndDate)
                 .ToList();

You can also use query syntax and say:

var hold = (from x in MyList
           orderby x.StartDate, x.EndDate descending
           select x).ToList();

ThenByDescending is an extension method on IOrderedEnumerable which is what is returned by OrderBy. See also the related method ThenBy.

Send HTTP GET request with header

Here's a code excerpt we're using in our app to set request headers. You'll note we set the CONTENT_TYPE header only on a POST or PUT, but the general method of adding headers (via a request interceptor) is used for GET as well.

/**
 * HTTP request types
 */
public static final int POST_TYPE   = 1;
public static final int GET_TYPE    = 2;
public static final int PUT_TYPE    = 3;
public static final int DELETE_TYPE = 4;

/**
 * HTTP request header constants
 */
public static final String CONTENT_TYPE         = "Content-Type";
public static final String ACCEPT_ENCODING      = "Accept-Encoding";
public static final String CONTENT_ENCODING     = "Content-Encoding";
public static final String ENCODING_GZIP        = "gzip";
public static final String MIME_FORM_ENCODED    = "application/x-www-form-urlencoded";
public static final String MIME_TEXT_PLAIN      = "text/plain";

private InputStream performRequest(final String contentType, final String url, final String user, final String pass,
    final Map<String, String> headers, final Map<String, String> params, final int requestType) 
            throws IOException {

    DefaultHttpClient client = HTTPClientFactory.newClient();

    client.getParams().setParameter(HttpProtocolParams.USER_AGENT, mUserAgent);

    // add user and pass to client credentials if present
    if ((user != null) && (pass != null)) {
        client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
    }

    // process headers using request interceptor
    final Map<String, String> sendHeaders = new HashMap<String, String>();
    if ((headers != null) && (headers.size() > 0)) {
        sendHeaders.putAll(headers);
    }
    if (requestType == HTTPRequestHelper.POST_TYPE || requestType == HTTPRequestHelper.PUT_TYPE ) {
        sendHeaders.put(HTTPRequestHelper.CONTENT_TYPE, contentType);
    }
    // request gzip encoding for response
    sendHeaders.put(HTTPRequestHelper.ACCEPT_ENCODING, HTTPRequestHelper.ENCODING_GZIP);

    if (sendHeaders.size() > 0) {
        client.addRequestInterceptor(new HttpRequestInterceptor() {

            public void process(final HttpRequest request, final HttpContext context) throws HttpException,
                IOException {
                for (String key : sendHeaders.keySet()) {
                    if (!request.containsHeader(key)) {
                        request.addHeader(key, sendHeaders.get(key));
                    }
                }
            }
        });
    }

    //.... code omitted ....//

}

Kotlin Error : Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7

A new solution if you use Android Studio 3.2, I solved this issue by added mavenCentral() to build.gradle of the project:

buildscript {
    ext.kotlin_version = '1.3.0'
    repositories {
        mavenCentral()
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

    }
}

allprojects {
    repositories {
        mavenCentral()
        google()
        jcenter()
    }
}

You should add the line as this order, the credited is for this answer

"Unable to launch the IIS Express Web server" error

In Debug > Website Properties.

change port number in Project Url to any nearest value and save

enter image description here

Lua - Current time in milliseconds

If you're using OpenResty then it provides for in-built millisecond time accuracy through the use of its ngx.now() function. Although if you want fine grained millisecond accuracy then you may need to call ngx.update_time() first. Or if you want to go one step further...

If you are using luajit enabled environment, such as OpenResty, then you can also use ffi to access C based time functions such as gettimeofday() e.g: (Note: The pcall check for the existence of struct timeval is only necessary if you're running it repeatedly e.g. via content_by_lua_file in OpenResty - without it you run into errors such as attempt to redefine 'timeval')

if pcall(ffi.typeof, "struct timeval") then
        -- check if already defined.
else
        -- undefined! let's define it!
        ffi.cdef[[
           typedef struct timeval {
                long tv_sec;
                long tv_usec;
           } timeval;

        int gettimeofday(struct timeval* t, void* tzp);
]]
end
local gettimeofday_struct = ffi.new("struct timeval")
local function gettimeofday()
        ffi.C.gettimeofday(gettimeofday_struct, nil)
        return tonumber(gettimeofday_struct.tv_sec) * 1000000 + tonumber(gettimeofday_struct.tv_usec)
end

Then the new lua gettimeofday() function can be called from lua to provide the clock time to microsecond level accuracy.

Indeed, one could take a similar approaching using clock_gettime() to obtain nanosecond accuracy.

CSS list-style-image size

I'm using:

_x000D_
_x000D_
li {_x000D_
 margin: 0;_x000D_
 padding: 36px 0 36px 84px;_x000D_
 list-style: none;_x000D_
 background-image: url("../../images/checked_red.svg");_x000D_
 background-repeat: no-repeat;_x000D_
 background-position: left center;_x000D_
 background-size: 40px;_x000D_
}
_x000D_
_x000D_
_x000D_

where background-size set the background image size.

Run jar file with command line arguments

For the question

How can i run a jar file in command prompt but with arguments

.

To pass arguments to the jar file at the time of execution

java -jar myjar.jar arg1 arg2

In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:

String arg1 = args[0];
String arg2 = args[1];

Why is this printing 'None' in the output?

Because of double print function. I suggest you to use return instead of print inside the function definition.

def lyrics():
    return "The very first line"
print(lyrics())

OR

def lyrics():
    print("The very first line")
lyrics()

What are the special dollar sign shell variables?

  • $_ last argument of last command
  • $# number of arguments passed to current script
  • $* / $@ list of arguments passed to script as string / delimited list

off the top of my head. Google for bash special variables.

Bootstrap: Position of dropdown menu relative to navbar item

If you want to display the menu up, just add the class "dropup"
and remove the class "dropdown" if exists from the same div.

<div class="btn-group dropup">

enter image description here

Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (23.1.0) and test app (23.0.1) differ

I was getting this error

Error:Execution failed for task ':app:preDebugAndroidTestBuild'. Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ. See https://d.android.com/r/tools/test-apk-dependency-conflicts.html for details.

I was having following dependencies in my build.gradle file under Gradle Scripts

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:support-v4:26.1.0'
implementation 'com.android.support:support-vector-drawable:26.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

So, I resolved it by commenting the following dependencies

testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

So my dependencies look like this

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:support-v4:26.1.0'
implementation 'com.android.support:support-vector-drawable:26.1.0'
//testImplementation 'junit:junit:4.12'
//androidTestImplementation 'com.android.support.test:runner:1.0.2'
//androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

Hope it helps!

Unfamiliar symbol in algorithm: what does ? mean?

In math, ? means FOR ALL.

Unicode character (\u2200, ?).

Alternative to itoa() for converting integer to string C++?

Allocate a string of sufficient length, then use snprintf.

Multiple file extensions in OpenFileDialog

This is from MSDN sample:

(*.bmp, *.jpg)|*.bmp;*.jpg

So for your case

openFileDialog1.Filter = "JPG (*.jpg,*.jpeg)|*.jpg;*.jpeg|TIFF (*.tif,*.tiff)|*.tif;*.tiff"

Why do you need ./ (dot-slash) before executable or script name to run it in bash?

When bash interprets the command line, it looks for commands in locations described in the environment variable $PATH. To see it type:

echo $PATH

You will have some paths separated by colons. As you will see the current path . is usually not in $PATH. So Bash cannot find your command if it is in the current directory. You can change it by having:

PATH=$PATH:.

This line adds the current directory in $PATH so you can do:

manage.py syncdb

It is not recommended as it has security issue, plus you can have weird behaviours, as . varies upon the directory you are in :)

Avoid:

PATH=.:$PATH

As you can “mask” some standard command and open the door to security breach :)

Just my two cents.

What is the default encoding of the JVM?

To get default java settings just use :

java -XshowSettings 

ImportError: No module named apiclient.discovery

I fixed the problem by reinstalling the package with:

pip install --force-reinstall google-api-python-client

How to get/generate the create statement for an existing hive table?

As of Hive 0.10 this patch-967 implements SHOW CREATE TABLE which "shows the CREATE TABLE statement that creates a given table, or the CREATE VIEW statement that creates a given view."

Usage:

SHOW CREATE TABLE myTable;

Ajax success function

It is because Ajax is asynchronous, the success or the error function will be called later, when the server answer the client. So, just move parts depending on the result into your success function like that :

jQuery.ajax({

            type:"post",
            dataType:"json",
            url: myAjax.ajaxurl,
            data: {action: 'submit_data', info: info},
            success: function(data) {
                successmessage = 'Data was succesfully captured';
                $("label#successmessage").text(successmessage);
            },
            error: function(data) {
                successmessage = 'Error';
                $("label#successmessage").text(successmessage);
            },
        });

        $(":input").val('');
        return false;

How to pass multiple parameters from ajax to mvc controller?

  var data = JSON.stringify
            ({
            'StrContactDetails': Details,
            'IsPrimary': true
            })

Get the client IP address using PHP

The simplest way to get the visitor’s/client’s IP address is using the $_SERVER['REMOTE_ADDR'] or $_SERVER['REMOTE_HOST'] variables.

However, sometimes this does not return the correct IP address of the visitor, so we can use some other server variables to get the IP address.

The below both functions are equivalent with the difference only in how and from where the values are retrieved.

getenv() is used to get the value of an environment variable in PHP.

// Function to get the client IP address
function get_client_ip() {
    $ipaddress = '';
    if (getenv('HTTP_CLIENT_IP'))
        $ipaddress = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $ipaddress = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
       $ipaddress = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $ipaddress = getenv('REMOTE_ADDR');
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}

$_SERVER is an array that contains server variables created by the web server.

// Function to get the client IP address
function get_client_ip() {
    $ipaddress = '';
    if (isset($_SERVER['HTTP_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if(isset($_SERVER['REMOTE_ADDR']))
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}

How to save data file into .RData?

Just to add an additional function should you need it. You can include a variable in the named location, for example a date identifier

date <- yyyymmdd
save(city, file=paste0("c:\\myuser\\somelocation\\",date,"_RData.Data")

This was you can always keep a check of when it was run