Programs & Examples On #Pdf manipulation

0

Documentation for using JavaScript code inside a PDF file

Probably you are looking for JavaScript™ for Acrobat® API Reference.

This reference should be the most complete. But, as @Orbling said, not all PDF viewers might support all of the API.

EDIT:

It turns out there are newer versions of the reference in Acrobat SDK (thanks to @jss).

Acrobat Developer Center contains links to different versions of documentation. Current version of JavaScript reference from Acrobat DC SDK is available there too.

Custom seekbar (thumb size, color and background)

All done in XML (no .png images). The clever bit is border_shadow.xml.

All about the vectors these days...

Screenshot:

seekbar
This is your SeekBar (res/layout/???.xml):

SeekBar

<SeekBar
    android:id="@+id/seekBar_luminosite"
    android:layout_width="300dp"
    android:layout_height="wrap_content"        
    android:progress="@integer/luminosite_defaut"
    android:progressDrawable="@drawable/seekbar_style"
    android:thumb="@drawable/custom_thumb"/>

Let's make it stylish (so you can easily customize it later):

style

res/drawable/seekbar_style.xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item 
        android:id="@android:id/background" 
        android:drawable="@drawable/border_shadow" >
    </item>

    <item 
        android:id="@android:id/progress" > 
        <clip 
            android:drawable="@drawable/seekbar_progress" />
    </item>
</layer-list>

thumb

res/drawable/custom_thumb.xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <solid android:color="@color/colorDekraOrange"/>
            <size
                android:width="35dp"
                android:height="35dp"/>
        </shape>
    </item>   
</layer-list>

progress

res/drawable/seekbar_progress.xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list 
    xmlns:android="http://schemas.android.com/apk/res/android" >
    <item 
        android:id="@+id/progressshape" >
        <clip>
            <shape 
                android:shape="rectangle" >
                <size android:height="5dp"/>
                <corners 
                    android:radius="5dp" />
                <solid android:color="@color/colorDekraYellow"/>        
            </shape>
        </clip>
    </item>
</layer-list>

shadow

res/drawable/border_shadow.xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">       
    <item>      
        <shape> 
            <corners 
                android:radius="5dp" />
            <gradient
                android:angle="270"
                android:startColor="#33000000"
                android:centerColor="#11000000"
                android:endColor="#11000000"
                android:centerY="0.2"
                android:type="linear"
            />          
        </shape> 
    </item>
</layer-list>

IntelliJ IDEA "cannot resolve symbol" and "cannot resolve method"

Most likely JDK configuration is not valid, try to remove and add the JDK again as I've described in the related question here.

Python - Get Yesterday's date as a string in YYYY-MM-DD format

>>> import datetime
>>> datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime("%F")
'2015-05-26'

Python: Writing to and Reading from serial port

a piece of code who work with python to read rs232 just in case somedoby else need it

ser = serial.Serial('/dev/tty.usbserial', 9600, timeout=0.5)
ser.write('*99C\r\n')
time.sleep(0.1)
ser.close()

http://localhost:50070 does not work HADOOP

Try

namenode -format
start-all.sh
stop-all.sh
jps

see namenode and datanode are running and browse

localhost:50070

If localhost:50070 is still not working, then you need to allows ports. So, check

netstat -anp | grep 50070

changing permission for files and folder recursively using shell command in mac

You can just use the -R (recursive) flag.

chmod -R 777 /Users/Test/Desktop/PATH

Get size of an Iterable in Java

TL;DR: Use the utility method Iterables.size(Iterable) of the great Guava library.

Of your two code snippets, you should use the first one, because the second one will remove all elements from values, so it is empty afterwards. Changing a data structure for a simple query like its size is very unexpected.

For performance, this depends on your data structure. If it is for example in fact an ArrayList, removing elements from the beginning (what your second method is doing) is very slow (calculating the size becomes O(n*n) instead of O(n) as it should be).

In general, if there is the chance that values is actually a Collection and not only an Iterable, check this and call size() in case:

if (values instanceof Collection<?>) {
  return ((Collection<?>)values).size();
}
// use Iterator here...

The call to size() will usually be much faster than counting the number of elements, and this trick is exactly what Iterables.size(Iterable) of Guava does for you.

How can I get the ID of an element using jQuery?

Above answers are great, but as jquery evolves.. so you can also do:

var myId = $("#test").prop("id");

AngularJS Folder Structure

After building a few applications, some in Symfony-PHP, some .NET MVC, some ROR, i've found that the best way for me is to use Yeoman.io with the AngularJS generator.

That's the most popular and common structure and best maintained.

And most importantly, by keeping that structure, it helps you separate your client side code and to make it agnostic to the server-side technology (all kinds of different folder structures and different server-side templating engines).

That way you can easily duplicate and reuse yours and others code.

Here it is before grunt build: (but use the yeoman generator, don't just create it!)

/app
    /scripts
            /controllers
            /directives
            /services
            /filters
            app.js
    /views
    /styles
    /img
    /bower_components
    index.html
bower.json

And after grunt build (concat, uglify, rev, etc...):

    /scripts
        scripts.min.js (all JS concatenated, minified and grunt-rev)
        vendor.min.js  (all bower components concatenated, minified and grunt-rev)
    /views
    /styles
        mergedAndMinified.css  (grunt-cssmin)
    /images
    index.html  (grunt-htmlmin)

How to make a machine trust a self-signed Java application

I was having the same issue. So I went to the Java options through Control Panel. Copied the web address that I was having an issue with to the exceptions and it was fixed.

Asp.net MVC ModelState.Clear

Well lots of us seem to have been bitten by this, and although the reason this happens makes sense I needed a way to ensure that the value on my Model was shown, and not ModelState.

Some have suggested ModelState.Remove(string key), but it's not obvious what key should be, especially for nested models. Here are a couple methods I came up with to assist with this.

The RemoveStateFor method will take a ModelStateDictionary, a Model, and an expression for the desired property, and remove it. HiddenForModel can be used in your View to create a hidden input field using only the value from the Model, by first removing its ModelState entry. (This could easily be expanded for the other helper extension methods).

/// <summary>
/// Returns a hidden input field for the specified property. The corresponding value will first be removed from
/// the ModelState to ensure that the current Model value is shown.
/// </summary>
public static MvcHtmlString HiddenForModel<TModel, TProperty>(this HtmlHelper<TModel> helper,
    Expression<Func<TModel, TProperty>> expression)
{
    RemoveStateFor(helper.ViewData.ModelState, helper.ViewData.Model, expression);
    return helper.HiddenFor(expression);
}

/// <summary>
/// Removes the ModelState entry corresponding to the specified property on the model. Call this when changing
/// Model values on the server after a postback, to prevent ModelState entries from taking precedence.
/// </summary>
public static void RemoveStateFor<TModel, TProperty>(this ModelStateDictionary modelState, TModel model,
    Expression<Func<TModel, TProperty>> expression)
{
    var key = ExpressionHelper.GetExpressionText(expression);

    modelState.Remove(key);
}

Call from a controller like this:

ModelState.RemoveStateFor(model, m => m.MySubProperty.MySubValue);

or from a view like this:

@Html.HiddenForModel(m => m.MySubProperty.MySubValue)

It uses System.Web.Mvc.ExpressionHelper to get the name of the ModelState property.

Why do people use Heroku when AWS is present? What distinguishes Heroku from AWS?

First things first, AWS and Heroku are different things. AWS offer Infrastructure as a Service (IaaS) whereas Heroku offer a Platform as a Service (PaaS).

What's the difference? Very approximately, IaaS gives you components you need in order to build things on top of it; PaaS gives you an environment where you just push code and some basic configuration and get a running application. IaaS can give you more power and flexibility, at the cost of having to build and maintain more yourself.

To get your code running on AWS and looking a bit like a Heroku deployment, you'll want some EC2 instances - you'll want a load balancer / caching layer installed on them (e.g. Varnish), you'll want instances running something like Passenger and nginx to serve your code, you'll want to deploy and configure a clustered database instance of something like PostgreSQL. You'll want a deployment system with something like Capistrano, and something doing log aggregation.

That's not an insignificant amount of work to set up and maintain. With Heroku, the effort required to get to that sort of stage is maybe a few lines of application code and a git push.

So you're this far, and you want to scale up. Great. You're using Puppet for your EC2 deployment, right? So now you configure your Capistrano files to spin up/down instances as needed; you re-jig your Puppet config so Varnish is aware of web-worker instances and will automatically pool between them. Or you heroku scale web:+5.

Hopefully that gives you an idea of the comparison between the two. Now to address your specific points:

Speed

Currently Heroku only runs on AWS instances in us-east and eu-west. For you, this sounds like what you want anyway. For others, it's potentially more of a consideration.

Security

I've seen a lot of internally-maintained production servers that are way behind on security updates, or just generally poorly put together. With Heroku, you have someone else managing that sort of thing, which is either a blessing or a curse depending on how you look at it!

When you deploy, you're effectively handing your code straight over to Heroku. This may be an issue for you. Their article on Dyno Isolation details their isolation technologies (it seems as though multiple dynos are run on individual EC2 instances). Several colleagues have expressed issues with these technologies and the strength of their isolation; I am alas not in a position of enough knowledge / experience to really comment, but my current Heroku deployments consider that "good enough". It may be an issue for you, I don't know.

Scaling

I touched on how one might implement this in my IaaS vs PaaS comparison above. Approximately, your application has a Procfile, which has lines of the form dyno_type: command_to_run, so for example (cribbed from http://devcenter.heroku.com/articles/process-model):

web:    bundle exec rails server
worker: bundle exec rake jobs:work

This, with a:

heroku scale web:2 worker:10

will result in you having 2 web dynos and 10 worker dynos running. Nice, simple, easy. Note that web is a special dyno type, which has access to the outside world, and is behind their nice web traffic multiplexer (probably some sort of Varnish / nginx combination) that will route traffic accordingly. Your workers probably interact with a message queue for similar routing, from which they'll get the location via a URL in the environment.

Cost Efficiency

Lots of people have lots of different opinions about this. Currently it's $0.05/hr for a dyno hour, compared to $0.025/hr for an AWS micro instance or $0.09/hr for an AWS small instance.

Heroku's dyno documentation says you have about 512MB of RAM, so it's probably not too unreasonable to consider a dyno as a bit like an EC2 micro instance. Is it worth double the price? How much do you value your time? The amount of time and effort required to build on top of an IaaS offering to get it to this standard is definitely not cheap. I can't really answer this question for you, but don't underestimate the 'hidden costs' of setup and maintenance.

(A bit of an aside, but if I connect to a dyno from here (heroku run bash), a cursory look shows 4 cores in /proc/cpuinfo and 36GB of RAM - this leads me to believe that I'm on a "High-Memory Double Extra Large Instance". The Heroku dyno documentation says each dyno receives 512MB of RAM, so I'm potentially sharing with up to 71 other dynos. (I don't have enough data about the homogeny of Heroku's AWS instances, so your milage may vary))

How do they fare against their competitors?

This, I'm afraid I can't really help you with. The only competitor I've ever really looked at was Google App Engine - at the time I was looking to deploy Java applications, and the amount of restrictions on usable frameworks and technologies was incredibly off-putting. This is more than "just a Java thing" - the amount of general restrictions and necessary considerations (the FAQ hints at several) seemed less than convenient. In contrast, deploying to Heroku has been a dream.

Conclusion

I hope this answers your questions (please comment if there are gaps / other areas you'd like addressed). I feel I should offer my personal position. I love Heroku for "quick deployments". When I'm starting an application, and I want some cheap hosting (the Heroku free tier is awesome - essentially if you only need one web dyno and 5MB of PostgreSQL, it's free to host an application), Heroku is my go-to position. For "Serious Production Deployment" with several paying customers, with a service-level-agreement, with dedicated time to spend on ops, et cetera, I can't quite bring myself to offload that much control to Heroku, and then either AWS or our own servers have been the hosting platform of choice.

Ultimately, it's about what works best for you. You say you're "a beginner programmer" - it might just be that using Heroku will let you focus on writing Ruby, and not have to spend time getting all the other infrastructure around your code built up. I'd definitely give it a try.


Note, AWS does actually have a PaaS offering, Elastic Beanstalk, that supports Ruby, Node.js, PHP, Python, .NET and Java. I think generally most people, when they see "AWS", jump to things like EC2 and S3 and EBS, which are definitely IaaS offerings

Alter SQL table - allow NULL column value

ALTER TABLE MyTable MODIFY Col3 varchar(20) NULL;

How to execute a java .class from the command line

If you have in your java source

package mypackage;

and your class is hello.java with

public class hello {

and in that hello.java you have

 public static void main(String[] args) {

Then (after compilation) changeDir (cd) to the directory where your hello.class is. Then

java -cp . mypackage.hello

Mind the current directory and the package name before the class name. It works for my on linux mint and i hope on the other os's also

Thanks Stack overflow for a wealth of info.

Java: Get first item from a collection

Guava provides an onlyElement Collector, but only use it if you expect the collection to have exactly one element.

Collection<String> stringCollection = ...;
String string = collection.stream().collect(MoreCollectors.onlyElement())

If you are unsure of how many elements there are, use findFirst.

Optional<String> optionalString = collection.stream().findFirst();

Encrypt and decrypt a String in java

I had a doubt that whether the encrypted text will be same for single text when encryption done by multiple times on a same text??

This depends strongly on the crypto algorithm you use:

  • One goal of some/most (mature) algorithms is that the encrypted text is different when encryption done twice. One reason to do this is, that an attacker how known the plain and the encrypted text is not able to calculate the key.
  • Other algorithm (mainly one way crypto hashes) like MD5 or SHA based on the fact, that the hashed text is the same for each encryption/hash.

convert base64 to image in javascript/jquery

Html

<img id="imgElem"></img>

Js

string baseStr64="/9j/4AAQSkZJRgABAQE...";
imgElem.setAttribute('src', "data:image/jpg;base64," + baseStr64);

How to use HTTP.GET in AngularJS correctly? In specific, for an external API call?

First, your success() handler just returns the data, but that's not returned to the caller of getData() since it's already in a callback. $http is an asynchronous call that returns a $promise, so you have to register a callback for when the data is available.

I'd recommend looking up Promises and the $q library in AngularJS since they're the best way to pass around asynchronous calls between services.

For simplicity, here's your same code re-written with a function callback provided by the calling controller:

var myApp = angular.module('myApp',[]);

myApp.service('dataService', function($http) {
    delete $http.defaults.headers.common['X-Requested-With'];
    this.getData = function(callbackFunc) {
        $http({
            method: 'GET',
            url: 'https://www.example.com/api/v1/page',
            params: 'limit=10, sort_by=created:desc',
            headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
        }).success(function(data){
            // With the data succesfully returned, call our callback
            callbackFunc(data);
        }).error(function(){
            alert("error");
        });
     }
});

myApp.controller('AngularJSCtrl', function($scope, dataService) {
    $scope.data = null;
    dataService.getData(function(dataResponse) {
        $scope.data = dataResponse;
    });
});

Now, $http actually already returns a $promise, so this can be re-written:

var myApp = angular.module('myApp',[]);

myApp.service('dataService', function($http) {
    delete $http.defaults.headers.common['X-Requested-With'];
    this.getData = function() {
        // $http() returns a $promise that we can add handlers with .then()
        return $http({
            method: 'GET',
            url: 'https://www.example.com/api/v1/page',
            params: 'limit=10, sort_by=created:desc',
            headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
         });
     }
});

myApp.controller('AngularJSCtrl', function($scope, dataService) {
    $scope.data = null;
    dataService.getData().then(function(dataResponse) {
        $scope.data = dataResponse;
    });
});

Finally, there's better ways to configure the $http service to handle the headers for you using config() to setup the $httpProvider. Checkout the $http documentation for examples.

Best Practice to Organize Javascript Library & CSS Folder Structure

 root/
   assets/
      lib/-------------------------libraries--------------------
          bootstrap/--------------Libraries can have js/css/images------------
              css/
              js/
              images/  
          jquery/
              js/
          font-awesome/
              css/
              images/
     common/--------------------common section will have application level resources             
          css/
          js/
          img/

 index.html

This is how I organized my application's static resources.

Python vs Bash - In which kind of tasks each one outruns the other performance-wise?

Generally, bash works better than python only in those environments where python is not available. :)

Seriously, I have to deal with both languages daily, and will take python instantly over bash if given the choice. Alas, I am forced to use bash on certain "small" platforms because someone has (mistakenly, IMHO) decided that python is "too large" to fit.

While it is true that bash might be faster than python for some select tasks, it can never be as quick to develop with, or as easy to maintain (at least after you get past 10 lines of code or so). Bash's sole strong point wrt python or ruby or lua, etc., is its ubiquity.

Why do I need to configure the SQL dialect of a data source?

Dialect is the SQL dialect that your database uses.

List of SQL dialects for Hibernate.

Either provide it in hibernate.cfg.xml as :

<hibernate-configuration>
   <session-factory name="session-factory">
      <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
       ...
   </session-factory>
</hibernate-configuration>

or in the properties file as :

hibernate.dialect=org.hibernate.dialect.SQLServerDialect

How to sum all column values in multi-dimensional array?

Here you have how I usually do this kind of operations.

// We declare an empty array in wich we will store the results
$sumArray = array();

// We loop through all the key-value pairs in $myArray
foreach ($myArray as $k=>$subArray) {

   // Each value is an array, we loop through it
   foreach ($subArray as $id=>$value) {

       // If $sumArray has not $id as key we initialize it to zero  
       if(!isset($sumArray[$id])){
           $sumArray[$id] = 0;
       }

       // If the array already has a key named $id, we increment its value
       $sumArray[$id]+=$value;
    }
 }

 print_r($sumArray);

Uncaught SyntaxError: Unexpected token < On Chrome

Error with Uncaught SyntaxError: Unexpected token < using @Mario answer but that was only part of my problem. Another problem is, javascript doesn't get any data from PHP file. That was solved using this code, inside PHP file: header("Content-Type: text/javascript; charset=utf-8"); This answer is found on this link, where I opened another question to solve this issue: Can't receive json data from PHP in Chrome and Opera

Good tutorial for using HTML5 History API (Pushstate?)

Here is a great screen-cast on the topic by Ryan Bates of railscasts. At the end he simply disables the ajax functionality if the history.pushState method is not available:

http://railscasts.com/episodes/246-ajax-history-state

cURL equivalent in Node.js?

I had a problem sending POST data to cloud DB from IOT RaspberryPi, but after hours I managed to get it straight.

I used command prompt to do so.

sudo curl --URL http://<username>.cloudant.com/<database_name> --user <api_key>:<pass_key> -X POST -H "Content-Type:application/json" --data '{"id":"123","type":"987"}'

Command prompt will show the problems - wrong username/pass; bad request etc.

--URL database/server location (I used simple free Cloudant DB) --user is the authentication part username:pass I entered through API pass -X defines what command to call (PUT,GET,POST,DELETE) -H content type - Cloudant is about document database, where JSON is used --data content itself sorted as JSON

How Do I Uninstall Yarn

Incase of windows, after executing npm uninstall -g yarn, still if yarn did not uninstalled, then go to "C:\Users\username\AppData\Local" and remove the yarn folder. Close the cmd and reopen the cmd and execute yarn . it will give you message 'yarn' is not recognized as an internal or external command, operable program or batch file.

Setting Spring Profile variable

There are at least two ways to do that:

  1. defining context param in web.xml – that breaks "one package for all environments" statement. I don't recommend that

  2. defining system property -Dspring.profiles.active=your-active-profile

I believe that defining system property is a much better approach. So how to define system property for Tomcat? On the internet I could find a lot of advice like "modify catalina.sh" because you will not find any configuration file for doing stuff like that. Modifying catalina.sh is a dirty unmaintainable solution. There is a better way to do that.

Just create file setenv.sh in Tomcat's bin directory with content:

JAVA_OPTS="$JAVA_OPTS -Dspring.profiles.active=dev"

and it will be loaded automatically during running catalina.sh start or run.

Here is a blog describing the above solution.

How to allow download of .json file with ASP.NET

Solution is you need to add json file extension type in MIME Types

Method 1

Go to IIS, Select your application and Find MIME Types

enter image description here

Click on Add from Right panel

File Name Extension = .json

MIME Type = application/json

enter image description here

After adding .json file type in MIME Types, Restart IIS and try to access json file


Method 2

Go to web.config of that application and add this lines in it

 <system.webServer>
   <staticContent>
     <mimeMap fileExtension=".json" mimeType="application/json" />
   </staticContent>
 </system.webServer>

How to list all available Kafka brokers in a cluster?

Alternate way using Zk-Client:

If you do not prefer to pass arguments to ./zookeeper-shell.sh and want to see the broker details from Zookeeper CLI, you need to install standalone Zookeeper (As traditional Kafka do not comes up with Jline JAR).

Once you install(unzip) the standalone Zookeeper,then:

  • Run the Zookeeper CLI:
    $ zookeeper/bin/zkCli.sh -server localhost:2181 #Make sure your Broker is already running

  • If it is successful, you can see the Zk client running as:

WATCHER::

WatchedEvent state:SyncConnected type:None path:null
[zk: localhost:2181(CONNECTED) 0]
  • From here you can explore the broker details using various commands:

$ ls /brokers/ids # Gives the list of active brokers
$ ls /brokers/topics #Gives the list of topics
$ get /brokers/ids/0 #Gives more detailed information of the broker id '0'

How can I display just a portion of an image in HTML/CSS?

As mentioned in the question, there is the clip css property, although it does require that the element being clipped is position: absolute; (which is a shame):

_x000D_
_x000D_
.container {_x000D_
  position: relative;_x000D_
}_x000D_
#clip {_x000D_
  position: absolute;_x000D_
  clip: rect(0, 100px, 200px, 0);_x000D_
  /* clip: shape(top, right, bottom, left); NB 'rect' is the only available option */_x000D_
}
_x000D_
<div class="container">_x000D_
  <img src="http://lorempixel.com/200/200/nightlife/3" />_x000D_
</div>_x000D_
<div class="container">_x000D_
  <img id="clip" src="http://lorempixel.com/200/200/nightlife/3" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

JS Fiddle demo, for experimentation.

To supplement the original answer – somewhat belatedly – I'm editing to show the use of clip-path, which has replaced the now-deprecated clip property.

The clip-path property allows a range of options (more-so than the original clip), of:

  • inset — rectangular/cuboid shapes, defined with four values as 'distance-from' (top right bottom left).
  • circlecircle(diameter at x-coordinate y-coordinate).
  • ellipseellipse(x-axis-length y-axis-length at x-coordinate y-coordinate).
  • polygon — defined by a series of x/y coordinates in relation to the element's origin of the top-left corner. As the path is closed automatically the realistic minimum number of points for a polygon should be three, any fewer (two) is a line or (one) is a point: polygon(x-coordinate1 y-coordinate1, x-coordinate2 y-coordinate2, x-coordinate3 y-coordinate3, [etc...]).
  • url — this can be either a local URL (using a CSS id-selector) or the URL of an external file (using a file-path) to identify an SVG, though I've not experimented with either (as yet), so I can offer no insight as to their benefit or caveat.

_x000D_
_x000D_
div.container {_x000D_
  display: inline-block;_x000D_
}_x000D_
#rectangular {_x000D_
  -webkit-clip-path: inset(30px 10px 30px 10px);_x000D_
  clip-path: inset(30px 10px 30px 10px);_x000D_
}_x000D_
#circle {_x000D_
  -webkit-clip-path: circle(75px at 50% 50%);_x000D_
  clip-path: circle(75px at 50% 50%)_x000D_
}_x000D_
#ellipse {_x000D_
  -webkit-clip-path: ellipse(75px 50px at 50% 50%);_x000D_
  clip-path: ellipse(75px 50px at 50% 50%);_x000D_
}_x000D_
#polygon {_x000D_
  -webkit-clip-path: polygon(50% 0, 100% 38%, 81% 100%, 19% 100%, 0 38%);_x000D_
  clip-path: polygon(50% 0, 100% 38%, 81% 100%, 19% 100%, 0 38%);_x000D_
}
_x000D_
<div class="container">_x000D_
  <img id="control" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
  <img id="rectangular" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
  <img id="circle" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
  <img id="ellipse" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>_x000D_
