Programs & Examples On #Monad transformers

Monad transformers are an abstraction for combining monads. This allows you to compose different computational effects, building up precisely controlled computational environments.

Convert Month Number to Month Name Function in SQL

SELECT DATENAME(MONTH,dateadd(month, -3,getdate()))

How to add header to a dataset in R?

You can do the following:

Load the data:

test <- read.csv(
          "http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data",
          header=FALSE)

Note that the default value of the header argument for read.csv is TRUE so in order to get all lines you need to set it to FALSE.

Add names to the different columns in the data.frame

names(test) <- c("A","B","C","D","E","F","G","H","I","J","K")

or alternative and faster as I understand (not reloading the entire dataset):

colnames(test) <- c("A","B","C","D","E","F","G","H","I","J","K")

successful/fail message pop up box after submit?

You are echoing outside the body tag of your HTML. Put your echos there, and you should be fine.

Also, remove the onclick="alert()" from your submit. This is the cause for your first undefined message.

<?php
  $posted = false;
  if( $_POST ) {
    $posted = true;

    // Database stuff here...
    // $result = mysql_query( ... )
    $result = $_POST['name'] == "danny"; // Dummy result
  }
?>

<html>
  <head></head>
  <body>

  <?php
    if( $posted ) {
      if( $result ) 
        echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
      else
        echo "<script type='text/javascript'>alert('failed!')</script>";
    }
  ?>
    <form action="" method="post">
      Name:<input type="text" id="name" name="name"/>
      <input type="submit" value="submit" name="submit"/>
    </form>
  </body>
</html>

How to read an external properties file in Maven

Using the suggested Maven properties plugin I was able to read in a buildNumber.properties file that I use to version my builds.

  <build>    
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>properties-maven-plugin</artifactId>
        <version>1.0-alpha-1</version>
        <executions>
          <execution>
            <phase>initialize</phase>
            <goals>
              <goal>read-project-properties</goal>
            </goals>
            <configuration>
              <files>
                <file>${basedir}/../project-parent/buildNumber.properties</file>
              </files>
            </configuration>
          </execution>
        </executions>
      </plugin>
   </plugins>

C# declare empty string array

Your syntax is invalid.

string[] arr = new string[5];

That will create arr, a referenced array of strings, where all elements of this array are null. (Since strings are reference types)

This array contains the elements from arr[0] to arr[4]. The new operator is used to create the array and initialize the array elements to their default values. In this example, all the array elements are initialized to null.

Single-Dimensional Arrays (C# Programming Guide)

Run / Open VSCode from Mac Terminal

open finder and go to applications and make sure that vscode exists there ,then open type in terminal export PATH="/Applications/Visual Studio Code.app/Contents/Resources/app/bin"

Which is fastest? SELECT SQL_CALC_FOUND_ROWS FROM `table`, or SELECT COUNT(*)

There are other options for you to benchmark:

1.) A window function will return the actual size directly (tested in MariaDB):

SELECT 
  `mytable`.*,
  COUNT(*) OVER() AS `total_count`
FROM `mytable`
ORDER BY `mycol`
LIMIT 10, 20

2.) Thinking out of the box, most of the time users don't need to know the EXACT size of the table, an approximate is often good enough.

SELECT `TABLE_ROWS` AS `rows_approx`
FROM `INFORMATION_SCHEMA`.`TABLES`
WHERE `TABLE_SCHEMA` = DATABASE()
  AND `TABLE_TYPE` = "BASE TABLE"
  AND `TABLE_NAME` = ?

Java default constructor

When we do not explicitly define a constructor for a class, then java creates a default constructor for the class. It is essentially a non-parameterized constructor, i.e. it doesn't accept any arguments.

The default constructor's job is to call the super class constructor and initialize all instance variables. If the super class constructor is not present then it automatically initializes the instance variables to zero. So, that serves the purpose of using constructor, which is to initialize the internal state of an object so that the code creating an instance will have a fully initialized, usable object.

Once we define our own constructor for the class, the default constructor is no longer used. So, neither of them is actually a default constructor.

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

For anyone looking at this and had no result with adding the Access-Control-Allow-Origin try also adding the Access-Control-Allow-Headers. May safe somebody from a headache.

Twitter bootstrap modal-backdrop doesn't disappear

FYI in case someone runs into this still... I've spent about 3 hours to discover that the best way to do it is as follows:

$("#my-modal").modal("hide");
$("#my-modal").hide();
$('.modal-backdrop').hide();
$("body").removeClass("modal-open");

That function to close the modal is very unintuitive.

Adding value to input field with jQuery

$.each(obj, function(index, value) {
    $('#looking_for_job_titles').tagsinput('add', value);
    console.log(value);
});

HTML5 Canvas Rotate Image

Here is Something I did

var ImgRotator = {
    angle:parseInt(45),
    image:{},
    src:"",
    canvasID:"",
    intervalMS:parseInt(500),
    jump:parseInt(5),
    start_action:function(canvasID, imgSrc, interval, jumgAngle){
        ImgRotator.jump = jumgAngle;
        ImgRotator.intervalMS = interval;
        ImgRotator.canvasID = canvasID;
        ImgRotator.src = imgSrc ;
        var image = new Image();
        var canvas = document.getElementById(ImgRotator.canvasID);
        image.onload = function() {
            ImgRotator.image = image;
            canvas.height = canvas.width = Math.sqrt( image.width* image.width+image.height*image.height);
            window.setInterval(ImgRotator.keepRotating,ImgRotator.intervalMS);
            //theApp.keepRotating();
        };
        image.src = ImgRotator.src;   
    },
    keepRotating:function(){
        ImgRotator.angle+=ImgRotator.jump;
        var canvas = document.getElementById(ImgRotator.canvasID);
        var ctx = canvas.getContext("2d");
        ctx.save();
        ctx.clearRect(0,0,canvas.width,canvas.height);
        ctx.translate(canvas.width/2,canvas.height/2);
        ctx.rotate(ImgRotator.angle*Math.PI/180); 
        ctx.drawImage(ImgRotator.image, -ImgRotator.image.width/2,-ImgRotator.image.height/2);
        ctx.restore();
    }
}

usage

ImgRotator.start_action("canva",
            "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxIQEhUSEhMVFhUVFRUVFRUVFRcVFRUQFRUWFhUVFRUYHSggGBolGxUVITEhJSkrLi4uFx8zODMsNygtLisBCgoKDg0OFhAQFy0lIB8rLS4tLS0rLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tKy0tKy0tLS0tLS0rLS0tLS0rLf/AABEIAL0BCgMBIgACEQEDEQH/xAAcAAACAgMBAQAAAAAAAAAAAAABAgADBAYHBQj/xAA9EAACAQIDBgMGAwYGAwEAAAABAgADEQQSIQUTMUFRYQYicQcygZGh8BRCsSNSwdHh8RUzYnKCkmOywkP/xAAZAQEBAQEBAQAAAAAAAAAAAAAAAQMCBAX/xAAkEQEAAwACAwACAQUAAAAAAAAAAQIRAyESMUETIlEEFDJhgf/aAAwDAQACEQMR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5TvGLrMcEtW5zMVzE6k2JXUi3S88948Z6bUnfbnGLp19m4tMSigHDFi6gkGth2I3lMDXyhCzqToFZea2nccLiFqotRGDI6q6MOBRgCp+RE0jxfhRUoYZzoXLUmtzptSckHqLZx/zvxAnr+zlj/h9JSb7tq9Jb8clKvUppf8A4qB8Jtxz8Y8sfWzARTGimasEkhEkigIZLwwFtAYwMhlRWYYxWS0ikMEa0lpR/9k=",
            500,15
            );

HTML

<canvas id="canva" width="350" height="350" style="border:solid thin black;"></canvas>

What does LPCWSTR stand for and how should it be handled with?

LPCWSTR stands for "Long Pointer to Constant Wide String". The W stands for Wide and means that the string is stored in a 2 byte character vs. the normal char. Common for any C/C++ code that has to deal with non-ASCII only strings.=

To get a normal C literal string to assign to a LPCWSTR, you need to prefix it with L

LPCWSTR a = L"TestWindow";

Using comma as list separator with AngularJS

I like simbu's approach, but I ain't comfortable to use first-child or last-child. Instead I only modify the content of a repeating list-comma class.

.list-comma + .list-comma::before {
    content: ', ';
}
<span class="list-comma" ng-repeat="destination in destinations">
    {{destination.name}}
</span>

Change some value inside the List<T>

I'd probably go with this (I know its not pure linq), keep a reference to the original list if you want to retain all items, and you should find the updated values are in there:

 foreach (var mc in list.Where(x => x.Name == "height"))  
     mc.Value = 30;

Oracle insert if not exists statement

MERGE INTO OPT
USING
    (SELECT 1 "one" FROM dual) 
ON
    (OPT.email= '[email protected]' and OPT.campaign_id= 100) 
WHEN NOT matched THEN
INSERT (email, campaign_id)
VALUES ('[email protected]',100) 
;

How do I replace NA values with zeros in an R dataframe?

I know the question is already answered, but doing it this way might be more useful to some:

Define this function:

na.zero <- function (x) {
    x[is.na(x)] <- 0
    return(x)
}

Now whenever you need to convert NA's in a vector to zero's you can do:

na.zero(some.vector)

Print all day-dates between two dates

Essentially the same as Gringo Suave's answer, but with a generator:

from datetime import datetime, timedelta


def datetime_range(start=None, end=None):
    span = end - start
    for i in xrange(span.days + 1):
        yield start + timedelta(days=i)

Then you can use it as follows:

In: list(datetime_range(start=datetime(2014, 1, 1), end=datetime(2014, 1, 5)))
Out: 
[datetime.datetime(2014, 1, 1, 0, 0),
 datetime.datetime(2014, 1, 2, 0, 0),
 datetime.datetime(2014, 1, 3, 0, 0),
 datetime.datetime(2014, 1, 4, 0, 0),
 datetime.datetime(2014, 1, 5, 0, 0)]

Or like this:

In []: for date in datetime_range(start=datetime(2014, 1, 1), end=datetime(2014, 1, 5)):
   ...:     print date
   ...:     
2014-01-01 00:00:00
2014-01-02 00:00:00
2014-01-03 00:00:00
2014-01-04 00:00:00
2014-01-05 00:00:00

What does the red exclamation point icon in Eclipse mean?

The solution that worked for me is the following one given..

I selected the particular project> right click >Build path>configure Build path> Libraries> I noticed that JRE system Library was showing(Unbound) hence..

selected that Library>click on Remove>click on Apply>click on add Library>JRE system Library>next>workspace default JRE>click on Finish>Apply>ok.

now you will not see these exclamation icon in your project.

MacOSX homebrew mysql root password

So, in case someone has the same situation and configuration as I had and is also about to go mad - this worked for me.

After a long story I had a brew-installed MariaDB which kept automatically restarting when I killed its process (this was brew's doing), which had a root password, which I did not know.

$ brew services list

This shows something like:

mariadb started jdoe /path/to/homebrew.mxcl.mariadb.plist

Stop the MySQL server with:

$ brew services stop mariadb

Then start it again without the root user (and not using brew):

$ mariadbd --skip-grant-tables &

Here, mysql_secure_installation did not work for me because of the --skip-grant-tables, and it would not work without the --skip-grant-tables because it needed the password (which I did not have).
Trying $(brew --prefix mysql)/bin/mysqladmin -u root password hunter2 only returned strange errors and did nothing; $(brew --prefix mariadb)/bin/mysqladmin -u root password hunter2 also didn't work, gave different errors, and suggestions that did not work for me.

But you can log into mysql now without credentials: $ mysql

Here, the old method of updating the user table for root doesn't work because "Column 'Password' is not updatable".
The new method uses alter user BUT only works after you have done flush privileges; so do that first.
Then:
MariaDB [(none)]> alter user 'root'@'localhost' identified by 'hunter2';
(MariaDB [(none)]> is the MySQL prompt here)
Then do flush privileges; again.
Exit the MySQL client.

Now as far as brew is concerned, MariaDB is still not running, and so use $ ps aux | grep -i mariadb to find the pid and $ kill -9 <pid> it.
Then use $ brew services start mariadb to start it again.

Format date and Subtract days using Moment.js

You have multiple oddities happening. The first has been edited in your post, but it had to do with the order that the methods were being called.

.format returns a string. String does not have a subtract method.

The second issue is that you are subtracting the day, but not actually saving that as a variable.

Your code, then, should look like:

var startdate = moment();
startdate = startdate.subtract(1, "days");
startdate = startdate.format("DD-MM-YYYY");

However, you can chain this together; this would look like:

var startdate = moment().subtract(1, "days").format("DD-MM-YYYY");

The difference is that we're setting startdate to the changes that you're doing on startdate, because moment is destructive.

How to uncheck a checkbox in pure JavaScript?

You will need to assign an ID to the checkbox:

<input id="checkboxId" type="checkbox" checked="" name="copyNewAddrToBilling">

and then in JavaScript:

document.getElementById("checkboxId").checked = false;

How do I reference the input of an HTML <textarea> control in codebehind?

You are not using a .NET control for your text area. Either add runat="server" to the HTML TextArea control or use a .NET control:

Try this:

<asp:TextBox id="TextArea1" TextMode="multiline" Columns="50" Rows="5" runat="server" />

Then reference it in your codebehind:

message.Body = TextArea1.Text;

Controlling a USB power supply (on/off) with Linux

According to the docs, there were several changes to the USB power management from kernels 2.6.32, which seem to settle in 2.6.38. Now you'll need to wait for the device to become idle, which is governed by the particular device driver. The driver needs to support it, otherwise the device will never reach this state. Unluckily, now the user has no chance to force this. However, if you're lucky and your device can become idle, then to turn this off you need to:

echo "0" > "/sys/bus/usb/devices/usbX/power/autosuspend"
echo "auto" > "/sys/bus/usb/devices/usbX/power/level"

or, for kernels around 2.6.38 and above:

echo "0" > "/sys/bus/usb/devices/usbX/power/autosuspend_delay_ms"
echo "auto" > "/sys/bus/usb/devices/usbX/power/control"

This literally means, go suspend at the moment the device becomes idle.

So unless your fan is something "intelligent" that can be seen as a device and controlled by a driver, you probably won't have much luck on current kernels.

CSS /JS to prevent dragging of ghost image?

Place the image as a background of an empty div, or under a transparent element. When the user clicks on the image to drag, they are clicking on a div.

See http://www.flickr.com/photos/thefella/5878724253/?f=hp

<div id="photo-drag-proxy"></div>

java.lang.OutOfMemoryError: Java heap space

To avoid that exception, if you are using JUnit and Spring try adding this in every test class:

@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)

