Programs & Examples On #Radcombobox

An ASP.Net UI component provided by the vendor Telerik. It provides extensions to dropdown list type functionality.

how to remove empty strings from list, then remove duplicate values from a list

Amiram's answer is correct, but Distinct() as implemented is an N2 operation; for each item in the list, the algorithm compares it to all the already processed elements, and returns it if it's unique or ignores it if not. We can do better.

A sorted list can be deduped in linear time; if the current element equals the previous element, ignore it, otherwise return it. Sorting is NlogN, so even having to sort the collection, we get some benefit:

public static IEnumerable<T> SortAndDedupe<T>(this IEnumerable<T> input)
{
   var toDedupe = input.OrderBy(x=>x);

   T prev;
   foreach(var element in toDedupe)
   {
      if(element == prev) continue;

      yield return element;
      prev = element;      
   }
}

//Usage
dtList  = dtList.Where(s => !string.IsNullOrWhitespace(s)).SortAndDedupe().ToList();

This returns the same elements; they're just sorted.

The result of a query cannot be enumerated more than once

Try explicitly enumerating the results by calling ToList().

Change

foreach (var item in query)

to

foreach (var item in query.ToList())

Convert JSON String to Pretty Print JSON output using Jackson

To indent any old JSON, just bind it as Object, like:

Object json = mapper.readValue(input, Object.class);

and then write it out with indentation:

String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);

this avoids your having to define actual POJO to map data to.

Or you can use JsonNode (JSON Tree) as well.

How to check if a query string value is present via JavaScript?

The plain javascript code sample which answers your question literally:

return location.search.indexOf('q=')>=0;

The plain javascript code sample which attempts to find if the q parameter exists and if it has a value:

var queryString=location.search;
var params=queryString.substring(1).split('&');
for(var i=0; i<params.length; i++){
    var pair=params[i].split('=');
    if(decodeURIComponent(pair[0])=='q' && pair[1])
        return true;
}
return false;

size of struct in C

Aligning to 6 bytes is not weird, because it is aligning to addresses multiple to 4.

So basically you have 34 bytes in your structure and the next structure should be placed on the address, that is multiple to 4. The closest value after 34 is 36. And this padding area counts into the size of the structure.

Disable Pinch Zoom on Mobile Web

IE has its own way: A css property, -ms-content-zooming. Setting it to none on the body or something should disable it.

Disable pinch to zoom in IE10

http://msdn.microsoft.com/en-us/library/ie/hh771891(v=vs.85).aspx

Change the color of a bullet in a html list?

You'll want to set a "list-style" via CSS, and give it a color: value. Example:

ul.colored {list-style: color: green;}

add new element in laravel collection object