<div class="container">_x000D_
  <img id="polygon" src="http://lorempixel.com/150/150/people/1" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

JS Fiddle demo, for experimentation.

References:

highlight the navigation menu for the current page

You can use Javascript to parse your DOM, and highlight the link with the same label than the first h1 tags. But I think it is overkill =)

It would be better to set a var wich contain the title of your page, and use it to add a class at the corresponding link.

findViewByID returns null

Just wanted to throw my specific case in here. Might help someone down the line.

I was using the directive in my Android UI XML like this:

Parent view:

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:tag="home_phone"
    android:background="@color/colorPrimary">

    ...

    <include
        layout="@layout/retry_button"
        android:visibility="gone" />

Child view (retry_button):

<com.foo.RetryButton
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/retry"
    android:layout_gravity="center"
    android:orientation="vertical"
    android:layout_width="100dp"
    android:layout_height="140dp">

.findViewById(R.id.retry) would always return null. But, if I moved the ID from the child view into the include tag, it started working.

Fixed parent:

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:tag="home_phone"
    android:background="@color/colorPrimary">

    ...

    <include
        layout="@layout/retry_button"
        android:id="@+id/retry"
        android:visibility="gone" />

Fixed child:

<com.foo.RetryButton
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_gravity="center"
    android:orientation="vertical"
    android:layout_width="100dp"
    android:layout_height="140dp">

The difference between fork(), vfork(), exec() and clone()

The fork(),vfork() and clone() all call the do_fork() to do the real work, but with different parameters.

asmlinkage int sys_fork(struct pt_regs regs)
{
    return do_fork(SIGCHLD, regs.esp, &regs, 0);
}

asmlinkage int sys_clone(struct pt_regs regs)
{
    unsigned long clone_flags;
    unsigned long newsp;

    clone_flags = regs.ebx;
    newsp = regs.ecx;
    if (!newsp)
        newsp = regs.esp;
    return do_fork(clone_flags, newsp, &regs, 0);
}
asmlinkage int sys_vfork(struct pt_regs regs)
{
    return do_fork(CLONE_VFORK | CLONE_VM | SIGCHLD, regs.esp, &regs, 0);
}
#define CLONE_VFORK 0x00004000  /* set if the parent wants the child to wake it up on mm_release */
#define CLONE_VM    0x00000100  /* set if VM shared between processes */

SIGCHLD means the child should send this signal to its father when exit.

For fork, the child and father has the independent VM page table, but since the efficiency, fork will not really copy any pages, it just set all the writeable pages to readonly for child process. So when child process want to write something on that page, an page exception happen and kernel will alloc a new page cloned from the old page with write permission. That's called "copy on write".

For vfork, the virtual memory is exactly by child and father---just because of that, father and child can't be awake concurrently since they will influence each other. So the father will sleep at the end of "do_fork()" and awake when child call exit() or execve() since then it will own new page table. Here is the code(in do_fork()) that the father sleep.

if ((clone_flags & CLONE_VFORK) && (retval > 0))
down(&sem);
return retval;

Here is the code(in mm_release() called by exit() and execve()) which awake the father.

up(tsk->p_opptr->vfork_sem);

For sys_clone(), it is more flexible since you can input any clone_flags to it. So pthread_create() call this system call with many clone_flags:

int clone_flags = (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGNAL | CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID | CLONE_SYSVSEM);

Summary: the fork(),vfork() and clone() will create child processes with different mount of sharing resource with the father process. We also can say the vfork() and clone() can create threads(actually they are processes since they have independent task_struct) since they share the VM page table with father process.

How to generate a random string of 20 characters

Here you go. Just specify the chars you want to allow on the first line.

char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
StringBuilder sb = new StringBuilder(20);
Random random = new Random();
for (int i = 0; i < 20; i++) {
    char c = chars[random.nextInt(chars.length)];
    sb.append(c);
}
String output = sb.toString();
System.out.println(output);

If you are using this to generate something sensitive like a password reset URL or session ID cookie or temporary password reset, be sure to use java.security.SecureRandom instead. Values produced by java.util.Random and java.util.concurrent.ThreadLocalRandom are mathematically predictable.

What's the best way to share data between activities?

Sharing data between activites example passing an email after login

"email" is the name that can be used to reference the value on the activity that's being requested

1 Code on the login page

Intent openLoginActivity = new Intent(getBaseContext(), Home.class);
    openLoginActivity.putExtra("email", getEmail);

2 code on the home page

Bundle extras = getIntent().getExtras();
    accountEmail = extras.getString("email");

How to combine GROUP BY, ORDER BY and HAVING

Your code should be contain WHILE before group by and having :

SELECT Email, COUNT(*)

FROM user_log

WHILE Email IS NOT NULL

GROUP BY Email

HAVING COUNT(*) > 1

ORDER BY UpdateDate DESC

VBA: How to delete filtered rows in Excel?

Use SpecialCells to delete only the rows that are visible after autofiltering:

ActiveSheet.Range("$A$1:$I$" & lines).SpecialCells _
    (xlCellTypeVisible).EntireRow.Delete

If you have a header row in your range that you don't want to delete, add an offset to the range to exclude it:

ActiveSheet.Range("$A$1:$I$" & lines).Offset(1, 0).SpecialCells _
    (xlCellTypeVisible).EntireRow.Delete

Good Linux (Ubuntu) SVN client

kdesvn is probably the best you'll find.

Last I checked it may hook in with konqueror, but its been a while, I've moved on to git :)

Changing Background Image with CSS3 Animations

The linear timing function will animate the defined properties linearly. For the background-image it seems to have this fade/resize effect while changing the frames of you animation (not sure if it is standard behavior, I would go with @Chukie B's approach).

If you use the steps function, it will animate discretely. See the timing function documentation on MDN for more detail. For you case, do like this:

-webkit-animation-timing-function: steps(1,end);
animation-timing-function: steps(1,end);

See this jsFiddle.

I'm not sure if it is standard behavior either, but when you say that there will be only one step, it allows you to change the starting point in the @keyframes section. This way you can define each frame of you animation.

Where is Maven Installed on Ubuntu

Here is a bash script for newer Maven copy and paste it...

# @author Yucca Nel

#!/bin/sh

#This installs maven2 & a default JDK 
sudo apt-get install maven2;

#Makes the /usr/lib/mvn in case...
sudo mkdir -p /usr/lib/mvn;

#Clean out /tmp...
sudo rm -rf /tmp/*;
cd /tmp;

#Update this line to reflect newer versions of maven
wget http://mirrors.powertech.no/www.apache.org/dist//maven/binaries/apache-maven-3.0.3-bin.tar.gz;
tar -xvf ./*gz;

#Move it to where it to logical location
sudo mv /tmp/apache-maven-3.* /usr/lib/mvn/;

#Link the new Maven to the bin... (update for higher/newer version)...
sudo ln -s /usr/lib/mvn/apache-maven-3.0.3/bin/mvn /usr/bin/mvn;

#test
mvn -version;

exit 0;

What does 'git blame' do?

The git blame command annotates lines with information from the revision which last modified the line, and... with Git 2.22 (Q2 2019), will do so faster, because of a performance fix around "git blame", especially in a linear history (which is the norm we should optimize for).

See commit f892014 (02 Apr 2019) by David Kastrup (fedelibre). (Merged by Junio C Hamano -- gitster -- in commit 4d8c4da, 25 Apr 2019)

blame.c: don't drop origin blobs as eagerly

When a parent blob already has chunks queued up for blaming, dropping the blob at the end of one blame step will cause it to get reloaded right away, doubling the amount of I/O and unpacking when processing a linear history.

Keeping such parent blobs in memory seems like a reasonable optimization that should incur additional memory pressure mostly when processing the merges from old branches.

How does one parse XML files?

I'm not sure whether "best practice for parsing XML" exists. There are numerous technologies suited for different situations. Which way to use depends on the concrete scenario.

You can go with LINQ to XML, XmlReader, XPathNavigator or even regular expressions. If you elaborate your needs, I can try to give some suggestions.

How can I get the current array index in a foreach loop?

This is the most exhaustive answer so far and gets rid of the need for a $i variable floating around. It is a combo of Kip and Gnarf's answers.

$array = array( 'cat' => 'meow', 'dog' => 'woof', 'cow' => 'moo', 'computer' => 'beep' );
foreach( array_keys( $array ) as $index=>$key ) {

    // display the current index + key + value
    echo $index . ':' . $key . $array[$key];

    // first index
    if ( $index == 0 ) {
        echo ' -- This is the first element in the associative array';
    }

    // last index
    if ( $index == count( $array ) - 1 ) {
        echo ' -- This is the last element in the associative array';
    }
    echo '<br>';
}

Hope it helps someone.

Error while retrieving information from the server RPC:s-7:AEC-0 in Google play?

on the BlueStacks emulator worked for me the following solution

Go to ”Settings” -> “Applications” -> “Manage Applications” and select “All

Go to “Google Play Services Framework” and select “Clear Data” & “Clear Cache” to remove all the data.

Go to “Google Play Store” and Select “Clear Data” & “Clear Cache” to remove all the data regarding Google Play Store.

Go to “Settings” -> “Accounts” -> “Google” -> Select “Your Account

Go to “Menu” and Select “Remove Account”.

Now “Restart” your mobile device.

Go to “Menu” and “Add Your Account”.

and try to perform update or download.

HQL ERROR: Path expected for join

You need to name the entity that holds the association to User. For example,

... INNER JOIN ug.user u ...

That's the "path" the error message is complaining about -- path from UserGroup to User entity.

Hibernate relies on declarative JOINs, for which the join condition is declared in the mapping metadata. This is why it is impossible to construct the native SQL query without having the path.

TSQL CASE with if comparison in SELECT statement

Please select the same in the outer select. You can't access the alias name in the same query.

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

Spring Boot default H2 jdbc connection (and H2 console)

As of Spring Boot 1.3.0.M3, the H2 console can be auto-configured.

The prerequisites are:

  • You are developing a web app
  • Spring Boot Dev Tools are enabled
  • H2 is on the classpath

Even if you don't use Spring Boot Dev Tools, you can still auto-configure the console by setting spring.h2.console.enabled to true

Check out this part of the documentation for all the details.

Note that when configuring in this way the console is accessible at: http://localhost:8080/h2-console/

How to select the first element with a specific attribute using XPath

As an explanation to Jonathan Fingland's answer:

  • multiple conditions in the same predicate ([position()=1 and @location='US']) must be true as a whole
  • multiple conditions in consecutive predicates ([position()=1][@location='US']) must be true one after another
  • this implies that [position()=1][@location='US'] != [@location='US'][position()=1]
    while [position()=1 and @location='US'] == [@location='US' and position()=1]
  • hint: a lone [position()=1] can be abbreviated to [1]

You can build complex expressions in predicates with the Boolean operators "and" and "or", and with the Boolean XPath functions not(), true() and false(). Plus you can wrap sub-expressions in parentheses.

How do I run Python code from Sublime Text 2?

If using python 3.x you need to edit the Python3.sublime-build

(Preferences > Browse packages > Python 3)

to look like this:

{
  "path": "/usr/local/bin",
  "cmd": ["python3", "-u", "$file"],
  "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
  "selector": "source.python"
}

Is it possible to start a shell session in a running container (without ssh)

With docker 1.3, there is a new command docker exec. This allows you to enter a running docker:

docker exec -it "id of running container" bash

Unity 2d jumping script

Usually for jumping people use Rigidbody2D.AddForce with Forcemode.Impulse. It may seem like your object is pushed once in Y axis and it will fall down automatically due to gravity.

Example:

rigidbody2D.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);

Return None if Dictionary key is not available

You could use a dict object's get() method, as others have already suggested. Alternatively, depending on exactly what you're doing, you might be able use a try/except suite like this:

try:
   <to do something with d[key]>
except KeyError:
   <deal with it not being there>

Which is considered to be a very "Pythonic" approach to handling the case.

How to Replace dot (.) in a string in Java

return sentence.replaceAll("\s",".");

Move all files except one

For bash, sth answer is correct. Here is the zsh (my shell of choice) syntax:

mv ~/Linux/Old/^Tux.png ~/Linux/New/

Requires EXTENDED_GLOB shell option to be set.

Get value of input field inside an iframe

document.getElementById("idframe").contentWindow.document.getElementById("idelement").value;

How to run certain task every day at a particular time using ScheduledExecutorService?

The following example work for me

public class DemoScheduler {

    public static void main(String[] args) {

        // Create a calendar instance
        Calendar calendar = Calendar.getInstance();

        // Set time of execution. Here, we have to run every day 4:20 PM; so,
        // setting all parameters.
        calendar.set(Calendar.HOUR, 8);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.AM_PM, Calendar.AM);

        Long currentTime = new Date().getTime();

        // Check if current time is greater than our calendar's time. If So,
        // then change date to one day plus. As the time already pass for
        // execution.
        if (calendar.getTime().getTime() < currentTime) {
            calendar.add(Calendar.DATE, 1);
        }

        // Calendar is scheduled for future; so, it's time is higher than
        // current time.
        long startScheduler = calendar.getTime().getTime() - currentTime;

        // Setting stop scheduler at 4:21 PM. Over here, we are using current
        // calendar's object; so, date and AM_PM is not needed to set
        calendar.set(Calendar.HOUR, 5);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.AM_PM, Calendar.PM);

        // Calculation stop scheduler
        long stopScheduler = calendar.getTime().getTime() - currentTime;

        // Executor is Runnable. The code which you want to run periodically.
        Runnable task = new Runnable() {

            @Override
            public void run() {

                System.out.println("test");
            }
        };

        // Get an instance of scheduler
        final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        // execute scheduler at fixed time.
        scheduler.scheduleAtFixedRate(task, startScheduler, stopScheduler, MILLISECONDS);
    }
}

reference: https://chynten.wordpress.com/2016/06/03/java-scheduler-to-run-every-day-on-specific-time/

Convert double to Int, rounded down

If you explicitly cast double to int, the decimal part will be truncated. For example:

int x = (int) 4.97542;   //gives 4 only
int x = (int) 4.23544;   //gives 4 only

Moreover, you may also use Math.floor() method to round values in case you want double value in return.

Split string with PowerShell and do something with each token

Another way to accomplish this is a combination of Justus Thane's and mklement0's answers. It doesn't make sense to do it this way when you look at a one liner example, but when you're trying to mass-edit a file or a bunch of filenames it comes in pretty handy:

$test = '   One      for the money   '
$option = [System.StringSplitOptions]::RemoveEmptyEntries
$($test.split(' ',$option)).foreach{$_}

This will come out as:

One
for
the
money

Apache gives me 403 Access Forbidden when DocumentRoot points to two different drives

For Apache 2.4.2: I was getting 403: Forbidden continuously when I was trying to access WAMP on my Windows 7 desktop from my iPhone on WiFi. On one blog, I found the solution - add Require all granted after Allow all in the <Directory> section. So this is how my <Directory> section looks like inside <VirtualHost>

<Directory "C:/wamp/www">
    Options Indexes FollowSymLinks MultiViews Includes ExecCGI
    AllowOverride All
    Order Allow,Deny
    Allow from all
    Require all granted
</Directory>

Adding a Button to a WPF DataGrid

Check this out:

XAML:

<DataGrid Name="DataGrid1">
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Click="ChangeText">Show/Hide</Button>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

Method:

private void ChangeText(object sender, RoutedEventArgs e)
{
    DemoModel model = (sender as Button).DataContext as DemoModel;
    model.DynamicText = (new Random().Next(0, 100).ToString());
}

Class:

class DemoModel : INotifyPropertyChanged
{
    protected String _text;
    public String Text
    {
        get { return _text; }
        set { _text = value; RaisePropertyChanged("Text"); }
    }

    protected String _dynamicText;
    public String DynamicText
    {
        get { return _dynamicText; }
        set { _dynamicText = value; RaisePropertyChanged("DynamicText"); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged(String propertyName)
    {
        PropertyChangedEventHandler temp = PropertyChanged;
        if (temp != null)
        {
            temp(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Initialization Code:

ObservableCollection<DemoModel> models = new ObservableCollection<DemoModel>();
models.Add(new DemoModel() { Text = "Some Text #1." });
models.Add(new DemoModel() { Text = "Some Text #2." });
models.Add(new DemoModel() { Text = "Some Text #3." });
models.Add(new DemoModel() { Text = "Some Text #4." });
models.Add(new DemoModel() { Text = "Some Text #5." });
DataGrid1.ItemsSource = models;

How to specify maven's distributionManagement organisation wide?

Regarding the answer from Michael Wyraz, where you use alt*DeploymentRepository in your settings.xml or command on the line, be careful if you are using version 3.0.0-M1 of the maven-deploy-plugin (which is the latest version at the time of writing), there is a bug in this version that could cause a server authentication issue.

A workaround is as follows. In the value:

releases::default::https://YOUR_NEXUS_URL/releases

you need to remove the default section, making it:

releases::https://YOUR_NEXUS_URL/releases

The prior version 2.8.2 does not have this bug.

Passing parameters to addTarget:action:forControlEvents

If you just want to change the text for the leftBarButtonItem shown by the navigation controller together with the new view, you may change the title of the current view just before calling pushViewController to the wanted text and restore it in the viewHasDisappered callback for future showings of the current view.

This approach keeps the functionality (popViewController) and the appearance of the shown arrow intact.

It works for us at least with iOS 12, built with Xcode 10.1 ...

Is there a way to run Bash scripts on Windows?

In order to run natively, you will likely need to use Cygwin (which I cannot live without when using Windows). So right off the bat, +1 for Cygwin. Anything else would be uncivilized.

HOWEVER, that being said, I have recently begun using a combination of utilities to easily PORT Bash scripts to Windows so that my anti-Linux coworkers can easily run complex tasks that are better handled by GNU utilities.

I can usually port a Bash script to Batch in a very short time by opening the original script in one pane and writing a Batch file in the other pane. The tools that I use are as follows:

I prefer UnxUtils to GnuWin32 because of the fact that [someone please correct me if I'm wrong] GnuWin utils normally have to be installed, whereas UnxUtils are standalone binaries that just work out-of-the-box.

However, the CoreUtils do not include some familiar *NIX utilities such as cURL, which is also available for Windows (curl.haxx.se/download.html).

I create a folder for the projects, and always SET PATH=. in the .bat file so that no other commands other than the basic CMD shell commands are referenced (as well as the particular UnxUtils required in the project folder for the Batch script to function as expected).

Then I copy the needed CoreUtils .exe files into the project folder and reference them in the .bat file such as ".\curl.exe -s google.com", etc.

The Bat2Exe program is where the magic happens. Once your Batch file is complete and has been tested successfully, launch Bat2Exe.exe, and specify the path to the project folder. Bat2Exe will then create a Windows binary containing all of the files in that specific folder, and will use the first .bat that it comes across to use as the main executable. You can even include a .ico file to use as the icon for the final .exe file that is generated.

I have tried a few of these type of programs, and many of the generated binaries get flagged as malware, but the Bat2Exe version that I referenced works perfectly and the generated .exe files scan completely clean.

The resulting executable can be run interactively by double-clicking, or run from the command line with parameters, etc., just like a regular Batch file, except you will be able to utilize the functionality of many of the tools that you will normally use in Bash.

I realize this is getting quite long, but if I may digress a bit, I have also written a Batch script that I call PortaBashy that my coworkers can launch from a network share that contains a portable Cygwin installation. It then sets the %PATH% variable to the normal *NIX format (/usr/bin:/usr/sbin:/bin:/sbin), etc. and can either launch into the Bash shell itself or launch the more-powerful and pretty MinTTY terminal emulator.

There are always numerous ways to accomplish what you are trying to set out to do; it's just a matter of combining the right tools for the job, and many times it boils down to personal preference.

What does ':' (colon) do in JavaScript?

var o = {
    r: 'some value',
    t: 'some other value'
};

is functionally equivalent to

var o = new Object();
o.r = 'some value';
o.t = 'some other value';

Hash table runtime complexity (insert, search and delete)

Depends on the how you implement hashing, in the worst case it can go to O(n), in best case it is 0(1) (generally you can achieve if your DS is not that big easily)

Add space between two particular <td>s

The simplest way:

td:nth-child(2) {
    padding-right: 20px;
}?

But that won't work if you need to work with background color or images in your table. In that case, here is a slightly more advanced solution (CSS3):

td:nth-child(2) {
    border-right: 10px solid transparent;
    -webkit-background-clip: padding;
    -moz-background-clip: padding;
    background-clip: padding-box;
}

It places a transparent border to the right of the cell and pulls the background color/image away from the border, creating the illusion of spacing between the cells.

Note: For this to work, the parent table must have border-collapse: separate. If you have to work with border-collapse: collapse then you have to apply the same border style to the next table cell, but on the left side, to accomplish the same results.

Select columns in PySpark dataframe

You can use an array and unpack it inside the select:

cols = ['_2','_4','_5']
df.select(*cols).show()

How does @synchronized lock/unlock in Objective-C?

In Objective-C, a @synchronized block handles locking and unlocking (as well as possible exceptions) automatically for you. The runtime dynamically essentially generates an NSRecursiveLock that is associated with the object you're synchronizing on. This Apple documentation explains it in more detail. This is why you're not seeing the log messages from your NSLock subclass — the object you synchronize on can be anything, not just an NSLock.

Basically, @synchronized (...) is a convenience construct that streamlines your code. Like most simplifying abstractions, it has associated overhead (think of it as a hidden cost), and it's good to be aware of that, but raw performance is probably not the supreme goal when using such constructs anyway.

Replace new lines with a comma delimiter with Notepad++?

Here's what worked for me with a similar list of strings in Notepad++ without any macros or anything else:

  1. Click Edit -> Blank Operations -> EOL to space [All the items should now be in a single line separated by a 'space']

  2. Select any 'space' and do a Replace All (by ',')

AttributeError: 'list' object has no attribute 'encode'

You need to unicode each element of the list individually

[x.encode('utf-8') for x in tmp]

How to reset settings in Visual Studio Code?

On Linux environment delete the folder "~/.config/Code" to reset Visual Studio Code Settings.

Rename a dictionary key

Using a check for newkey!=oldkey, this way you can do:

if newkey!=oldkey:  
    dictionary[newkey] = dictionary[oldkey]
    del dictionary[oldkey]

How to remove duplicate objects in a List<MyObject> without equals/hashcode?

Here is one way of removing a duplicate object.

The blog class should be something like this or similar, like proper pojo

public class Blog {

    private String title;
    private String author;
    private String url;
    private String description;

    private int hashCode;



    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
       this.title = title;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public boolean equals(Object obj) {

        Blog blog = (Blog)obj;

        if(title.equals(blog.title) &&
                author.equals(blog.author) &&
                url.equals(blog.url) &&
                description.equals(blog.description))
        {
            hashCode = blog.hashCode;
            return true;
        }else{
            hashCode = super.hashCode();
            return false;
        }
    }

}

And use it like this to remove duplicates objects. The key data structure here is the Set and LinkedHashSet. It will remove duplicates and also keep order of entry

    Blog blog1 = new Blog();
    blog1.setTitle("Game of Thrones");
    blog1.setAuthor("HBO");
    blog1.setDescription("The best TV show in the US");
    blog1.setUrl("www.hbonow.com/gameofthrones");

    Blog blog2 = new Blog();
    blog2.setTitle("Game of Thrones");
    blog2.setAuthor("HBO");
    blog2.setDescription("The best TV show in the US");
    blog2.setUrl("www.hbonow.com/gameofthrones");

    Blog blog3 = new Blog();
    blog3.setTitle("Ray Donovan");
    blog3.setAuthor("Showtime");
    blog3.setDescription("The second best TV show in the US");
    blog3.setUrl("www.showtime.com/raydonovan");

    ArrayList<Blog> listOfBlogs = new ArrayList<>();

    listOfBlogs.add(blog1);
    listOfBlogs.add(blog2);
    listOfBlogs.add(blog3);


    Set<Blog> setOfBlogs = new LinkedHashSet<>(listOfBlogs);

    listOfBlogs.clear();
    listOfBlogs.addAll(setOfBlogs);

    for(int i=0;i<listOfBlogs.size();i++)
        System.out.println(listOfBlogs.get(i).getTitle());

Running this should print

Game of Thrones
Ray Donovan

The second one will be removed because it is a duplicate of the first object.

How to list npm user-installed packages?

One way might be to find the root directory of modules using:

npm root
/Users/me/repos/my_project/node_modules

And then list that directory...

ls /Users/me/repos/my_project/node_modules
grunt                   grunt-contrib-jshint

The user-installed packages in this case are grunt and grunt-contrib-jshint

PHP, Get tomorrows date from date

here's working function

function plus_one_day($date){
 $date2 = formatDate4db($date);
 $date1 = str_replace('-', '/', $date2);
 $tomorrow = date('Y-m-d',strtotime($date1 . "+1 days"));
 return $tomorrow; }

Calculating distance between two geographic locations

distanceTo will give you the distance in meters between the two given location ej target.distanceTo(destination).

distanceBetween give you the distance also but it will store the distance in a array of float( results[0]). the doc says If results has length 2 or greater, the initial bearing is stored in results[1]. If results has length 3 or greater, the final bearing is stored in results[2]

hope that this helps

i've used distanceTo to get the distance from point A to B i think that is the way to go.

What does from __future__ import absolute_import actually do?

The difference between absolute and relative imports come into play only when you import a module from a package and that module imports an other submodule from that package. See the difference:

$ mkdir pkg
$ touch pkg/__init__.py
$ touch pkg/string.py
$ echo 'import string;print(string.ascii_uppercase)' > pkg/main1.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pkg/main1.py", line 1, in <module>
    import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
>>> 
$ echo 'from __future__ import absolute_import;import string;print(string.ascii_uppercase)' > pkg/main2.py
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> 

In particular:

$ python2 pkg/main2.py
Traceback (most recent call last):
  File "pkg/main2.py", line 1, in <module>
    from __future__ import absolute_import;import string;print(string.ascii_uppercase)
AttributeError: 'module' object has no attribute 'ascii_uppercase'
$ python2
Python 2.7.9 (default, Dec 13 2014, 18:02:08) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> 
$ python2 -m pkg.main2
ABCDEFGHIJKLMNOPQRSTUVWXYZ

Note that python2 pkg/main2.py has a different behaviour then launching python2 and then importing pkg.main2 (which is equivalent to using the -m switch).

If you ever want to run a submodule of a package always use the -m switch which prevents the interpreter for chaining the sys.path list and correctly handles the semantics of the submodule.

Also, I much prefer using explicit relative imports for package submodules since they provide more semantics and better error messages in case of failure.

How to make Scrollable Table with fixed headers using CSS

I can think of a cheeky way to do it, I don't think this will be the best option but it will work.

Create the header as a separate table then place the other in a div and set a max size, then allow the scroll to come in by using overflow.

_x000D_
_x000D_
table {_x000D_
  width: 500px;_x000D_
}_x000D_
_x000D_
.scroll {_x000D_
  max-height: 60px;_x000D_
  overflow: auto;_x000D_
}
_x000D_
<table border="1">_x000D_
  <tr>_x000D_
  <th>head1</th>_x000D_
  <th>head2</th>_x000D_
  <th>head3</th>_x000D_
  <th>head4</th>_x000D_
  </tr>_x000D_
</table>_x000D_
<div class="scroll">_x000D_
  <table>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>More Text</td><td>More Text</td><td>More Text</td><td>More Text</td></tr>_x000D_
    <tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
    <tr><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td></tr>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Task vs Thread differences

The Thread class is used for creating and manipulating a thread in Windows.

A Task represents some asynchronous operation and is part of the Task Parallel Library, a set of APIs for running tasks asynchronously and in parallel.

In the days of old (i.e. before TPL) it used to be that using the Thread class was one of the standard ways to run code in the background or in parallel (a better alternative was often to use a ThreadPool), however this was cumbersome and had several disadvantages, not least of which was the performance overhead of creating a whole new thread to perform a task in the background.

Nowadays using tasks and the TPL is a far better solution 90% of the time as it provides abstractions which allows far more efficient use of system resources. I imagine there are a few scenarios where you want explicit control over the thread on which you are running your code, however generally speaking if you want to run something asynchronously your first port of call should be the TPL.

BAT file to map to network drive without running as admin

I tried to create a mapped network driver via 'net use' with admin privilege but failed, it does not show. And if I add it through UI, it disappeared after reboot, now I made that through powershell. So, I think you can run powershell scripts from a .bat file, and the script is

New-PSDrive -Name "P" -PSProvider "FileSystem" -Root "\\Server01\Public"

add -persist at the end, you will create a persisted mapped network drive

New-PSDrive -Name "P" -PSProvider "FileSystem" -Root "\\Server01\Scripts" -Persist

for more details, refer New-PSDrive - Microsoft Docs

How to efficiently build a tree from a flat structure?

one elegant way to do this is to represent items in the list as string holding a dot separated list of parents, and finally a value:

server.port=90
server.hostname=localhost
client.serverport=90
client.database.port=1234
client.database.host=localhost

When assembling a tree, you would end up with something like:

server:
  port: 90
  hostname: localhost
client:
  serverport=1234
  database:
    port: 1234
    host: localhost

I have a configuration library that implements this override configuration (tree) from command line arguments (list). The algorithm to add a single item to the list to a tree is here.

Understanding string reversal via slicing

You can use reversed() function. For example

x = "abcd"
for i in reversed(x):
        print(i, end="")
print("\n")
L = [1,2,3]
for i in reversed(L):
        print(i, end="")

prints dcba and 321

Twitter Bootstrap dropdown menu

It's also possible to customise your bootstrap build by using:

http://twitter.github.com/bootstrap/customize.html

All the plugins are included by default.

How to list the files in current directory?

I used this answer with my local directory ( for example E:// ) it is worked fine for the first directory and for the seconde directory the output made a java null pointer exception, after searching for the reason i discover that the problem was created by the hidden directory, and this directory was created by windows to avoid this problem just use this

public void recursiveSearch(File file ) {
 File[] filesList = file.listFiles();
    for (File f : filesList) {
        if (f.isDirectory() && !f.isHidden()) {
            System.out.println("Directoy name is  -------------->" + f.getName());
            recursiveSearch(f);
        }
        if( f.isFile() ){
            System.out.println("File name is  -------------->" + f.getName());
        }
    }
}

How do you compare structs for equality in C?

This compliant example uses the #pragma pack compiler extension from Microsoft Visual Studio to ensure the structure members are packed as tightly as possible:

#include <string.h>

#pragma pack(push, 1)
struct s {
  char c;
  int i;
  char buffer[13];
};
#pragma pack(pop)

void compare(const struct s *left, const struct s *right) { 
  if (0 == memcmp(left, right, sizeof(struct s))) {
    /* ... */
  }
}