How to send a header using a HTTP request through a curl call?

You can also send multiple headers, data (JSON for example), and specify Call method (POST,GET) into a single CUrl call like this:

curl -X POST(Get or whatever) \
  http://your_url.com/api/endpoint \
  -H 'Content-Type: application/json' \
  -H 'header-element1: header-data1' \
  -H 'header-element2: header-data2' \

......more headers................

  -d '{
  "JsonExArray": [
    {
      "json_prop": "1",
    },
    {
      "json_prop": "2",
    }
  ]
}'

Javascript reduce() on Object

Try out this one liner arrow function

Object.values(o).map(a => a.value, o).reduce((ac, key, index, arr) => ac+=key)

How to iterate object keys using *ngFor

Angular now has a type of iterate Object for exactly this scenario, called a Set. It fit my needs when I found this question searching. You create the set, "add" to it like you'd "push" to an array, and drop it in an ngFor just like an array. No pipes or anything.

this.myObjList = new Set();

...

this.myObjList.add(obj);

...

<ul>
   <li *ngFor="let object of myObjList">
     {{object}}
   </li>
</ul>

SQL split values to multiple rows

The original question was for MySQL and SQL in general. The example below is for the new versions of MySQL. Unfortunately, a generic query that would work on any SQL server is not possible. Some servers do no support CTE, others do not have substring_index, yet others have built-in functions for splitting a string into multiple rows.

--- the answer follows ---

Recursive queries are convenient when the server does not provide built-in functionality. They can also be the bottleneck.

The following query was written and tested on MySQL version 8.0.16. It will not work on version 5.7-. The old versions do not support Common Table Expression (CTE) and thus recursive queries.

with recursive
  input as (
        select 1 as id, 'a,b,c' as names
      union
        select 2, 'b'
    ),
  recurs as (
        select id, 1 as pos, names as remain, substring_index( names, ',', 1 ) as name
          from input
      union all
        select id, pos + 1, substring( remain, char_length( name ) + 2 ),
            substring_index( substring( remain, char_length( name ) + 2 ), ',', 1 )
          from recurs
          where char_length( remain ) > char_length( name )
    )
select id, name
  from recurs
  order by id, pos;

How do I retrieve an HTML element's actual width and height?

If offsetWidth returns 0, you can get element's style width property and search it for a number. "100px" -> 100

/\d*/.exec(MyElement.style.width)

How to use custom font in a project written in Android Studio

1st add font.ttf file on font Folder. Then Add this line in onCreate method

    Typeface typeface = ResourcesCompat.getFont(getApplicationContext(), R.font.myfont);
    mytextView.setTypeface(typeface);

And here is my xml

            <TextView
            android:id="@+id/idtext1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="7dp"
            android:gravity="center"
            android:text="My Text"
            android:textColor="#000"
            android:textSize="10sp"
        />

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

since npm 5.2.0, there's a new command "npx" included with npm that makes this much simpler, if you run:

npx mocha <args>

Note: the optional args are forwarded to the command being executed (mocha in this case)

this will automatically pick the executable "mocha" command from your locally installed mocha (always add it as a dev dependency to ensure the correct one is always used by you and everyone else).

Be careful though that if you didn't install mocha, this command will automatically fetch and use latest version, which is great for some tools (like scaffolders for example), but might not be the most recommendable for certain dependencies where you might want to pin to a specific version.

You can read more on npx here


Now, if instead of invoking mocha directly, you want to define a custom npm script, an alias that might invoke other npm binaries...

you don't want your library tests to fail depending on the machine setup (mocha as global, global mocha version, etc), the way to use the local mocha that works cross-platform is:

node node_modules/.bin/mocha

npm puts aliases to all the binaries in your dependencies on that special folder. Finally, npm will add node_modules/.bin to the PATH automatically when running an npm script, so in your package.json you can do just:

"scripts": {
  "test": "mocha"
}

and invoke it with

npm test

how to find my angular version in my project?

ng --version command will show only the installed angular version in your computer instead of the actual project version.

if you really want to know the project version, Go to your project, use the below command

npm list -local

enter image description here

How to receive serial data using android bluetooth

The issue with the null connection is related to the findBT() function. you must change the device name from "MattsBlueTooth" to your device name as well as confirm the UUID for your service/device. Use something like BLEScanner app to confrim both on Android.

Return outside function error in Python

You are not writing your code inside any function, you can return from functions only. Remove return statement and just print the value you want.

How to automatically crop and center an image

Example with img tag but without background-image

This solution retains the img tag so that we do not lose the ability to drag or right-click to save the image but without background-image just center and crop with css.

Maintain the aspect ratio fine except in very hight images. (check the link)

(view in action)

Markup

<div class="center-cropped">
    <img src="http://placehold.it/200x150" alt="" />
</div>

? CSS

div.center-cropped {
  width: 100px;
  height: 100px;
  overflow:hidden;
}
div.center-cropped img {
  height: 100%;
  min-width: 100%;
  left: 50%;
  position: relative;
  transform: translateX(-50%);
}

Convert Mongoose docs to json

It worked for me:

Products.find({}).then(a => console.log(a.map(p => p.toJSON())))


also if you want use getters, you should add its option also (on defining schema):

new mongoose.Schema({...}, {toJSON: {getters: true}})

Save and retrieve image (binary) from SQL Server using Entity Framework 6

Convert the image to a byte[] and store that in the database.


Add this column to your model:

public byte[] Content { get; set; }

Then convert your image to a byte array and store that like you would any other data:

public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
    using(var ms = new MemoryStream())
    {
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);

        return ms.ToArray();
    }
}

public Image ByteArrayToImage(byte[] byteArrayIn)
{
     using(var ms = new MemoryStream(byteArrayIn))
     {
         var returnImage = Image.FromStream(ms);

         return returnImage;
     }
}

Source: Fastest way to convert Image to Byte array

var image = new ImageEntity()
{
   Content = ImageToByteArray(image)
};

_context.Images.Add(image);
_context.SaveChanges();

When you want to get the image back, get the byte array from the database and use the ByteArrayToImage and do what you wish with the Image

This stops working when the byte[] gets to big. It will work for files under 100Mb

casting int to char using C++ style casting

Using static cast would probably result in something like this:

// This does not prevent a possible type overflow
const char char_max = -1;

int i = 48;
char c = (i & char_max);

To prevent possible type overflow you could do this:

const char char_max = (char)(((unsigned char) char(-1)) / 2);

int i = 128;
char c = (i & char_max); // Would always result in positive signed values.

Where reinterpret_cast would probably just directly convert to char, without any cast safety. -> Never use reinterpret_cast if you can also use static_cast. If you're casting between classes, static_cast will also ensure, that the two types are matching (the object is a derivate of the cast type).

If your object a polymorphic type and you don't know which one it is, you should use dynamic_cast which will perform a type check at runtime and return nullptr if the types do not match.

IF you need const_cast you most likely did something wrong and should think about possible alternatives to fix const correctness in your code.

Eliminate extra separators below UITableView

I just add this line at the ViewDidLoad function and problem fixed.

tableView.tableFooterView = [[UIView alloc] init]; 

Erasing elements from a vector

Depending on why you are doing this, using a std::set might be a better idea than std::vector.

It allows each element to occur only once. If you add it multiple times, there will only be one instance to erase anyway. This will make the erase operation trivial. The erase operation will also have lower time complexity than on the vector, however, adding elements is slower on the set so it might not be much of an advantage.

This of course won't work if you are interested in how many times an element has been added to your vector or the order the elements were added.

How do you perform address validation?

You can try Pitney Bowes “IdentifyAddress” Api available at - https://identify.pitneybowes.com/

The service analyses and compares the input addresses against the known address databases around the world to output a standardized detail. It corrects addresses, adds missing postal information and formats it using the format preferred by the applicable postal authority. I also uses additional address databases so it can provide enhanced detail, including address quality, type of address, transliteration (such as from Chinese Kanji to Latin characters) and whether an address is validated to the premise/house number, street, or city level of reference information.

You will find a lot of samples and sdk available on the site and i found it extremely easy to integrate.

Where can I find the Java SDK in Linux after installing it?

This question still seems relevant, and the answer seems to be a moving target.

On my debian system (buster):

> update-java-alternatives -l
java-1.11.0-openjdk-amd64      1111       /usr/lib/jvm/java-1.11.0-openjdk-amd64

However, if you actually go look there, you'll see there are multiple directories and symbolic links placed there by the package system to simplify future maintenance.

The actual directory is java-11-openjdk-amd64, with another symlink of default-java. There is also an openjdk-11 directory, but it appears to only contain a source.zip file.

Given this, for Debian ONLY, I would guess the best value to use is /usr/lib/jvm/default-java, as this should always be valid, even if you decide to install a totally different version of java, or even switch vendors.

The normal reason to want to know the path is because some application wants it, and you probably don't want that app to break because you did an upgrade that changed version numbers.

Fastest way to compute entropy in Python

Uniformly distributed data (high entropy):

s=range(0,256)

Shannon entropy calculation step by step:

import collections
import math

# calculate probability for each byte as number of occurrences / array length
probabilities = [n_x/len(s) for x,n_x in collections.Counter(s).items()]
# [0.00390625, 0.00390625, 0.00390625, ...]

# calculate per-character entropy fractions
e_x = [-p_x*math.log(p_x,2) for p_x in probabilities]
# [0.03125, 0.03125, 0.03125, ...]

# sum fractions to obtain Shannon entropy
entropy = sum(e_x)
>>> entropy 
8.0

One-liner (assuming import collections):

def H(s): return sum([-p_x*math.log(p_x,2) for p_x in [n_x/len(s) for x,n_x in collections.Counter(s).items()]])

A proper function:

import collections
import math

def H(s):
    probabilities = [n_x/len(s) for x,n_x in collections.Counter(s).items()]
    e_x = [-p_x*math.log(p_x,2) for p_x in probabilities]    
    return sum(e_x)

Test cases - English text taken from CyberChef entropy estimator:

>>> H(range(0,256))
8.0
>>> H(range(0,64))
6.0
>>> H(range(0,128))
7.0
>>> H([0,1])
1.0
>>> H('Standard English text usually falls somewhere between 3.5 and 5')
4.228788210509104

How can I compile a Java program in Eclipse without running it?

Right click on Yourproject(in project Explorer)-->Build Project

It will compile all files in your project and updates your build folder, all without running.

Sass Nesting for :hover does not work

For concatenating selectors together when nesting, you need to use the parent selector (&):

.class {
    margin:20px;
    &:hover {
        color:yellow;
    }
}

How can I revert multiple Git commits (already pushed) to a published repository?

If you've already pushed things to a remote server (and you have other developers working off the same remote branch) the important thing to bear in mind is that you don't want to rewrite history

Don't use git reset --hard

You need to revert changes, otherwise any checkout that has the removed commits in its history will add them back to the remote repository the next time they push; and any other checkout will pull them in on the next pull thereafter.