As mentioned above if you wish to as a new element your queried collection you can use:

    $items = DB::select(DB::raw('SELECT * FROM items WHERE items.id = '.$id.'  ;'));
    foreach($items as $item){
        $product = DB::select(DB::raw(' select * from product
               where product_id = '. $id.';' ));

        $items->push($product);
        // or 
        // $items->put('products', $product);
    }

but if you wish to add new element to each queried element you need to do like:

    $items = DB::select(DB::raw('SELECT * FROM items WHERE items.id = '.$id.'  ;'));
    foreach($items as $item){
           $product = DB::select(DB::raw(' select * from product
                 where product_id = '. $id.';' ));

          $item->add_whatever_element_you_want = $product;
    }

add_whatever_element_you_want can be whatever you wish that your element is named (like product for example).

Javascript add leading zeroes to date

You could use ternary operator to format the date like an "if" statement.

For example:

var MyDate = new Date();
MyDate.setDate(MyDate.getDate()+10);
var MyDateString = (MyDate.getDate() < 10 ? '0' + MyDate.getDate() : MyDate.getDate()) + '/' + ((d.getMonth()+1) < 10 ? '0' + (d.getMonth()+1) : (d.getMonth()+1)) + '/' + MyDate.getFullYear();

So

(MyDate.getDate() < 10 ? '0' + MyDate.getDate() : MyDate.getDate())

would be similar to an if statement, where if the getDate() returns a value less than 10, then return a '0' + the Date, or else return the date if greater than 10 (since we do not need to add the leading 0). Same for the month.

Edit: Forgot that getMonth starts with 0, so added the +1 to account for it. Of course you could also just say d.getMonth() < 9 :, but I figured using the +1 would help make it easier to understand.

How to get rid of underline for Link component of React Router?

Look here -> https://material-ui.com/guides/composition/#button.

This is the official material-ui guide. Maybe it'll be useful to you as it was for me.

However, in some cases, underline persists and you may want to use text-decoration: "none" for that. For a more cleaner approach, you can import and use makeStyles from material-ui/core.

import { makeStyles } from '@material-ui/core';

const useStyles = makeStyles(() => ({
    menu-btn: {
        textDecoration: 'none',
    },
}));

const classes = useStyles();

And then set className attribute to {classes.menu-btn} in your JSX code.

Angular.js and HTML5 date input value -- how to get Firefox to show a readable date value in a date input?

The problem is that value is ignored when ng-model is present.

Firefox, which doesn't currently support type="date", will convert all the values to string. Since you (rightly) want date to be a real Date object and not a string, I think the best choice is to create another variable, for instance dateString, and then link the two variables:

<input type="date" ng-model="dateString" />
function MainCtrl($scope, dateFilter) {
    $scope.date = new Date();

    $scope.$watch('date', function (date)
    {
        $scope.dateString = dateFilter(date, 'yyyy-MM-dd');
    });

    $scope.$watch('dateString', function (dateString)
    {
        $scope.date = new Date(dateString);
    });
}

Fiddle

The actual structure is for demonstration purposes only. You'd be better off creating your own directive, especially in order to:

Please notice that I've used yyyy-MM-dd, because it's a format directly supported by the JavaScript Date object. In case you want to use another one, you must make the conversion yourself.


EDIT

Here is a way to make a clean directive:

myModule.directive(
    'dateInput',
    function(dateFilter) {
        return {
            require: 'ngModel',
            template: '<input type="date"></input>',
            replace: true,
            link: function(scope, elm, attrs, ngModelCtrl) {
                ngModelCtrl.$formatters.unshift(function (modelValue) {
                    return dateFilter(modelValue, 'yyyy-MM-dd');
                });

                ngModelCtrl.$parsers.unshift(function(viewValue) {
                    return new Date(viewValue);
                });
            },
        };
});

Fiddle

That's a basic directive, there's still a lot of room for improvement, for example:

  • allow the use of a custom format instead of yyyy-MM-dd,
  • check that the date typed by the user is correct.

JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

Well, what I do on every project is a mix of the options above.

First, add the jsr310 dependency:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

Important detail: put this dependency on the top of your depedencies list. I already see a project where the Localdate error persists even with this dependency on the pom.xml. But changing the order of the depedency the error was gone.

On your /src/main/resources/application.yml file, setup the write-dates-as-timestamps property:

spring:
  jackson:
    serialization:
      write-dates-as-timestamps: false

And create a ObjectMapper bean as this:

@Configuration
public class WebConfigurer {

    @Bean
    @Primary
    public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.build();
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        return objectMapper;
    }

}

Following this configuration, the conversion always work on Spring Boot 1.5.x without any error.

Bonus: Spring AMQP Queue configuration

Working with Spring AMQP, pay attention if you have a new instance of Jackson2JsonMessageConverter (common thing when creating a SimpleRabbitListenerContainerFactory). You need to pass the ObjectMapper bean to it, like:

Jackson2JsonMessageConverter converter = new Jackson2JsonMessageConverter(objectMapper);

Otherwise, you will receive the same error.

Android Spinner : Avoid onItemSelected calls during initialization

My solution:

protected boolean inhibit_spinner = true;


@Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int pos, long arg3) {

            if (inhibit_spinner) {
                inhibit_spinner = false;
            }else {

            if (getDataTask != null) getDataTask.cancel(true);
            updateData();
            }

        }

How do you use colspan and rowspan in HTML tables?

I have used ngIf for one of my similar logic. it is as follows:

_x000D_
_x000D_
<table>
<tr *ngFor="let object of objectData; let i= index;">
<td *ngIf="(i%(object.rowSpan))==0" [attr.rowspan]="object.rowSpan">{{object.value}}</td>
</tr>
</table>
_x000D_
_x000D_
_x000D_

here, i'm getting rowspan value from my model object.

Count character occurrences in a string in C++

#include <boost/range/algorithm/count.hpp>

std::string str = "a_b_c";
int cnt = boost::count(str, '_');

flow 2 columns of text automatically with CSS

This solution will split into two columns and divide the content half in one line half in the other. This comes in handy if you are working with data that gets loaded into the first column, and want it to flow evenly every time. :). You can play with the amount that gets put into the first col. This will work with lists as well.

Enjoy.

<html>
<head>
<title>great script for dividing things into cols</title>



    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
    <script>
$(document).ready(function(){

var count=$('.firstcol span').length;
var selectedIndex =$('.firstcol span').eq(count/2-1);
var selectIndexafter=selectedIndex.nextAll();


if (count>1)
{
selectIndexafter.appendTo('.secondcol');
}

 });

</script>
<style>
body{font-family:arial;}
.firstcol{float:left;padding-left:100px;}
.secondcol{float:left;color:blue;position:relative;top:-20;px;padding-left:100px;}
.secondcol h3 {font-size:18px;font-weight:normal;color:grey}
span{}
</style>

</head>
<body>

<div class="firstcol">

<span>1</span><br />
<span>2</span><br />
<span>3</span><br />
<span>4</span><br />
<span>5</span><br />
<span>6</span><br />
<span>7</span><br />
<span>8</span><br />
<span>9</span><br />
<span>10</span><br />
<!--<span>11</span><br />
<span>12</span><br />
<span>13</span><br />
<span>14</span><br />
<span>15</span><br />
<span>16</span><br />
<span>17</span><br />
<span>18</span><br />
<span>19</span><br />
<span>20</span><br />
<span>21</span><br />
<span>22</span><br />
<span>23</span><br />
<span>24</span><br />
<span>25</span><br />-->
</div>


<div class="secondcol">


</div>


</body>

</html>

Limit Get-ChildItem recursion depth

@scanlegentil I like this.
A little improvement would be:

$Depth = 2
$Path = "."

$Levels = "\*" * $Depth
$Folder = Get-Item $Path
$FolderFullName = $Folder.FullName
Resolve-Path $FolderFullName$Levels | Get-Item | ? {$_.PsIsContainer} | Write-Host

As mentioned, this would only scan the specified depth, so this modification is an improvement:

$StartLevel = 1 # 0 = include base folder, 1 = sub-folders only, 2 = start at 2nd level
$Depth = 2      # How many levels deep to scan
$Path = "."     # starting path

For ($i=$StartLevel; $i -le $Depth; $i++) {
    $Levels = "\*" * $i
    (Resolve-Path $Path$Levels).ProviderPath | Get-Item | Where PsIsContainer |
    Select FullName
}

Arrays in type script

You can also do this as well (shorter cut) instead of having to do instance declaration. You do this in JSON instead.

class Book {
    public BookId: number;
    public Title: string;
    public Author: string;
    public Price: number;
    public Description: string;
}

var bks: Book[] = [];

 bks.push({BookId: 1, Title:"foo", Author:"foo", Price: 5, Description: "foo"});   //This is all done in JSON.

Where do I get servlet-api.jar from?

Make sure that you're using the same Servlet API specification that your Web container supports. Refer to this chart if you're using Tomcat: http://tomcat.apache.org/whichversion.html

The Web container that you use will definitely have the API jars you require.

Tomcat 6 for example has it in apache-tomcat-6.0.26/lib/servlet-api.jar

Bigger Glyphicons

_x000D_
_x000D_
<button class="btn btn-default glyphicon glyphicon-plus fa-2x" type="button">_x000D_
</button>_x000D_
_x000D_
<!--fa-2x , fa-3x , fa-4x ... -->_x000D_
<button class="btn btn-default glyphicon glyphicon-plus fa-3x" type="button">_x000D_
</button>
_x000D_
_x000D_
_x000D_

What does hash do in python?

The hash is used by dictionaries and sets to quickly look up the object. A good starting point is Wikipedia's article on hash tables.

How to delete a file after checking whether it exists

Use System.IO.File.Delete like so:

System.IO.File.Delete(@"C:\test.txt")

From the documentation:

If the file to be deleted does not exist, no exception is thrown.

Can I add a custom attribute to an HTML tag?

Another approach, which is clean and will keep the document valid, is to concatenate the data you want into another tag e.g. id, then use split to take what you want when you want it.

<html>
<script>
  function demonstrate(){
    var x = document.getElementById("example data").querySelectorAll("input");
    console.log(x);
    for(i=0;i<x.length;i++){
      var line_to_illustrate = x[i].id  + ":" + document.getElementById ( x[i].id ).value;
      //concatenated values
      console.log("this is all together: " + line_to_illustrate); 
      //split values
      var split_line_to_illustrate = line_to_illustrate.split(":");
      for(j=0;j<split_line_to_illustrate.length;j++){
        console.log("item " + j+ " is: " + split_line_to_illustrate[j]);
      }      
    }
  }
</script> 

<body>

<div id="example data">
  <!-- consider the id values representing a 'from-to' relationship -->
  <input id="1:2" type="number" name="quantity" min="0" max="9" value="2">
  <input id="1:4" type="number" name="quantity" min="0" max="9" value="1">
  <input id="3:6" type="number" name="quantity" min="0" max="9" value="5">  
</div>

<input type="button" name="" id="?" value="show me" onclick="demonstrate()"/>

</body>
</html>

Drop data frame columns by name

Beyond select(-one_of(drop_col_names)) demonstrated in earlier answers, there are a couple other dplyr options for dropping columns using select() that do not involve defining all the specific column names (using the dplyr starwars sample data for some variety in column names):

library(dplyr)
starwars %>% 
  select(-(name:mass)) %>%        # the range of columns from 'name' to 'mass'
  select(-contains('color')) %>%  # any column name that contains 'color'
  select(-starts_with('bi')) %>%  # any column name that starts with 'bi'
  select(-ends_with('er')) %>%    # any column name that ends with 'er'
  select(-matches('^f.+s$')) %>%  # any column name matching the regex pattern
  select_if(~!is.list(.)) %>%     # not by column name but by data type
  head(2)

# A tibble: 2 x 2
homeworld species
  <chr>     <chr>  
1 Tatooine  Human  
2 Tatooine  Droid 

If you need to drop a column that may or may not exist in the data frame, here's a slight twist using select_if() that unlike using one_of() will not throw an Unknown columns: warning if the column name does not exist. In this example 'bad_column' is not a column in the data frame:

starwars %>% 
  select_if(!names(.) %in% c('height', 'mass', 'bad_column'))

What's the proper value for a checked attribute of an HTML checkbox?

Strictly speaking, you should put something that makes sense - according to the spec here, the most correct version is:

<input name=name id=id type=checkbox checked=checked>

For HTML, you can also use the empty attribute syntax, checked="", or even simply checked (for stricter XHTML, this is not supported).

Effectively, however, most browsers will support just about any value between the quotes. All of the following will be checked:

<input name=name id=id type=checkbox checked>
<input name=name id=id type=checkbox checked="">
<input name=name id=id type=checkbox checked="yes">
<input name=name id=id type=checkbox checked="blue">
<input name=name id=id type=checkbox checked="false">

And only the following will be unchecked:

<input name=name id=id type=checkbox>

See also this similar question on disabled="disabled".

Oracle's default date format is YYYY-MM-DD, WHY?

The format YYYY-MM-DD is part of ISO8601 a standard for the exchange of date (and time) information.

It's very brave of Oracle to adopt an ISO standard like this, but at the same time, strange they didn't go all the way.

In general people resist anything different, but there are many good International reasons for it.

I know I'm saying revolutionary things, but we should all embrace ISO standards, even it we do it a bit at a time.

SQL NVARCHAR and VARCHAR Limits

I understand that there is a 4000 max set for NVARCHAR(MAX)

Your understanding is wrong. nvarchar(max) can store up to (and beyond sometimes) 2GB of data (1 billion double byte characters).

From nchar and nvarchar in Books online the grammar is

nvarchar [ ( n | max ) ]

The | character means these are alternatives. i.e. you specify either n or the literal max.

If you choose to specify a specific n then this must be between 1 and 4,000 but using max defines it as a large object datatype (replacement for ntext which is deprecated).

In fact in SQL Server 2008 it seems that for a variable the 2GB limit can be exceeded indefinitely subject to sufficient space in tempdb (Shown here)

Regarding the other parts of your question

Truncation when concatenating depends on datatype.

  1. varchar(n) + varchar(n) will truncate at 8,000 characters.
  2. nvarchar(n) + nvarchar(n) will truncate at 4,000 characters.
  3. varchar(n) + nvarchar(n) will truncate at 4,000 characters. nvarchar has higher precedence so the result is nvarchar(4,000)
  4. [n]varchar(max) + [n]varchar(max) won't truncate (for < 2GB).
  5. varchar(max) + varchar(n) won't truncate (for < 2GB) and the result will be typed as varchar(max).
  6. varchar(max) + nvarchar(n) won't truncate (for < 2GB) and the result will be typed as nvarchar(max).
  7. nvarchar(max) + varchar(n) will first convert the varchar(n) input to nvarchar(n) and then do the concatenation. If the length of the varchar(n) string is greater than 4,000 characters the cast will be to nvarchar(4000) and truncation will occur.

Datatypes of string literals

If you use the N prefix and the string is <= 4,000 characters long it will be typed as nvarchar(n) where n is the length of the string. So N'Foo' will be treated as nvarchar(3) for example. If the string is longer than 4,000 characters it will be treated as nvarchar(max)

If you don't use the N prefix and the string is <= 8,000 characters long it will be typed as varchar(n) where n is the length of the string. If longer as varchar(max)

For both of the above if the length of the string is zero then n is set to 1.

Newer syntax elements.

1. The CONCAT function doesn't help here

DECLARE @A5000 VARCHAR(5000) = REPLICATE('A',5000);

SELECT DATALENGTH(@A5000 + @A5000), 
       DATALENGTH(CONCAT(@A5000,@A5000));

The above returns 8000 for both methods of concatenation.

2. Be careful with +=

DECLARE @A VARCHAR(MAX) = '';

SET @A+= REPLICATE('A',5000) + REPLICATE('A',5000)

DECLARE @B VARCHAR(MAX) = '';

SET @B = @B + REPLICATE('A',5000) + REPLICATE('A',5000)


SELECT DATALENGTH(@A), 
       DATALENGTH(@B);`

Returns

-------------------- --------------------
8000                 10000

Note that @A encountered truncation.

How to resolve the problem you are experiencing.

You are getting truncation either because you are concatenating two non max datatypes together or because you are concatenating a varchar(4001 - 8000) string to an nvarchar typed string (even nvarchar(max)).

To avoid the second issue simply make sure that all string literals (or at least those with lengths in the 4001 - 8000 range) are prefaced with N.

To avoid the first issue change the assignment from

DECLARE @SQL NVARCHAR(MAX);
SET @SQL = 'Foo' + 'Bar' + ...;

To

DECLARE @SQL NVARCHAR(MAX) = ''; 
SET @SQL = @SQL + N'Foo' + N'Bar'

so that an NVARCHAR(MAX) is involved in the concatenation from the beginning (as the result of each concatenation will also be NVARCHAR(MAX) this will propagate)

Avoiding truncation when viewing

Make sure you have "results to grid" mode selected then you can use

select @SQL as [processing-instruction(x)] FOR XML PATH 

The SSMS options allow you to set unlimited length for XML results. The processing-instruction bit avoids issues with characters such as < showing up as &lt;.

Error: TypeError: $(...).dialog is not a function

I just experienced this with the line:

$('<div id="editor" />').dialogelfinder({

I got the error "dialogelfinder is not a function" because another component was inserting a call to load an older version of JQuery (1.7.2) after the newer version was loaded.

As soon as I commented out the second load, the error went away.

Spark - repartition() vs coalesce()

I would like to add to Justin and Power's answer that -

repartition will ignore existing partitions and create new ones. So you can use it to fix data skew. You can mention partition keys to define the distribution. Data skew is one of the biggest problems in the 'big data' problem space.

coalesce will work with existing partitions and shuffle a subset of them. It can't fix the data skew as much as repartition does. Therefore even if it is less expensive it might not be the thing you need.

How can I get all the request headers in Django?

I don't think there is any easy way to get only HTTP headers. You have to iterate through request.META dict to get what all you need.

django-debug-toolbar takes the same approach to show header information. Have a look at this file responsible for retrieving header information.

How to add custom method to Spring Data JPA

I liked Danila's solution and started using it but nobody else on the team liked having to create 4 classes for each repository. Danila's solution is the only one here that let's you use the Spring Data methods in the Impl class. However, I found a way to do it with just a single class:

public interface UserRepository extends MongoAccess, PagingAndSortingRepository<User> {

    List<User> getByUsername(String username);


    default List<User> getByUsernameCustom(String username) {
        // Can call Spring Data methods!
        findAll();

        // Can write your own!
        MongoOperations operations = getMongoOperations();
        return operations.find(new Query(Criteria.where("username").is(username)), User.class);
    }
}

You just need some way of getting access to your db bean (in this example, MongoOperations). MongoAccess provides that access to all of your repositories by retrieving the bean directly:

public interface MongoAccess {
    default MongoOperations getMongoOperations() {
        return BeanAccessor.getSingleton(MongoOperations.class);
    }
}

Where BeanAccessor is:

@Component
public class BeanAccessor implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public static <T> T getSingleton(Class<T> clazz){
        return applicationContext.getBean(clazz);
    }

    public static <T> T getSingleton(String beanName, Class<T> clazz){
        return applicationContext.getBean(beanName, clazz);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        BeanAccessor.applicationContext = applicationContext;
    }

}

Unfortunately, you can't @Autowire in an interface. You could autowire the bean into a MongoAccessImpl and provide a method in the interface to access it, but Spring Data blows up. I don't think it expects to see an Impl associated even indirectly with PagingAndSortingRepository.

Disable XML validation in Eclipse

Ensure your encoding is correct for all of your files, this can sometimes happen if you have the encoding wrong for your file or the wrong encoding in your XML header.

So, if I have the following NewFile.xml:

<?xml version="1.0" encoding="UTF-16"?>
<bar foo="foiré" />

And the eclipse encoding is UTF-8:

Eclipse Encoding Resource

The encoding of your file, the defined encoding in Eclipse (through Properties->Resource) and the declared encoding in the XML document all need to agree.

The validator is attempting to read the file, expecting <?xml ... but because the encoding is different from that expected, it's not finding it. Hence the error: Content is not allowed in prolog. The prolog is the bit before the <?xml declaration.

EDIT: Sorry, didn't realise that the .xml files were generated and actually contain javascript.

When you suspend the validators, the error messages that you've generated don't go away. To get them to go away, you have to manually delete them.

  1. Suspend the validators
  2. Click on the 'Content is not allowed in prolog' message, right click and delete. You can select multiple ones, or all of them.
  3. Do a Project->Clean. The messages should not come back.

I think that because you've suspended the validators, Eclipse doesn't realise it has to delete the old error messages which came from the validators.

Remove .php extension with .htaccess

Try

RewriteEngine On 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME}.php -f 
RewriteRule ^(.*)$ $1.php [L] 

Move layouts up when soft keyboard is shown?

You can also use this code in onCreate() method:

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

c# dictionary one key many values

Microsoft just added an official prelease version of exactly what you're looking for (called a MultiDictionary) available through NuGet here: https://www.nuget.org/packages/Microsoft.Experimental.Collections/

Info on usage and more details can be found through the official MSDN blog post here: http://blogs.msdn.com/b/dotnet/archive/2014/06/20/would-you-like-a-multidictionary.aspx

I'm the developer for this package, so let me know either here or on MSDN if you have any questions about performance or anything.

Hope that helps.

Update

The MultiValueDictionary is now on the corefxlab repo, and you can get the NuGet package from this MyGet feed.

How to write a Python module/package?

Python 3 - UPDATED 18th November 2015

Found the accepted answer useful, yet wished to expand on several points for the benefit of others based on my own experiences.

Module: A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended.

Module Example: Assume we have a single python script in the current directory, here I am calling it mymodule.py

The file mymodule.py contains the following code:

def myfunc():
    print("Hello!")

If we run the python3 interpreter from the current directory, we can import and run the function myfunc in the following different ways (you would typically just choose one of the following):

>>> import mymodule
>>> mymodule.myfunc()
Hello!
>>> from mymodule import myfunc
>>> myfunc()
Hello!
>>> from mymodule import *
>>> myfunc()
Hello!

Ok, so that was easy enough.

Now assume you have the need to put this module into its own dedicated folder to provide a module namespace, instead of just running it ad-hoc from the current working directory. This is where it is worth explaining the concept of a package.

Package: Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A. Just like the use of modules saves the authors of different modules from having to worry about each other’s global variable names, the use of dotted module names saves the authors of multi-module packages like NumPy or the Python Imaging Library from having to worry about each other’s module names.

Package Example: Let's now assume we have the following folder and files. Here, mymodule.py is identical to before, and __init__.py is an empty file:

.
+-- mypackage
    +-- __init__.py
    +-- mymodule.py

The __init__.py files are required to make Python treat the directories as containing packages. For further information, please see the Modules documentation link provided later on.

Our current working directory is one level above the ordinary folder called mypackage

$ ls
mypackage

If we run the python3 interpreter now, we can import and run the module mymodule.py containing the required function myfunc in the following different ways (you would typically just choose one of the following):

>>> import mypackage
>>> from mypackage import mymodule
>>> mymodule.myfunc()
Hello!
>>> import mypackage.mymodule
>>> mypackage.mymodule.myfunc()
Hello!
>>> from mypackage import mymodule
>>> mymodule.myfunc()
Hello!
>>> from mypackage.mymodule import myfunc
>>> myfunc()
Hello!
>>> from mypackage.mymodule import *
>>> myfunc()
Hello!

Assuming Python 3, there is excellent documentation at: Modules

In terms of naming conventions for packages and modules, the general guidelines are given in PEP-0008 - please see Package and Module Names

Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.

How to find which columns contain any NaN value in Pandas dataframe

UPDATE: using Pandas 0.22.0

Newer Pandas versions have new methods 'DataFrame.isna()' and 'DataFrame.notna()'

In [71]: df
Out[71]:
     a    b  c
0  NaN  7.0  0
1  0.0  NaN  4
2  2.0  NaN  4
3  1.0  7.0  0
4  1.0  3.0  9
5  7.0  4.0  9
6  2.0  6.0  9
7  9.0  6.0  4
8  3.0  0.0  9
9  9.0  0.0  1

In [72]: df.isna().any()
Out[72]:
a     True
b     True
c    False
dtype: bool

as list of columns:

In [74]: df.columns[df.isna().any()].tolist()
Out[74]: ['a', 'b']

to select those columns (containing at least one NaN value):

In [73]: df.loc[:, df.isna().any()]
Out[73]:
     a    b
0  NaN  7.0
1  0.0  NaN
2  2.0  NaN
3  1.0  7.0
4  1.0  3.0
5  7.0  4.0
6  2.0  6.0
7  9.0  6.0
8  3.0  0.0
9  9.0  0.0

OLD answer:

Try to use isnull():

In [97]: df
Out[97]:
     a    b  c
0  NaN  7.0  0
1  0.0  NaN  4
2  2.0  NaN  4
3  1.0  7.0  0
4  1.0  3.0  9
5  7.0  4.0  9
6  2.0  6.0  9
7  9.0  6.0  4
8  3.0  0.0  9
9  9.0  0.0  1

In [98]: pd.isnull(df).sum() > 0
Out[98]:
a     True
b     True
c    False
dtype: bool

or as @root proposed clearer version:

In [5]: df.isnull().any()
Out[5]:
a     True
b     True
c    False
dtype: bool

In [7]: df.columns[df.isnull().any()].tolist()
Out[7]: ['a', 'b']

to select a subset - all columns containing at least one NaN value:

In [31]: df.loc[:, df.isnull().any()]
Out[31]:
     a    b
0  NaN  7.0
1  0.0  NaN
2  2.0  NaN
3  1.0  7.0
4  1.0  3.0
5  7.0  4.0
6  2.0  6.0
7  9.0  6.0
8  3.0  0.0
9  9.0  0.0

How to open an external file from HTML

You may need an extra "/"

<a href="file:///server/directory/file.xlsx">Click me!</a>

Type safety: Unchecked cast

A warning is just that. A warning. Sometimes warnings are irrelevant, sometimes they're not. They're used to call your attention to something that the compiler thinks could be a problem, but may not be.

In the case of casts, it's always going to give a warning in this case. If you are absolutely certain that a particular cast will be safe, then you should consider adding an annotation like this (I'm not sure of the syntax) just before the line:

@SuppressWarnings (value="unchecked")

how to get value of selected item in autocomplete

When autocomplete changes a value, it fires a autocompletechange event, not the change event

$(document).ready(function () {
    $('#tags').on('autocompletechange change', function () {
        $('#tagsname').html('You selected: ' + this.value);
    }).change();
});

Demo: Fiddle

Another solution is to use select event, because the change event is triggered only when the input is blurred

$(document).ready(function () {
    $('#tags').on('change', function () {
        $('#tagsname').html('You selected: ' + this.value);
    }).change();
    $('#tags').on('autocompleteselect', function (e, ui) {
        $('#tagsname').html('You selected: ' + ui.item.value);
    });
});

Demo: Fiddle

Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets

In Xcode 8.0 you can simply do it by changing insets in size inspector.

Select the UIButton -> Attributes Inspector -> go to size inspector and modify the content, image and title insets.

enter image description here

And if you want to change image on right side you can simply change the semantic property to Force Right-to-left in Attribute inspector .

enter image description here

Float to String format specifier

In C#, float is an alias for System.Single (a bit like intis an alias for System.Int32).

Get month name from Date

A quick hack I used which works well:

_x000D_
_x000D_
const monthNumber = 8;_x000D_
const yearNumber = 2018;_x000D_
const date = `${['Jan', 'Feb', 'Mar', 'Apr',_x000D_
  'May', 'Jun', 'Jul', 'Aug',_x000D_
  'Sep', 'Oct', 'Nov', 'Dec'][monthNumber - 1]_x000D_
      } ${yearNumber}`;_x000D_
_x000D_
console.log(date);
_x000D_
_x000D_
_x000D_

IBOutlet and IBAction

IBAction and IBOutlet are macros defined to denote variables and methods that can be referred to in Interface Builder.

IBAction resolves to void and IBOutlet resolves to nothing, but they signify to Xcode and Interface builder that these variables and methods can be used in Interface builder to link UI elements to your code.

If you're not going to be using Interface Builder at all, then you don't need them in your code, but if you are going to use it, then you need to specify IBAction for methods that will be used in IB and IBOutlet for objects that will be used in IB.

Getting the Username from the HKEY_USERS values

It is possible to query this information from WMI. The following command will output a table with a row for every user along with the SID for each user.

wmic useraccount get name,sid

You can also export this information to CSV:

wmic useraccount get name,sid /format:csv > output.csv

I have used this on Vista and 7. For more information see WMIC - Take Command-line Control over WMI.

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

Haskell

foldl (+) 0 [1,2,3,4,5]

Python

reduce(lambda a,b: a+b, [1,2,3,4,5], 0)

Obviously, that is a trivial example to illustrate a point. In Python you would just do sum([1,2,3,4,5]) and even Haskell purists would generally prefer sum [1,2,3,4,5].

For non-trivial scenarios when there is no obvious convenience function, the idiomatic pythonic approach is to explicitly write out the for loop and use mutable variable assignment instead of using reduce or a fold.

That is not at all the functional style, but that is the "pythonic" way. Python is not designed for functional purists. See how Python favors exceptions for flow control to see how non-functional idiomatic python is.

JavaScript Object Id

Actually, you don't need to modify the object prototype. The following should work to 'obtain' unique ids for any object, efficiently enough.

var __next_objid=1;
function objectId(obj) {
    if (obj==null) return null;
    if (obj.__obj_id==null) obj.__obj_id=__next_objid++;
    return obj.__obj_id;
}

ActiveRecord find and only return selected columns

My answer comes quite late because I'm a pretty new developer. This is what you can do:

Location.select(:name, :website, :city).find(row.id)

Btw, this is Rails 4

document.getElementById('btnid').disabled is not working in firefox and chrome

Try setting the disabled attribute directly:

if ( someCondition == true ) {
   document.getElementById('btn1').setAttribute('disabled', 'disabled');
} else {
   document.getElementById('btn1').removeAttribute('disabled');
}

How many times a substring occurs

Here's a solution that works for both non-overlapping and overlapping occurrences. To clarify: an overlapping substring is one whose last character is identical to its first character.

def substr_count(st, sub):
    # If a non-overlapping substring then just
    # use the standard string `count` method
    # to count the substring occurences
    if sub[0] != sub[-1]:
        return st.count(sub)

    # Otherwise, create a copy of the source string,
    # and starting from the index of the first occurence
    # of the substring, adjust the source string to start
    # from subsequent occurences of the substring and keep
    # keep count of these occurences
    _st = st[::]
    start = _st.index(sub)
    cnt = 0

    while start is not None:
        cnt += 1
        try:
            _st = _st[start + len(sub) - 1:]
            start = _st.index(sub)
        except (ValueError, IndexError):
            return cnt

    return cnt

Javascript : get <img> src and set as variable?

If you don't have an id on the image but have a parent div this is also a technique you can use.

<div id="myDiv"><img src="http://www.example.com/image.png"></div>

var myVar = document.querySelectorAll('#myDiv img')[0].src

URL encoding the space character: + or %20?

This confusion is because URLs are still 'broken' to this day.

Take "http://www.google.com" for instance. This is a URL. A URL is a Uniform Resource Locator and is really a pointer to a web page (in most cases). URLs actually have a very well-defined structure since the first specification in 1994.

We can extract detailed information about the "http://www.google.com" URL:

+---------------+-------------------+
|      Part     |      Data         |
+---------------+-------------------+
|  Scheme       | http              |
|  Host         | www.google.com    |
+---------------+-------------------+

If we look at a more complex URL such as:

"https://bob:[email protected]:8080/file;p=1?q=2#third"

we can extract the following information:

+-------------------+---------------------+
|        Part       |       Data          |
+-------------------+---------------------+
|  Scheme           | https               |
|  User             | bob                 |
|  Password         | bobby               |
|  Host             | www.lunatech.com    |
|  Port             | 8080                |
|  Path             | /file;p=1           |
|  Path parameter   | p=1                 |
|  Query            | q=2                 |
|  Fragment         | third               |
+-------------------+---------------------+

https://bob:[email protected]:8080/file;p=1?q=2#third
\___/   \_/ \___/ \______________/ \__/\_______/ \_/ \___/
  |      |    |          |          |      | \_/  |    |
Scheme User Password    Host       Port  Path |   | Fragment
        \_____________________________/       | Query
                       |               Path parameter
                   Authority

The reserved characters are different for each part.

For HTTP URLs, a space in a path fragment part has to be encoded to "%20" (not, absolutely not "+"), while the "+" character in the path fragment part can be left unencoded.

Now in the query part, spaces may be encoded to either "+" (for backwards compatibility: do not try to search for it in the URI standard) or "%20" while the "+" character (as a result of this ambiguity) has to be escaped to "%2B".

This means that the "blue+light blue" string has to be encoded differently in the path and query parts:

"http://example.com/blue+light%20blue?blue%2Blight+blue".

From there you can deduce that encoding a fully constructed URL is impossible without a syntactical awareness of the URL structure.

This boils down to:

You should have %20 before the ? and + after.

Source

An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4

This is all you need:

  1. Right-click on your project, select Maven -> Remove Maven Nature.

  2. Open you terminal, navgate to your project folder and run mvn eclipse:clean

  3. Right click on your Project and select Configure -> Convert into Maven Project

  4. Right click on your Project and select Maven -> Update Project

What is the difference between YAML and JSON?

Technically YAML offers a lot more than JSON (YAML v1.2 is a superset of JSON):

  • comments
  • anchors and inheritance - example of 3 identical items:

    item1: &anchor_name
      name: Test
      title: Test title
    item2: *anchor_name
    item3:
      <<: *anchor_name
      # You may add extra stuff.
    
  • ...

Most of the time people will not use those extra features and the main difference is that YAML uses indentation whilst JSON uses brackets. This makes YAML more concise and readable (for the trained eye).

Which one to choose?

  • YAML extra features and concise notation makes it a good choice for configuration files (non-user provided files).
  • JSON limited features, wide support, and faster parsing makes it a great choice for interoperability and user provided data.

How to use shared memory with Linux in C

try this code sample, I tested it, source: http://www.makelinux.net/alp/035

#include <stdio.h> 
#include <sys/shm.h> 
#include <sys/stat.h> 

int main () 
{
  int segment_id; 
  char* shared_memory; 
  struct shmid_ds shmbuffer; 
  int segment_size; 
  const int shared_segment_size = 0x6400; 

  /* Allocate a shared memory segment.  */ 
  segment_id = shmget (IPC_PRIVATE, shared_segment_size, 
                 IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR); 
  /* Attach the shared memory segment.  */ 
  shared_memory = (char*) shmat (segment_id, 0, 0); 
  printf ("shared memory attached at address %p\n", shared_memory); 
  /* Determine the segment's size. */ 
  shmctl (segment_id, IPC_STAT, &shmbuffer); 
  segment_size  =               shmbuffer.shm_segsz; 
  printf ("segment size: %d\n", segment_size); 
  /* Write a string to the shared memory segment.  */ 
  sprintf (shared_memory, "Hello, world."); 
  /* Detach the shared memory segment.  */ 
  shmdt (shared_memory); 

  /* Reattach the shared memory segment, at a different address.  */ 
  shared_memory = (char*) shmat (segment_id, (void*) 0x5000000, 0); 
  printf ("shared memory reattached at address %p\n", shared_memory); 
  /* Print out the string from shared memory.  */ 
  printf ("%s\n", shared_memory); 
  /* Detach the shared memory segment.  */ 
  shmdt (shared_memory); 

  /* Deallocate the shared memory segment.  */ 
  shmctl (segment_id, IPC_RMID, 0); 

  return 0; 
} 

Converting rows into columns and columns into rows using R

Simply use the base transpose function t, wrapped with as.data.frame:

final_df <- as.data.frame(t(starting_df))
final_df
     A    B    C    D
a    1    2    3    4
b 0.02 0.04 0.06 0.08
c Aaaa Bbbb Cccc Dddd

Above updated. As docendo discimus pointed out, t returns a matrix. As Mark suggested wrapping it with as.data.frame gets back a data frame instead of a matrix. Thanks!

How to filter WooCommerce products by custom attribute

Try WooCommerce Product Filter, plugin developed by Mihajlovicnenad.com. You can filter your products by any criteria. Also, it integrates with your Shop and archive pages perfectly. Here is a screenshot. And this is just one of the layouts, you can customize and make your own. Look at demo site. Thanks! enter image description here

How to escape indicator characters (i.e. : or - ) in YAML

If you're using @ConfigurationProperties with Spring Boot 2 to inject maps with keys that contain colons then you need an additional level of escaping using square brackets inside the quotes because spring only allows alphanumeric and '-' characters, stripping out the rest. Your new key would look like this:

"[8.11.32.120:8000]": GoogleMapsKeyforThisDomain

See this github issue for reference.

TypeError: unhashable type: 'numpy.ndarray'

Your variable energies probably has the wrong shape:

>>> from numpy import array
>>> set([1,2,3]) & set(range(2, 10))
set([2, 3])
>>> set(array([1,2,3])) & set(range(2,10))
set([2, 3])
>>> set(array([[1,2,3],])) & set(range(2,10))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'numpy.ndarray'

And that's what happens if you read columnar data using your approach:

>>> data
array([[  1.,   2.,   3.],
       [  3.,   4.,   5.],
       [  5.,   6.,   7.],
       [  8.,   9.,  10.]])
>>> hsplit(data,3)[0]
array([[ 1.],
       [ 3.],
       [ 5.],
       [ 8.]])

Probably you can simply use

>>> data[:,0]
array([ 1.,  3.,  5.,  8.])

instead.

(P.S. Your code looks like it's undecided about whether it's data or elementdata. I've assumed it's simply a typo.)

in python how do I convert a single digit number into a double digits string?

This is a dumb solution but I was getting type errors with the other solutions above. So if all else fails, yolo:

images3digit = []

for i in images:
        if len(i)==1:
            i = '00'+i
            images3digit.append(i)
        elif len(i)==2:
            i = '0'+i
            images3digit.append(i)
        elif len(i)==3:
            images3digit.append(i)

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

Same as AMIB answer, for soft delete error "Unknown column 'table_alias.deleted_at'", just add ->withTrashed() then handle it yourself like ->whereRaw('items_alias.deleted_at IS NULL')

How do I align a label and a textarea?

Try this:

textarea { vertical-align: top; }? 

How to do a num_rows() on COUNT query in codeigniter?

This will only return 1 row, because you're just selecting a COUNT(). you will use mysql_num_rows() on the $query in this case.

If you want to get a count of each of the ID's, add GROUP BY id to the end of the string.

Performance-wise, don't ever ever ever use * in your queries. If there is 100 unique fields in a table and you want to get them all, you write out all 100, not *. This is because * has to recalculate how many fields it has to go, every single time it grabs a field, which takes a lot more time to call.

jQuery posting valid json in request body

An actual JSON request would look like this:

data: '{"command":"on"}',

Where you're sending an actual JSON string. For a more general solution, use JSON.stringify() to serialize an object to JSON, like this:

data: JSON.stringify({ "command": "on" }),

To support older browsers that don't have the JSON object, use json2.js which will add it in.


What's currently happening is since you have processData: false, it's basically sending this: ({"command":"on"}).toString() which is [object Object]...what you see in your request.

Multiple contexts with the same path error running web service in Eclipse using Tomcat

If you are using STS and your server is Pivotal Just double click on the server and go to >Modules tab >display Configure the Web Modules on this server.>you can just remove modules and run once again.

Running a single test from unittest.TestCase via the command line

TL;DR: This would very likely work:

python mypkg/tests/test_module.py MyCase.testItIsHot

The explanation:

  • The convenient way

      python mypkg/tests/test_module.py MyCase.testItIsHot
    

    would work, but its unspoken assumption is you already have this conventional code snippet inside (typically at the end of) your test file.

    if __name__ == "__main__":
        unittest.main()
    
  • The inconvenient way

      python -m unittest mypkg.tests.test_module.TestClass.test_method
    

    would always work, without requiring you to have that if __name__ == "__main__": unittest.main() code snippet in your test source file.

So why is the second method considered inconvenient? Because it would be a pain in the <insert one of your body parts here> to type that long, dot-delimited path by hand. While in the first method, the mypkg/tests/test_module.py part can be auto-completed, either by a modern shell, or by your editor.

Onclick event to remove default value in a text input field

This is the right, cross-browser way to do it :

<input type="text" value="Enter Your Name" onfocus="if(this.value  == 'Enter Your Name') { this.value = ''; } " onblur="if(this.value == '') { this.value = 'Enter Your Name'; } " />

How to insert an image in python

Install PIL(Python Image Library) :

then:

from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();

Run Bash Command from PHP

Check if have not set a open_basedir in php.ini or .htaccess of domain what you use. That will jail you in directory of your domain and php will get only access to execute inside this directory.

Calculate median in c#

Sometime in the future. This is I think as simple as it can get.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Median
{
    class Program
    {
        static void Main(string[] args)
        {
            var mediaValue = 0.0;
            var items = new[] { 1, 2, 3, 4,5 };
            var getLengthItems = items.Length;
            Array.Sort(items);
            if (getLengthItems % 2 == 0)
            {
                var firstValue = items[(items.Length / 2) - 1];
                var secondValue = items[(items.Length / 2)];
                mediaValue = (firstValue + secondValue) / 2.0;
            }
            if (getLengthItems % 2 == 1)
            {
                mediaValue = items[(items.Length / 2)];
            }
            Console.WriteLine(mediaValue);
            Console.WriteLine("Enter to Exit!");
            Console.ReadKey();
        }
    }
}

seek() function?

Regarding seek() there's not too much to worry about.

First of all, it is useful when operating over an open file.

It's important to note that its syntax is as follows:

fp.seek(offset, from_what)

where fp is the file pointer you're working with; offset means how many positions you will move; from_what defines your point of reference:

  • 0: means your reference point is the beginning of the file
  • 1: means your reference point is the current file position
  • 2: means your reference point is the end of the file

if omitted, from_what defaults to 0.

Never forget that when managing files, there'll always be a position inside that file where you are currently working on. When just open, that position is the beginning of the file, but as you work with it, you may advance.
seek will be useful to you when you need to walk along that open file, just as a path you are traveling into.

Read a file in Node.js

1).For ASync :

var fs = require('fs');
fs.readFile(process.cwd()+"\\text.txt", function(err,data)
            {
                if(err)
                    console.log(err)
                else
                    console.log(data.toString());
            });

2).For Sync :

var fs = require('fs');
var path = process.cwd();
var buffer = fs.readFileSync(path + "\\text.txt");
console.log(buffer.toString());

Read and write a String from text file

Earlier solutions answers question, but in my case deleting old content of file while writing was a problem.

So, I created piece of code for writing to file in documents directory without deleting previous content. You probably need better error handling, but I believe it's good starting point. Swift 4. Usuage:

    let filename = "test.txt"
    createOrOverwriteEmptyFileInDocuments(filename: filename)
    if let handle = getHandleForFileInDocuments(filename: filename) {
        writeString(string: "aaa", fileHandle: handle)
        writeString(string: "bbb", fileHandle: handle)
        writeString(string: "\n", fileHandle: handle)
        writeString(string: "ccc", fileHandle: handle)
    }

Helper methods:

func createOrOverwriteEmptyFileInDocuments(filename: String){
    guard let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
        debugPrint("ERROR IN createOrOverwriteEmptyFileInDocuments")
        return
    }
    let fileURL = dir.appendingPathComponent(filename)
    do {
        try "".write(to: fileURL, atomically: true, encoding: .utf8)
    }
    catch {
        debugPrint("ERROR WRITING STRING: " + error.localizedDescription)
    }
    debugPrint("FILE CREATED: " + fileURL.absoluteString)
}

private func writeString(string: String, fileHandle: FileHandle){
    let data = string.data(using: String.Encoding.utf8)
    guard let dataU = data else {
        debugPrint("ERROR WRITING STRING: " + string)
        return
    }
    fileHandle.seekToEndOfFile()
    fileHandle.write(dataU)
}

private func getHandleForFileInDocuments(filename: String)->FileHandle?{
    guard let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
        debugPrint("ERROR OPENING FILE")
        return nil
    }
    let fileURL = dir.appendingPathComponent(filename)
    do {
        let fileHandle: FileHandle? = try FileHandle(forWritingTo: fileURL)
        return fileHandle
    }
    catch {
        debugPrint("ERROR OPENING FILE: " + error.localizedDescription)
        return nil
    }
}

UTC Date/Time String to Timezone

Assuming the UTC is not included in the string then:

date_default_timezone_set('America/New_York');
$datestring = '2011-01-01 15:00:00';  //Pulled in from somewhere
$date = date('Y-m-d H:i:s T',strtotime($datestring . ' UTC'));
echo $date;  //Should get '2011-01-01 10:00:00 EST' or something like that

Or you could use the DateTime object.

XPath OR operator for different nodes

All title nodes with zipcode or book node as parent:

Version 1:

//title[parent::zipcode|parent::book]

Version 2:

//bookstore/book/title|//bookstore/city/zipcode/title

Version 3: (results are sorted based on source data rather than the order of book then zipcode)

//title[../../../*[book or magazine] or ../../../../*[city/zipcode]]

or - used within true/false - a Boolean operator in xpath

| - a Union operator in xpath that appends the query to the right of the operator to the result set from the left query.

How to get the function name from within that function?

In ES6, you can just use myFunction.name.

Note: Beware that some JS minifiers might throw away function names, to compress better; you may need to tweak their settings to avoid that.

In ES5, the best thing to do is:

function functionName(fun) {
  var ret = fun.toString();
  ret = ret.substr('function '.length);
  ret = ret.substr(0, ret.indexOf('('));
  return ret;
}

Using Function.caller is non-standard. Function.caller and arguments.callee are both forbidden in strict mode.

Edit: nus's regex based answer below achieves the same thing, but has better performance!

How to add elements of a Java8 stream into an existing List

I would concatenate the old list and new list as streams and save the results to destination list. Works well in parallel, too.

I will use the example of accepted answer given by Stuart Marks:

List<String> destList = Arrays.asList("foo");
List<String> newList = Arrays.asList("0", "1", "2", "3", "4", "5");

destList = Stream.concat(destList.stream(), newList.stream()).parallel()
            .collect(Collectors.toList());
System.out.println(destList);

//output: [foo, 0, 1, 2, 3, 4, 5]

Hope it helps.

Right query to get the current number of connections in a PostgreSQL DB

Aggregation of all postgres sessions per their status (how many are idle, how many doing something...)

select state, count(*) from pg_stat_activity  where pid <> pg_backend_pid() group by 1 order by 1;

Installing Tomcat 7 as Service on Windows Server 2008

Looks like now they have the bat in the zip as well

note that you can use windows sc command to do more

e.g.

sc config tomcat7 start= auto

yes the space before auto is NEEDED

Serializing PHP object to JSON

json_encode() will only encode public member variables. so if you want to include the private once you have to do it by yourself (as the others suggested)

How can I plot a histogram such that the heights of the bars sum to 1 in matplotlib?

Here is another simple solution using np.histogram() method.

myarray = np.random.random(100)
results, edges = np.histogram(myarray, normed=True)
binWidth = edges[1] - edges[0]
plt.bar(edges[:-1], results*binWidth, binWidth)

You can indeed check that the total sums up to 1 with:

> print sum(results*binWidth)
1.0

How do I download a package from apt-get without installing it?

Try

apt-get -d install <packages>

It is documented in man apt-get.

Just for clarification; the downloaded packages are located in the apt package cache at

/var/cache/apt/archives

How to clear PermGen space Error in tomcat

This one worked for me, in startup.bat the following line needs to be added if it doesn't exist set JAVA_OPTS with the value -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256. The full line:

set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256

Calculate cosine similarity given 2 sentence strings

The short answer is "no, it is not possible to do that in a principled way that works even remotely well". It is an unsolved problem in natural language processing research and also happens to be the subject of my doctoral work. I'll very briefly summarize where we are and point you to a few publications:

Meaning of words

The most important assumption here is that it is possible to obtain a vector that represents each word in the sentence in quesion. This vector is usually chosen to capture the contexts the word can appear in. For example, if we only consider the three contexts "eat", "red" and "fluffy", the word "cat" might be represented as [98, 1, 87], because if you were to read a very very long piece of text (a few billion words is not uncommon by today's standard), the word "cat" would appear very often in the context of "fluffy" and "eat", but not that often in the context of "red". In the same way, "dog" might be represented as [87,2,34] and "umbrella" might be [1,13,0]. Imagening these vectors as points in 3D space, "cat" is clearly closer to "dog" than it is to "umbrella", therefore "cat" also means something more similar to "dog" than to an "umbrella".

This line of work has been investigated since the early 90s (e.g. this work by Greffenstette) and has yielded some surprisingly good results. For example, here is a few random entries in a thesaurus I built recently by having my computer read wikipedia:

theory -> analysis, concept, approach, idea, method
voice -> vocal, tone, sound, melody, singing
james -> william, john, thomas, robert, george, charles

These lists of similar words were obtained entirely without human intervention- you feed text in and come back a few hours later.

The problem with phrases

You might ask why we are not doing the same thing for longer phrases, such as "ginger foxes love fruit". It's because we do not have enough text. In order for us to reliably establish what X is similar to, we need to see many examples of X being used in context. When X is a single word like "voice", this is not too hard. However, as X gets longer, the chances of finding natural occurrences of X get exponentially slower. For comparison, Google has about 1B pages containing the word "fox" and not a single page containing "ginger foxes love fruit", despite the fact that it is a perfectly valid English sentence and we all understand what it means.

Composition

To tackle the problem of data sparsity, we want to perform composition, i.e. to take vectors for words, which are easy to obtain from real text, and to put the together in a way that captures their meaning. The bad news is nobody has been able to do that well so far.

The simplest and most obvious way is to add or multiply the individual word vectors together. This leads to undesirable side effect that "cats chase dogs" and "dogs chase cats" would mean the same to your system. Also, if you are multiplying, you have to be extra careful or every sentences will end up represented by [0,0,0,...,0], which defeats the point.

Further reading

I will not discuss the more sophisticated methods for composition that have been proposed so far. I suggest you read Katrin Erk's "Vector space models of word meaning and phrase meaning: a survey". This is a very good high-level survey to get you started. Unfortunately, is not freely available on the publisher's website, email the author directly to get a copy. In that paper you will find references to many more concrete methods. The more comprehensible ones are by Mitchel and Lapata (2008) and Baroni and Zamparelli (2010).


Edit after comment by @vpekar: The bottom line of this answer is to stress the fact that while naive methods do exist (e.g. addition, multiplication, surface similarity, etc), these are fundamentally flawed and in general one should not expect great performance from them.

Are multiple `.gitignore`s frowned on?

You can have multiple .gitignore, each one of course in its own directory.
To check which gitignore rule is responsible for ignoring a file, use git check-ignore: git check-ignore -v -- afile.

And you can have different version of a .gitignore file per branch: I have already seen that kind of configuration for ensuring one branch ignores a file while the other branch does not: see this question for instance.

If your repo includes several independent projects, it would be best to reference them as submodules though.
That would be the actual best practices, allowing each of those projects to be cloned independently (with their respective .gitignore files), while being referenced by a specific revision in a global parent project.
See true nature of submodules for more.


Note that, since git 1.8.2 (March 2013) you can do a git check-ignore -v -- yourfile in order to see which gitignore run (from which .gitignore file) is applied to 'yourfile', and better understand why said file is ignored.
See "which gitignore rule is ignoring my file?"

How to compare two vectors for equality element by element in C++?

Your code (vector1 == vector2) is correct C++ syntax. There is an == operator for vectors.

If you want to compare short vector with a portion of a longer vector, you can use theequal() operator for vectors. (documentation here)

Here's an example:

using namespace std;

if( equal(vector1.begin(), vector1.end(), vector2.begin()) )
    DoSomething();

How do I fix a "Performance counter registry hive consistency" when installing SQL Server R2 Express?

Ignoring the check results in a corrupted install. This is the only solution that worked for me:

  1. Create a C# console app with the following code: Console.WriteLine(string.Format("{0,3}", CultureInfo.InstalledUICulture.Parent.LCID.ToString("X")).Replace(" ", "0"));

  2. Run the app and get the 3 digit code.

  3. Run > Regedit, open the following path: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib

Now, if you don't have a folder underneath that path with the 3 digit code from step 2, create it. If you do have the folder, check that it has the "Counter" and "Help" values set under that path. It probably doesn't -- which is why the check fails.

Create the missing Counter and Help keys (REG_MULTI_SZ). For the values, copy them from the existing path above (probably 009).

The check should now pass.

How to get first 5 characters from string

You can use the substr function like this:

echo substr($myStr, 0, 5);

The second argument to substr is from what position what you want to start and third arguments is for how many characters you want to return.

conditional Updating a list using LINQ

How about

(from k in myList
 where k.id > 35
 select k).ToList().ForEach(k => k.Name = "Banana");

How can I shrink the drawable on a button?

I made a custom button class to achieve this.

CustomButton.java

public class CustomButton extends android.support.v7.widget.AppCompatButton {

    private Drawable mDrawable;

    public CustomButton(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray a = context.getTheme().obtainStyledAttributes(
                attrs,
                R.styleable.CustomButton,
                0, 0);

        try {
            float mWidth = a.getDimension(R.styleable.CustomButton_drawable_width, 0);
            float mHeight = a.getDimension(R.styleable.CustomButton_drawable_width, 0);

            Drawable[] drawables = this.getCompoundDrawables();
            Drawable[] resizedDrawable = new Drawable[4];

            for (int i = 0; i < drawables.length; i++) {
                if (drawables[i] != null) {
                    mDrawable = drawables[i];
                }
                resizedDrawable[i] = getResizedDrawable(drawables[i], mWidth, mHeight);
            }

            this.setCompoundDrawables(resizedDrawable[0], resizedDrawable[1], resizedDrawable[2], resizedDrawable[3]);
        } finally {
            a.recycle();
        }
    }

    public Drawable getmDrawable() {
        return mDrawable;
    }

    private Drawable getResizedDrawable(Drawable drawable, float mWidth, float mHeight) {
        if (drawable == null) {
            return null;
        }

        try {
            Bitmap bitmap;

            bitmap = Bitmap.createBitmap((int)mWidth, (int)mHeight, Bitmap.Config.ARGB_8888);

            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
            drawable.draw(canvas);
            return drawable;
        } catch (OutOfMemoryError e) {
            // Handle the error
            return null;
        }
    }
}

attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomButton">
        <attr name="drawable_width" format="dimension" />
        <attr name="drawable_height" format="dimension" />
    </declare-styleable>
</resources>

Usage in xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.MainActivity">

     <com.example.CustomButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:drawableTop="@drawable/ic_hero"
            android:text="Avenger"
            custom:drawable_height="10dp"
            custom:drawable_width="10dp" />

</RelativeLayout>

Does HTTP use UDP?

If you are streaming an mp3 or video that may not necessarily be over HTTP, in fact I'd be suprised if it was. It would probably be another protocol over TCP but I see no reason why you cannot stream over UDP.

If you do you have to take into account that there is no certainty that your data will arrive at the other end, but I can take it that you know about UDP.

To answer you question, No, HTTP does NOT use UDP. For what you talk about though, mp3/video streaming COULD happen over UDP and in my opinion should never happen over HTTP.

How to round up a number in Javascript?

ok, this has been answered, but I thought you might like to see my answer that calls the math.pow() function once. I guess I like keeping things DRY.

function roundIt(num, precision) {
    var rounder = Math.pow(10, precision);
    return (Math.round(num * rounder) / rounder).toFixed(precision)
};

It kind of puts it all together. Replace Math.round() with Math.ceil() to round-up instead of rounding-off, which is what the OP wanted.

Find a value anywhere in a database

Here, very sweet and small solution:

1) create a store procedure:

create procedure get_table
@find_str varchar(50)
as 
begin
  declare @col_name varchar(500), @tab_name varchar(500);
  declare @find_tab TABLE(table_name varchar(100), column_name varchar(100));

  DECLARE tab_col cursor for 
  select C.name as 'col_name', T.name as tab_name
  from sys.tables as T
  left outer join sys.columns as C on  C.object_id=T.object_id
  left outer join sys.types as TP on  C.system_type_id=TP.system_type_id
  where type='U' 
  and TP.name in('text','ntext','varchar','char','nvarchar','nchar');

  open tab_col
  fetch next from tab_col into @col_name, @tab_name

  while @@FETCH_STATUS = 0
  begin        
    insert into @find_tab 
    exec('select ''' +  @tab_name + ''',''' + @col_name + ''' from ' + @tab_name + 
    ' where ' + @col_name + '=''' + @find_str + ''' group by ' + 
    @col_name + ' having count(*)>0');

    fetch next from tab_col into @col_name, @tab_name;
  end
  CLOSE tab_col;  
  DEALLOCATE tab_col; 
  select table_name, column_name from @find_tab;

end

==========================

2) call procedure by calling store procedure:
exec get_table 'serach_string';

Curl to return http status code along with the response

In my experience we usually use curl this way

curl -f http://localhost:1234/foo || exit 1

curl: (22) The requested URL returned error: 400 Bad Request

This way we can pipe the curl when it fails, and it also shows the status code.

ORACLE IIF Statement

Oracle doesn't provide such IIF Function. Instead, try using one of the following alternatives:

DECODE Function:

SELECT DECODE(EMP_ID, 1, 'True', 'False') from Employee

CASE Function:

SELECT CASE WHEN EMP_ID = 1 THEN 'True' ELSE 'False' END from Employee

Is it possible to opt-out of dark mode on iOS 13?

In Xcode 12, you can change add as "appearances". This will work!!

XAMPP permissions on Mac OS X?

For new XAMPP-VM for Mac OS X,
I change the ownership to daemon user and solve the problem.

For example,

$ chown -R daemon:daemon /opt/lampp/htdocs/hello-laravel/storage

Converting ArrayList to HashMap

[edited]

using your comment about productCode (and assuming product code is a String) as reference...

 for(Product p : productList){
        s.put(p.getProductCode() , p);
    }

HTTP Status 405 - Method Not Allowed Error for Rest API

@Produces({"text/plain","application/xml","application/json"}) change this to @Produces("text/plain") and try,

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

When You are sending a single quote in a query

empid = " T'via"
empid =escape(empid)

When You get the value including a single quote

var xxx  = request.QueryString("empid")
xxx= unscape(xxx)

If you want to search/ insert the value which includes a single quote in a query xxx=Replace(empid,"'","''")

PHP date yesterday

strtotime(), as in date("F j, Y", strtotime("yesterday"));

How do I set up curl to permanently use a proxy?

Curl will look for a .curlrc file in your home folder when it starts. You can create (or edit) this file and add this line:

proxy = yourproxy.com:8080

How to debug Javascript with IE 8

I was hoping to add this as a comment to Marcus Westin's reply, but I can't find a link - maybe I need more reputation?


Anyway, thanks, I found this code snippet useful for quick debugging in IE. I have made some quick tweaks to fix a problem that stopped it working for me, also to scroll down automatically and use fixed positioning so it will appear in the viewport. Here's my version in case anyone finds it useful:

myLog = function() {

    var _div = null;

    this.toJson = function(obj) {

        if (typeof window.uneval == 'function') { return uneval(obj); }
        if (typeof obj == 'object') {
            if (!obj) { return 'null'; }
            var list = [];
            if (obj instanceof Array) {
                    for (var i=0;i < obj.length;i++) { list.push(this.toJson(obj[i])); }
                    return '[' + list.join(',') + ']';
            } else {
                    for (var prop in obj) { list.push('"' + prop + '":' + this.toJson(obj[prop])); }
                    return '{' + list.join(',') + '}';
            }
        } else if (typeof obj == 'string') {
            return '"' + obj.replace(/(["'])/g, '\\$1') + '"';
        } else {
            return new String(obj);
        }

    };

    this.createDiv = function() {

        myLog._div = document.body.appendChild(document.createElement('div'));

        var props = {
            position:'fixed', top:'10px', right:'10px', background:'#333', border:'5px solid #333', 
            color: 'white', width: '400px', height: '300px', overflow: 'auto', fontFamily: 'courier new',
            fontSize: '11px', whiteSpace: 'nowrap'
        }

        for (var key in props) { myLog._div.style[key] = props[key]; }

    };


    if (!myLog._div) { this.createDiv(); }

    var logEntry = document.createElement('span');

    for (var i=0; i < arguments.length; i++) {
        logEntry.innerHTML += this.toJson(arguments[i]) + '<br />';
    }

    logEntry.innerHTML += '<br />';

    myLog._div.appendChild(logEntry);

    // Scroll automatically to the bottom
    myLog._div.scrollTop = myLog._div.scrollHeight;

}

How to check if div element is empty

Using plain javascript

 var isEmpty = document.getElementById('cartContent').innerHTML === "";

And if you are using jquery it can be done like

 var isEmpty = $("#cartContent").html() === "";

How to get row from R data.frame

10 years later ---> Using tidyverse we could achieve this simply and borrowing a leaf from Christopher Bottoms. For a better grasp, see slice().

library(tidyverse)
x <- structure(list(A = c(5,    3.5, 3.25, 4.25,  1.5 ), 
                    B = c(4.25, 4,   4,    4.5,   4.5 ),
                    C = c(4.5,  2.5, 4,    2.25,  3   )
),
.Names    = c("A", "B", "C"),
class     = "data.frame",
row.names = c(NA, -5L)
)

x
#>      A    B    C
#> 1 5.00 4.25 4.50
#> 2 3.50 4.00 2.50
#> 3 3.25 4.00 4.00
#> 4 4.25 4.50 2.25
#> 5 1.50 4.50 3.00

y<-c(A=5, B=4.25, C=4.5)
y
#>    A    B    C 
#> 5.00 4.25 4.50

#The slice() verb allows one to subset data row-wise. 
x <- x %>% slice(1) #(n) for the nth row, or (i:n) for range i to n, (i:n()) for i to last row...

x
#>   A    B   C
#> 1 5 4.25 4.5

#Test that the items in the row match the vector you wanted
x[1,]==y
#>      A    B    C
#> 1 TRUE TRUE TRUE

Created on 2020-08-06 by the reprex package (v0.3.0)

Executing Javascript from Python

You can also use Js2Py which is written in pure python and is able to both execute and translate javascript to python. Supports virtually whole JavaScript even labels, getters, setters and other rarely used features.

import js2py

js = """
function escramble_758(){
var a,b,c
a='+1 '
b='84-'
a+='425-'
b+='7450'
c='9'
document.write(a+c+b)
}
escramble_758()
""".replace("document.write", "return ")

result = js2py.eval_js(js)  # executing JavaScript and converting the result to python string 

Advantages of Js2Py include portability and extremely easy integration with python (since basically JavaScript is being translated to python).

To install:

pip install js2py

Find p-value (significance) in scikit-learn LinearRegression

EDIT: Probably not the right way to do it, see comments

You could use sklearn.feature_selection.f_regression.

click here for the scikit-learn page

How to pattern match using regular expression in Scala?

To expand a little on Andrew's answer: The fact that regular expressions define extractors can be used to decompose the substrings matched by the regex very nicely using Scala's pattern matching, e.g.:

val Process = """([a-cA-C])([^\s]+)""".r // define first, rest is non-space
for (p <- Process findAllIn "aha bah Cah dah") p match {
  case Process("b", _) => println("first: 'a', some rest")
  case Process(_, rest) => println("some first, rest: " + rest)
  // etc.
}

Git: How configure KDiff3 as merge tool and diff tool

(When trying to find out how to use kdiff3 from WSL git I ended up here and got the final pieces, so I'll post my solution for anyone else also stumbling in here while trying to find that answer)

How to use kdiff3 as diff/merge tool for WSL git

With Windows update 1903 it is a lot easier; just use wslpath and there is no need to share TMP from Windows to WSL since the Windows side now has access to the WSL filesystem via \wsl$:

[merge]
    renormalize = true
    guitool = kdiff3
[diff]
    tool = kdiff3
[difftool]
    prompt = false
[difftool "kdiff3"]
    # Unix style paths must be converted to windows path style
    cmd = kdiff3.exe \"`wslpath -w $LOCAL`\" \"`wslpath -w $REMOTE`\"
    trustExitCode = false
[mergetool]
    keepBackup = false
    prompt = false
[mergetool "kdiff3"]
    path = kdiff3.exe
    trustExitCode = false

Before Windows update 1903

Steps for using kdiff3 installed on Windows 10 as diff/merge tool for git in WSL:

  1. Add the kdiff3 installation directory to the Windows Path.
  2. Add TMP to the WSLENV Windows environment variable (WSLENV=TMP/up). The TMP dir will be used by git for temporary files, like previous revisions of files, so the path must be on the windows filesystem for this to work.
  3. Set TMPDIR to TMP in .bashrc:
# If TMP is passed via WSLENV then use it as TMPDIR
[[ ! -z "$WSLENV" && ! -z "$TMP" ]] && export TMPDIR=$TMP
  1. Convert unix-path to windows-path when calling kdiff3. Sample of my .gitconfig:
[merge]
    renormalize = true
    guitool = kdiff3
[diff]
    tool = kdiff3
[difftool]
    prompt = false
[difftool "kdiff3"]
    #path = kdiff3.exe
    # Unix style paths must be converted to windows path style by changing '/mnt/c/' or '/c/' to 'c:/'
    cmd = kdiff3.exe \"`echo $LOCAL | sed 's_^\\(/mnt\\)\\?/\\([a-z]\\)/_\\2:/_'`\" \"`echo $REMOTE | sed 's_^\\(/mnt\\)\\?/\\([a-z]\\)/_\\2:/_'`\"
    trustExitCode = false
[mergetool]
    keepBackup = false
    prompt = false
[mergetool "kdiff3"]
    path = kdiff3.exe
    trustExitCode = false

Find the index of a char in string?

The String class exposes some methods to enable this, such as IndexOf and LastIndexOf, so that you may do this:

Dim myText = "abcde"
Dim dIndex = myText.IndexOf("d")
If (dIndex > -1) Then

End If

Undefined reference to main - collect2: ld returned 1 exit status

It means that es3.c does not define a main function, and you are attempting to create an executable out of it. An executable needs to have an entry point, thereby the linker complains.

To compile only to an object file, use the -c option:

gcc es3.c -c
gcc es3.o main.c -o es3

The above compiles es3.c to an object file, then compiles a file main.c that would contain the main function, and the linker merges es3.o and main.o into an executable called es3.

Copy files on Windows Command Line with Progress

I used the copy command with the /z switch for copying over network drives. Also works for copying between local drives. Tested on XP Home edition.

set pythonpath before import statements

This will add a path to your Python process / instance (i.e. the running executable). The path will not be modified for any other Python processes. Another running Python program will not have its path modified, and if you exit your program and run again the path will not include what you added before. What are you are doing is generally correct.

set.py:

import sys
sys.path.append("/tmp/TEST")

loop.py

import sys
import time
while True:
  print sys.path
  time.sleep(1)

run: python loop.py &

This will run loop.py, connected to your STDOUT, and it will continue to run in the background. You can then run python set.py. Each has a different set of environment variables. Observe that the output from loop.py does not change because set.py does not change loop.py's environment.

A note on importing

Python imports are dynamic, like the rest of the language. There is no static linking going on. The import is an executable line, just like sys.path.append....

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

Just do the following:

build.gradle

(module:app)


android {
            ....
      defaultConfig {
              multiDexEnabled true // enable mun
      }
}

And add below dependency in your build.gradle app level file

dependencies {
    implementation 'com.android.support:multidex:1.0.3'
} 

Regex to match only letters

Use a character set: [a-zA-Z] matches one letter from A–Z in lowercase and uppercase. [a-zA-Z]+ matches one or more letters and ^[a-zA-Z]+$ matches only strings that consist of one or more letters only (^ and $ mark the begin and end of a string respectively).

If you want to match other letters than A–Z, you can either add them to the character set: [a-zA-ZäöüßÄÖÜ]. Or you use predefined character classes like the Unicode character property class \p{L} that describes the Unicode characters that are letters.

Using Server.MapPath in external C# Classes in ASP.NET

System.Reflection.Assembly.GetAssembly(type).Location

IF the file you are trying to get is the assembly location for a type. But if the files are relative to the assembly location then you can use this with System.IO namespace to get the exact path of the file.

How to detect scroll direction

Following example will listen to MOUSE scroll only, no touch nor trackpad scrolls.

It uses jQuery.on() (As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document).

$('#elem').on( 'DOMMouseScroll mousewheel', function ( event ) {
  if( event.originalEvent.detail > 0 || event.originalEvent.wheelDelta < 0 ) { //alternative options for wheelData: wheelDeltaX & wheelDeltaY
    //scroll down
    console.log('Down');
  } else {
    //scroll up
    console.log('Up');
  }
  //prevent page fom scrolling
  return false;
});

Works on all browsers.

fiddle: http://jsfiddle.net/honk1/gWnNv/7/

What is the best way to uninstall gems from a rails3 project?

With newer versions of bundler you can use the clean task:

$ bundle help clean
Usage:
    bundle clean

Options:
    [--dry-run=only print out changes, do not actually clean gems]
    [--force=forces clean even if --path is not set]
    [--no-color=Disable colorization in output]
    -V, [--verbose=Enable verbose output mode]

Cleans up unused gems in your bundler directory
$ bundle clean --dry-run --force
Would have removed actionmailer (3.1.12)
Would have removed actionmailer (3.2.0.rc2)
Would have removed actionpack (3.1.12)
Would have removed actionpack (3.2.0.rc2)
Would have removed activemodel (3.1.12)
...

edit:

This is not recommended if you're using a global gemset (i.e. - all of your projects keep their gems in the same place). There're few ways to keep each project's gems separate, though:

  1. rvm gemsets (http://rvm.io/gemsets/basics)
  2. bundle install with any of the following options: --deployment or --path=<path> (http://bundler.io/v1.3/man/bundle-install.1.html)

How to query for today's date and 7 days before data?

Try this way:

select * from tab
where DateCol between DateAdd(DD,-7,GETDATE() ) and GETDATE() 

Mockito: InvalidUseOfMatchersException

Inspite of using all the matchers, I was getting the same issue:

"org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
1 matchers expected, 3 recorded:"

It took me little while to figure this out that the method I was trying to mock was a static method of a class(say Xyz.class) which contains only static method and I forgot to write following line:

PowerMockito.mockStatic(Xyz.class);

May be it will help others as it may also be the cause of the issue.

Write single CSV file using spark-csv

This answer expands on the accepted answer, gives more context, and provides code snippets you can run in the Spark Shell on your machine.

More context on accepted answer

The accepted answer might give you the impression the sample code outputs a single mydata.csv file and that's not the case. Let's demonstrate:

val df = Seq("one", "two", "three").toDF("num")
df
  .repartition(1)
  .write.csv(sys.env("HOME")+ "/Documents/tmp/mydata.csv")

Here's what's outputted:

Documents/
  tmp/
    mydata.csv/
      _SUCCESS
      part-00000-b3700504-e58b-4552-880b-e7b52c60157e-c000.csv

N.B. mydata.csv is a folder in the accepted answer - it's not a file!

How to output a single file with a specific name

We can use spark-daria to write out a single mydata.csv file.

import com.github.mrpowers.spark.daria.sql.DariaWriters
DariaWriters.writeSingleFile(
    df = df,
    format = "csv",
    sc = spark.sparkContext,
    tmpFolder = sys.env("HOME") + "/Documents/better/staging",
    filename = sys.env("HOME") + "/Documents/better/mydata.csv"
)

This'll output the file as follows:

Documents/
  better/
    mydata.csv

S3 paths

You'll need to pass s3a paths to DariaWriters.writeSingleFile to use this method in S3:

DariaWriters.writeSingleFile(
    df = df,
    format = "csv",
    sc = spark.sparkContext,
    tmpFolder = "s3a://bucket/data/src",
    filename = "s3a://bucket/data/dest/my_cool_file.csv"
)

See here for more info.

Avoiding copyMerge

copyMerge was removed from Hadoop 3. The DariaWriters.writeSingleFile implementation uses fs.rename, as described here. Spark 3 still used Hadoop 2, so copyMerge implementations will work in 2020. I'm not sure when Spark will upgrade to Hadoop 3, but better to avoid any copyMerge approach that'll cause your code to break when Spark upgrades Hadoop.

Source code

Look for the DariaWriters object in the spark-daria source code if you'd like to inspect the implementation.

PySpark implementation

It's easier to write out a single file with PySpark because you can convert the DataFrame to a Pandas DataFrame that gets written out as a single file by default.

from pathlib import Path
home = str(Path.home())
data = [
    ("jellyfish", "JALYF"),
    ("li", "L"),
    ("luisa", "LAS"),
    (None, None)
]
df = spark.createDataFrame(data, ["word", "expected"])
df.toPandas().to_csv(home + "/Documents/tmp/mydata-from-pyspark.csv", sep=',', header=True, index=False)

Limitations

The DariaWriters.writeSingleFile Scala approach and the df.toPandas() Python approach only work for small datasets. Huge datasets can not be written out as single files. Writing out data as a single file isn't optimal from a performance perspective because the data can't be written in parallel.

How can I include css files using node, express, and ejs?

In your app or server.js file include this line:

app.use(express.static('public'));

In your index.ejs, following line will help you:

<link rel="stylesheet" type="text/css" href="/css/style.css" />

I hope this helps, it did for me!

'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel

I wrote this method to handle UTF8 arrays and JSON problems. It works fine with array (simple and multidimensional).

/**
 * Encode array from latin1 to utf8 recursively
 * @param $dat
 * @return array|string
 */
   public static function convert_from_latin1_to_utf8_recursively($dat)
   {
      if (is_string($dat)) {
         return utf8_encode($dat);
      } elseif (is_array($dat)) {
         $ret = [];
         foreach ($dat as $i => $d) $ret[ $i ] = self::convert_from_latin1_to_utf8_recursively($d);

         return $ret;
      } elseif (is_object($dat)) {
         foreach ($dat as $i => $d) $dat->$i = self::convert_from_latin1_to_utf8_recursively($d);

         return $dat;
      } else {
         return $dat;
      }
   }
// Sample use
// Just pass your array or string and the UTF8 encode will be fixed
$data = convert_from_latin1_to_utf8_recursively($data);

Unable to copy file - access to the path is denied

Changing the output path worked for me in Visual Studio 2015. This should help - Changing the Build Output directory

Error handling in AngularJS http get then construct

I could not really work with the above. So this might help someone.

$http.get(url)
  .then(
    function(response) {
        console.log('get',response)
    }
  ).catch(
    function(response) {
    console.log('return code: ' + response.status);
    }
  )

See also the $http response parameter.

Send Outlook Email Via Python?

Simplest of all solutions for OFFICE 365:

from O365 import Message

html_template =     """ 
            <html>
            <head>
                <title></title>
            </head>
            <body>
                    {}
            </body>
            </html>
        """

final_html_data = html_template.format(df.to_html(index=False))

o365_auth = ('sender_username@company_email.com','Password')
m = Message(auth=o365_auth)
m.setRecipients('receiver_username@company_email.com')
m.setSubject('Weekly report')
m.setBodyHTML(final)
m.sendMessage()

here df is a dataframe converted to html Table, which is being injected to html_template

MySQL: #1075 - Incorrect table definition; autoincrement vs another key?

Identified this solution while reading this thread. Figured id post this for the next guy possibly.

When dealing with Laravel migration file from a package, I Ran into this issue.

My old value was

$table->increments('id');

My new

$table->integer('id')->autoIncrement();

What is the max size of VARCHAR2 in PL/SQL and SQL?

As per official documentation link shared by Andre Kirpitch, Oracle 10g gives a maximum size of 4000 bytes or characters for varchar2. If you are using a higher version of oracle (for example Oracle 12c), you can get a maximum size upto 32767 bytes or characters for varchar2. To utilize the extended datatype feature of oracle 12, you need to start oracle in upgrade mode. Follow the below steps in command prompt:

1) Login as sysdba (sqlplus / as sysdba)

2) SHUTDOWN IMMEDIATE;

3) STARTUP UPGRADE;

4) ALTER SYSTEM SET max_string_size=extended;

5) Oracle\product\12.1.0.2\rdbms\admin\utl32k.sql

6) SHUTDOWN IMMEDIATE;

7) STARTUP;

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

If you are not on Oracle 12C, you can use TOP N query like below.

SELECT *
 FROM
   ( SELECT rownum rnum
          , a.*
       FROM sometable a 
   ORDER BY name
   )
WHERE rnum BETWEEN 10 AND 20;

You can even move this from clause in with clause as follows

WITH b AS
( SELECT rownum rnum
      , a.* 
   FROM sometable a ORDER BY name
) 
SELECT * FROM b 
WHERE rnum BETWEEN 10 AND 20;

Here actually we are creating a inline view and renaming rownum as rnum. You can use rnum in main query as filter criteria.

How to commit to remote git repository

git push

or

git push server_name master

should do the trick, after you have made a commit to your local repository.

Why are only final variables accessible in anonymous class?

When an anonymous inner class is defined within the body of a method, all variables declared final in the scope of that method are accessible from within the inner class. For scalar values, once it has been assigned, the value of the final variable cannot change. For object values, the reference cannot change. This allows the Java compiler to "capture" the value of the variable at run-time and store a copy as a field in the inner class. Once the outer method has terminated and its stack frame has been removed, the original variable is gone but the inner class's private copy persists in the class's own memory.

(http://en.wikipedia.org/wiki/Final_%28Java%29)

MySQL Error 1153 - Got a packet bigger than 'max_allowed_packet' bytes

In etc/my.cnf try changing the max_allowed _packet and net_buffer_length to

max_allowed_packet=100000000
net_buffer_length=1000000 

if this is not working then try changing to

max_allowed_packet=100M
net_buffer_length=100K 

TensorFlow not found using pip

If you are trying to install Tensorflow with Anaconda on Windows, a free advice is to please uninstall anaconda and download a 64-bit Python version, ending with amd64 from releases page. For me, its python-3.7.8-amd64.exe

Then install Tensorflow in a virtual environment by following the instructions on official website of Tensorflow.

Setting the default ssh key location

man ssh gives me this options would could be useful.

-i identity_file Selects a file from which the identity (private key) for RSA or DSA authentication is read. The default is ~/.ssh/identity for protocol version 1, and ~/.ssh/id_rsa and ~/.ssh/id_dsa for pro- tocol version 2. Identity files may also be specified on a per- host basis in the configuration file. It is possible to have multiple -i options (and multiple identities specified in config- uration files).

So you could create an alias in your bash config with something like

alias ssh="ssh -i /path/to/private_key"

I haven't looked into a ssh configuration file, but like the -i option this too could be aliased

-F configfile Specifies an alternative per-user configuration file. If a configuration file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored. The default for the per-user configuration file is ~/.ssh/config.

VB.NET - Remove a characters from a String

Function RemoveCharacter(ByVal stringToCleanUp, ByVal characterToRemove)
  ' replace the target with nothing
  ' Replace() returns a new String and does not modify the current one
  Return stringToCleanUp.Replace(characterToRemove, "")
End Function

Here's more information about VB's Replace function

Original purpose of <input type="hidden">?

I can only imagine of sending a value from the server to the client which is (unchanged) sent back to maintain a kind of a state.

Precisely. In fact, it's still being used for this purpose today because HTTP as we know it today is still, at least fundamentally, a stateless protocol.

This use case was actually first described in HTML 3.2 (I'm surprised HTML 2.0 didn't include such a description):

type=hidden
These fields should not be rendered and provide a means for servers to store state information with a form. This will be passed back to the server when the form is submitted, using the name/value pair defined by the corresponding attributes. This is a work around for the statelessness of HTTP. Another approach is to use HTTP "Cookies".

<input type=hidden name=customerid value="c2415-345-8563">

While it's worth mentioning that HTML 3.2 became a W3C Recommendation only after JavaScript's initial release, it's safe to assume that hidden fields have pretty much always served the same purpose.

How can I get customer details from an order in WooCommerce?

I was looking for something like this. It works well.

So get the mobile number in WooCommerce plugin like this -

$customer_id = get_current_user_id();
print get_user_meta($customer_id, 'billing_phone', true);

GitLab git user password

On my Windows 10 machine it was because the SSH_GIT environment variable wasn't set to use the putty plink I had installed on my machine.

Parsing JSON objects for HTML table

Here are two ways to do the same thing, with or without jQuery:

_x000D_
_x000D_
// jquery way_x000D_
$(document).ready(function () {_x000D_
    _x000D_
  var json = [{"User_Name":"John Doe","score":"10","team":"1"},{"User_Name":"Jane Smith","score":"15","team":"2"},{"User_Name":"Chuck Berry","score":"12","team":"2"}];_x000D_
        _x000D_
  var tr;_x000D_
  for (var i = 0; i < json.length; i++) {_x000D_
    tr = $('<tr/>');_x000D_
    tr.append("<td>" + json[i].User_Name + "</td>");_x000D_
    tr.append("<td>" + json[i].score + "</td>");_x000D_
    tr.append("<td>" + json[i].team + "</td>");_x000D_
    $('table').first().append(tr);_x000D_
  }  _x000D_
});_x000D_
_x000D_
// without jquery_x000D_
function ready(){_x000D_
 var json = [{"User_Name":"John Doe","score":"10","team":"1"},{"User_Name":"Jane Smith","score":"15","team":"2"},{"User_Name":"Chuck Berry","score":"12","team":"2"}];_x000D_
  const table = document.getElementsByTagName('table')[1];_x000D_
  json.forEach((obj) => {_x000D_
      const row = table.insertRow(-1)_x000D_
    row.innerHTML = `_x000D_
      <td>${obj.User_Name}</td>_x000D_
      <td>${obj.score}</td>_x000D_
      <td>${obj.team}</td>_x000D_
    `;_x000D_
  });_x000D_
};_x000D_
_x000D_
if (document.attachEvent ? document.readyState === "complete" : document.readyState !== "loading"){_x000D_
  ready();_x000D_
} else {_x000D_
  document.addEventListener('DOMContentLoaded', ready);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table>_x000D_
    <tr>_x000D_
        <th>User_Name</th>_x000D_
        <th>score</th>_x000D_
        <th>team</th>_x000D_
    </tr>_x000D_
</table>'_x000D_
<table>_x000D_
    <tr>_x000D_
        <th>User_Name</th>_x000D_
        <th>score</th>_x000D_
        <th>team</th>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Run two async tasks in parallel and collect results in .NET 4.5

async Task<int> LongTask1() { 
  ...
  return 0; 
}

async Task<int> LongTask2() { 
  ...
  return 1; 
}

...
{
   Task<int> t1 = LongTask1();
   Task<int> t2 = LongTask2();
   await Task.WhenAll(t1,t2);
   //now we have t1.Result and t2.Result
}

How can I include null values in a MIN or MAX?

I try to use a union to combine two queries to format the returns you want:

SELECT recordid, startdate, enddate FROM tmp Where enddate is null UNION SELECT recordid, MIN(startdate), MAX(enddate) FROM tmp GROUP BY recordid

But I have no idea if the Union would have great impact on the performance

Convert A String (like testing123) To Binary In Java

The usual way is to use String#getBytes() to get the underlying bytes and then present those bytes in some other form (hex, binary whatever).

Note that getBytes() uses the default charset, so if you want the string converted to some specific character encoding, you should use getBytes(String encoding) instead, but many times (esp when dealing with ASCII) getBytes() is enough (and has the advantage of not throwing a checked exception).

For specific conversion to binary, here is an example:

  String s = "foo";
  byte[] bytes = s.getBytes();
  StringBuilder binary = new StringBuilder();
  for (byte b : bytes)
  {
     int val = b;
     for (int i = 0; i < 8; i++)
     {
        binary.append((val & 128) == 0 ? 0 : 1);
        val <<= 1;
     }
     binary.append(' ');
  }
  System.out.println("'" + s + "' to binary: " + binary);

Running this example will yield:

'foo' to binary: 01100110 01101111 01101111 

android download pdf from url then open it with a pdf reader

This is the best method to download and view PDF file.You can just call it from anywhere as like

PDFTools.showPDFUrl(context, url);

here below put the code. It will works fine

public class PDFTools {
private static final String TAG = "PDFTools";
private static final String GOOGLE_DRIVE_PDF_READER_PREFIX = "http://drive.google.com/viewer?url=";
private static final String PDF_MIME_TYPE = "application/pdf";
private static final String HTML_MIME_TYPE = "text/html";


public static void showPDFUrl(final Context context, final String pdfUrl ) {
    if ( isPDFSupported( context ) ) {
        downloadAndOpenPDF(context, pdfUrl);
    } else {
        askToOpenPDFThroughGoogleDrive( context, pdfUrl );
    }
}


@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static void downloadAndOpenPDF(final Context context, final String pdfUrl) {
    // Get filename
    //final String filename = pdfUrl.substring( pdfUrl.lastIndexOf( "/" ) + 1 );
    String filename = "";
    try {
        filename = new GetFileInfo().execute(pdfUrl).get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    // The place where the downloaded PDF file will be put
    final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), filename );
    Log.e(TAG,"File Path:"+tempFile);
    if ( tempFile.exists() ) {
        // If we have downloaded the file before, just go ahead and show it.
        openPDF( context, Uri.fromFile( tempFile ) );
        return;
    }

    // Show progress dialog while downloading
    final ProgressDialog progress = ProgressDialog.show( context, context.getString( R.string.pdf_show_local_progress_title ), context.getString( R.string.pdf_show_local_progress_content ), true );

    // Create the download request
    DownloadManager.Request r = new DownloadManager.Request( Uri.parse( pdfUrl ) );
    r.setDestinationInExternalFilesDir( context, Environment.DIRECTORY_DOWNLOADS, filename );
    final DownloadManager dm = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE );
    BroadcastReceiver onComplete = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ( !progress.isShowing() ) {
                return;
            }
            context.unregisterReceiver( this );

            progress.dismiss();
            long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1 );
            Cursor c = dm.query( new DownloadManager.Query().setFilterById( downloadId ) );

            if ( c.moveToFirst() ) {
                int status = c.getInt( c.getColumnIndex( DownloadManager.COLUMN_STATUS ) );
                if ( status == DownloadManager.STATUS_SUCCESSFUL ) {
                    openPDF( context, Uri.fromFile( tempFile ) );
                }
            }
            c.close();
        }
    };
    context.registerReceiver( onComplete, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) );

    // Enqueue the request
    dm.enqueue( r );
}


public static void askToOpenPDFThroughGoogleDrive( final Context context, final String pdfUrl ) {
    new AlertDialog.Builder( context )
            .setTitle( R.string.pdf_show_online_dialog_title )
            .setMessage( R.string.pdf_show_online_dialog_question )
            .setNegativeButton( R.string.pdf_show_online_dialog_button_no, null )
            .setPositiveButton( R.string.pdf_show_online_dialog_button_yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    openPDFThroughGoogleDrive(context, pdfUrl);
                }
            })
            .show();
}

public static void openPDFThroughGoogleDrive(final Context context, final String pdfUrl) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setDataAndType(Uri.parse(GOOGLE_DRIVE_PDF_READER_PREFIX + pdfUrl ), HTML_MIME_TYPE );
    context.startActivity( i );
}

public static final void openPDF(Context context, Uri localUri ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setDataAndType( localUri, PDF_MIME_TYPE );
    context.startActivity( i );
}

public static boolean isPDFSupported( Context context ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), "test.pdf" );
    i.setDataAndType( Uri.fromFile( tempFile ), PDF_MIME_TYPE );
    return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
}

// get File name from url
static class GetFileInfo extends AsyncTask<String, Integer, String>
{
    protected String doInBackground(String... urls)
    {
        URL url;
        String filename = null;
        try {
            url = new URL(urls[0]);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            conn.setInstanceFollowRedirects(false);
            if(conn.getHeaderField("Content-Disposition")!=null){
                String depo = conn.getHeaderField("Content-Disposition");

                String depoSplit[] = depo.split("filename=");
                filename = depoSplit[1].replace("filename=", "").replace("\"", "").trim();
            }else{
                filename = "download.pdf";
            }
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
        }
        return filename;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        // use result as file name
    }
}

}

try it. it will works, enjoy

MongoDb query condition on comparing 2 fields

You can use a $where. Just be aware it will be fairly slow (has to execute Javascript code on every record) so combine with indexed queries if you can.

db.T.find( { $where: function() { return this.Grade1 > this.Grade2 } } );

or more compact:

db.T.find( { $where : "this.Grade1 > this.Grade2" } );

UPD for mongodb v.3.6+

you can use $expr as described in recent answer

How to convert HTML file to word?

Try using pandoc

pandoc -f html -t docx -o output.docx input.html

If the input or output format is not specified explicitly, pandoc will attempt to guess it from the extensions of the input and output filenames.
— pandoc manual

So you can even use

pandoc -o output.docx input.html

Add centered text to the middle of a <hr/>-like line

This worked for me and does not require background color behind the text to hide a border line, instead uses actual hr tag. You can play around with the widths to get different sizes of hr lines.

<div>
    <div style="display:inline-block;width:45%"><hr width='80%' /></div>
    <div style="display:inline-block;width: 9%;text-align: center;vertical-align:90%;text-height: 24px"><h4>OR</h4></div>
    <div style="display:inline-block;width:45%;float:right" ><hr width='80%'/></div>
</div>

Android Fragment handle back button press

I'm working with SlidingMenu and Fragment, present my case here and hope helps somebody.

Logic when [Back] key pressed :

  1. When SlidingMenu shows, close it, no more things to do.
  2. Or when 2nd(or more) Fragment showing, slide back to previous Fragment, and no more things to do.
  3. SlidingMenu not shows, current Fragment is #0, do the original [Back] key does.

    public class Main extends SherlockFragmentActivity
    {
      private SlidingMenu menu=null;
      Constants.VP=new ViewPager(this);
    
      //Some stuff...
    
      @Override
      public void onBackPressed()
      {
        if(menu.isMenuShowing())
        {
          menu.showContent(true); //Close SlidingMenu when menu showing
          return;
        }
        else
        {
          int page=Constants.VP.getCurrentItem();
          if(page>0)
          {
            Constants.VP.setCurrentItem(page-1, true); //Show previous fragment until Fragment#0
            return;
          }
          else
          {super.onBackPressed();} //If SlidingMenu is not showing and current Fragment is #0, do the original [Back] key does. In my case is exit from APP
        }
      }
    }
    

Comparing double values in C#

From the documentation:

Precision in Comparisons The Equals method should be used with caution, because two apparently equivalent values can be unequal due to the differing precision of the two values. The following example reports that the Double value .3333 and the Double returned by dividing 1 by 3 are unequal.

...

Rather than comparing for equality, one recommended technique involves defining an acceptable margin of difference between two values (such as .01% of one of the values). If the absolute value of the difference between the two values is less than or equal to that margin, the difference is likely to be due to differences in precision and, therefore, the values are likely to be equal. The following example uses this technique to compare .33333 and 1/3, the two Double values that the previous code example found to be unequal.

So if you really need a double, you should use the techique described on the documentation. If you can, change it to a decimal. It' will be slower, but you won't have this type of problem.

Converting bytes to megabytes

BTW: Hard drive manufacturers don't count as authorities on this one!

Oh, yes they do (and the definition they assume from the S.I. is the correct one). On a related issue, see this post on CodingHorror.

Static variables in C++

Excuse me when I answer your questions out-of-order, it makes it easier to understand this way.

When static variable is declared in a header file is its scope limited to .h file or across all units.

There is no such thing as a "header file scope". The header file gets included into source files. The translation unit is the source file including the text from the header files. Whatever you write in a header file gets copied into each including source file.

As such, a static variable declared in a header file is like a static variable in each individual source file.

Since declaring a variable static this way means internal linkage, every translation unit #includeing your header file gets its own, individual variable (which is not visible outside your translation unit). This is usually not what you want.

I would like to know what is the difference between static variables in a header file vs declared in a class.

In a class declaration, static means that all instances of the class share this member variable; i.e., you might have hundreds of objects of this type, but whenever one of these objects refers to the static (or "class") variable, it's the same value for all objects. You could think of it as a "class global".

Also generally static variable is initialized in .cpp file when declared in a class right ?

Yes, one (and only one) translation unit must initialize the class variable.

So that does mean static variable scope is limited to 2 compilation units ?

As I said:

  • A header is not a compilation unit,
  • static means completely different things depending on context.

Global static limits scope to the translation unit. Class static means global to all instances.

I hope this helps.

PS: Check the last paragraph of Chubsdad's answer, about how you shouldn't use static in C++ for indicating internal linkage, but anonymous namespaces. (Because he's right. ;-) )

'Invalid update: invalid number of rows in section 0

Swift Version --> Remove the object from your data array before you call

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        print("Deleted")

        currentCart.remove(at: indexPath.row) //Remove element from your array 
        self.tableView.deleteRows(at: [indexPath], with: .automatic)
    }
}

How can I override inline styles with external CSS?

<div style="background: red;">
    The inline styles for this div should make it red.
</div>

div[style] {
   background: yellow !important;
}

Below is the link for more details: http://css-tricks.com/override-inline-styles-with-css/

Rebase feature branch onto another feature branch

  1. Switch to Branch2

    git checkout Branch2
    
  2. Apply the current (Branch2) changes on top of the Branch1 changes, staying in Branch2:

    git rebase Branch1
    

Which would leave you with the desired result in Branch2:

a -- b -- c                      <-- Master
           \
            d -- e               <-- Branch1
           \
            d -- e -- f' -- g'   <-- Branch2

You can delete Branch1.

convert string date to java.sql.Date

worked for me too:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date parsed = null;
    try {
        parsed = sdf.parse("02/01/2014");
    } catch (ParseException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    java.sql.Date data = new java.sql.Date(parsed.getTime());
    contato.setDataNascimento( data);

    // Contato DataNascimento era Calendar
    //contato.setDataNascimento(Calendar.getInstance());         

    // grave nessa conexão!!! 
    ContatoDao dao = new ContatoDao("mysql");           

    // método elegante 
    dao.adiciona(contato); 
    System.out.println("Banco: ["+dao.getNome()+"] Gravado! Data: "+contato.getDataNascimento());

Should ol/ul be inside <p> or outside?

The second. The first is invalid.

  • A paragraph cannot contain a list.
  • A list cannot contain a paragraph unless that paragraph is contained entirely within a single list item.

A browser will handle it like so:

<p>tetxtextextete 
<!-- Start of paragraph -->
<ol>
<!-- Start of ordered list. Paragraphs cannot contain lists. Insert </p> -->
<li>first element</li></ol>
<!-- A list item element. End of list -->
</p>
<!-- End of paragraph, but not inside paragraph, discard this tag to recover from the error -->
<p>other textetxet</p>
<!-- Another paragraph -->

Writing/outputting HTML strings unescaped

Supposing your content is inside a string named mystring...

You can use:

@Html.Raw(mystring)

Alternatively you can convert your string to HtmlString or any other type that implements IHtmlString in model or directly inline and use regular @:

@{ var myHtmlString = new HtmlString(mystring);}
@myHtmlString

How to specify the default error page in web.xml?

You can also specify <error-page> for exceptions using <exception-type>, eg below:

<error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/errorpages/exception.html</location>
</error-page>

Or map a error code using <error-code>:

<error-page>
    <error-code>404</error-code>
    <location>/errorpages/404error.html</location>
</error-page>

GROUP BY without aggregate function

I know you said you want to understand group by if you have data like this:

COL-A  COL-B  COL-C  COL-D
  1      Ac      C1     D1
  2      Bd      C2     D2
  3      Ba      C1     D3
  4      Ab      C1     D4
  5      C       C2     D5

And you want to make the data appear like:

COL-A  COL-B  COL-C  COL-D
  4      Ab      C1     D4
  1      Ac      C1     D1
  3      Ba      C1     D3
  2      Bd      C2     D2
  5      C       C2     D5

You use:

select * from table_name
order by col-c,colb

Because I think this is what you intend to do.

How to sum up elements of a C++ vector?

It is easy. C++11 provides an easy way to sum up elements of a vector.

sum = 0; 
vector<int> vec = {1,2,3,4,5,....}
for(auto i:vec) 
   sum+=i;
cout<<" The sum is :: "<<sum<<endl; 

Heroku 'Permission denied (publickey) fatal: Could not read from remote repository' woes

I had the exact same error (on windows 7) and the cause was different. I solved it in a different way so I thought I'd add the cause and solution here for others.

Even though the error seemed to point to heroku really the error was saying "Heroku can't get to the git repository". I swore I had the same keys on all the servers because I created it and uploaded it to one after the other at the same time.

After spending almost a day on this I realized that because git was only showing me the fingerprint and not the actual key. I couldn't verify that it's key matched the one on my HD or heroku. I looked in the known hosts file and guess what... it shows the keys for each server and I was able to clearly see that the git and heroku public keys did not match.

1) I deleted all the files in my key folder, the key from github using their website, and the key from heroku using git bash and the command heroku keys:clear

2) Followed github's instructions here to generate a new key pair and upload the public key to git

3) using git bash- heroku keys:add to upload the same key to heroku.

Now git push heroku master works.

what a nightmare, hope this helped somebody.

Bryan

What difference is there between WebClient and HTTPWebRequest classes in .NET?

Also WebClient doesn't have timeout property. And that's the problem, because dafault value is 100 seconds and that's too much to indicate if there's no Internet connection.

Workaround for that problem is here https://stackoverflow.com/a/3052637/1303422

Swing/Java: How to use the getText and setText string properly

in your action performed method, call:

label1.setText(nameField.getText());

This way, when the button is clicked, label will be updated to the nameField text.

How to add a touch event to a UIView?

Swift 3:

let tapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapGestureRecognizer(_:)))
view.addGestureRecognizer(tapGestureRecognizer)

func handleTapGestureRecognizer(_ gestureRecognizer: UITapGestureRecognizer) {

}

Missing artifact com.oracle:ojdbc6:jar:11.2.0 in pom.xml

You need to check your config file if it has correct values such as systempath and artifact Id.

    <dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc6</artifactId>
    <version>1.0</version>
    <scope>system</scope>
    <systemPath>C:\Users\Akshay\Downloads\ojdbc6.jar</systemPath>
    </dependency> 

JavaScript: Check if mouse button down?

The following snippet will attempt to execute the "doStuff" function 2 seconds after the mouseDown event occurs in document.body. If the user lifts up the button, the mouseUp event will occur and cancel the delayed execution.

I'd advise using some method for cross-browser event attachment - setting the mousedown and mouseup properties explicitly was done to simplify the example.

function doStuff() {
  // does something when mouse is down in body for longer than 2 seconds
}

var mousedownTimeout;

document.body.onmousedown = function() { 
  mousedownTimeout = window.setTimeout(doStuff, 2000);
}

document.body.onmouseup = function() {
  window.clearTimeout(mousedownTimeout);
}

Update date + one year in mysql

This post helped me today, but I had to experiment to do what I needed. Here is what I found.

Should you want to add more complex time periods, for example 1 year and 15 days, you can use

UPDATE tablename SET datefieldname = curdate() + INTERVAL 15 DAY + INTERVAL 1 YEAR;

I found that using DATE_ADD doesn't allow for adding more than one interval. And there is no YEAR_DAYS interval keyword, though there are others that combine time periods. If you are adding times, use now() rather than curdate().

What does ECU units, CPU core and memory mean when I launch a instance

For linuxes I've figured out that ECU could be measured by sysbench:

sysbench --num-threads=128 --test=cpu --cpu-max-prime=50000 --max-requests=50000 run

Total time (t) should be calculated by formula:

ECU=1925/t

And my example test results:

|   instance type   |   time   |   ECU   |
|-------------------|----------|---------|
| m1.small          |  1735,62 |       1 |
| m3.xlarge         |   147,62 |      13 |
| m3.2xlarge        |    74,61 |      26 |
| r3.large          |   295,84 |       7 |
| r3.xlarge         |   148,18 |      13 |
| m4.xlarge         |   146,71 |      13 |
| m4.2xlarge        |    73,69 |      26 |
| c4.xlarge         |   123,59 |      16 |
| c4.2xlarge        |    61,91 |      31 |
| c4.4xlarge        |    31,14 |      62 |

How to run a program in Atom Editor?

You can run specific lines of script by highlighting them and clicking shift + ctrl + b

You can also use command line by going to the root folder and writing: $ node nameOfFile.js

PHP header redirect 301 - what are the implications?

The effect of the 301 would be that the search engines will index /option-a instead of /option-x. Which is probably a good thing since /option-x is not reachable for the search index and thus could have a positive effect on the index. Only if you use this wisely ;-)

After the redirect put exit(); to stop the rest of the script to execute

header("HTTP/1.1 301 Moved Permanently"); 
header("Location: /option-a"); 
exit();

Joining two table entities in Spring Data JPA

For a typical example of employees owning one or more phones, see this wikibook section.

For your specific example, if you want to do a one-to-one relationship, you should change the next code in ReleaseDateType model:

@Column(nullable = true) 
private Integer media_Id;

for:

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name="CACHE_MEDIA_ID", nullable=true)
private CacheMedia cacheMedia ;

and in CacheMedia model you need to add:

@OneToOne(cascade=ALL, mappedBy="ReleaseDateType")
private ReleaseDateType releaseDateType;

then in your repository you should replace:

@Query("Select * from A a  left join B b on a.id=b.id")
public List<ReleaseDateType> FindAllWithDescriptionQuery();

by:

//In this case a query annotation is not need since spring constructs the query from the method name
public List<ReleaseDateType> findByCacheMedia_Id(Integer id); 

or by:

@Query("FROM ReleaseDateType AS rdt WHERE cm.rdt.cacheMedia.id = ?1")    //This is using a named query method
public List<ReleaseDateType> FindAllWithDescriptionQuery(Integer id);

Or if you prefer to do a @OneToMany and @ManyToOne relation, you should change the next code in ReleaseDateType model:

@Column(nullable = true) 
private Integer media_Id;

for:

@OneToMany(cascade=ALL, mappedBy="ReleaseDateType")
private List<CacheMedia> cacheMedias ;

and in CacheMedia model you need to add:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="RELEASE_DATE_TYPE_ID", nullable=true)
private ReleaseDateType releaseDateType;

then in your repository you should replace:

@Query("Select * from A a  left join B b on a.id=b.id")
public List<ReleaseDateType> FindAllWithDescriptionQuery();

by:

//In this case a query annotation is not need since spring constructs the query from the method name
public List<ReleaseDateType> findByCacheMedias_Id(Integer id); 

or by:

@Query("FROM ReleaseDateType AS rdt LEFT JOIN rdt.cacheMedias AS cm WHERE cm.id = ?1")    //This is using a named query method
public List<ReleaseDateType> FindAllWithDescriptionQuery(Integer id);

How do I replace whitespaces with underscore?

You don't need regular expressions. Python has a built-in string method that does what you need:

mystring.replace(" ", "_")

How to get rid of "Unnamed: 0" column in a pandas DataFrame?

This is usually caused by your CSV having been saved along with an (unnamed) index (RangeIndex).

(The fix would actually need to be done when saving the DataFrame, but this isn't always an option.)

Workaround: read_csv with index_col=[0] argument

IMO, the simplest solution would be to read the unnamed column as the index. Specify an index_col=[0] argument to pd.read_csv, this reads in the first column as the index. (Note the square brackets).

df = pd.DataFrame('x', index=range(5), columns=list('abc'))
df

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

# Save DataFrame to CSV.
df.to_csv('file.csv')

<!- ->

pd.read_csv('file.csv')

   Unnamed: 0  a  b  c
0           0  x  x  x
1           1  x  x  x
2           2  x  x  x
3           3  x  x  x
4           4  x  x  x

# Now try this again, with the extra argument.
pd.read_csv('file.csv', index_col=[0])

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

Note
You could have avoided this in the first place by using index=False if the output CSV was created in pandas, if your DataFrame does not have an index to begin with:

df.to_csv('file.csv', index=False)

But as mentioned above, this isn't always an option.


Stopgap Solution: Filtering with str.match

If you cannot modify the code to read/write the CSV file, you can just remove the column by filtering with str.match:

df 

   Unnamed: 0  a  b  c
0           0  x  x  x
1           1  x  x  x
2           2  x  x  x
3           3  x  x  x
4           4  x  x  x

df.columns
# Index(['Unnamed: 0', 'a', 'b', 'c'], dtype='object')

df.columns.str.match('Unnamed')
# array([ True, False, False, False])

df.loc[:, ~df.columns.str.match('Unnamed')]
 
   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

How to override equals method in Java

//Written by K@stackoverflow
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        ArrayList<Person> people = new ArrayList<Person>();
        people.add(new Person("Subash Adhikari", 28));
        people.add(new Person("K", 28));
        people.add(new Person("StackOverflow", 4));
        people.add(new Person("Subash Adhikari", 28));

        for (int i = 0; i < people.size() - 1; i++) {
            for (int y = i + 1; y <= people.size() - 1; y++) {
                boolean check = people.get(i).equals(people.get(y));

                System.out.println("-- " + people.get(i).getName() + " - VS - " + people.get(y).getName());
                System.out.println(check);
            }
        }
    }
}

//written by K@stackoverflow
public class Person {
    private String name;
    private int age;

    public Person(String name, int age){
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }

        if (obj.getClass() != this.getClass()) {
            return false;
        }

        final Person other = (Person) obj;
        if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
            return false;
        }

        if (this.age != other.age) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 53 * hash + (this.name != null ? this.name.hashCode() : 0);
        hash = 53 * hash + this.age;
        return hash;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Output:

run:

-- Subash Adhikari - VS - K false

-- Subash Adhikari - VS - StackOverflow false

-- Subash Adhikari - VS - Subash Adhikari true

-- K - VS - StackOverflow false

-- K - VS - Subash Adhikari false

-- StackOverflow - VS - Subash Adhikari false

-- BUILD SUCCESSFUL (total time: 0 seconds)

jQuery OR Selector?

If you're looking to use the standard construct of element = element1 || element2 where JavaScript will return the first one that is truthy, you could do exactly that:

element = $('#someParentElement .somethingToBeFound') || $('#someParentElement .somethingElseToBeFound');

which would return the first element that is actually found. But a better way would probably be to use the jQuery selector comma construct (which returns an array of found elements) in this fashion:

element = $('#someParentElement').find('.somethingToBeFound, .somethingElseToBeFound')[0];

which will return the first found element.

I use that from time to time to find either an active element in a list or some default element if there is no active element. For example:

element = $('ul#someList').find('li.active, li:first')[0] 

which will return any li with a class of active or, should there be none, will just return the last li.

Either will work. There are potential performance penalties, though, as the || will stop processing as soon as it finds something truthy whereas the array approach will try to find all elements even if it has found one already. Then again, using the || construct could potentially have performance issues if it has to go through several selectors before finding the one it will return, because it has to call the main jQuery object for each one (I really don't know if this is a performance hit or not, it just seems logical that it could be). In general, though, I use the array approach when the selector is a rather long string.

ldconfig error: is not a symbolic link

I ran into this issue with the Oracle 11R2 client. Not sure if the Oracle installer did this or someone did it here before i arrived. It was not 64-bit vs 32-bit, all was 64-bit.

The error was that libexpat.so.1 was not a symbolic link.

It turned out that there were two identical files, libexpat.so.1.5.2 and libexpat.so.1. Removing the offending file and making it a symlink to the 1.5.2 version caused the error to go away.

Makes sense that you'd want the well-known name to be a symlink to the current version. If you do this, it's less likely that you'll end up with a stale library.

Pipe subprocess standard output to a variable

To get the output of ls, use stdout=subprocess.PIPE.

>>> proc = subprocess.Popen('ls', stdout=subprocess.PIPE)
>>> output = proc.stdout.read()
>>> print output
bar
baz
foo

The command cdrecord --help outputs to stderr, so you need to pipe that indstead. You should also break up the command into a list of tokens as I've done below, or the alternative is to pass the shell=True argument but this fires up a fully-blown shell which can be dangerous if you don't control the contents of the command string.

>>> proc = subprocess.Popen(['cdrecord', '--help'], stderr=subprocess.PIPE)
>>> output = proc.stderr.read()
>>> print output
Usage: wodim [options] track1...trackn
Options:
    -version    print version information and exit
    dev=target  SCSI target to use as CD/DVD-Recorder
    gracetime=# set the grace time before starting to write to #.
...

If you have a command that outputs to both stdout and stderr and you want to merge them, you can do that by piping stderr to stdout and then catching stdout.

subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

As mentioned by Chris Morgan, you should be using proc.communicate() instead of proc.read().

>>> proc = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> out, err = proc.communicate()
>>> print 'stdout:', out
stdout: 
>>> print 'stderr:', err
stderr:Usage: wodim [options] track1...trackn
Options:
    -version    print version information and exit
    dev=target  SCSI target to use as CD/DVD-Recorder
    gracetime=# set the grace time before starting to write to #.
...

How to remove new line characters from data rows in mysql?

Removes trailing returns when importing from Excel. When you execute this, you may receive an error that there is no WHERE; ignore and execute.

UPDATE table_name SET col_name = TRIM(TRAILING '\r' FROM col_name)

Change span text?

Replace whatever is in the address bar with this:

javascript:document.getElementById('serverTime').innerHTML='[text here]';

Example.

Start/Stop and Restart Jenkins service on Windows

To stop Jenkins Please avoid shutting down the Java process or the Windows service. These are not usual commands. Use those only if your Jenkins is causing problems.

Use Jenkins' way to stop that protects from data loss.

http://[jenkins-server]/[command]

where [command] can be any one of the following

  • exit
  • restart
  • reload

Example: if my local PC is running Jenkins at port 8080, it will be

http://localhost:8080/exit

Is it possible to return empty in react render function?

Returning falsy value in the render() function will render nothing. So you can just do

 render() {
    let finalClasses = "" + (this.state.classes || "");
    return !isTimeout && <div>{this.props.children}</div>;
  }

What happens to a declared, uninitialized variable in C? Does it have a value?

Static variables (file scope and function static) are initialized to zero:

int x; // zero
int y = 0; // also zero

void foo() {
    static int x; // also zero
}

Non-static variables (local variables) are indeterminate. Reading them prior to assigning a value results in undefined behavior.

void foo() {
    int x;
    printf("%d", x); // the compiler is free to crash here
}

In practice, they tend to just have some nonsensical value in there initially - some compilers may even put in specific, fixed values to make it obvious when looking in a debugger - but strictly speaking, the compiler is free to do anything from crashing to summoning demons through your nasal passages.

As for why it's undefined behavior instead of simply "undefined/arbitrary value", there are a number of CPU architectures that have additional flag bits in their representation for various types. A modern example would be the Itanium, which has a "Not a Thing" bit in its registers; of course, the C standard drafters were considering some older architectures.

Attempting to work with a value with these flag bits set can result in a CPU exception in an operation that really shouldn't fail (eg, integer addition, or assigning to another variable). And if you go and leave a variable uninitialized, the compiler might pick up some random garbage with these flag bits set - meaning touching that uninitialized variable may be deadly.

(grep) Regex to match non-ASCII characters?

I use [^\t\r\n\x20-\x7E]+ and that seems to be working fine.

Why is the gets function so dangerous that it should not be used?

You can't remove API functions without breaking the API. If you would, many applications would no longer compile or run at all.

This is the reason that one reference gives:

Reading a line that overflows the array pointed to by s results in undefined behavior. The use of fgets() is recommended.

How to increase Maximum Upload size in cPanel?

Unfortunately, this is something you will have to ask you provider to do.

If your the owner of the server and can login to WHM it's under:

Tweak Settings => PHP Settings => Maximum Upload Size

Newer version have it listed under:

Home => Service Configuration => PHP Configuration Editor => Tweak Settings => PHP

Checking if a collection is null or empty in Groovy

There is indeed a Groovier Way.

if(members){
    //Some work
}

does everything if members is a collection. Null check as well as empty check (Empty collections are coerced to false). Hail Groovy Truth. :)

Create a Path from String in Java7

Even when the question is regarding Java 7, I think it adds value to know that from Java 11 onward, there is a static method in Path class that allows to do this straight away:

With all the path in one String:

Path.of("/tmp/foo");

With the path broken down in several Strings:

Path.of("/tmp","foo");

Using AND/OR in if else PHP statement

AND and OR are just syntactic sugar for && and ||, like in JavaScript, or other C styled syntax languages.

It appears AND and OR have lower precedence than their C style equivalents.

C++ Double Address Operator? (&&)

As other answers have mentioned, the && token in this context is new to C++0x (the next C++ standard) and represent an "rvalue reference".

Rvalue references are one of the more important new things in the upcoming standard; they enable support for 'move' semantics on objects and permit perfect forwarding of function calls.

It's a rather complex topic - one of the best introductions (that's not merely cursory) is an article by Stephan T. Lavavej, "Rvalue References: C++0x Features in VC10, Part 2"

Note that the article is still quite heavy reading, but well worthwhile. And even though it's on a Microsoft VC++ Blog, all (or nearly all) the information is applicable to any C++0x compiler.

How to yum install Node.JS on Amazon Linux

I usually use NVM to install node on server. It gives me option to install multiple version of nodejs. Commands are given below

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash

then check if it's install properly

command -v nvm

after that, run this to install latest version

nvm install node

or

nvm install 11

Get clicked item and its position in RecyclerView

Based on the link: Why doesn't RecyclerView have onItemClickListener()? and How RecyclerView is different from Listview?, and also @Duncan's general idea, I give my solution here:

  • Define one interface RecyclerViewClickListener for a passing message from the adapter to Activity/Fragment:

      public interface RecyclerViewClickListener {
          public void recyclerViewListClicked(View v, int position);
      }
    
  • In Activity/Fragment implement the interface, and also pass listener to adapter:

      @Override
      public void recyclerViewListClicked(View v, int position){... ...}
    
      //set up adapter and pass clicked listener this
      myAdapter = new MyRecyclerViewAdapter(context, this);
    
  • In Adapter and ViewHolder:

      public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ItemViewHolder> {
         ... ... 
         private Context context;
         private static RecyclerViewClickListener itemListener;
    
    
         public MyRecyclerViewAdapter(Context context, RecyclerViewClickListener itemListener) {
             this.context = context;
             this.itemListener = itemListener;
             ... ...
         }
    
    
         //ViewHolder class implement OnClickListener, 
         //set clicklistener to itemView and, 
         //send message back to Activity/Fragment 
         public static class ItemViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
             ... ...
             public ItemViewHolder(View convertView) {
                 super(convertView);
                 ... ...
                 convertView.setOnClickListener(this);
             }
    
             @Override
             public void onClick(View v) {
                 itemListener.recyclerViewListClicked(v, this.getPosition());     
    
             }
         }
      }
    

After testing, it works fine.

[UPDATE]

Since API 22, RecyclerView.ViewHolder.getPosition() is deprecated, so instead with getLayoutPosition().

Which Android IDE is better - Android Studio or Eclipse?

Both are equally good. With Android Studio you have ADT tools integrated, and with eclipse you need to integrate them manually. With Android Studio, it feels like a tool designed from the outset with Android development in mind. Go ahead, they have same features.

jquery live hover

.live() has been deprecated as of jQuery 1.7

Use .on() instead and specify a descendant selector

http://api.jquery.com/on/

$("table").on({
  mouseenter: function(){
    $(this).addClass("inside");
  },
  mouseleave: function(){
    $(this).removeClass("inside");
  }
}, "tr");  // descendant selector

How to initialize a list of strings (List<string>) with many string values

Your function is just fine but isn't working because you put the () after the last }. If you move the () to the top just next to new List<string>() the error stops.

Sample below:

List<string> optionList = new List<string>()
{
    "AdditionalCardPersonAdressType","AutomaticRaiseCreditLimit","CardDeliveryTimeWeekDay"
};

Android: show/hide status bar/power bar

fun Activity.setStatusBarVisibility(isVisible: Boolean) {
    //see details https://developer.android.com/training/system-ui/immersive
    if (isVisible) {
        window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
        window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
    } else {
        window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                or View.SYSTEM_UI_FLAG_FULLSCREEN)
    }
}

Are "while(true)" loops so bad?

It's your gun, your bullet and your foot...

It's bad because you are asking for trouble. It won't be you or any of the other posters on this page who have examples of short/simple while loops.

The trouble will start at some very random time in the future. It might be caused by another programmer. It might be the person installing the software. It might be the end user.

Why? I had to find out why a 700K LOC app would gradually start burning 100% of the CPU time until every CPU was saturated. It was an amazing while (true) loop. It was big and nasty but it boiled down to:

x = read_value_from_database()
while (true) 
 if (x == 1)
  ...
  break;
 else if (x ==2)
  ...
  break;
and lots more else if conditions
}

There was no final else branch. If the value did not match an if condition the loop kept running until the end of time.

Of course, the programmer blamed the end users for not picking a value the programmer expected. (I then eliminated all instances of while(true) in the code.)

IMHO it is not good defensive programming to use constructs like while(true). It will come back to haunt you.

(But I do recall professors grading down if we did not comment every line, even for i++;)

How to convert LINQ query result to List?

You need to use the select new LINQ keyword to explicitly convert your tbcourseentity into the custom type course. Example of select new:

var q = from o in db.Orders
        where o.Products.ProductName.StartsWith("Asset") && 
              o.PaymentApproved == true
        select new { name   = o.Contacts.FirstName + " " +
                              o.Contacts.LastName, 
                     product = o.Products.ProductName, 
                     version = o.Products.Version + 
                              (o.Products.SubVersion * 0.1)
                   };

http://www.hookedonlinq.com/LINQtoSQL5MinuteOverview.ashx

How to download Google Play Services in an Android emulator?

If your emulator x86 this method works your me.

Download and install http://opengapps.org/app/opengapps-app-v16.apk. And select nano pack

More info http://opengapps.org/app/

enter image description here

enter image description here

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

Using LINQ with large lists (when costly to touch each element) AND if you can live with the possibility of duplicates:

new int[5].Select(o => (int)(rnd.NextDouble() * maxIndex)).Select(i => YourIEnum.ElementAt(i))

For my use i had a list of 100.000 elements, and because of them being pulled from a DB I about halfed (or better) the time compared to a rnd on the whole list.

Having a large list will reduce the odds greatly for duplicates.

Convert list to dictionary using linq and not worrying about duplicates

Starting from Carra's solution you can also write it as:

foreach(var person in personList.Where(el => !myDictionary.ContainsKey(el.FirstAndLastName)))
{
    myDictionary.Add(person.FirstAndLastName, person);
}

csv.Error: iterator should return strings, not bytes

You open the file in text mode.

More specifically:

ifile  = open('sample.csv', "rt", encoding=<theencodingofthefile>)

Good guesses for encoding is "ascii" and "utf8". You can also leave the encoding off, and it will use the system default encoding, which tends to be UTF8, but may be something else.