Change the image source on rollover using jQuery

I know you're asking about using jQuery, but you can achieve the same effect in browsers that have JavaScript turned off using CSS:

#element {
    width: 100px; /* width of image */
    height: 200px; /* height of image */
    background-image: url(/path/to/image.jpg);
}

#element:hover {
    background-image: url(/path/to/other_image.jpg);
}

There's a longer description here

Even better, however, is to use sprites: simple-css-image-rollover

How to Select Every Row Where Column Value is NOT Distinct

This is significantly faster than the EXISTS way:

SELECT [EmailAddress], [CustomerName] FROM [Customers] WHERE [EmailAddress] IN
  (SELECT [EmailAddress] FROM [Customers] GROUP BY [EmailAddress] HAVING COUNT(*) > 1)

How to sort an array in descending order in Ruby

What about:

 a.sort {|x,y| y[:bar]<=>x[:bar]}

It works!!

irb
>> a = [
?>   { :foo => 'foo', :bar => 2 },
?>   { :foo => 'foo', :bar => 3 },
?>   { :foo => 'foo', :bar => 5 },
?> ]
=> [{:bar=>2, :foo=>"foo"}, {:bar=>3, :foo=>"foo"}, {:bar=>5, :foo=>"foo"}]

>>  a.sort {|x,y| y[:bar]<=>x[:bar]}
=> [{:bar=>5, :foo=>"foo"}, {:bar=>3, :foo=>"foo"}, {:bar=>2, :foo=>"foo"}]

"Python version 2.7 required, which was not found in the registry" error when attempting to install netCDF4 on Windows 8

I think it really depends on why this error is given. It may be the bitness issue, but it may also be because of a deinstaller bug that leaves registry entries behind.

I just had this case because I need two versions of Python on my system. When I tried to install SCons (using Python2), the .msi installer failed, saying it only found Python3 in the registry. So I uninstalled it, with the result that no Python was found at all. Frustrating! (workaround: install SCons with pip install --egg --upgrade scons)

Anyway, I'm sure there are threads on that phenomenon. I just thought it would fit here because this was one of my top search results.

How to efficiently count the number of keys/properties of an object in JavaScript?

Here are some performance tests for three methods;

https://jsperf.com/get-the-number-of-keys-in-an-object

Object.keys().length

20,735 operations per second

Very simple and compatible. Runs fast but expensive because it creates a new array of keys, which that then gets thrown away.

return Object.keys(objectToRead).length;

loop through the keys

15,734 operations per second

let size=0;
for(let k in objectToRead) {
  size++
}
return size;

Slightly slower, but nowhere near the memory usage, so probably better if you're interested in optimising for mobile or other small machines

Using Map instead of Object

953,839,338 operations per second

return mapToRead.size;

Basically, Map tracks its own size so we're just returning a number field. Far, far faster than any other method. If you have control of the object, convert them to maps instead.

Text to speech(TTS)-Android

// variable declaration
TextToSpeech tts;