If you have not pushed changes to a remote, you can use

git reset --hard <hash>

If you have pushed changes, but are sure nobody has pulled them you can use

git reset --hard
git push -f

If you have pushed changes, and someone has pulled them into their checkout you can still do it but the other team-member/checkout would need to collaborate:

(you) git reset --hard <hash>
(you) git push -f

(them) git fetch
(them) git reset --hard origin/branch

But generally speaking that's turning into a mess. So, reverting:

The commits to remove are the lastest

This is possibly the most common case, you've done something - you've pushed them out and then realized they shouldn't exist.

First you need to identify the commit to which you want to go back to, you can do that with:

git log

just look for the commit before your changes, and note the commit hash. you can limit the log to the most resent commits using the -n flag: git log -n 5

Then reset your branch to the state you want your other developers to see:

git revert  <hash of first borked commit>..HEAD

The final step is to create your own local branch reapplying your reverted changes:

git branch my-new-branch
git checkout my-new-branch
git revert <hash of each revert commit> .

Continue working in my-new-branch until you're done, then merge it in to your main development branch.

The commits to remove are intermingled with other commits

If the commits you want to revert are not all together, it's probably easiest to revert them individually. Again using git log find the commits you want to remove and then:

git revert <hash>
git revert <another hash>
..

Then, again, create your branch for continuing your work:

git branch my-new-branch
git checkout my-new-branch
git revert <hash of each revert commit> .

Then again, hack away and merge in when you're done.

You should end up with a commit history which looks like this on my-new-branch

2012-05-28 10:11 AD7six             o [my-new-branch] Revert "Revert "another mistake""
2012-05-28 10:11 AD7six             o Revert "Revert "committing a mistake""
2012-05-28 10:09 AD7six             o [master] Revert "committing a mistake"
2012-05-28 10:09 AD7six             o Revert "another mistake"
2012-05-28 10:08 AD7six             o another mistake
2012-05-28 10:08 AD7six             o committing a mistake
2012-05-28 10:05 Bob                I XYZ nearly works

Better way®

Especially that now that you're aware of the dangers of several developers working in the same branch, consider using feature branches always for your work. All that means is working in a branch until something is finished, and only then merge it to your main branch. Also consider using tools such as git-flow to automate branch creation in a consistent way.

Help with packages in java - import does not work

The standard Java classloader is a stickler for directory structure. Each entry in the classpath is a directory or jar file (or zip file, really), which it then searches for the given class file. For example, if your classpath is ".;my.jar", it will search for com.example.Foo in the following locations:

./com/example/
my.jar:/com/example/

That is, it will look in the subdirectory that has the 'modified name' of the package, where '.' is replaced with the file separator.

Also, it is noteworthy that you cannot nest .jar files.

Java JTable setting Column Width

Use this code. It worked for me. I considered for 3 columns. Change the loop value for your code.

TableColumn column = null;
for (int i = 0; i < 3; i++) {
    column = table.getColumnModel().getColumn(i);
    if (i == 0) 
        column.setMaxWidth(10);
    if (i == 2)
        column.setMaxWidth(50);
}

How to access share folder in virtualbox. Host Win7, Guest Fedora 16?

You probably need to change your mount command from:

[root@localhost Desktop]# sudo mount -t vboxsf D:\share_folder_vm \share_folder

to:

[root@localhost Desktop]# sudo mount -t vboxsf share_name \share_folder

where share_name is the "Name" of the share in the VirtualBox -> Shared Folders -> Folder List list box. The argument you have ("D:\share_folder_vm") is the "Path" of the share on the host, not the "Name".

URL encoding in Android

try {
                    query = URLEncoder.encode(query, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

UIDevice uniqueIdentifier deprecated - What to do now?

It looks like for iOS 6, Apple is recommending you use the NSUUID class.

From the message now in the UIDevice docs for uniqueIdentifier property:

Deprecated in iOS 5.0. Use the identifierForVendor property of this class or the advertisingIdentifier property of the ASIdentifierManager class instead, as appropriate, or use the UUID method of the NSUUID class to create a UUID and write it to the user defaults database.

How to check if image exists with given url?

$.ajax({
    url:'http://www.example.com/somefile.ext',
    type:'HEAD',
    error: function(){
            //do something depressing
    },
    success: function(){
            //do something cheerful :)
    }
});

from: http://www.ambitionlab.com/how-to-check-if-a-file-exists-using-jquery-2010-01-06

fs.writeFile in a promise, asynchronous-synchronous stuff

const util = require('util')
const fs = require('fs');

const fs_writeFile = util.promisify(fs.writeFile)

fs_writeFile('message.txt', 'Hello Node.js')
    .catch((error) => {
        console.log(error)
    });

How to return a value from __init__ in Python?

Well, if you don't care about the object instance anymore ... you can just replace it!

class MuaHaHa():
def __init__(self, ret):
    self=ret

print MuaHaHa('foo')=='foo'

Ignore self-signed ssl cert using Jersey Client

For Jersey 2.*:

Client client = ClientBuilder.newBuilder()
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                }).build();

-> https://jersey.java.net/documentation/latest/migration.html

Remove json element

  1. Fix the errors in the JSON: http://jsonlint.com/
  2. Parse the JSON (since you have tagged the question with JavaScript, use json2.js)
  3. Delete the property from the object you created
  4. Stringify the object back to JSON.

How to get file name from file path in android

Other Way is:

String[] parts = selectedFilePath.split("/");
    final String fileName = parts[parts.length-1];

How to analyze a JMeter summary report?

A Jmeter Test Plan must have listener to showcase the result of performance test execution.

  • Listeners capture the response coming back from Server while Jmeter runs and showcase in the form of – tree, tables, graphs and log files.

  • It also allows you to save the result in a file for future reference. There are many types of listeners Jmeter provides. Some of them are: Summary Report, Aggregate Report, Aggregate Graph, View Results Tree, View Results in Table etc.

Here is the detailed understanding of each parameter in Summary report.

By referring to the figure:

image

Label: It is the name/URL for the specific HTTP(s) Request. If you have selected “Include group name in label?” option then the name of the Thread Group is applied as the prefix to each label.

Samples: This indicates the number of virtual users per request.

Average: It is the average time taken by all the samples to execute specific label. In our case, the average time for Label 1 is 942 milliseconds & total average time is 584 milliseconds.

Min: The shortest time taken by a sample for specific label. If we look at Min value for Label 1 then, out of 20 samples shortest response time one of the sample had was 584 milliseconds.

Max: The longest time taken by a sample for specific label. If we look at Max value for Label 1 then, out of 20 samples longest response time one of the sample had was 2867 milliseconds.

Std. Dev.: This shows the set of exceptional cases which were deviating from the average value of sample response time. The lesser this value more consistent the data. Standard deviation should be less than or equal to half of the average time for a label.

Error%: Percentage of Failed requests per Label.

Throughput: Throughput is the number of request that are processed per time unit(seconds, minutes, hours) by the server. This time is calculated from the start of first sample to the end of the last sample. Larger throughput is better.

KB/Sec: This indicates the amount of data downloaded from server during the performance test execution. In short, it is the Throughput measured in Kilobytes per second.

For more information: http://www.testingjournals.com/understand-summary-report-jmeter/

Can table columns with a Foreign Key be NULL?

Yes, you can enforce the constraint only when the value is not NULL. This can be easily tested with the following example:

CREATE DATABASE t;
USE t;

CREATE TABLE parent (id INT NOT NULL,
                     PRIMARY KEY (id)
) ENGINE=INNODB;

CREATE TABLE child (id INT NULL, 
                    parent_id INT NULL,
                    FOREIGN KEY (parent_id) REFERENCES parent(id)
) ENGINE=INNODB;


INSERT INTO child (id, parent_id) VALUES (1, NULL);
-- Query OK, 1 row affected (0.01 sec)


INSERT INTO child (id, parent_id) VALUES (2, 1);

-- ERROR 1452 (23000): Cannot add or update a child row: a foreign key 
-- constraint fails (`t/child`, CONSTRAINT `child_ibfk_1` FOREIGN KEY
-- (`parent_id`) REFERENCES `parent` (`id`))

The first insert will pass because we insert a NULL in the parent_id. The second insert fails because of the foreign key constraint, since we tried to insert a value that does not exist in the parent table.

Tomcat 7.0.43 "INFO: Error parsing HTTP request header"

For me, the problem was passing in a larger than normally expected HTTP header. I resolved it by setting maxHttpHeaderSize="1048576" attribute on the Connector node in server.xml.

How do I check/uncheck all checkboxes with a button using jQuery?

Check All with uncheck/check controller if all items is/isnt checked

JS:

e = checkbox id t= checkbox (item) class n= checkbox check all class

function checkAll(e,t,n){jQuery("#"+e).click(function(e){if(this.checked){jQuery("."+t).each(function(){this.checked=true;jQuery("."+n).each(function(){this.checked=true})})}else{jQuery("."+t).each(function(){this.checked=false;jQuery("."+n).each(function(){this.checked=false})})}});jQuery("."+t).click(function(e){var r=jQuery("."+t).length;var i=0;var s=0;jQuery("."+t).each(function(){if(this.checked==true){i++}if(this.checked==false){s++}});if(r==i){jQuery("."+n).each(function(){this.checked=true})}if(i<r){jQuery("."+n).each(function(){this.checked=false})}})}

HTML:

Check ALL controle class : chkall_ctrl

<input type="checkbox"name="chkall" id="chkall_up" class="chkall_ctrl"/>
<br/>
1.<input type="checkbox" value="1" class="chkall" name="chk[]" id="chk1"/><br/>
2.<input type="checkbox" value="2" class="chkall" name="chk[]" id="chk2"/><br/>
3.<input type="checkbox" value="3" class="chkall" name="chk[]" id="chk3"/><br/>
<br/>
<input type="checkbox"name="chkall" id="chkall_down" class="chkall_ctrl"/>

<script>
jQuery(document).ready(function($)
{
  checkAll('chkall_up','chkall','chkall_ctrl');
  checkAll('chkall_down','chkall','chkall_ctrl');
});
 </script>

LIKE operator in LINQ

Ideally you should use StartWith or EndWith.

Here is an example:

DataContext  dc = new DCGeneral();
List<Person> lstPerson= dc.GetTable<Person>().StartWith(c=> c.strNombre).ToList();

return lstPerson;

Add days to JavaScript Date

Just spent ages trying to work out what the deal was with the year not adding when following the lead examples below.

If you want to just simply add n days to the date you have you are best to just go:

myDate.setDate(myDate.getDate() + n);

or the longwinded version

var theDate = new Date(2013, 11, 15);
var myNewDate = new Date(theDate);
myNewDate.setDate(myNewDate.getDate() + 30);
console.log(myNewDate);

This today/tomorrow stuff is confusing. By setting the current date into your new date variable you will mess up the year value. if you work from the original date you won't.

Preventing scroll bars from being hidden for MacOS trackpad users in WebKit/Blink

For a one-page web application where I add scrollable sections dynamically, I trigger OSX's scrollbars by programmatically scrolling one pixel down and back up:

// Plain JS:
var el = document.getElementById('scrollable-section');
el.scrollTop = 1;
el.scrollTop = 0;

// jQuery:
$('#scrollable-section').scrollTop(1).scrollTop(0);

This triggers the visual cue fading in and out.

Convert base64 png data to javascript file objects

You can create a Blob from your base64 data, and then read it asDataURL:

var img_b64 = canvas.toDataURL('image/png');
var png = img_b64.split(',')[1];

var the_file = new Blob([window.atob(png)],  {type: 'image/png', encoding: 'utf-8'});

var fr = new FileReader();
fr.onload = function ( oFREvent ) {
    var v = oFREvent.target.result.split(',')[1]; // encoding is messed up here, so we fix it
    v = atob(v);
    var good_b64 = btoa(decodeURIComponent(escape(v)));
    document.getElementById("uploadPreview").src = "data:image/png;base64," + good_b64;
};
fr.readAsDataURL(the_file);

Full example (includes junk code and console log): http://jsfiddle.net/tTYb8/


Alternatively, you can use .readAsText, it works fine, and its more elegant.. but for some reason text does not sound right ;)

fr.onload = function ( oFREvent ) {
    document.getElementById("uploadPreview").src = "data:image/png;base64,"
    + btoa(oFREvent.target.result);
};
fr.readAsText(the_file, "utf-8"); // its important to specify encoding here

Full example: http://jsfiddle.net/tTYb8/3/

Loop through files in a folder using VBA?

Dir takes wild cards so you could make a big difference adding the filter for test up front and avoiding testing each file

Sub LoopThroughFiles()
    Dim StrFile As String
    StrFile = Dir("c:\testfolder\*test*")
    Do While Len(StrFile) > 0
        Debug.Print StrFile
        StrFile = Dir
    Loop
End Sub

Editing the date formatting of x-axis tick labels in matplotlib

While the answer given by Paul H shows the essential part, it is not a complete example. On the other hand the matplotlib example seems rather complicated and does not show how to use days.

So for everyone in need here is a full working example:

from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

myDates = [datetime(2012,1,i+3) for i in range(10)]
myValues = [5,6,4,3,7,8,1,2,5,4]
fig, ax = plt.subplots()
ax.plot(myDates,myValues)

myFmt = DateFormatter("%d")
ax.xaxis.set_major_formatter(myFmt)

## Rotate date labels automatically
fig.autofmt_xdate()
plt.show()

Replacing Numpy elements if condition is met

The quickest (and most flexible) way is to use np.where, which chooses between two arrays according to a mask(array of true and false values):

import numpy as np
a = np.random.randint(0, 5, size=(5, 4))
b = np.where(a<3,0,1)
print('a:',a)
print()
print('b:',b)

which will produce:

a: [[1 4 0 1]
 [1 3 2 4]
 [1 0 2 1]
 [3 1 0 0]
 [1 4 0 1]]

b: [[0 1 0 0]
 [0 1 0 1]
 [0 0 0 0]
 [1 0 0 0]
 [0 1 0 0]]

git push rejected

First use

git pull https://github.com/username/repository master

and then try

git push -u origin master

How to create an XML document using XmlDocument?

Working with a dictionary ->level2 above comes from a dictionary in my case (just in case anybody will find it useful) Trying the first example I stumbled over this error: "This document already has a 'DocumentElement' node." I was inspired by the answer here

and edited my code: (xmlDoc.DocumentElement.AppendChild(body))

//a dictionary:
Dictionary<string, string> Level2Data 
{
    {"level2", "text"},
    {"level2", "other text"},
    {"same_level2", "more text"}
}
//xml Decalration:
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = xmlDoc.DocumentElement;
xmlDoc.InsertBefore(xmlDeclaration, root);
// add body
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.AppendChild(body);
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.DocumentElement.AppendChild(body); //without DocumentElement ->ERR



foreach (KeyValuePair<string, string> entry in Level2Data)
{
    //write to xml: - it works version 1.
    XmlNode keyNode = xmlDoc.CreateElement(entry.Key); //open TAB
    keyNode.InnerText = entry.Value;
    body.AppendChild(keyNode); //close TAB

    //Write to xmml verdion 2: (uncomment the next 4 lines and comment the above 3 - version 1
    //XmlElement key = xmlDoc.CreateElement(string.Empty, entry.Key, string.Empty);
    //XmlText value = xmlDoc.CreateTextNode(entry.Value);
    //key.AppendChild(value);
    //body.AppendChild(key);
}

Both versions (1 and 2 inside foreach loop) give the output:

<?xml version="1.0" encoding="UTF-8"?>
<body>
    <level1>
        <level2>text</level2>
        <level2>ther text</level2>
         <same_level2>more text</same_level2>
    </level1>
</body>

(Note: third line "same level2" in dictionary can be also level2 as the others but I wanted to ilustrate the advantage of the dictionary - in my case I needed level2 with different names.

IntelliJ and Tomcat.. Howto..?

You can also debug tomcat using the community edition (Unlike what is said above).

Start tomcat in debug mode, for example like this: .\catalina.bat jpda run

In intellij: Run > Edit Configurations > +

Select "Remote" Name the connection: "somename" Set "Port:" 8000 (default 5005)

Select Run > Debug "somename"

Search all of Git history for a string?

git rev-list --all | (
    while read revision; do
        git grep -F 'password' $revision
    done
)

IntelliJ shortcut to show a popup of methods in a class that can be searched

You can type "this." and wait a second, a popup with methods and properties will display.

Not a shortcut, but it works for me.

PS: if you are in a static method, type the class name.

Examples of GoF Design Patterns in Java's core libraries

RMI is based on Proxy.

Should be possible to cite one for most of the 23 patterns in GoF:

  1. Abstract Factory: java.sql interfaces all get their concrete implementations from JDBC JAR when driver is registered.
  2. Builder: java.lang.StringBuilder.
  3. Factory Method: XML factories, among others.
  4. Prototype: Maybe clone(), but I'm not sure I'm buying that.
  5. Singleton: java.lang.System
  6. Adapter: Adapter classes in java.awt.event, e.g., WindowAdapter.
  7. Bridge: Collection classes in java.util. List implemented by ArrayList.
  8. Composite: java.awt. java.awt.Component + java.awt.Container
  9. Decorator: All over the java.io package.
  10. Facade: ExternalContext behaves as a facade for performing cookie, session scope and similar operations.
  11. Flyweight: Integer, Character, etc.
  12. Proxy: java.rmi package
  13. Chain of Responsibility: Servlet filters
  14. Command: Swing menu items
  15. Interpreter: No directly in JDK, but JavaCC certainly uses this.
  16. Iterator: java.util.Iterator interface; can't be clearer than that.
  17. Mediator: JMS?
  18. Memento:
  19. Observer: java.util.Observer/Observable (badly done, though)
  20. State:
  21. Strategy:
  22. Template:
  23. Visitor:

I can't think of examples in Java for 10 out of the 23, but I'll see if I can do better tomorrow. That's what edit is for.

How do I connect to a MySQL Database in Python?

First step to get The Library: Open terminal and execute pip install mysql-python-connector. After the installation go the second step.

Second Step to import the library: Open your python file and write the following code: import mysql.connector

Third step to connect to the server: Write the following code:

conn = mysql.connector.connect(host=you host name like localhost or 127.0.0.1, username=your username like root, password = your password)

Third step Making the cursor: Making a cursor makes it easy for us to run queries. To make the cursor use the following code: cursor = conn.cursor()

Executing queries: For executing queries you can do the following: cursor.execute(query)

If the query changes any thing in the table you need to add the following code after the execution of the query: conn.commit()

Getting values from a query: If you want to get values from a query then you can do the following: cursor.excecute('SELECT * FROM table_name') for i in cursor: print(i) #Or for i in cursor.fetchall(): print(i)

The fetchall() method returns a list with many tuples that contain the values that you requested ,row after row .

Closing the connection: To close the connection you should use the following code: conn.close()

Handling exception: To Handel exception you can do it Vai the following method: try: #Logic pass except mysql.connector.errors.Error: #Logic pass To use a database: For example you are a account creating system where you are storing the data in a database named blabla, you can just add a database parameter to the connect() method ,like

mysql.connector.connect(database = database name)

don't remove other informations like host,username,password.

What is @ModelAttribute in Spring MVC?

Annotation that binds a method parameter or method return value to a named model attribute, exposed to a web view.

public String add(@ModelAttribute("specified") Model model) {
    ...
}

Java generating non-repeating random numbers

If you're using JAVA 8 or more than use stream functionality following way,

Stream.generate(() -> (new Random()).nextInt(10000)).distinct().limit(10000);

How to remove outliers from a dataset

1 way to do that is

my.NEW.data.frame <- my.data.frame[-boxplot.stats(my.data.frame$my.column)$out, ]

or

my.high.value <- which(my.data.frame$age > 200 | my.data.frame$age < 0) 
my.NEW.data.frame <- my.data.frame[-my.high.value, ]

SQL Query NOT Between Two Dates

For there to be an overlap the table's start_date has to be LESS THAN the interval end date (i.e. it has to start before the end of the interval) AND the table's end_date has to be GREATER THAN the interval start date. You may need to use <= and >= depending on your requirements.

What is the use of hashCode in Java?

hashCode() is a unique code which is generated by the JVM for every object creation.

We use hashCode() to perform some operation on hashing related algorithm like Hashtable, Hashmap etc..

The advantages of hashCode() make searching operation easy because when we search for an object that has unique code, it helps to find out that object.

But we can't say hashCode() is the address of an object. It is a unique code generated by JVM for every object.

That is why nowadays hashing algorithm is the most popular search algorithm.

How can I loop through enum values for display in radio buttons?

Two options:

for (let item in MotifIntervention) {
    if (isNaN(Number(item))) {
        console.log(item);
    }
}

Or

Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));

(code in playground)


Edit

String enums look different than regular ones, for example:

enum MyEnum {
    A = "a",
    B = "b",
    C = "c"
}

Compiles into:

var MyEnum;
(function (MyEnum) {
    MyEnum["A"] = "a";
    MyEnum["B"] = "b";
    MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));

Which just gives you this object:

{
    A: "a",
    B: "b",
    C: "c"
}

You can get all the keys (["A", "B", "C"]) like this:

Object.keys(MyEnum);

And the values (["a", "b", "c"]):

Object.keys(MyEnum).map(key => MyEnum[key])

Or using Object.values():

Object.values(MyEnum)

How to decrypt hash stored by bcrypt

# Maybe you search this ??
For example in my case I use Symfony 4.4 (PHP).
If you want to update User, you need to insert the User password 
encrypted and test with the current Password not encrypted to verify 
if it's the same User. 

For example :