// TextToSpeech initialization, must go within the onCreate method
tts = new TextToSpeech(getActivity(), new TextToSpeech.OnInitListener() {
 @Override
 public void onInit(int i) {
  if (i == TextToSpeech.SUCCESS) {
   int result = tts.setLanguage(Locale.US);
   if (result == TextToSpeech.LANG_MISSING_DATA ||
    result == TextToSpeech.LANG_NOT_SUPPORTED) {
    Log.e("TTS", "Lenguage not supported");
   }
  } else {
   Log.e("TTS", "Initialization failed");
  }
 }
});

// method call
public void buttonSpeak().setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View view) {
  speak();
 }
});
}

private void speak() {
 tts.speak("Text to Speech Test", TextToSpeech.QUEUE_ADD, null);
}

@Override
public void onDestroy() {
 if (tts != null) {
  tts.stop();
  tts.shutdown();
 }
 super.onDestroy();
}

taken from: Text to Speech Youtube Tutorial

How to export the Html Tables data into PDF using Jspdf

A good option is AutoTable(a Table plugin for jsPDF), it includes themes, rowspan, colspan, extract data from html, works with json, you can also personalize your headers and make them horizontals. Here is a demo.

enter image description here

What is a .pid file and what does it contain?

To understand pid files, refer this DOC

Some times there are certain applications that require additional support of extra plugins and utilities. So it keeps track of these utilities and plugin process running ids using this pid file for reference.

That is why whenever you restart an application all necessary plugins and dependant apps must be restarted since the pid file will become stale.

converting string to long in python

Well, longs can't hold anything but integers.

One option is to use a float: float('234.89')

The other option is to truncate or round. Converting from a float to a long will truncate for you: long(float('234.89'))

>>> long(float('1.1'))
1L
>>> long(float('1.9'))
1L
>>> long(round(float('1.1')))
1L
>>> long(round(float('1.9')))
2L

Getting data from selected datagridview row and which event?

Simple solution would be as below. This is improvement of solution from vale.

private void dgMapTable_SelectionChanged(object sender, EventArgs e) 
{
    int active_map=0;
    if(dgMapTable.SelectedRows.Count>0)
        active_map = dgMapTable.SelectedRows[0].Index;
    // User code if required Process_ROW(active_map);
}

Note for other reader, for above code to work FullRowSelect selection mode for datagridview should be used. You may extend this to give message if more than two rows selected.

Efficient iteration with index in Scala

A simple and efficient way, inspired from the implementation of transform in SeqLike.scala

    var i = 0
    xs foreach { el =>
      println("String #" + i + " is " + xs(i))
      i += 1
    }

Make UINavigationBar transparent

From IOS7 :

self.navigationController.navigationBar.translucent = YES;
self.navigationController.navigationBar.shadowImage = [UIImage new];
self.navigationController.view.backgroundColor = [UIColor clearColor];
[self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];

What are the correct version numbers for C#?

I've summarised most of the versions in this table. The only ones missing should be ASP.NET Core versions. I've also added different versions of ASP.NET MVC.

Note that ASP.NET 5 has been rebranded as ASP.NET Core 1.0 and ASP.NET MVC 6 has been rebranded as ASP.NET Core MVC 1.0.0. I believe this change occurred sometime around Jan 2016.

I have included the release date of ASP.NET 5 RC1 in the table, but I've yet to include ASP.NET core 1.0 and other core versions, because I couldn't find the exact release dates. You can read more about the release dates regarding ASP.NET Core here: When is ASP.NET Core 1.0 (ASP.NET 5 / vNext) scheduled for release?

Version

How to print a double with two decimals in Android?

For Displaying digit upto two decimal places there are two possibilities - 1) Firstly, you only want to display decimal digits if it's there. For example - i) 12.10 to be displayed as 12.1, ii) 12.00 to be displayed as 12. Then use-

DecimalFormat formater = new DecimalFormat("#.##"); 

2) Secondly, you want to display decimal digits irrespective of decimal present For example -i) 12.10 to be displayed as 12.10. ii) 12 to be displayed as 12.00.Then use-

DecimalFormat formater = new DecimalFormat("0.00"); 

How to show Snackbar when Activity starts?

You can also define a super class for all your activities and find the view once in the parent activity.

for example

AppActivity.java :

public class AppActivity extends AppCompatActivity {

    protected View content;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        changeLanguage("fa");
        content = findViewById(android.R.id.content);
    }
}

and your snacks would look like this in every activity in your app:

Snackbar.make(content, "hello every body", Snackbar.LENGTH_SHORT).show();

It is better for performance you have to find the view once for every activity.

Deleting Elements in an Array if Element is a Certain value VBA

here is a sample of code using the CopyMemory function to do the job.

It is supposedly "much faster" (depending of the size and type of the array...).

i am not the author, but i tested it :

Sub RemoveArrayElement_Str(ByRef AryVar() As String, ByVal RemoveWhich As Long) 

'// The size of the array elements
'// In the case of string arrays, they are
'// simply 32 bit pointers to BSTR's.
Dim byteLen As Byte

'// String pointers are 4 bytes
byteLen = 4

'// The copymemory operation is not necessary unless
'// we are working with an array element that is not
'// at the end of the array
If RemoveWhich < UBound(AryVar) Then
    '// Copy the block of string pointers starting at
    ' the position after the
    '// removed item back one spot.
    CopyMemory ByVal VarPtr(AryVar(RemoveWhich)), ByVal _
        VarPtr(AryVar(RemoveWhich + 1)), (byteLen) * _
        (UBound(AryVar) - RemoveWhich)
End If

'// If we are removing the last array element
'// just deinitialize the array
'// otherwise chop the array down by one.
If UBound(AryVar) = LBound(AryVar) Then
    Erase AryVar
Else
    ReDim Preserve AryVar(LBound(AryVar) To UBound(AryVar) - 1)
End If
End Sub

“Origin null is not allowed by Access-Control-Allow-Origin” error for request made by application running from a file:// URL

There is a small problem in the solution posted by CodeGroover above , where if you change a file, you'll have to restart the server to actually use the updated file (at least, in my case).

So searching a bit, I found this one To use:

sudo npm -g install simple-http-server # to install
nserver # to use

And then it will serve at http://localhost:8000.

How to submit form on change of dropdown list?

Very easy to use select option submit

<select name="sortby" onchange="this.form.submit()">
       <option value="">Featured</option>
       <option value="asc" >Price: Low to High</option>
        <option value="desc">Price: High to Low</option>                                   
</select>

This code use and enjoy now:

Read More: Go Link

Map HTML to JSON

Representing complex HTML documents will be difficult and full of corner cases, but I just wanted to share a couple techniques to show how to get this kind of program started. This answer differs in that it uses data abstraction and the toJSON method to recursively build the result

Below, html2json is a tiny function which takes an HTML node as input and it returns a JSON string as the result. Pay particular attention to how the code is quite flat but it's still plenty capable of building a deeply nested tree structure – all possible with virtually zero complexity

_x000D_
_x000D_
// data Elem = Elem Node_x000D_
_x000D_
const Elem = e => ({_x000D_
  toJSON : () => ({_x000D_
    tagName: _x000D_
      e.tagName,_x000D_
    textContent:_x000D_
      e.textContent,_x000D_
    attributes:_x000D_
      Array.from(e.attributes, ({name, value}) => [name, value]),_x000D_
    children:_x000D_
      Array.from(e.children, Elem)_x000D_
  })_x000D_
})_x000D_
_x000D_
// html2json :: Node -> JSONString_x000D_
const html2json = e =>_x000D_
  JSON.stringify(Elem(e), null, '  ')_x000D_
  _x000D_
console.log(html2json(document.querySelector('main')))
_x000D_
<main>_x000D_
  <h1 class="mainHeading">Some heading</h1>_x000D_
  <ul id="menu">_x000D_
    <li><a href="/a">a</a></li>_x000D_
    <li><a href="/b">b</a></li>_x000D_
    <li><a href="/c">c</a></li>_x000D_
  </ul>_x000D_
  <p>some text</p>_x000D_
</main>
_x000D_
_x000D_
_x000D_

In the previous example, the textContent gets a little butchered. To remedy this, we introduce another data constructor, TextElem. We'll have to map over the childNodes (instead of children) and choose to return the correct data type based on e.nodeType – this gets us a littler closer to what we might need

_x000D_
_x000D_
// data Elem = Elem Node | TextElem Node_x000D_
_x000D_
const TextElem = e => ({_x000D_
  toJSON: () => ({_x000D_
    type:_x000D_
      'TextElem',_x000D_
    textContent:_x000D_
      e.textContent_x000D_
  })_x000D_
})_x000D_
_x000D_
const Elem = e => ({_x000D_
  toJSON : () => ({_x000D_
    type:_x000D_
      'Elem',_x000D_
    tagName: _x000D_
      e.tagName,_x000D_
    attributes:_x000D_
      Array.from(e.attributes, ({name, value}) => [name, value]),_x000D_
    children:_x000D_
      Array.from(e.childNodes, fromNode)_x000D_
  })_x000D_
})_x000D_
_x000D_
// fromNode :: Node -> Elem_x000D_
const fromNode = e => {_x000D_
  switch (e.nodeType) {_x000D_
    case 3:  return TextElem(e)_x000D_
    default: return Elem(e)_x000D_
  }_x000D_
}_x000D_
_x000D_
// html2json :: Node -> JSONString_x000D_
const html2json = e =>_x000D_
  JSON.stringify(Elem(e), null, '  ')_x000D_
  _x000D_
console.log(html2json(document.querySelector('main')))
_x000D_
<main>_x000D_
  <h1 class="mainHeading">Some heading</h1>_x000D_
  <ul id="menu">_x000D_
    <li><a href="/a">a</a></li>_x000D_
    <li><a href="/b">b</a></li>_x000D_
    <li><a href="/c">c</a></li>_x000D_
  </ul>_x000D_
  <p>some text</p>_x000D_
</main>
_x000D_
_x000D_
_x000D_

Anyway, that's just two iterations on the problem. Of course you'll have to address corner cases where they come up, but what's nice about this approach is that it gives you a lot of flexibility to encode the HTML however you wish in JSON – and without introducing too much complexity

In my experience, you could keep iterating with this technique and achieve really good results. If this answer is interesting to anyone and would like me to expand upon anything, let me know ^_^

Related: Recursive methods using JavaScript: building your own version of JSON.stringify

How to sort a Collection<T>?

Collections by themselves do not have a predefined order, therefore you must convert them to a java.util.List. Then you can use one form of java.util.Collections.sort

Collection< T > collection = ...;

List< T > list = new ArrayList< T >( collection );

Collections.sort( list );
 // or
Collections.sort( list, new Comparator< T >( ){...} );

// list now is sorted

How to make a list of n numbers in Python and randomly select any number?

As for the first part:

>>> N = 5
>>> count_list = [i+1 for i in xrange(N)]
>>> count_list
[1, 2, 3, 4, 5]
>>>

As for the second, read 9.6. random — Generate pseudo-random numbers.

>>> from random import choice
>>> a = choice(count_list)
>>> a
1
>>> count_list.remove(a)
>>> count_list
[2, 3, 4, 5]

That's the general idea.

By the way, you may also be interested in reading Random selection of elements in a list, with no repeats (Python recipe).

There are a few implementations of fast random selection.

Handling of non breaking space: <p>&nbsp;</p> vs. <p> </p>

If I understand your issue this should work

&emsp—the em space; this should be a very wide space, typically as much as four real spaces. &ensp—the en space; this should be a somewhat wide space, roughly two regular spaces. &thinsp—this will be a narrow space, even more narrow than a regular space.

Sources: http://hea-www.harvard.edu/~fine/Tech/html-sentences.html

How do I get the latest version of my code?

I suspect that what's happened may be that you've deleted the files that you modified (because you didn't care about those changes) and now git is taking the deletion to be a change.

Here is an approach that moves your changes out of your working copy and into the "stash" (retrievable should it actually turn out that you ever need them again), so you can then pull the latest changes down from the upstream.

git stash  
git pull

If you ever want to retrieve your files (potential conflicts with upstream changes and all), run a git stash apply to stick those changes on top of your code. That way, you have an "undo" approach.

How to make one Observable sequence wait for another to complete before emitting?

Here's a reusable way of doing it (it's typescript but you can adapt it to js):

export function waitFor<T>(signal: Observable<any>) {
    return (source: Observable<T>) =>
        new Observable<T>(observer =>
            signal.pipe(first())
                .subscribe(_ =>
                    source.subscribe(observer)
                )
        );
}

and you can use it like any operator:

var two = someOtherObservable.pipe(waitFor(one), take(1));

It's basically an operator that defers the subscribe on the source observable until the signal observable emits the first event.

Redirect after Login on WordPress

This should solve your problem. Adapted from an answer found here.

Add the following snippet of code in the functions.php file of your theme:

function admin_default_page() {
  return '/new-dashboard-url';
}

add_filter('login_redirect', 'admin_default_page');

Is there a difference between /\s/g and /\s+/g?

In the first regex, each space character is being replaced, character by character, with the empty string.

In the second regex, each contiguous string of space characters is being replaced with the empty string because of the +.

However, just like how 0 multiplied by anything else is 0, it seems as if both methods strip spaces in exactly the same way.

If you change the replacement string to '#', the difference becomes much clearer:

var str = '  A B  C   D EF ';
console.log(str.replace(/\s/g, '#'));  // ##A#B##C###D#EF#
console.log(str.replace(/\s+/g, '#')); // #A#B#C#D#EF#

LinkButton Send Value to Code Behind OnClick

Add a CommandName attribute, and optionally a CommandArgument attribute, to your LinkButton control. Then set the OnCommand attribute to the name of your Command event handler.

<asp:LinkButton ID="ENameLinkBtn" runat="server" CommandName="MyValueGoesHere" CommandArgument="OtherValueHere" 
          style="font-weight: 700; font-size: 8pt;" OnCommand="ENameLinkBtn_Command" ><%# Eval("EName") %></asp:LinkButton>

<asp:Label id="Label1" runat="server"/>

Then it will be available when in your handler:

protected void ENameLinkBtn_Command (object sender, CommandEventArgs e)
{
   Label1.Text = "You chose: " + e.CommandName + " Item " + e.CommandArgument;
}

More info on MSDN

Radio Buttons "Checked" Attribute Not Working

If you have multiple of the same name with the checked attribute it will take the last checked radio on the page.

_x000D_
_x000D_
<form>_x000D_
    <label>Do you want to accept American Express?</label>_x000D_
    Yes<input id="amex" style="width: 20px;" type="radio" name="Contact0_AmericanExpress"  />  _x000D_
    maybe<input id="amex" style="width: 20px;" type="radio" name="Contact0_AmericanExpress"  checked="checked" />  _x000D_
    No<input style="width: 20px;" type="radio" name="Contact0_AmericanExpress" class="check" checked="checked" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Best practices for adding .gitignore file for Python projects?

Here are some other files that may be left behind by setuptools:

MANIFEST
*.egg-info

How to get the size of the current screen in WPF?

This will give you the current screen based on the top left of the window just call this.CurrentScreen() to get info on the current screen.

using System.Windows;
using System.Windows.Forms;

namespace Common.Helpers
{
    public static class WindowHelpers
     {
        public static Screen CurrentScreen(this Window window)
         {
             return Screen.FromPoint(new System.Drawing.Point((int)window.Left,(int)window.Top));
         }
     }
}

How to resolve the "ADB server didn't ACK" error?

On my Mac, I wrote this code in my Terminal:

xxx-MacBook-Pro:~ xxx$ cd /Users/xxx/Documents/0_Software/adt20140702/sdk/platform-tools/

xxx-MacBook-Pro:platform-tools xxx$ ./adb kill-server

xxx-MacBook-Pro:platform-tools xxx$ ./adb start-server

  • daemon not running. starting it now on port 5037 *
  • daemon started successfully *

xxx-MacBook-Pro:platform-tools tuananh$

Hope this help.

Digital Certificate: How to import .cer file in to .truststore file using?

# Copy the certificate into the directory Java_home\Jre\Lib\Security
# Change your directory to Java_home\Jre\Lib\Security>
# Import the certificate to a trust store.

keytool -import -alias ca -file somecert.cer -keystore cacerts -storepass changeit [Return]

Trust this certificate: [Yes]

changeit is the default truststore password

Keep SSH session alive

I wanted a one-time solution:

ssh -o ServerAliveInterval=60 [email protected]

Stored it in an alias:

alias sshprod='ssh -v -o ServerAliveInterval=60 [email protected]'

Now can connect like this:

me@MyMachine:~$ sshprod

How to embed new Youtube's live video permanent URL?

Here's how to do it in Squarespace using the embed block classes to create responsiveness.

Put this into a code block:

<div class="sqs-block embed-block sqs-block-embed" data-block-type="22" >
    <div class="sqs-block-content"><div class="intrinsic" style="max-width:100%">
        <div class="embed-block-wrapper embed-block-provider-YouTube" style="padding-bottom:56.20609%;">
            <iframe allow="autoplay; fullscreen" scrolling="no" data-image-dimensions="854x480" allowfullscreen="true" src="https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID_HERE" width="854" data-embed="true" frameborder="0" title="YouTube embed" class="embedly-embed" height="480">
            </iframe>
        </div>
    </div>
</div>

Tweak however you'd like!

Embed an External Page Without an Iframe?

Question is good, but the answer is : it depends on that.

If the other webpage doesn't contain any form or text, for example you can use the CURL method to pickup the exact content and after then showing on your page. YOu can do it without using an iframe.

But, if the page what you want to embed contains for example a form it will not work correctly , because the form handling is on that site.

how to access the command line for xampp on windows

In the version 3.2.4 of the XAMPP Control Panel, there is button that can open a command line prompt (red rectangle in the next figure)

enter image description here

After pressing the button, you will see the command prompt window.

enter image description here

From this window you can navigate through the different folders and start the different services available.

How to use aria-expanded="true" to change a css property

You could use querySelector() with attribute selector '[attribute="value"]', then affect css rule using .style, as you can see in the example below:

_x000D_
_x000D_
document.querySelector('a[aria-expanded="true"]').style.backgroundColor = "#42DCA3";
_x000D_
<ul><li class="active">_x000D_
  <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true"> <span class="network-name">Google+ with aria expanded true</span></a>_x000D_
  </li>_x000D_
  <li>_x000D_
    <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="false"> <span class="network-name">Google+ with aria expanded false</span></a>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

jQuery solution :

If you want to use a jQuery solution you could simply use css() method :

$('a[aria-expanded="true"]').css('background-color','#42DCA3');

Hope this helps.

YouTube URL in Video Tag

This will give you the answer you need. The easiest way to do it is with the youTube-provided methods. How to Embed Youtube Videos into HTML5 <video> Tag?

INSTALL_FAILED_UPDATE_INCOMPATIBLE when I try to install compiled .apk on device

if the APK is built in project with Android.mk file. Maybe it's because of the sign certificate has been changed.

in my problem, I have add LOCAL_CERTIFICATE := platform. as the original apk is signed without this tag.

how to bind img src in angular 2 in ngFor?

Angular 2.x to 8 Compatible!

You can directly give the source property of the current object in the img src attribute. Please see my code below:

<div *ngFor="let brochure of brochureList">
    <img class="brochure-poster" [src]="brochure.imageUrl" />
</div>

NOTE: You can as well use string interpolation but that is not a legit way to do it. Property binding was created for this very purpose hence better use this.

NOT RECOMMENDED :

<img class="brochure-poster" src="{{brochure.imageUrl}}"/>

Its because that defeats the purpose of property binding. It is more meaningful to use that for setting the properties. {{}} is a normal string interpolation expression, that does not reveal to anyone reading the code that it makes special meaning. Using [] makes it easily to spot the properties that are set dynamically.

Here is my brochureList contains the following json received from service(you can assign it to any variable):

[ {
            "productId":1,
            "productName":"Beauty Products",
            "productCode": "XXXXXX",            
            "description":  "Skin Care",           
            "imageUrl":"app/Images/c1.jpg"
         },
        {
             "productId":2,
            "productName":"Samsung Galaxy J5",
            "productCode": "MOB-124",      
            "description":  "8GB, Gold",
            "imageUrl":"app/Images/c8.jpg"
         }]

What is the difference between Cloud, Grid and Cluster?

Cloud: is simply an aggregate of computing power. You can think of the entire "cloud" as single server, for your purposes. It's conceptually much like an old school mainframe where you could submit your jobs to and have it return the result, except that nowadays the concept is applied more widely. (I.e. not just raw computing, also entire services, or storage ...)

Grid: a grid is simply many computers which together might solve a given problem/crunch data. The fundamental difference between a grid and a cluster is that in a grid each node is relatively independent of others; problems are solved in a divide and conquer fashion.

Cluster: conceptually it is essentially smashing up many machines to make a really big & powerful one. This is a much more difficult architecture than cloud or grid to get right because you have to orchestrate all nodes to work together, and provide consistency of things such as cache, memory, and not to mention clocks. Of course clouds have much the same problem, but unlike clusters clouds are not conceptually one big machine, so the entire architecture doesn't have to treat it as such. You can for instance not allocate the full capacity of your data center to a single request, whereas that is kind of the point of a cluster: to be able to throw 100% of the oomph at a single problem.

Delete an element in a JSON object

Let's assume you want to overwrite the same file:

import json

with open('data.json', 'r') as data_file:
    data = json.load(data_file)

for element in data:
    element.pop('hours', None)

with open('data.json', 'w') as data_file:
    data = json.dump(data, data_file)

dict.pop(<key>, not_found=None) is probably what you where looking for, if I understood your requirements. Because it will remove the hours key if present and will not fail if not present.

However I am not sure I understand why it makes a difference to you whether the hours key contains some days or not, because you just want to get rid of the whole key / value pair, right?

Now, if you really want to use del instead of pop, here is how you could make your code work:

import json

with open('data.json') as data_file:
    data = json.load(data_file)

for element in data:
    if 'hours' in element:
        del element['hours']

with open('data.json', 'w') as data_file:
    data = json.dump(data, data_file)

EDIT So, as you can see, I added the code to write the data back to the file. If you want to write it to another file, just change the filename in the second open statement.

I had to change the indentation, as you might have noticed, so that the file has been closed during the data cleanup phase and can be overwritten at the end.

with is what is called a context manager, whatever it provides (here the data_file file descriptor) is available ONLY within that context. It means that as soon as the indentation of the with block ends, the file gets closed and the context ends, along with the file descriptor which becomes invalid / obsolete.

Without doing this, you wouldn't be able to open the file in write mode and get a new file descriptor to write into.

I hope it's clear enough...

SECOND EDIT

This time, it seems clear that you need to do this:

with open('dest_file.json', 'w') as dest_file:
    with open('source_file.json', 'r') as source_file:
        for line in source_file:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            dest_file.write(json.dumps(element))

Clear android application user data

// To delete all the folders and files within folders recursively
File sdDir = new File(sdPath);

if(sdDir.exists())
    deleteRecursive(sdDir);




// Delete any folder on a device if exists
void deleteRecursive(File fileOrDirectory) {
    if (fileOrDirectory.isDirectory())
    for (File child : fileOrDirectory.listFiles())
        deleteRecursive(child);

    fileOrDirectory.delete();
}

Get first key in a (possibly) associative array?

You could try

array_keys($data)[0]

Is there a way to delete all the data from a topic or delete the topic before every run?

I use the utility below to cleanup after my integration test run.

It uses the latest AdminZkClient api. The older api has been deprecated.

import javax.inject.Inject
import kafka.zk.{AdminZkClient, KafkaZkClient}
import org.apache.kafka.common.utils.Time

class ZookeeperUtils @Inject() (config: AppConfig) {

  val testTopic = "users_1"

  val zkHost = config.KafkaConfig.zkHost
  val sessionTimeoutMs = 10 * 1000
  val connectionTimeoutMs = 60 * 1000
  val isSecure = false
  val maxInFlightRequests = 10
  val time: Time = Time.SYSTEM

  def cleanupTopic(config: AppConfig) = {

    val zkClient = KafkaZkClient.apply(zkHost, isSecure, sessionTimeoutMs, connectionTimeoutMs, maxInFlightRequests, time)
    val zkUtils = new AdminZkClient(zkClient)

    val pp = new Properties()
    pp.setProperty("delete.retention.ms", "10")
    pp.setProperty("file.delete.delay.ms", "1000")
    zkUtils.changeTopicConfig(testTopic , pp)
    //    zkUtils.deleteTopic(testTopic)

    println("Waiting for topic to be purged. Then reset to retain records for the run")
    Thread.sleep(60000L)

    val resetProps = new Properties()
    resetProps.setProperty("delete.retention.ms", "3000000")
    resetProps.setProperty("file.delete.delay.ms", "4000000")
    zkUtils.changeTopicConfig(testTopic , resetProps)

  }


}

There is an option delete topic. But, it marks the topic for deletion. Zookeeper later deletes the topic. Since this can be unpredictably long, I prefer the retention.ms approach

How do I get the directory of the PowerShell script I execute?

PowerShell 3 has the $PSScriptRoot automatic variable:

Contains the directory from which a script is being run.

In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.

Don't be fooled by the poor wording. PSScriptRoot is the directory of the current file.

In PowerShell 2, you can calculate the value of $PSScriptRoot yourself:

# PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition

How to encode the plus (+) symbol in a URL

Just to add this to the list:

Uri.EscapeUriString("Hi there+Hello there") // Hi%20there+Hello%20there
Uri.EscapeDataString("Hi there+Hello there") // Hi%20there%2BHello%20there

See https://stackoverflow.com/a/34189188/98491

Usually you want to use EscapeDataString which does it right.

Folder is locked and I can't unlock it

If the file was locked by yourself(same svn account), you can follow these steps:

Right click on the locked file or folder, and select TortoiseSVN->Get lock... , and check on "[] Steal the locks" at the bottom left corner of the dialog, click "OK". If it complete successfully, that's ok. When you right click on the file again, you can see TortoiseSVN->Release lock..., click to unlock.

How to insert new cell into UITableView in Swift

Here is your code for add data into both tableView:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var table1Text: UITextField!
    @IBOutlet weak var table2Text: UITextField!
    @IBOutlet weak var table1: UITableView!
    @IBOutlet weak var table2: UITableView!

    var table1Data = ["a"]
    var table2Data = ["1"]

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func addData(sender: AnyObject) {

        //add your data into tables array from textField
        table1Data.append(table1Text.text)
        table2Data.append(table2Text.text)

        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            //reload your tableView
            self.table1.reloadData()
            self.table2.reloadData()
        })


        table1Text.resignFirstResponder()
        table2Text.resignFirstResponder()
    }

    //delegate methods
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == table1 {
            return table1Data.count
        }else if tableView == table2 {
            return table2Data.count
        }
        return Int()
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        if tableView == table1 {
            let cell = table1.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell

            let row = indexPath.row
            cell.textLabel?.text = table1Data[row]

            return cell
        }else if tableView == table2 {

            let cell = table2.dequeueReusableCellWithIdentifier("Cell1", forIndexPath: indexPath) as! UITableViewCell

            let row = indexPath.row
            cell.textLabel?.text = table2Data[row]

            return cell
        }

        return UITableViewCell()
    }
}

And your result will be:

enter image description here

Java dynamic array sizes?

I recommend using vectors instead. Very easy to use and has many predefined methods for implementation.

import java.util.*;

Vector<Integer> v=new Vector<Integer>(5,2);

to add an element simply use:

v.addElement(int);

In the (5,2) the first 5 is the initial size of the vector. If you exceed the initial size,the vector will grow by 2 places. If it exceeds again, then it will again increase by 2 places and so on.

What is the meaning of 'No bundle URL present' in react-native?

I had this same issue. But my problem was my Mac and iPhone were not in same wifi network.

So ensure that they are all in same network and rebuild once again. If this is not the case, try the solutions mentioned by other members here.

Rotating a view in Android

fun rotateArrow(view: View): Boolean {
    return if (view.rotation == 0F) {
        view.animate().setDuration(200).rotation(180F)
        true
    } else {
         view.animate().setDuration(200).rotation(0F)
         false
    }
}

Create or write/append in text file

Although there are many ways to do this. But if you want to do it in an easy way and want to format text before writing it to log file. You can create a helper function for this.

if (!function_exists('logIt')) {
    function logIt($logMe)
    {
        $logFilePath = storage_path('logs/cron.log.'.date('Y-m-d').'.log');
        $cronLogFile = fopen($logFilePath, "a");
        fwrite($cronLogFile, date('Y-m-d H:i:s'). ' : ' .$logMe. PHP_EOL);
        fclose($cronLogFile);
    }
}

Android - drawable with rounded corners at the top only

Create roung_top_corners.xml on drawable and copy the below code

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<corners
    android:topLeftRadius="22dp"
    android:topRightRadius="22dp"
    android:bottomLeftRadius="0dp"
    android:bottomRightRadius="0dp"
    />
<gradient
    android:angle="180"
    android:startColor="#1d2b32"
    android:centerColor="#465059"
    android:endColor="#687079"
    android:type="linear" />
<padding
    android:left="0dp"
    android:top="0dp"
    android:right="0dp"
    android:bottom="0dp"
    />