public function updateUser(Request $req)
      {
         $entityManager = $this->getDoctrine()->getManager();
         $repository = $entityManager->getRepository(User::class);
         $user = $repository->find($req->get(id)); /// get User from your DB

         if($user == null){
            throw  $this->createNotFoundException('User don't exist!!', $user);
         }
         $password_old_encrypted = $user->getPassword();//in your DB is always encrypted.
         $passwordToUpdate = $req->get('password'); // not encrypted yet from request.

         $passwordToUpdateEncrypted = password_hash($passwordToUpdate , PASSWORD_DEFAULT);

          ////////////VERIFY IF IT'S THE SAME PASSWORD
         $isPass = password_verify($passwordToUpdateEncrypted , $password_old_encrypted );

         if($isPass === false){ // failure
            throw  $this->createNotFoundException('Your password it's not verify', null);
         }

        return $isPass; //// true!! it's the same password !!!

      }

Can jQuery check whether input content has changed?

You can employ the use of data in jQuery and catch all of the events which then tests it against it's last value (untested):

$(document).ready(function() {  
    $("#fieldId").bind("keyup keydown keypress change blur", function() {
        if ($(this).val() != jQuery.data(this, "lastvalue") {
         alert("changed");
        }
        jQuery.data(this, "lastvalue", $(this).val());
    });
});

This would work pretty good against a long list of items too. Using jQuery.data means you don't have to create a javascript variable to track the value. You could do $("#fieldId1, #fieldId2, #fieldId3, #fieldId14, etc") to track many fields.

UPDATE: Added blur to the bind list.

Webdriver and proxy server for firefox

Just to add to the above given solutions.,

Adding the list of possibilities (integer values) for the "network.proxy.type".

0 - Direct connection (or) no proxy. 

1 - Manual proxy configuration

2 - Proxy auto-configuration (PAC).

4 - Auto-detect proxy settings.

5 - Use system proxy settings. 

So, Based on our requirement, the "network.proxy.type" value should be set as mentioned below.

FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("network.proxy.type", 1);
WebDriver driver = new FirefoxDriver(profile);

Simple calculations for working with lat/lon and km distance?

If you're using Java, Javascript or PHP, then there's a library that will do these calculations exactly, using some amusingly complicated (but still fast) trigonometry:

http://www.jstott.me.uk/jcoord/

How can I turn a string into a list in Python?

The list() function [docs] will convert a string into a list of single-character strings.

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:

>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'

You can also loop over the characters in the string as you can loop over the elements of a list:

>>> for c in 'hello':
...     print c + c,
... 
hh ee ll ll oo

Convert JSON to DataTable

It can also be achieved using below code.

DataSet data = JsonConvert.DeserializeObject<DataSet>(json);

Using GPU from a docker container?

Ok i finally managed to do it without using the --privileged mode.

I'm running on ubuntu server 14.04 and i'm using the latest cuda (6.0.37 for linux 13.04 64 bits).


Preparation

Install nvidia driver and cuda on your host. (it can be a little tricky so i will suggest you follow this guide https://askubuntu.com/questions/451672/installing-and-testing-cuda-in-ubuntu-14-04)

ATTENTION : It's really important that you keep the files you used for the host cuda installation


Get the Docker Daemon to run using lxc

We need to run docker daemon using lxc driver to be able to modify the configuration and give the container access to the device.

One time utilization :

sudo service docker stop
sudo docker -d -e lxc

Permanent configuration Modify your docker configuration file located in /etc/default/docker Change the line DOCKER_OPTS by adding '-e lxc' Here is my line after modification

DOCKER_OPTS="--dns 8.8.8.8 --dns 8.8.4.4 -e lxc"

Then restart the daemon using

sudo service docker restart

How to check if the daemon effectively use lxc driver ?

docker info

The Execution Driver line should look like that :

Execution Driver: lxc-1.0.5

Build your image with the NVIDIA and CUDA driver.

Here is a basic Dockerfile to build a CUDA compatible image.

FROM ubuntu:14.04
MAINTAINER Regan <http://stackoverflow.com/questions/25185405/using-gpu-from-a-docker-container>

RUN apt-get update && apt-get install -y build-essential
RUN apt-get --purge remove -y nvidia*

ADD ./Downloads/nvidia_installers /tmp/nvidia                             > Get the install files you used to install CUDA and the NVIDIA drivers on your host
RUN /tmp/nvidia/NVIDIA-Linux-x86_64-331.62.run -s -N --no-kernel-module   > Install the driver.
RUN rm -rf /tmp/selfgz7                                                   > For some reason the driver installer left temp files when used during a docker build (i don't have any explanation why) and the CUDA installer will fail if there still there so we delete them.
RUN /tmp/nvidia/cuda-linux64-rel-6.0.37-18176142.run -noprompt            > CUDA driver installer.
RUN /tmp/nvidia/cuda-samples-linux-6.0.37-18176142.run -noprompt -cudaprefix=/usr/local/cuda-6.0   > CUDA samples comment if you don't want them.
RUN export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda/lib64         > Add CUDA library into your PATH
RUN touch /etc/ld.so.conf.d/cuda.conf                                     > Update the ld.so.conf.d directory
RUN rm -rf /temp/*  > Delete installer files.

Run your image.

First you need to identify your the major number associated with your device. Easiest way is to do the following command :

ls -la /dev | grep nvidia

If the result is blank, use launching one of the samples on the host should do the trick. The result should look like that enter image description here As you can see there is a set of 2 numbers between the group and the date. These 2 numbers are called major and minor numbers (wrote in that order) and design a device. We will just use the major numbers for convenience.

Why do we activated lxc driver? To use the lxc conf option that allow us to permit our container to access those devices. The option is : (i recommend using * for the minor number cause it reduce the length of the run command)

--lxc-conf='lxc.cgroup.devices.allow = c [major number]:[minor number or *] rwm'

So if i want to launch a container (Supposing your image name is cuda).

docker run -ti --lxc-conf='lxc.cgroup.devices.allow = c 195:* rwm' --lxc-conf='lxc.cgroup.devices.allow = c 243:* rwm' cuda

C# cannot convert method to non delegate type

Because getTitle is not a string, it returns a reference or delegate to a method (if you like), if you don't explicitly call the method.

Call your method this way:

string t= obj.getTitle() ; //obj.getTitle()  says return the title string object

However, this would work:

Func<string> method = obj.getTitle; // this compiles to a delegate and points to the method

string s = method();//call the delegate or using this syntax `method.Invoke();`

Convert a Unicode string to a string in Python (containing extra symbols)

Here is an example code

import unicodedata    
raw_text = u"here $%6757 dfgdfg"
convert_text = unicodedata.normalize('NFKD', raw_text).encode('ascii','ignore')

How to remove all namespaces from XML with C#?

And this is the perfect solution that will also remove XSI elements. (If you remove the xmlns and don't remove XSI, .Net shouts at you...)

string xml = node.OuterXml;
//Regex below finds strings that start with xmlns, may or may not have :and some text, then continue with =
//and ", have a streach of text that does not contain quotes and end with ". similar, will happen to an attribute
// that starts with xsi.
string strXMLPattern = @"xmlns(:\w+)?=""([^""]+)""|xsi(:\w+)?=""([^""]+)""";
xml = Regex.Replace(xml, strXMLPattern, "");

Get all mysql selected rows into an array

you can call mysql_fetch_array() for no_of_row time

Android ListView headers

You probably are looking for an ExpandableListView which has headers (groups) to separate items (childs).

Nice tutorial on the subject: here.

Python pandas: fill a dataframe row by row

If your input rows are lists rather than dictionaries, then the following is a simple solution:

import pandas as pd
list_of_lists = []
list_of_lists.append([1,2,3])
list_of_lists.append([4,5,6])

pd.DataFrame(list_of_lists, columns=['A', 'B', 'C'])
#    A  B  C
# 0  1  2  3
# 1  4  5  6

window.onload vs <body onload=""/>

There is no difference, but you should not use either.

In many browsers, the window.onload event is not triggered until all images have loaded, which is not what you want. Standards based browsers have an event called DOMContentLoaded which fires earlier, but it is not supported by IE (at the time of writing this answer). I'd recommend using a javascript library which supports a cross browser DOMContentLoaded feature, or finding a well written function you can use. jQuery's $(document).ready(), is a good example.

Split string into list in jinja?

After coming back to my own question after 5 year and seeing so many people found this useful, a little update.

A string variable can be split into a list by using the split function (it can contain similar values, set is for the assignment) . I haven't found this function in the official documentation but it works similar to normal Python. The items can be called via an index, used in a loop or like Dave suggested if you know the values, it can set variables like a tuple.

{% set list1 = variable1.split(';') %}
The grass is {{ list1[0] }} and the boat is {{ list1[1] }}

or

{% set list1 = variable1.split(';') %}
{% for item in list1 %}
    <p>{{ item }}<p/>
{% endfor %} 

or

{% set item1, item2 = variable1.split(';') %}
The grass is {{ item1 }} and the boat is {{ item2 }}

jQuery using append with effects

When you append to the div, hide it and show it with the argument "slow".

$("#img_container").append(first_div).hide().show('slow');

Which is the fastest algorithm to find prime numbers?

It depends on your application. There are some considerations:

  • Do you need just the information whether a few numbers are prime, do you need all prime numbers up to a certain limit, or do you need (potentially) all prime numbers?
  • How big are the numbers you have to deal with?

The Miller-Rabin and analogue tests are only faster than a sieve for numbers over a certain size (somewhere around a few million, I believe). Below that, using a trial division (if you just have a few numbers) or a sieve is faster.

Non-conformable arrays error in code

The problem is that omega in your case is matrix of dimensions 1 * 1. You should convert it to a vector if you wish to multiply t(X) %*% X by a scalar (that is omega)

In particular, you'll have to replace this line:

omega   = rgamma(1,a0,1) / L0

with:

omega   = as.vector(rgamma(1,a0,1) / L0)

everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.) or c(t(.)). Both are equivalent.

Here's the modified code that should work:

gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1, 
                     a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
    m0      = c(m01, m02) 
    C0      = matrix(nrow = 2, ncol = 2) 
    C0[1,1] = 1 / k01 
    C0[1,2] = 0 
    C0[2,1] = 0 
    C0[2,2] = 1 / k02 
    beta    = mvrnorm(1,m0,C0) 
    omega   = as.vector(rgamma(1,a0,1) / L0)
    draws   = matrix(ncol = 3,nrow = ndraw) 
    it      = -nburn 

    while (it < ndraw) {
        it    = it + 1 
        C1    = solve(solve(C0) + omega * t(X) %*% X) 
        m1    = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
        beta  = mvrnorm(1, m1, C1) 
        a1    = a0 + n / 2 
        L1    = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2 
        omega = as.vector(rgamma(1, a1, 1) / L1)
        if (it > 0) { 
            draws[it,1] = beta[1]
            draws[it,2] = beta[2]
            draws[it,3] = omega
        }
    }
    return(draws)
}

HTML button opening link in new tab

Try this code.

<input type="button" value="Open Window"
onclick="window.open('http://www.google.com')">

Max parallel http connections in a browser?

Note that increasing a browser's max connections per server to an excessive number (as some sites suggest) can and does lock other users out of small sites with hosting plans that limit the total simultaneous connections on the server.

Parsing HTML using Python

I would use EHP

https://github.com/iogf/ehp

Here it is:

from ehp import *

doc = '''<html>
<head>Heading</head>
<body attr1='val1'>
    <div class='container'>
        <div id='class'>Something here</div>
        <div>Something else</div>
    </div>
</body>
</html>
'''

html = Html()
dom = html.feed(doc)
for ind in dom.find('div', ('class', 'container')):
    print ind.text()

Output:

Something here
Something else

Angular 4/5/6 Global Variables

Not really recommended but none of the other answers are really global variables. For a truly global variable you could do this.

Index.html

<body>
  <app-root></app-root>
  <script>
    myTest = 1;
  </script>
</body>

Component or anything else in Angular

..near the top right after imports:

declare const myTest: any;

...later:

console.warn(myTest); // outputs '1'

Iterate over a Javascript associative array in sorted order

You can use the Object.keys built-in method:

var sorted_keys = Object.keys(a).sort()

(Note: this does not work in very old browsers not supporting EcmaScript5, notably IE6, 7 and 8. For detailed up-to-date statistics, see this table)

Scroll to bottom of Div on page load (jQuery)

UPDATE : see Mike Todd's solution for a complete answer.


$("#div1").animate({ scrollTop: $('#div1').height()}, 1000);

if you want it to be animated (over 1000 milliseconds).

$('#div1').scrollTop($('#div1').height())

if you want it instantaneous.

How to keep a VMWare VM's clock in sync?

VMware experiences a lot of clock drift. This Google search for 'vmware clock drift' links to several articles.

The first hit may be the most useful for you: http://www.fjc.net/linux/linux-and-vmware-related-issues/linux-2-6-kernels-and-vmware-clock-drift-issues

How to pass parameters in GET requests with jQuery

The data parameter of ajax method allows you send data to server side.On server side you can request the data.See the code

var id=5;
$.ajax({
    type: "get",
    url: "url of server side script",
    data:{id:id},
    success: function(res){
        console.log(res);
    },
error:function(error)
{
console.log(error);
}
});

At server side receive it using $_GET variable.

$_GET['id'];

Where can I view Tomcat log files in Eclipse?

Double click and open the server. Go to 'Arguments'. -Dcatalina.base= .. something. Go to that something. Your logs are there.

Java using enum with switch statement

I am doing it like

public enum State
{
    // Retrieving, // the MediaRetriever is retrieving music //
    Stopped, // media player is stopped and not prepared to play
    Preparing, // media player is preparing...
    Playing, // playback active (media player ready!). (but the media player
                // may actually be
                // paused in this state if we don't have audio focus. But we
                // stay in this state
                // so that we know we have to resume playback once we get
                // focus back)
    Paused; // playback paused (media player ready!)

    //public final static State[] vals = State.values();//copy the values(), calling values() clones the array

};

public State getState()
{
        return mState;   
}

And use in Switch Statement

switch (mService.getState())
{
case Stopped:
case Paused:

    playPause.setBackgroundResource(R.drawable.selplay);
    break;

case Preparing:
case Playing:

    playPause.setBackgroundResource(R.drawable.selpause);
    break;    
}

"Warning: iPhone apps should include an armv6 architecture" even with build config set

Try changing your deployment target to something higher than an armv6 processor. The settings for xCode are referencing the operating system level, for instance: iOS version#{3.1, 3.2, 4.0, 4.1, 4.2, 4.3, 5.0, 5.1}

(i)You can set this in the build settings tab or the summary tab. Start at the top left of the window in the Project Navigator, with all the files listed in it. Click the top-most one which has a blue icon.

(ii)If you are planning on using the programmable shader line circuitry, which is accessed and controlled through openGL ES 2.0 API, then you should set your "Deployment Version" to about 4.3, which I believe is only available on devices such as the 3GS or newer. xCode is reporting that iOS 4.2.5 or higher is needed run armv7 code. And once again, this processor, I believe, started with the 3GS.* iOS 4.3 seems to be the choice for me, for now.

http://theiphonewiki.com/wiki/index.php?title=Armv7

http://en.wikipedia.org/wiki/List_of_iOS_devices

How to check heap usage of a running JVM from the command line?

If you start execution with gc logging turned on you get the info on file. Otherwise 'jmap -heap ' will give you what you want. See the jmap doc page for more.

Please note that jmap should not be used in a production environment unless absolutely needed as the tool halts the application to be able to determine actual heap usage. Usually this is not desired in a production environment.

Margin-Top not working for span element?

Looks like you missed some options, try to add:

position: relative;
top: 25px;

How to read a file into a variable in shell?

In cross-platform, lowest-common-denominator sh you use:

#!/bin/sh
value=`cat config.txt`
echo "$value"

In bash or zsh, to read a whole file into a variable without invoking cat:

#!/bin/bash
value=$(<config.txt)
echo "$value"

Invoking cat in bash or zsh to slurp a file would be considered a Useless Use of Cat.

Note that it is not necessary to quote the command substitution to preserve newlines.

See: Bash Hacker's Wiki - Command substitution - Specialities.

Storing a Key Value Array into a compact JSON string

So why don't you simply use a key-value literal?

var params = {
    'slide0001.html': 'Looking Ahead',
    'slide0002.html': 'Forecase',
    ...
};

return params['slide0001.html']; // returns: Looking Ahead

Prevent text selection after double click

To prevent text selection ONLY after a double click:

You could use MouseEvent#detail property. For mousedown or mouseup events, it is 1 plus the current click count.

document.addEventListener('mousedown', function (event) {
  if (event.detail > 1) {
    event.preventDefault();
    // of course, you still do not know what you prevent here...
    // You could also check event.ctrlKey/event.shiftKey/event.altKey
    // to not prevent something useful.
  }
}, false);

See https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail

Cannot open output file, permission denied

The problem is related to Sam´s response:

"have encountered the same problem you have. I found that it may have some relationship with the way you terminate your run result. When you run your code, whether it has a printout, the debugger will call the console which print a "Press any key to continue...". If you terminate the console by pressing key, it's ok; if you do it by click the close button, the problem comes as you described. When you terminate it in the latter way, you have to wait several minutes before you can rebuild your code."

Avoid kill processes, and we have two choices, wait until the process release the .EXE file or this problem will be solved faster restarting the IDE.

How do I skip a header from CSV files in Spark?

In Spark 2.0 a CSV reader is build into Spark, so you can easily load a CSV file as follows:

spark.read.option("header","true").csv("filePath")

Convert unix time to readable date in pandas dataframe

Alternatively, by changing a line of the above code:

# df.date = df.date.apply(lambda d: datetime.strptime(d, "%Y-%m-%d"))
df.date = df.date.apply(lambda d: datetime.datetime.fromtimestamp(int(d)).strftime('%Y-%m-%d'))

It should also work.

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

I solved the error by modifying the following property in hibernate.cfg.xml

  <property name="hibernate.hbm2ddl.auto">validate</property>

Earlier, the table was getting deleted each time I ran the program and now it doesnt, as hibernate only validates the schema and does not affect changes to it.

Oracle - How to generate script from sql developer

This worked for me:

  • In SQL Developer, right click the object that you want to generate a script for. i.e. the table name
  • Select Quick DLL > Save To File
  • This will then write the create statement to an external sql file.

Note, you can also highlight multiple objects at the same time, so you could generate one script that contains create statements for all tables within the database.

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

I think you need to include only these options in build.gradle:

packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
    }

p.s same answer from my post in : Error :: duplicate files during packaging of APK

Sound effects in JavaScript / HTML5

I ran into this while programming a musicbox card generator. Started with different libraries but everytime there was a glitch somehow. The lag on normal audio implementation was bad, no multiple plays... eventually ended up using lowlag library + soundmanager:

http://lowlag.alienbill.com/ and http://www.schillmania.com/projects/soundmanager2/

You can check out the implementation here: http://musicbox.grit.it/

I generated wav + ogg files for multi browser plays. This musicbox player works responsive on ipad, iphone, Nexus, mac, pc,... works for me.

Convert text to columns in Excel using VBA

Try this

Sub Txt2Col()
    Dim rng As Range

    Set rng = [C7]
    Set rng = Range(rng, Cells(Rows.Count, rng.Column).End(xlUp))

    rng.TextToColumns Destination:=rng, DataType:=xlDelimited, ' rest of your settings

Update: button click event to act on another sheet

Private Sub CommandButton1_Click()
    Dim rng As Range
    Dim sh As Worksheet

    Set sh = Worksheets("Sheet2")
    With sh
        Set rng = .[C7]
        Set rng = .Range(rng, .Cells(.Rows.Count, rng.Column).End(xlUp))

        rng.TextToColumns Destination:=rng, DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote,  _
        ConsecutiveDelimiter:=False, _
        Tab:=False, _
        Semicolon:=False, _
        Comma:=True, 
        Space:=False, 
        Other:=False, _
        FieldInfo:=Array(Array(1, xlGeneralFormat), Array(2, xlGeneralFormat), Array(3, xlGeneralFormat)), _
        TrailingMinusNumbers:=True
    End With
End Sub

Note the .'s (eg .Range) they refer to the With statement object

Convert an image to grayscale

None of the examples above create 8-bit (8bpp) bitmap images. Some software, such as image processing, only supports 8bpp. Unfortunately the MS .NET libraries do not have a solution. The PixelFormat.Format8bppIndexed format looks promising but after a lot of attempts I couldn't get it working.

To create a true 8-bit bitmap file you need to create the proper headers. Ultimately I found the Grayscale library solution for creating 8-bit bitmap (BMP) files. The code is very simple:

Image image = Image.FromFile("c:/path/to/image.jpg");
GrayBMP_File.CreateGrayBitmapFile(image, "c:/path/to/8bpp/image.bmp");

The code for this project is far from pretty but it works, with one little simple-to-fix problem. The author hard-coded the image resolution to 10x10. Image processing programs do not like this. The fix is open GrayBMP_File.cs (yeah, funky file naming, I know) and replace lines 50 and 51 with the code below. The example sets the resolution to 200x200 but you should change it to the proper number.

int resX = 200;
int resY = 200;
// horizontal resolution
Copy_to_Index(DIB_header, BitConverter.GetBytes(resX * 100), 24);
// vertical resolution 
Copy_to_Index(DIB_header, BitConverter.GetBytes(resY * 100), 28);

How do I change db schema to dbo

Way to do it for an individual thing:

alter schema dbo transfer jonathan.MovieData

Can't compile C program on a Mac after upgrade to Mojave

apue.h dependency was still missing in my /usr/local/include after I managed to fix this problem on Mac OS Catalina following the instructions of this answer

I downloaded the dependency manually from git and placed it in /usr/local/include

What's the difference between all the Selection Segues?

For clarity, I'd like to illustrate @Joey's answer above with these gifs :

Show

enter image description here

Show Detail

enter image description here

Present Modally

enter image description here

Present As Popover

enter image description here

What's the difference between using CGFloat and float?

just mention that - Jan, 2020 Xcode 11.3/iOS13

Swift 5

From the CoreGraphics source code

public struct CGFloat {
    /// The native type used to store the CGFloat, which is Float on
    /// 32-bit architectures and Double on 64-bit architectures.
    public typealias NativeType = Double

Finding the last index of an array

The array has a Length property that will give you the length of the array. Since the array indices are zero-based, the last item will be at Length - 1.

string[] items = GetAllItems();
string lastItem = items[items.Length - 1];
int arrayLength = array.Length;

When declaring an array in C#, the number you give is the length of the array:

string[] items = new string[5]; // five items, index ranging from 0 to 4.

What is the facade design pattern?

A facade should not be described as a class which contains a lot of other classes. It is in fact a interface to this classes and should make the usage of the classes easier otherwise the facade class is useless.

jQuery posting valid json in request body

An actual JSON request would look like this:

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

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

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

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


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

Simple Popup by using Angular JS

If you are using bootstrap.js then the below code might be useful. This is very simple. Dont have to write anything in js to invoke the pop-up.

Source :http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Modal Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>

</div>

</body>
</html>

Error parsing yaml file: mapping values are not allowed here

My issue was a missing set of quotes;

Foo: bar 'baz'

should be

Foo: "bar 'baz'"

How to use ArgumentCaptor for stubbing?

The line

when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);

would do the same as

when(someObject.doSomething(Matchers.any())).thenReturn(true);

So, using argumentCaptor.capture() when stubbing has no added value. Using Matchers.any() shows better what really happens and therefor is better for readability. With argumentCaptor.capture(), you can't read what arguments are really matched. And instead of using any(), you can use more specific matchers when you have more information (class of the expected argument), to improve your test.

And another problem: If using argumentCaptor.capture() when stubbing it becomes unclear how many values you should expect to be captured after verification. We want to capture a value during verification, not during stubbing because at that point there is no value to capture yet. So what does the argument captors capture method capture during stubbing? It capture anything because there is nothing to be captured yet. I consider it to be undefined behavior and I don't want to use undefined behavior.

close fancy box from function from within open 'fancybox'

Add $.fancybox.close() to where ever you want it to be trigged, in a function or a callback, end of an ajax call!

Woohoo.

Can Android Studio be used to run standard Java projects?

I have been able to do it using following steps:

  1. Open Android Studio and select 'Import Project'.
    Android Studio import a project

  2. Browse to your project folder in the browse window and select it.

How to model type-safe enum types?

A slightly less verbose way of declaring named enumerations:

object WeekDay extends Enumeration("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat") {
  type WeekDay = Value
  val Sun, Mon, Tue, Wed, Thu, Fri, Sat = Value
}

WeekDay.valueOf("Wed") // returns Some(Wed)
WeekDay.Fri.toString   // returns Fri

Of course the problem here is that you will need to keep the ordering of the names and vals in sync which is easier to do if name and val are declared on the same line.

How to validate IP address in Python?

I only needed to parse IP v4 addresses. My solution based on Chills strategy follows:

def getIP():
valid = False
while not valid :
octets = raw_input( "Remote Machine IP Address:" ).strip().split(".")
try: valid=len( filter( lambda(item):0<=int(item)<256, octets) ) == 4
except: valid = False
return ".".join( octets )

Easiest way to convert a Blob into a byte array

The easiest way is this.

byte[] bytes = rs.getBytes("my_field");

Binding List<T> to DataGridView in WinForm

Yes, it is possible to do with out rebinding by implementing INotifyPropertyChanged Interface.

Pretty Simple example is available here,

http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx

How to write data with FileOutputStream without losing old data?

Use the constructor that takes a File and a boolean

FileOutputStream(File file, boolean append) 

and set the boolean to true. That way, the data you write will be appended to the end of the file, rather than overwriting what was already there.

React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

This error can be received but be aware it can be a red herring to the real issue. In my case, there wasn't an issue with the JSON as the error states, but rather a 404 was occurring that it could not pull the JSON data to process in the 1st place thus resulting in this error.

The fix for this was that in order to use fetch on a .json file in a local project, the .json file must be accessible. This can be done by placing it in a folder such as the public folder in the root of the project. Once I moved the json file into that folder, the 404 turned into a 200, and the Unexpected token < in JSON at position 0 error was resolved.

How can I reverse the order of lines in a file?

tac <file_name>

example:

$ cat file1.txt
1
2
3
4
5

$ tac file1.txt
5
4
3
2
1

How do you make an array of structs in C?

Another way of initializing an array of structs is to initialize the array members explicitly. This approach is useful and simple if there aren't too many struct and array members.

Use the typedef specifier to avoid re-using the struct statement everytime you declare a struct variable:

typedef struct
{
    double p[3];//position
    double v[3];//velocity
    double a[3];//acceleration
    double radius;
    double mass;
}Body;

Then declare your array of structs. Initialization of each element goes along with the declaration:

Body bodies[n] = {{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}, 
                  {{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}, 
                  {{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}};

To repeat, this is a rather simple and straightforward solution if you don't have too many array elements and large struct members and if you, as you stated, are not interested in a more dynamic approach. This approach can also be useful if the struct members are initialized with named enum-variables (and not just numbers like the example above) whereby it gives the code-reader a better overview of the purpose and function of a structure and its members in certain applications.

Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject

Quickfix

I had similar issue and I resolved it doing the following

  1. Navigate to jenkins > Manage jenkins > In-process Script Approval
  2. There was a pending command, which I had to approve.

In process approval link in Jenkins 2.61 Alternative 1: Disable sandbox

As this article explains in depth, groovy scripts are run in sandbox mode by default. This means that a subset of groovy methods are allowed to run without administrator approval. It's also possible to run scripts not in sandbox mode, which implies that the whole script needs to be approved by an administrator at once. This preventing users from approving each line at the time.

Running scripts without sandbox can be done by unchecking this checkbox in your project config just below your script: enter image description here

Alternative 2: Disable script security

As this article explains it also possible to disable script security completely. First install the permissive script security plugin and after that change your jenkins.xml file add this argument:

-Dpermissive-script-security.enabled=true

So you jenkins.xml will look something like this:

<executable>..bin\java</executable>
<arguments>-Dpermissive-script-security.enabled=true -Xrs -Xmx4096m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --httpPort=80 --webroot="%BASE%\war"</arguments>

Make sure you know what you are doing if you implement this!

Usage of unicode() and encode() functions in Python

str is text representation in bytes, unicode is text representation in characters.

You decode text from bytes to unicode and encode a unicode into bytes with some encoding.

That is:

>>> 'abc'.decode('utf-8')  # str to unicode
u'abc'
>>> u'abc'.encode('utf-8') # unicode to str
'abc'

UPD Sep 2020: The answer was written when Python 2 was mostly used. In Python 3, str was renamed to bytes, and unicode was renamed to str.

>>> b'abc'.decode('utf-8') # bytes to str
'abc'
>>> 'abc'.encode('utf-8'). # str to bytes
b'abc'

How do I copy a hash in Ruby?

If you're using Rails you can do:

h1 = h0.deep_dup

http://apidock.com/rails/Hash/deep_dup

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

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

Example of a basic OptionMenu:

from Tkinter import *

master = Tk()

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

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

mainloop()

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


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

from tkinter import *

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

master = Tk()

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

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

mainloop()

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

from tkinter import *

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

master = Tk()

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

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

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

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

mainloop()

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

finding multiples of a number in Python

You can do:

def mul_table(n,i=1):
    print(n*i)
    if i !=10:
        mul_table(n,i+1)
mul_table(7)

Missing .map resource?

I had similar expirience like yours. I have Denwer server. When I loaded my http://new.new local site without using via script src jquery.min.js file at index.php in Chrome I got error 500 jquery.min.map in console. I resolved this problem simply - I disabled extension Wunderlist in Chrome and voila - I never see this error more. Although, No, I found this error again - when Wunderlist have been on again. So, check your extensions and try to disable all of them or some of them or one by one. Good luck!

how to delete the content of text file without deleting itself

using : New Java 7 NIO library, try

        if(!Files.exists(filePath.getParent())) {
            Files.createDirectory(filePath.getParent());
        }
        if(!Files.exists(filePath)) {
            Files.createFile(filePath);
        }
        // Empty the file content
        writer = Files.newBufferedWriter(filePath);
        writer.write("");
        writer.flush();

The above code checks if Directoty exist if not creates the directory, checks if file exists is yes it writes empty string and flushes the buffer, in the end yo get the writer pointing to empty file

How to disable clicking inside div

The CSS property that can be used is:

pointer-events:none

!IMPORTANT Keep in mind that this property is not supported by Opera Mini and IE 10 and below (inclusive). Another solution is needed for these browsers.

jQuery METHOD If you want to disable it via script and not CSS property, these can help you out: If you're using jQuery versions 1.4.3+:

$('selector').click(false);

If not:

$('selector').click(function(){return false;});

You can re-enable clicks with pointer-events: auto; (Documentation)

Note that pointer-events overrides the cursor property, so if you want the cursor to be something other than the standard cursor, your css should be place after pointer-events.

getOutputStream() has already been called for this response

I got the same problem, and I solved just adding "return;" at the end of the FileInputStream.

Here is my JSP

_x000D_
_x000D_
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"_x000D_
 pageEncoding="ISO-8859-1"%>_x000D_
<%@ page import="java.io.*"%>_x000D_
<%@ page trimDirectiveWhitespaces="true"%>_x000D_
_x000D_
<%_x000D_
_x000D_
 try {_x000D_
  FileInputStream ficheroInput = new FileInputStream("C:\\export_x_web.pdf");_x000D_
  int tamanoInput = ficheroInput.available();_x000D_
  byte[] datosPDF = new byte[tamanoInput];_x000D_
  ficheroInput.read(datosPDF, 0, tamanoInput);_x000D_
_x000D_
  response.setHeader("Content-disposition", "inline; filename=export_sise_web.pdf");_x000D_
  response.setContentType("application/pdf");_x000D_
  response.setContentLength(tamanoInput);_x000D_
  response.getOutputStream().write(datosPDF);_x000D_
_x000D_
  response.getOutputStream().flush();_x000D_
  response.getOutputStream().close();_x000D_
_x000D_
  ficheroInput.close();_x000D_
  return;_x000D_
_x000D_
 } catch (Exception e) {_x000D_
_x000D_
 }_x000D_
%>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to copy a collection from one database to another in MongoDB

This might be just a special case, but for a collection of 100k documents with two random string fields (length is 15-20 chars), using a dumb mapreduce is almost twice as fast as find-insert/copyTo:

db.coll.mapReduce(function() { emit(this._id, this); }, function(k,vs) { return vs[0]; }, { out : "coll2" })

Cannot simply use PostgreSQL table name ("relation does not exist")

Postgres process query different from other RDMS. Put schema name in double quote before your table name like this, "SCHEMA_NAME"."SF_Bands"

How do I make a batch file terminate upon encountering an error?

Here is a polyglot program for BASH and Windows CMD that runs a series of commands and quits out if any of them fail:

#!/bin/bash 2> nul

:; set -o errexit
:; function goto() { return $?; }

command 1 || goto :error

command 2 || goto :error

command 3 || goto :error

:; exit 0
exit /b 0

:error
exit /b %errorlevel%

I have used this type of thing in the past for a multiple platform continuous integration script.

Export and import table dump (.sql) using pgAdmin

An another way, you can do it easily with CMD on Windows

Put your installed version (mine is 11).

cd C:\Program Files\PostgreSQL\11\bin\

and run simple query

psql -U <postgre_username> -d <db_name> < <C:\path\data_dump.sql>

enter password then wait the final console message.

Why is it bad style to `rescue Exception => e` in Ruby?

The real rule is: Don't throw away exceptions. The objectivity of the author of your quote is questionable, as evidenced by the fact that it ends with

or I will stab you

Of course, be aware that signals (by default) throw exceptions, and normally long-running processes are terminated through a signal, so catching Exception and not terminating on signal exceptions will make your program very hard to stop. So don't do this:

#! /usr/bin/ruby

while true do
  begin
    line = STDIN.gets
    # heavy processing
  rescue Exception => e
    puts "caught exception #{e}! ohnoes!"
  end
end

No, really, don't do it. Don't even run that to see if it works.

However, say you have a threaded server and you want all exceptions to not:

  1. be ignored (the default)
  2. stop the server (which happens if you say thread.abort_on_exception = true).

Then this is perfectly acceptable in your connection handling thread:

begin
  # do stuff
rescue Exception => e
  myLogger.error("uncaught #{e} exception while handling connection: #{e.message}")
    myLogger.error("Stack trace: #{backtrace.map {|l| "  #{l}\n"}.join}")
end

The above works out to a variation of Ruby's default exception handler, with the advantage that it doesn't also kill your program. Rails does this in its request handler.

Signal exceptions are raised in the main thread. Background threads won't get them, so there is no point in trying to catch them there.

This is particularly useful in a production environment, where you do not want your program to simply stop whenever something goes wrong. Then you can take the stack dumps in your logs and add to your code to deal with specific exception further down the call chain and in a more graceful manner.

Note also that there is another Ruby idiom which has much the same effect:

a = do_something rescue "something else"

In this line, if do_something raises an exception, it is caught by Ruby, thrown away, and a is assigned "something else".

Generally, don't do that, except in special cases where you know you don't need to worry. One example:

debugger rescue nil

The debugger function is a rather nice way to set a breakpoint in your code, but if running outside a debugger, and Rails, it raises an exception. Now theoretically you shouldn't be leaving debug code lying around in your program (pff! nobody does that!) but you might want to keep it there for a while for some reason, but not continually run your debugger.

Note:

  1. If you've run someone else's program that catches signal exceptions and ignores them, (say the code above) then:

    • in Linux, in a shell, type pgrep ruby, or ps | grep ruby, look for your offending program's PID, and then run kill -9 <PID>.
    • in Windows, use the Task Manager (CTRL-SHIFT-ESC), go to the "processes" tab, find your process, right click it and select "End process".
  2. If you are working with someone else's program which is, for whatever reason, peppered with these ignore-exception blocks, then putting this at the top of the mainline is one possible cop-out:

    %W/INT QUIT TERM/.each { |sig| trap sig,"SYSTEM_DEFAULT" }
    

    This causes the program to respond to the normal termination signals by immediately terminating, bypassing exception handlers, with no cleanup. So it could cause data loss or similar. Be careful!

  3. If you need to do this:

    begin
      do_something
    rescue Exception => e
      critical_cleanup
      raise
    end
    

    you can actually do this:

    begin
      do_something
    ensure
      critical_cleanup
    end
    

    In the second case, critical cleanup will be called every time, whether or not an exception is thrown.

Excel formula to search if all cells in a range read "True", if not, then show "False"

You can just AND the results together if they are stored as TRUE / FALSE values:

=AND(A1:D2)

Or if stored as text, use an array formula - enter the below and press Ctrl+Shift+Enter instead of Enter.

=AND(EXACT(A1:D2,"TRUE"))

How to get the title of HTML page with JavaScript?

Use document.title:

_x000D_
_x000D_
console.log(document.title)
_x000D_
<title>Title test</title>
_x000D_
_x000D_
_x000D_

MDN Web Docs

Get div's offsetTop positions in React

You may be encouraged to use the Element.getBoundingClientRect() method to get the top offset of your element. This method provides the full offset values (left, top, right, bottom, width, height) of your element in the viewport.

Check the John Resig's post describing how helpful this method is.

ip address validation in python using regex

Why not use a library function to validate the ip address?

>>> ip="241.1.1.112343434" 
>>> socket.inet_aton(ip)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
socket.error: illegal IP address string passed to inet_aton

How to Lock Android App's Orientation to Portrait in Phones and Landscape in Tablets?

Set the Screen orientation to portrait in Manifest file under the activity Tag.

Here the example

You need to enter in every Activity

Add The Following Lines in Activity

for portrait

android:screenOrientation="portrait"
tools:ignore="LockedOrientationActivity"

for landscape

android:screenOrientation="landscape"
tools:ignore="LockedOrientationActivity"

Here The Example of MainActivity

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="org.thcb.app">
 
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity"
            android:screenOrientation="portrait"
            tools:ignore="LockedOrientationActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

<activity android:name=".MainActivity2"
            android:screenOrientation="landscape"
            tools:ignore="LockedOrientationActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Difference between BYTE and CHAR in column datatypes

Depending on the system configuration, size of CHAR mesured in BYTES can vary. In your examples:

  1. Limits field to 11 BYTE
  2. Limits field to 11 CHARacters


Conclusion: 1 CHAR is not equal to 1 BYTE.

Absolute position of an element on the screen using jQuery

BTW, if anyone want to get coordinates of element on screen without jQuery, please try this:

function getOffsetTop (el) {
    if (el.offsetParent) return el.offsetTop + getOffsetTop(el.offsetParent)
    return el.offsetTop || 0
}
function getOffsetLeft (el) {
    if (el.offsetParent) return el.offsetLeft + getOffsetLeft(el.offsetParent)
    return el.offsetleft || 0
}
function coordinates(el) {
    var y1 = getOffsetTop(el) - window.scrollY;
    var x1 = getOffsetLeft(el) - window.scrollX; 
    var y2 = y1 + el.offsetHeight;
    var x2 = x1 + el.offsetWidth;
    return {
        x1: x1, x2: x2, y1: y1, y2: y2
    }
}

Java: convert List<String> to a String

You can do this:

String aToString = java.util.Arrays.toString(anArray);
// Do not need to do this if you are OK with '[' and ']'
aToString = aToString.substring(1, aToString.length() - 1);

Or a one-liner (only when you do not want '[' and ']')

String aToString = java.util.Arrays.toString(anArray).substring(1).replaceAll("\\]$", "");

Hope this helps.

Set width of a "Position: fixed" div relative to parent div

Here is a little hack that we ran across while fixing some redraw issues on a large app.

Use -webkit-transform: translateZ(0); on the parent. Of course this is specific to Chrome.

http://jsfiddle.net/senica/bCQEa/

-webkit-transform: translateZ(0);

CSS two div width 50% in one line with line break in file

The problem you run into when setting width to 50% is the rounding of subpixels. If the width of your container is i.e. 99 pixels, a width of 50% can result in 2 containers of 50 pixels each.

Using float is probably easiest, and not such a bad idea. See this question for more details on how to fix the problem then.

If you don't want to use float, try using a width of 49%. This will work cross-browser as far as I know, but is not pixel-perfect..

html:

<div id="a">A</div>
<div id="b">B</div>

css:

#a, #b {
    width: 49%;
    display: inline-block; 
}
#a {background-color: red;}
#b {background-color: blue;}

Make an image width 100% of parent div, but not bigger than its own width

I found an answer which worked for me and can be found in the following link:

Full Width Containers in Limited Width Parents

OVER_QUERY_LIMIT in Google Maps API v3: How do I pause/delay in Javascript to slow it down?

Using "setInterval" & "clearInterval" fixes the problem:

function drawMarkers(map, markers) {
    var _this = this,
        geocoder = new google.maps.Geocoder(),
        geocode_filetrs;

    _this.key = 0;

    _this.interval = setInterval(function() {
        _this.markerData = markers[_this.key];

        geocoder.geocode({ address: _this.markerData.address }, yourCallback(_this.markerData));

        _this.key++;

        if ( ! markers[_this.key]) {
            clearInterval(_this.interval);
        }

    }, 300);
}

increase font size of hyperlink text html

There is a way simpler way. You put the href in a paragraph just created for that href. For example:

HREF name

AttributeError: module 'cv2.cv2' has no attribute 'createLBPHFaceRecognizer'

Check your OpenCV version

import cv2
cv2.__version__

If your are running Python v3.x and OpenCV v4 and above:

pip install opencv-contrib-python

Try running your program again. This should now work.

Font awesome is not showing icon

Check that the path to your CSS file is correct. Rather prefer absolute links, they are easier to understand since we know where we start from and search engines will also prefer them over relative links. And to reduce bandwidth rather use the link from font-awesome servers:

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" type="text/css">

Moreover if you use it, there will be no need of uploading extra fonts to your server and you will be sure that you point to the right CSS file, and you will also benefit from the latest updates instantly.

Convert nested Python dict to object?

I had some problems with __getattr__ not being called so I constructed a new style class version:

class Struct(object):
    '''The recursive class for building and representing objects with.'''
    class NoneStruct(object):
        def __getattribute__(*args):
            return Struct.NoneStruct()

        def __eq__(self, obj):
            return obj == None

    def __init__(self, obj):
        for k, v in obj.iteritems():
            if isinstance(v, dict):
                setattr(self, k, Struct(v))
            else:
                setattr(self, k, v)

    def __getattribute__(*args):
        try:
            return object.__getattribute__(*args)
        except:            
            return Struct.NoneStruct()

    def __repr__(self):
        return '{%s}' % str(', '.join('%s : %s' % (k, repr(v)) for 
(k, v) in self.__dict__.iteritems()))

This version also has the addition of NoneStruct that is returned when an attribute is called that is not set. This allows for None testing to see if an attribute is present. Very usefull when the exact dict input is not known (settings etc.).

bla = Struct({'a':{'b':1}})
print(bla.a.b)
>> 1
print(bla.a.c == None)
>> True

PHP Parse error: syntax error, unexpected T_PUBLIC

You can remove public keyword from your functions, because, you have to define a class in order to declare public, private or protected function

where is create-react-app webpack config and files?

Webpack configuration is being handled by react-scripts. You can find all webpack config inside node_modules react-scripts/config.

And If you want to customize webpack config, you can follow this customize-webpack-config

Operation must use an updatable query. (Error 3073) Microsoft Access

I know my answer is 7 years late, but here's my suggestion anyway:

When Access complains about an UPDATE query that includes a JOIN, just save the query, with RecordsetType property set to Dynaset (Inconsistent Updates).

This will sometimes allow the UPDATE to work.

Choose File Dialog

Was looking for a file/folder browser myself recently and decided to make a new explorer activity (Android library): https://github.com/vaal12/AndroidFileBrowser

Matching Test application https://github.com/vaal12/FileBrowserTestApplication- is a sample how to use.

Allows picking directories and files from phone file structure.

How to update attributes without validation

USE update_attribute instead of update_attributes

Updates a single attribute and saves the record without going through the normal validation procedure.

if a.update_attribute('state', a.state)

Note:- 'update_attribute' update only one attribute at a time from the code given in question i think it will work for you.

How do I parallelize a simple Python loop?

Dask futures; I'm surprised no one has mentioned it yet . . .

from dask.distributed import Client

client = Client(n_workers=8) # In this example I have 8 cores and processes (can also use threads if desired)

def my_function(i):
    output = <code to execute in the for loop here>
    return output

futures = []

for i in <whatever you want to loop across here>:
    future = client.submit(my_function, i)
    futures.append(future)

results = client.gather(futures)
client.close()

Set color of TextView span in Android

String text = "I don't like Hasina.";
textView.setText(spannableString(text, 8, 14));

private SpannableString spannableString(String text, int start, int end) {
    SpannableString spannableString = new SpannableString(text);
    ColorStateList redColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{0xffa10901});
    TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, redColor, null);

    spannableString.setSpan(highlightSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannableString.setSpan(new BackgroundColorSpan(0xFFFCFF48), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannableString.setSpan(new RelativeSizeSpan(1.5f), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

    return spannableString;
}

Output:

enter image description here

How do I call an Angular 2 pipe with multiple arguments?

You're missing the actual pipe.

{{ myData | date:'fullDate' }}

Multiple parameters can be separated by a colon (:).

{{ myData | myPipe:'arg1':'arg2':'arg3' }}

Also you can chain pipes, like so:

{{ myData | date:'fullDate' | myPipe:'arg1':'arg2':'arg3' }}

Overflow-x:hidden doesn't prevent content from overflowing in mobile browsers

try

html, body {
  overflow-x:hidden 
} 

instead of just

body {
  overflow-x:hidden 
}

Always show vertical scrollbar in <select>

It will work in IE7. But here you need to fixed the size less than the number of option and not use overflow-y:scroll. In your example you have 2 option but you set size=10, which will not work.

Suppose your select has 10 option, then fixed size=9.

Here, in your code reference you used height:100px with size:2. I remove the height css, because its not necessary and change the size:5 and it works fine.

Here is your modified code from jsfiddle:

<select size="5" style="width:100px;">
 <option>1</option>
 <option>2</option>
 <option>3</option>
 <option>4</option>
 <option>5</option>
 <option>6</option>
</select>

this will generate a larger select box than size:2 create.In case of small size the select box will not display the scrollbar,you have to check with appropriate size quantity.Without scrollbar it will work if click on the upper and lower icons of scrollbar.I show both example in your fiddle with size:2 and size greater than 2(e.g: 3,5).

Here is your desired result. I think this will help you:

CSS

  .wrapper{
    border: 1px dashed red;
    height: 150px;
    overflow-x: hidden;
    overflow-y: scroll;
    width: 150px;
 }
 .wrapper .selection{
   width:150px;
   border:1px solid #ccc
 }

HTML

<div class="wrapper">
<select size="15" class="selection">
    <option>Item 1</option>
    <option>Item 2</option>
    <option>Item 3</option>
</select>
</div>

What does the term "canonical form" or "canonical representation" in Java mean?

I believe there are two related uses of canonical: forms and instances.

A canonical form means that values of a particular type of resource can be described or represented in multiple ways, and one of those ways is chosen as the favored canonical form. (That form is canonized, like books that made it into the bible, and the other forms are not.) A classic example of a canonical form is paths in a hierarchical file system, where a single file can be referenced in a number of ways:

myFile.txt                                   # in current working dir
../conf/myFile.txt                           # relative to the CWD
/apps/tomcat/conf/myFile.txt                 # absolute path using symbolic links
/u1/local/apps/tomcat-5.5.1/conf/myFile.txt  # absolute path with no symlinks

The classic definition of the canonical representation of that file would be the last path. With local or relative paths you cannot globally identify the resource without contextual information. With absolute paths you can identify the resource, but cannot tell if two paths refer to the same entity. With two or more paths converted to their canonical forms, you can do all the above, plus determine if two resources are the same or not, if that is important to your application (solve the aliasing problem).

Note that the canonical form of a resource is not a quality of that particular form itself; there can be multiple possible canonical forms for a given type like file paths (say, lexicographically first of all possible absolute paths). One form is just selected as the canonical form for a particular application reason, or maybe arbitrarily so that everyone speaks the same language.

Forcing objects into their canonical instances is the same basic idea, but instead of determining one "best" representation of a resource, it arbitrarily chooses one instance of a class of instances with the same "content" as the canonical reference, then converts all references to equivalent objects to use the one canonical instance.

This can be used as a technique for optimizing both time and space. If there are multiple instances of equivalent objects in an application, then by forcing them all to be resolved as the single canonical instance of a particular value, you can eliminate all but one of each value, saving space and possibly time since you can now compare those values with reference identity (==) as opposed to object equivalence (equals() method).

A classic example of optimizing performance with canonical instances is collapsing strings with the same content. Calling String.intern() on two strings with the same character sequence is guaranteed to return the same canonical String object for that text. If you pass all your strings through that canonicalizer, you know equivalent strings are actually identical object references, i.e., aliases

The enum types in Java 5.0+ force all instances of a particular enum value to use the same canonical instance within a VM, even if the value is serialized and deserialized. That is why you can use if (day == Days.SUNDAY) with impunity in java if Days is an enum type. Doing this for your own classes is certainly possible, but takes care. Read Effective Java by Josh Bloch for details and advice.

How do I make a <div> move up and down when I'm scrolling the page?

Just for a more animated and cute solution:

$(window).scroll(function(){
  $("#div").stop().animate({"marginTop": ($(window).scrollTop()) + "px", "marginLeft":($(window).scrollLeft()) + "px"}, "slow" );
});

And a pen for those who want to see: http://codepen.io/think123/full/mAxlb, and fork: http://codepen.io/think123/pen/mAxlb

Update: and a non-animated jQuery solution:

$(window).scroll(function(){
  $("#div").css({"margin-top": ($(window).scrollTop()) + "px", "margin-left":($(window).scrollLeft()) + "px"});
});

Group by month and year in MySQL

This is how I do it:

GROUP BY  EXTRACT(YEAR_MONTH FROM t.summaryDateTime);

How do I get the XML root node with C#?

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(response.GetResponseStream());
string rootNode = XmlDoc.ChildNodes[0].Name;

jQuery UI - Close Dialog When Clicked Outside

Sorry to drag this up after so long but I used the below. Any disadvantages? See the open function...

$("#popup").dialog(
{
    height: 670,
    width: 680,
    modal: true,
    autoOpen: false,
    close: function(event, ui) { $('#wrap').show(); },
    open: function(event, ui) 
    { 
        $('.ui-widget-overlay').bind('click', function()
        { 
            $("#popup").dialog('close'); 
        }); 
    }
});

How can you debug a CORS request with cURL?

The bash script "corstest" below works for me. It is based on Jun's comment above.

usage

corstest [-v] url

examples

./corstest https://api.coindesk.com/v1/bpi/currentprice.json
https://api.coindesk.com/v1/bpi/currentprice.json Access-Control-Allow-Origin: *

the positive result is displayed in green

./corstest https://github.com/IonicaBizau/jsonrequest
https://github.com/IonicaBizau/jsonrequest does not support CORS
you might want to visit https://enable-cors.org/ to find out how to enable CORS

the negative result is displayed in red and blue

the -v option will show the full curl headers

corstest

#!/bin/bash
# WF 2018-09-20
# https://stackoverflow.com/a/47609921/1497139

#ansi colors
#http://www.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html
blue='\033[0;34m'  
red='\033[0;31m'  
green='\033[0;32m' # '\e[1;32m' is too bright for white bg.
endColor='\033[0m'

#
# a colored message 
#   params:
#     1: l_color - the color of the message
#     2: l_msg - the message to display
#
color_msg() {
  local l_color="$1"
  local l_msg="$2"
  echo -e "${l_color}$l_msg${endColor}"
}


#
# show the usage
#
usage() {
  echo "usage: [-v] $0 url"
  echo "  -v |--verbose: show curl result" 
  exit 1 
}

if [ $# -lt 1 ]
then
  usage
fi

# commandline option
while [  "$1" != ""  ]
do
  url=$1
  shift

  # optionally show usage
  case $url in      
    -v|--verbose)
       verbose=true;
       ;;          
  esac
done  


if [ "$verbose" = "true" ]
then
  curl -s -X GET $url -H 'Cache-Control: no-cache' --head 
fi
origin=$(curl -s -X GET $url -H 'Cache-Control: no-cache' --head | grep -i access-control)


if [ $? -eq 0 ]
then
  color_msg $green "$url $origin"
else
  color_msg $red "$url does not support CORS"
  color_msg $blue "you might want to visit https://enable-cors.org/ to find out how to enable CORS"
fi

changing visibility using javascript

Use display instead of visibility. display: none for invisible and no setting for visible.

Splitting a continuous variable into equal sized groups

ntile from dplyr now does this but behaves weirdly with NA's.

I've used similar code in the following function that works in base R and does the equivalent of the cut2 solution above:

ntile_ <- function(x, n) {
    b <- x[!is.na(x)]
    q <- floor((n * (rank(b, ties.method = "first") - 1)/length(b)) + 1)
    d <- rep(NA, length(x))
    d[!is.na(x)] <- q
    return(d)
}

Remove final character from string

Simple:

st =  "abcdefghij"
st = st[:-1]

There is also another way that shows how it is done with steps:

list1 = "abcdefghij"
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)

This is also a way with user input:

list1 = input ("Enter :")
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)

To make it take away the last word in a list:

list1 = input("Enter :")
list2 = list1.split()
print(list2)
list3 = list2[:-1]
print(list3)

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status

Remove local git tags that are no longer on the remote repository

Show the difference between local and remote tags:

diff <(git tag | sort) <( git ls-remote --tags origin | cut -f2 | grep -v '\^' | sed 's#refs/tags/##' | sort)
  • git tag gives the list of local tags
  • git ls-remote --tags gives the list of full paths to remote tags
  • cut -f2 | grep -v '\^' | sed 's#refs/tags/##' parses out just the tag name from list of remote tag paths
  • Finally we sort each of the two lists and diff them

The lines starting with "< " are your local tags that are no longer in the remote repo. If they are few, you can remove them manually one by one, if they are many, you do more grep-ing and piping to automate it.