<size
    android:width="270dp"
    android:height="60dp"
    /></shape>

Iterate keys in a C++ map

I know this doesn't answer your question, but one option you may want to look at is just having two vectors with the same index being "linked" information..

So in..

std::vector<std::string> vName;

std::vector<int> vNameCount;

if you want the count of names by name you just do your quick for loop over vName.size(), and when ya find it that is the index for vNameCount that you are looking for.

Sure this may not give ya all the functionality of the map, and depending may or may not be better, but it might be easier if ya don't know the keys, and shouldn't add too much processing.

Just remember when you add/delete from one you have to do it from the other or things will get crazy heh :P

PDF to byte array and vice versa

Calling toString() on an InputStream doesn't do what you think it does. Even if it did, a PDF contains binary data, so you wouldn't want to convert it to a string first.

What you need to do is read from the stream, write the results into a ByteArrayOutputStream, then convert the ByteArrayOutputStream into an actual byte array by calling toByteArray():

InputStream inputStream = new FileInputStream(sourcePath);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

int data;
while( (data = inputStream.read()) >= 0 ) {
    outputStream.write(data);
}

inputStream.close();
return outputStream.toByteArray();

How do you import classes in JSP?

Use the following import statement to import java.util.List:

<%@ page import="java.util.List" %>

BTW, to import more than one class, use the following format:

<%@ page import="package1.myClass1,package2.myClass2,....,packageN.myClassN" %>

How to mute an html5 video player using jQuery

$("video").prop('muted', true); //mute

AND

$("video").prop('muted', false); //unmute

See all events here

(side note: use attr if in jQuery < 1.6)

Looping over arrays, printing both index and value

users=("kamal" "jamal" "rahim" "karim" "sadia")
index=()
t=-1

for i in ${users[@]}; do
  t=$(( t + 1 ))
  if [ $t -eq 0 ]; then
    for j in ${!users[@]}; do
      index[$j]=$j
    done
  fi
  echo "${index[$t]} is $i"
done

What does Java option -Xmx stand for?

C:\java -X

    -Xmixed           mixed mode execution (default)
    -Xint             interpreted mode execution only
    -Xbootclasspath:<directories and zip/jar files separated by ;>
                      set search path for bootstrap classes and resources
    -Xbootclasspath/a:<directories and zip/jar files separated by ;>
                      append to end of bootstrap class path
    -Xbootclasspath/p:<directories and zip/jar files separated by ;>
                      prepend in front of bootstrap class path
    -Xnoclassgc       disable class garbage collection
    -Xincgc           enable incremental garbage collection
    -Xloggc:<file>    log GC status to a file with time stamps
    -Xbatch           disable background compilation
    -Xms<size>        set initial Java heap size
    -Xmx<size>        set maximum Java heap size
    -Xss<size>        set java thread stack size
    -Xprof            output cpu profiling data
    -Xfuture          enable strictest checks, anticipating future default
    -Xrs              reduce use of OS signals by Java/VM (see documentation)
    -Xcheck:jni       perform additional checks for JNI functions
    -Xshare:off       do not attempt to use shared class data
    -Xshare:auto      use shared class data if possible (default)
    -Xshare:on        require using shared class data, otherwise fail.

The -X options are non-standard and subject to change without notice.

nginx- duplicate default server error

In my case junk files from editor caused the problem. I had a config as below:

#...
http {
 # ...
 include ../sites/*;
}

In the ../sites directory initially I had a default.config file. However, by mistake I saved duplicate files as default.config.save and default.config.save.1. Removing them resolved the issue.

Apache2: 'AH01630: client denied by server configuration'

I got resolved my self after spending couple of hours.

I installed Apache/2.4.7 (Ubuntu) through coookbook in vagrant vm.

/etc/apache2/apache2.conf file does not have <VirtualHost *:80> element by default.

I did two changes to get it done

  1. added <VirtualHost *:80>
  2. added
    Options Indexes FollowSymLinks
    AllowOverride all
    Allow from all

then finally I just booted vm..

HTTP 404 when accessing .svc file in IIS

I had to add the extension .svc to the allowed extensions in the request filtering settings (got 404.7 errors before).

enter image description here

PHP is_numeric or preg_match 0-9 validation

Not exactly the same.

From the PHP docs of is_numeric:

'42' is numeric
'1337' is numeric
'1e4' is numeric
'not numeric' is NOT numeric
'Array' is NOT numeric
'9.1' is numeric

With your regex you only check for 'basic' numeric values.

Also is_numeric() should be faster.

How to convert JSON to string?

You can use the JSON stringify method.

JSON.stringify({x: 5, y: 6}); // '{"x":5,"y":6}' or '{"y":6,"x":5}'

There is pretty good support for this across the board when it comes to browsers, as shown on http://caniuse.com/#search=JSON. You will note, however, that versions of IE earlier than 8 do not support this functionality natively.

If you wish to cater to those users as well you will need a shim. Douglas Crockford has provided his own JSON Parser on github.

Why use 'git rm' to remove a file instead of 'rm'?

If you just use rm, you will need to follow it up with git add <fileRemoved>. git rm does this in one step.

You can also use git rm --cached which will remove the file from the index (staging it for deletion on the next commit), but keep your copy in the local file system.

How to download a file from a URL in C#?

Include this namespace

using System.Net;

Download Asynchronously and put a ProgressBar to show the status of the download within the UI Thread Itself

private void BtnDownload_Click(object sender, RoutedEventArgs e)
{
    using (WebClient wc = new WebClient())
    {
        wc.DownloadProgressChanged += wc_DownloadProgressChanged;
        wc.DownloadFileAsync (
            // Param1 = Link of file
            new System.Uri("http://www.sayka.com/downloads/front_view.jpg"),
            // Param2 = Path to save
            "D:\\Images\\front_view.jpg"
        );
    }
}
// Event to track the progress
void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    progressBar.Value = e.ProgressPercentage;
}

How do you tell if a string contains another string in POSIX sh?

In special cases where you want to find whether a word is contained in a long text, you can iterate through the long text with a loop.

found=F
query_word=this
long_string="many many words in this text"
for w in $long_string; do
    if [ "$w" = "$query_word" ]; then
          found=T
          break
    fi
done

This is pure Bourne shell.

How can I start PostgreSQL on Windows?

first find your binaries file where it is saved. get the path in terminal mine is

C:\Users\LENOVO\Documents\postgresql-9.5.21-1-windows-x64-binaries (1)\pgsql\bin

then find your local user data path, it is in mostly

C:\usr\local\pgsql\data

now all we have to hit following command in the binary terminal path:

C:\Users\LENOVO\Documents\postgresql-9.5.21-1-windows-x64-binaries (1)\pgsql\bin>pg_ctl -D "C:\usr\local\pgsql\data" start

all done!

autovaccum launcher started! cheers!

iOS app 'The application could not be verified' only on one device

Just had the same problem and I found out that the issue is with expired certificate. My app was distributed (AdHoc) through firebase and few days ago app was working just fine. Today I've realized that I can't install it because 'The application could not be verified'.

Finally I realized that certificate that I was using for app signing has expired 2 days ago. You need to upload it again and you'll be able to install it.

Creating a static class with no instances

The Pythonic way to create a static class is simply to declare those methods outside of a class (Java uses classes both for objects and for grouping related functions, but Python modules are sufficient for grouping related functions that do not require any object instance). However, if you insist on making a method at the class level that doesn't require an instance (rather than simply making it a free-standing function in your module), you can do so by using the "@staticmethod" decorator.

That is, the Pythonic way would be:

# My module
elements = []

def add_element(x):
  elements.append(x)

But if you want to mirror the structure of Java, you can do:

# My module
class World(object):
  elements = []

  @staticmethod
  def add_element(x):
    World.elements.append(x)

You can also do this with @classmethod if you care to know the specific class (which can be handy if you want to allow the static method to be inherited by a class inheriting from this class):

# My module
class World(object):
  elements = []

  @classmethod
  def add_element(cls, x):
    cls.elements.append(x)

Correct way to select from two tables in SQL Server with no common field to join on

Cross join will help to join multiple tables with no common fields.But be careful while joining as this join will give cartesian resultset of two tables. QUERY:

SELECT 
   table1.columnA
 , table2,columnA
FROM table1 
CROSS JOIN table2

Alternative way to join on some condition that is always true like

SELECT 
   table1.columnA
 , table2,columnA
FROM table1 
INNER JOIN table2 ON 1=1

But this type of query should be avoided for performance as well as coding standards.

Appending to list in Python dictionary

dates_dict[key] = dates_dict.get(key, []).append(date) sets dates_dict[key] to None as list.append returns None.

In [5]: l = [1,2,3]

In [6]: var = l.append(3)

In [7]: print var
None

You should use collections.defaultdict

import collections
dates_dict = collections.defaultdict(list)

Remove all whitespaces from NSString

Easy task using stringByReplacingOccurrencesOfString

NSString *search = [searchbar.text stringByReplacingOccurrencesOfString:@" " withString:@""];

How to add multiple classes to a ReactJS Component?

I use classnames when there is a fair amount of logic required for deciding the classes to (not) use. An overly simple example:

...
    var liClasses = classNames({
      'main-class': true,
      'activeClass': self.state.focused === index
    });

    return (<li className={liClasses}>{data.name}</li>);
...

That said, if you don't want to include a dependency then there are better answers below.

Download single files from GitHub

I think the new url structure is raw.giturl for example:

git file

raw

$(...).datepicker is not a function - JQuery - Bootstrap

I had similiar problem. The quick fix I found is to change:

<div class="input-group datepicker" data-provide="datepicker">

to

<div class="input-group date" data-provide="datepicker">

SELECTING with multiple WHERE conditions on same column

can't really see your table, but flag cannot be both 'Volunteer' and 'Uploaded'. If you have multiple values in a column, you can use

WHERE flag LIKE "%Volunteer%" AND flag LIKE "%UPLOADED%"

not really applicable seeing the formatted table.

How to send POST request in JSON using HTTPClient in Android?

In this answer I am using an example posted by Justin Grammens.

About JSON

JSON stands for JavaScript Object Notation. In JavaScript properties can be referenced both like this object1.name and like this object['name'];. The example from the article uses this bit of JSON.

The Parts
A fan object with email as a key and [email protected] as a value

{
  fan:
    {
      email : '[email protected]'
    }
}

So the object equivalent would be fan.email; or fan['email'];. Both would have the same value of '[email protected]'.

About HttpClient Request

The following is what our author used to make a HttpClient Request. I do not claim to be an expert at all this so if anyone has a better way to word some of the terminology feel free.

public static HttpResponse makeRequest(String path, Map params) throws Exception 
{
    //instantiates httpclient to make request
    DefaultHttpClient httpclient = new DefaultHttpClient();

    //url with the post data
    HttpPost httpost = new HttpPost(path);

    //convert parameters into JSON object
    JSONObject holder = getJsonObjectFromMap(params);

    //passes the results to a string builder/entity
    StringEntity se = new StringEntity(holder.toString());

    //sets the post request as the resulting string
    httpost.setEntity(se);
    //sets a request header so the page receving the request
    //will know what to do with it
    httpost.setHeader("Accept", "application/json");
    httpost.setHeader("Content-type", "application/json");

    //Handles what is returned from the page 
    ResponseHandler responseHandler = new BasicResponseHandler();
    return httpclient.execute(httpost, responseHandler);
}

Map

If you are not familiar with the Map data structure please take a look at the Java Map reference. In short, a map is similar to a dictionary or a hash.

private static JSONObject getJsonObjectFromMap(Map params) throws JSONException {

    //all the passed parameters from the post request
    //iterator used to loop through all the parameters
    //passed in the post request
    Iterator iter = params.entrySet().iterator();

    //Stores JSON
    JSONObject holder = new JSONObject();

    //using the earlier example your first entry would get email
    //and the inner while would get the value which would be '[email protected]' 
    //{ fan: { email : '[email protected]' } }

    //While there is another entry
    while (iter.hasNext()) 
    {
        //gets an entry in the params
        Map.Entry pairs = (Map.Entry)iter.next();

        //creates a key for Map
        String key = (String)pairs.getKey();

        //Create a new map
        Map m = (Map)pairs.getValue();   

        //object for storing Json
        JSONObject data = new JSONObject();

        //gets the value
        Iterator iter2 = m.entrySet().iterator();
        while (iter2.hasNext()) 
        {
            Map.Entry pairs2 = (Map.Entry)iter2.next();
            data.put((String)pairs2.getKey(), (String)pairs2.getValue());
        }

        //puts email and '[email protected]'  together in map
        holder.put(key, data);
    }
    return holder;
}

Please feel free to comment on any questions that arise about this post or if I have not made something clear or if I have not touched on something that your still confused about... etc whatever pops in your head really.

(I will take down if Justin Grammens does not approve. But if not then thanks Justin for being cool about it.)

Update

I just happend to get a comment about how to use the code and realized that there was a mistake in the return type. The method signature was set to return a string but in this case it wasnt returning anything. I changed the signature to HttpResponse and will refer you to this link on Getting Response Body of HttpResponse the path variable is the url and I updated to fix a mistake in the code.

log4j configuration via JVM argument(s)?

Generally, as long as your log4j.properties file is on the classpath, Log4j should just automatically pick it up at JVM startup.

How to save the contents of a div as a image?

Do something like this:

A <div> with ID of #imageDIV, another one with ID #download and a hidden <div> with ID #previewImage.

Include the latest version of jquery, and jspdf.debug.js from the jspdf CDN

Then add this script:

var element = $("#imageDIV"); // global variable
var getCanvas; // global variable
$('document').ready(function(){
  html2canvas(element, {
    onrendered: function (canvas) {
      $("#previewImage").append(canvas);
      getCanvas = canvas;
    }
  });
});
$("#download").on('click', function () {
  var imgageData = getCanvas.toDataURL("image/png");
  // Now browser starts downloading it instead of just showing it
  var newData = imageData.replace(/^data:image\/png/, "data:application/octet-stream");
  $("#download").attr("download", "image.png").attr("href", newData);
});

The div will be saved as a PNG on clicking the #download

Execute specified function every X seconds

Use System.Windows.Forms.Timer.

private Timer timer1; 
public void InitTimer()
{
    timer1 = new Timer();
    timer1.Tick += new EventHandler(timer1_Tick);
    timer1.Interval = 2000; // in miliseconds
    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    isonline();
}

You can call InitTimer() in Form1_Load().

How can I get new selection in "select" in Angular 2?

Another option is to store the object in value as a string:

<select [ngModel]="selectedDevice | json" (ngModelChange)="onChange($event)">
    <option [value]="i | json" *ngFor="let i of devices">{{i}}</option>
</select>

component:

onChange(val) {
    this.selectedDevice = JSON.parse(val);
}

This was the only way I could get two way binding working to set the select value on page load. This was because my list that populates the select box was not the exact same object as my select was bound to and it needs to be the same object, not just same property values.

How to compare two dates along with time in java

Use compareTo()

Return Values

0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.

Like

if(date1.compareTo(date2)>0) 

Should I use encodeURI or encodeURIComponent for encoding URLs?

xkr.us has a great discussion, with examples. To quote their summary:

The escape() method does not encode the + character which is interpreted as a space on the server side as well as generated by forms with spaces in their fields. Due to this shortcoming and the fact that this function fails to handle non-ASCII characters correctly, you should avoid use of escape() whenever possible. The best alternative is usually encodeURIComponent().

escape() will not encode: @*/+

Use of the encodeURI() method is a bit more specialized than escape() in that it encodes for URIs as opposed to the querystring, which is part of a URL. Use this method when you need to encode a string to be used for any resource that uses URIs and needs certain characters to remain un-encoded. Note that this method does not encode the ' character, as it is a valid character within URIs.

encodeURI() will not encode: ~!@#$&*()=:/,;?+'

Lastly, the encodeURIComponent() method should be used in most cases when encoding a single component of a URI. This method will encode certain chars that would normally be recognized as special chars for URIs so that many components may be included. Note that this method does not encode the ' character, as it is a valid character within URIs.

encodeURIComponent() will not encode: ~!*()'

Can't start Tomcat as Windows Service

On a 64-bit system you have to make sure that both the Tomcat application and the JDK are the same architecture: either both are x86 or x64.

In case you want to change the Tomcat instance to x64 you might have to download the tomcat8.exe or tomcat9.exe and the tcnative-1.dll with the appropriate x64 versions. You can get those at http://svn.apache.org/viewvc/tomcat/.

Alternatively you can point Tomcat to the x86 JDK by changing the Java Virtual Machine path in the Tomcat config.

How to send value attribute from radio button in PHP

Radio buttons have another attribute - checked or unchecked. You need to set which button was selected by the user, so you have to write PHP code inside the HTML with these values - checked or unchecked. Here's one way to do it:

The PHP code:

<?PHP
    $male_status = 'unchecked';
    $female_status = 'unchecked';

    if (isset($_POST['Submit1'])) {
         $selected_radio = $_POST['gender'];

         if ($selected_radio == 'male') {
                $male_status = 'checked';
          }else if ($selected_radio == 'female') {
                $female_status = 'checked';
          }
    }
?>

The HTML FORM code:

<FORM name ="form1" method ="post" action ="radioButton.php">
   <Input type = 'Radio' Name ='gender' value= 'male'
   <?PHP print $male_status; ?>
   >Male
   <Input type = 'Radio' Name ='gender' value= 'female' 
   <?PHP print $female_status; ?>
   >Female
   <P>
   <Input type = "Submit" Name = "Submit1" VALUE = "Select a Radio Button">
</FORM>

Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

This is a fast way to encode the array, the array shape and the array dtype:

def numpy_to_bytes(arr: np.array) -> str:
    arr_dtype = bytearray(str(arr.dtype), 'utf-8')
    arr_shape = bytearray(','.join([str(a) for a in arr.shape]), 'utf-8')
    sep = bytearray('|', 'utf-8')
    arr_bytes = arr.ravel().tobytes()
    to_return = arr_dtype + sep + arr_shape + sep + arr_bytes
    return to_return

def bytes_to_numpy(serialized_arr: str) -> np.array:
    sep = '|'.encode('utf-8')
    i_0 = serialized_arr.find(sep)
    i_1 = serialized_arr.find(sep, i_0 + 1)
    arr_dtype = serialized_arr[:i_0].decode('utf-8')
    arr_shape = tuple([int(a) for a in serialized_arr[i_0 + 1:i_1].decode('utf-8').split(',')])
    arr_str = serialized_arr[i_1 + 1:]
    arr = np.frombuffer(arr_str, dtype = arr_dtype).reshape(arr_shape)
    return arr

To use the functions:

a = np.ones((23, 23), dtype = 'int')
a_b = numpy_to_bytes(a)
a1 = bytes_to_numpy(a_b)
np.array_equal(a, a1) and a.shape == a1.shape and a.dtype == a1.dtype

How do you add a timer to a C# console application

In C# 5.0+ and .NET Framework 4.5+ you can use async/await:

async void RunMethodEvery(Action method, double seconds)
{
    while (true)
    {
        await Task.Delay(TimeSpan.FromSeconds(seconds));
        method();
    }
 }

Trigger css hover with JS

If you bind events to the onmouseover and onmouseout events in Jquery, you can then trigger that effect using mouseenter().

What are you trying to accomplish?

How to get the url parameters using AngularJS

Simple and easist way to get url value

First add # to url (e:g -  test.html#key=value)

url in browser (https://stackover.....king-angularjs-1-5#?brand=stackoverflow)

var url = window.location.href 

(output: url = "https://stackover.....king-angularjs-1-5#?brand=stackoverflow")

url.split('=').pop()
output "stackoverflow"

Install a Python package into a different directory using pip?

Nobody seems to have mentioned the -t option but that the easiest:

pip install -t <direct directory> <package>

Javascript callback when IFRAME is finished loading?

I wanted to hide the waiting spinner div when the i frame content is fully loaded on IE, i tried literally every solution mentioned in Stackoverflow.Com, but with nothing worked as i wanted.

Then i had an idea, that when the i frame content is fully loaded, the $(Window ) load event might be fired. And that exactly what happened. So, i wrote this small script, and worked like magic:

     $(window).load(function () {
     //alert("Done window ready ");
     var lblWait = document.getElementById("lblWait");
     if (lblWait != null ) {
         lblWait.style.visibility = "false";
         document.getElementById("divWait").style.display = "none";
     }
 });

Hope this helps.

compare two list and return not matching items using linq

If u wanna Select items of List from 2nd list:

MainList.Where(p => 2ndlist.Contains(p.columns from MainList )).ToList();

Remove all occurrences of char from string

package com.acn.demo.action;

public class RemoveCharFromString {

    static String input = "";
    public static void main(String[] args) {
        input = "abadbbeb34erterb";
        char token = 'b';
        removeChar(token);
    }

    private static void removeChar(char token) {
        // TODO Auto-generated method stub
        System.out.println(input);
        for (int i=0;i<input.length();i++) {
            if (input.charAt(i) == token) {
            input = input.replace(input.charAt(i), ' ');
                System.out.println("MATCH FOUND");
            }
            input = input.replaceAll(" ", "");
            System.out.println(input);
        }
    }
}

Mysql - How to quit/exit from stored procedure

If you want an "early exit" for a situation in which there was no error, then use the accepted answer posted by @piotrm. Most typically, however, you will be bailing due to an error condition (especially in a SQL procedure).

As of MySQL v5.5 you can throw an exception. Negating exception handlers, etc. that will achieve the same result, but in a cleaner, more precise manner.

Here's how:

DECLARE CUSTOM_EXCEPTION CONDITION FOR SQLSTATE '45000';

IF <Some Error Condition> THEN      
    SIGNAL CUSTOM_EXCEPTION
    SET MESSAGE_TEXT = 'Your Custom Error Message';
END IF;     

Note SQLSTATE '45000' equates to "Unhandled user-defined exception condition". By default, this will produce an error code of 1644 (which has that same meaning). Note that you can throw other condition codes or error codes if you want (plus additional details for exception handling).

For more on this subject, check out:

https://dev.mysql.com/doc/refman/5.5/en/signal.html

How to raise an error within a MySQL function

http://www.databasejournal.com/features/mysql/mysql-error-handling-using-the-signal-and-resignal-statements.html

Addendum

As I'm re-reading this post of mine, I realized I had something additional to add. Prior to MySQL v5.5, there was a way to emulate throwing an exception. It's not the same thing exactly, but this was the analogue: Create an error via calling a procedure which does not exist. Call the procedure by a name which is meaningful in order to get a useful means by which to determine what the problem was. When the error occurs, you'll get to see the line of failure (depending on your execution context).

For example:

CALL AttemptedToInsertSomethingInvalid;

Note that when you create a procedure, there is no validation performed on such things. So while in something like a compiled language, you could never call a function that wasn't there, in a script like this it will simply fail at runtime, which is exactly what is desired in this case!

How to access model hasMany Relation with where condition?

I think this is what you're looking for (Laravel 4, see http://laravel.com/docs/eloquent#querying-relations)

$games = Game::whereHas('video', function($q)
{
    $q->where('available','=', 1);

})->get();

R numbers from 1 to 100

Your mistake is looking for range, which gives you the range of a vector, for example:

range(c(10, -5, 100))

gives

 -5 100

Instead, look at the : operator to give sequences (with a step size of one):

1:100

or you can use the seq function to have a bit more control. For example,

##Step size of 2
seq(1, 100, by=2)

or

##length.out: desired length of the sequence
seq(1, 100, length.out=5)

How to set up ES cluster?

It is usually handled automatically.

If autodiscovery doesn't work. Edit the elastic search config file, by enabling unicast discovery

Node 1:

    cluster.name: mycluster
    node.name: "node1"
    node.master: true
    node.data: true
    discovery.zen.ping.multicast.enabled: false
    discovery.zen.ping.unicast.hosts: ["node1.example.com"]

Node 2:

    cluster.name: mycluster
    node.name: "node2"
    node.master: false
    node.data: true
    discovery.zen.ping.multicast.enabled: false
    discovery.zen.ping.unicast.hosts: ["node1.example.com"]

and so on for node 3,4,5. Make node 1 master, and the rest only as data nodes.

Edit: Please note that by ES rule, if you have N nodes, then by convention, N/2+1 nodes should be masters for fail-over mechanisms They may or may not be data nodes, though.

Also, in case auto-discovery doesn't work, most probable reason is because the network doesn't allow it (and therefore disabled). If too many auto-discovery pings take place across multiple servers, the resources to manage those pings will prevent other services from running correctly.

For ex, think of a 10,000 node cluster and all 10,000 nodes doing the auto-pings.

Show SOME invisible/whitespace characters in Eclipse

Unfortunately, you can only turn on all invisible (whitespace) characters at the same time. I suggest you file an enhancement request but I doubt they will pick it up.

The text component in Eclipse is very complicated as it is and they are not keen on making them even worse.

[UPDATE] This has been fixed in Eclipse 3.7: Go to Window > Preferences > General > Editors > Text Editors

Click on the link "whitespace characters" to fine tune what should be shown.

Kudos go to John Isaacks

How do I install pip on macOS or OS X?

I recommend Anaconda to you. It's the leading open data science platform powered by Python. There are many basic packages installed. Anaconda (conda) comes with its own installation of pip.

How to check if a given directory exists in Ruby

All the other answers are correct, however, you might have problems if you're trying to check directory in a user's home directory. Make sure you expand the relative path before checking:

File.exists? '~/exists'
=> false
File.directory? '~/exists'
=> false
File.exists? File.expand_path('~/exists')
=> true

Omitting one Setter/Getter in Lombok

If you have setter and getter as private it will come up in PMD checks.

Why is my power operator (^) not working?

Instead of using ^, use 'pow' function which is a predefined function which performs the Power operation and it can be used by including math.h header file.

^ This symbol performs BIT-WISE XOR operation in C, C++.

Replace a^i with pow(a,i).

python: get directory two levels up

You can use this as a generic solution:

import os

def getParentDir(path, level=1):
  return os.path.normpath( os.path.join(path, *([".."] * level)) )

jquery: animate scrollLeft

First off I should point out that css animations would probably work best if you are doing this a lot but I ended getting the desired effect by wrapping .scrollLeft inside .animate

$('.swipeRight').click(function()
{

    $('.swipeBox').animate( { scrollLeft: '+=460' }, 1000);
});

$('.swipeLeft').click(function()
{
    $('.swipeBox').animate( { scrollLeft: '-=460' }, 1000);
});

The second parameter is speed, and you can also add a third parameter if you are using smooth scrolling of some sort.

Return multiple values in JavaScript?

Since ES6 you can do this

let newCodes = function() {  
    const dCodes = fg.codecsCodes.rs
    const dCodes2 = fg.codecsCodes2.rs
    return {dCodes, dCodes2}
};

let {dCodes, dCodes2} = newCodes()

Return expression {dCodes, dCodes2} is property value shorthand and is equivalent to this {dCodes: dCodes, dCodes2: dCodes2}.

This assignment on last line is called object destructing assignment. It extracts property value of an object and assigns it to variable of same name. If you'd like to assign return values to variables of different name you could do it like this let {dCodes: x, dCodes2: y} = newCodes()

Concatenate string with field value in MySQL

SELECT ..., CONCAT( 'category_id=', tableOne.category_id) as query2  FROM tableOne 
LEFT JOIN tableTwo
ON tableTwo.query = query2

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();

Bootstrap Responsive Text Size

Simplest way is to use dimensions in % or em. Just change the base font size everything will change.

Less

@media (max-width: @screen-xs) {
    body{font-size: 10px;}
}

@media (max-width: @screen-sm) {
    body{font-size: 14px;}
}


h5{
    font-size: 1.4rem;
}       

Look at all the ways at https://stackoverflow.com/a/21981859/406659

You could use viewport units (vh,vw...) but they dont work on Android < 4.4

Simple GUI Java calculator

assuming that string1 is your whole operation

use mdas

double result;
string recurAndCheck(string operation){
  if(operation.indexOf("/")){
     String leftSide = recurAndCheck(operation.split("/")[0]);
     string rightSide = recurAndCheck(operation.split("/")[1]);
     result = Double.parseDouble(leftSide)/Double.parseDouble(rightSide);

  } else if (..continue w/ *...) {
    //same as above but change / with *
  } else if (..continue w/ -) { 
    //change as above but change with -
  } else if (..continuew with +) {
    //change with add
  } else {
    return;
  }
}

do-while loop in R

Building on the other answers, I wanted to share an example of using the while loop construct to achieve a do-while behaviour. By using a simple boolean variable in the while condition (initialized to TRUE), and then checking our actual condition later in the if statement. One could also use a break keyword instead of the continue <- FALSE inside the if statement (probably more efficient).

  df <- data.frame(X=c(), R=c())  
  x <- x0
  continue <- TRUE

  while(continue)
  {
    xi <- (11 * x) %% 16
    df <- rbind(df, data.frame(X=x, R=xi))
    x <- xi

    if(xi == x0)
    {
      continue <- FALSE
    }
  }