Programs & Examples On #Rss

Really Simple Syndication (RSS) is a family of web feed formats used to publish frequently updated works—such as blog entries, news headlines, audio, and video—in a standardized format.

preg_match(); - Unknown modifier '+'

You need to use delimiters with regexes in PHP. You can use the often used /, but PHP lets you use any matching characters, so @ and # are popular.

Further Reading.

If you are interpolating variables inside your regex, be sure to pass the delimiter you chose as the second argument to preg_quote().

How to parse an RSS feed using JavaScript?

If you are looking for a simple and free alternative to Google Feed API for your rss widget then could be a suitable solution for that.

You may try to see how it works on a sample code from the api documentation below:

google.load("feeds", "1");_x000D_
    function initialize() {_x000D_
      var feed = new google.feeds.Feed("");_x000D_
      feed.load(function(result) {_x000D_
        if (!result.error) {_x000D_
          var container = document.getElementById("feed");_x000D_
          for (var i = 0; i < result.feed.entries.length; i++) {_x000D_
            var entry = result.feed.entries[i];_x000D_
            var div = document.createElement("div");_x000D_
  <head>    _x000D_
     <script src=""></script>_x000D_
    <p><b>Result from the API:</b></p>_x000D_
    <div id="feed"></div>_x000D_

UEFA/FIFA scores API is free and useful. The API is in active development, stable and recently the first versioned release called alpha was put online. Check the blog section to follow updates and changes.

Best Way to read rss feed in .net Using C#

Use this :

private string GetAlbumRSS(SyndicationItem album)

        string url = "";
        foreach (SyndicationElementExtension ext in album.ElementExtensions)
            if (ext.OuterName == "itemRSS") url = ext.GetObject<string>();
        return (url);

    protected void Page_Load(object sender, EventArgs e)
        string albumRSS;
        string url = "";
        XmlReader r = XmlReader.Create(url);
        SyndicationFeed albums = SyndicationFeed.Load(r);
        foreach (SyndicationItem album in albums.Items)

            cell.InnerHtml = cell.InnerHtml +string.Format("<br \'><a href='{0}'>{1}</a>", album.Links[0].Uri, album.Title.Text);
            albumRSS = GetAlbumRSS(album);



Best way to parse RSS/Atom feeds with PHP

I've always used the SimpleXML functions built in to PHP to parse XML documents. It's one of the few generic parsers out there that has an intuitive structure to it, which makes it extremely easy to build a meaningful class for something specific like an RSS feed. Additionally, it will detect XML warnings and errors, and upon finding any you could simply run the source through something like HTML Tidy (as ceejayoz mentioned) to clean it up and attempt it again.

Consider this very rough, simple class using SimpleXML:

class BlogPost
    var $date;
    var $ts;
    var $link;

    var $title;
    var $text;

class BlogFeed
    var $posts = array();

    function __construct($file_or_url)
        $file_or_url = $this->resolveFile($file_or_url);
        if (!($x = simplexml_load_file($file_or_url)))

        foreach ($x->channel->item as $item)
            $post = new BlogPost();
            $post->date  = (string) $item->pubDate;
            $post->ts    = strtotime($item->pubDate);
            $post->link  = (string) $item->link;
            $post->title = (string) $item->title;
            $post->text  = (string) $item->description;

            // Create summary as a shortened body and remove images, 
            // extraneous line breaks, etc.
            $post->summary = $this->summarizeText($post->text);

            $this->posts[] = $post;

    private function resolveFile($file_or_url) {
        if (!preg_match('|^https?:|', $file_or_url))
            $feed_uri = $_SERVER['DOCUMENT_ROOT'] .'/shared/xml/'. $file_or_url;
            $feed_uri = $file_or_url;

        return $feed_uri;

    private function summarizeText($summary) {
        $summary = strip_tags($summary);

        // Truncate summary line to 100 characters
        $max_len = 100;
        if (strlen($summary) > $max_len)
            $summary = substr($summary, 0, $max_len) . '...';

        return $summary;

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

Parse RSS with jQuery

The jQuery-rss project is pretty lightweight and doesn't impose any particular styling.

The syntax can be as simple as


See a working example at

How to apply CSS to iframe?

I met this issue with Google Calendar. I wanted to style it on a darker background and change font.

Luckily, the URL from the embed code had no restriction on direct access, so by using PHP function file_get_contents it is possible to get the entire content from the page. Instead of calling the Google URL, it is possible to call a php file located on your server, ex. google.php, which will contain the original content with modifications:

$content = file_get_contents('');

Adding the path to your stylesheet:

$content = str_replace('</head>','<link rel="stylesheet" href="" /></head>', $content);

(This will place your stylesheet last just before the head end tag.)

Specify the base url form the original url in case css and js are called relatively:

$content = str_replace('</title>','</title><base href="" />', $content);

The final google.php file should look like this:

$content = file_get_contents('');
$content = str_replace('</title>','</title><base href="" />', $content);
$content = str_replace('</head>','<link rel="stylesheet" href="" /></head>', $content);
echo $content;

Then you change the iframe embed code to:

<iframe src="" style="border: 0" width="800" height="600" frameborder="0" scrolling="no"></iframe>

Good luck!

Reverse ip, find domain names on ip address

You can use nslookup on the IP. Reverse DNS is defined with the domain.



yields, and then you do:


this will ask and yield the domain name (if there is one defined for reverse DNS).

Resizing a button

Another alternative is that you are allowed to have multiple classes in a tag. Consider:

 <div class="button big">This is a big button</div>
 <div class="button small">This is a small button</div>

And the CSS:

 .button {
     /* all your common button styles */

 .big {
     height: 60px;
     width: 100px;
 .small {
     height: 40px;
     width: 70px;

and so on.

SQL Server : converting varchar to INT

I would try triming the number to see what you get:

select len(rtrim(ltrim(userid))) from audit

if that return the correct value then just do:

select convert(int, rtrim(ltrim(userid))) from audit

if that doesn't return the correct value then I would do a replace to remove the empty space:

 select convert(int, replace(userid, char(0), '')) from audit

How to JUnit test that two List<E> contain the same elements in the same order?

  • My answer about whether Iterables.elementsEqual is best choice:

Iterables.elementsEqual is enough to compare 2 Lists.

Iterables.elementsEqual is used in more general scenarios, It accepts more general types: Iterable. That is, you could even compare a List with a Set. (by iterate order, it is important)

Sure ArrayList and LinkedList define equals pretty good, you could call equals directly. While when you use a not well defined List, Iterables.elementsEqual is the best choice. One thing should be noticed: Iterables.elementsEqual does not accept null

  • To convert List to array: Iterables.toArray is easer.

  • For unit test, I recommend add empty list to your test case.

Jetty: HTTP ERROR: 503/ Service Unavailable

None of these answers worked for me.

I had to remove all deployed java web app:

  • Windows/Show View/Other...
  • Go the the Server folder and select "Servers"
  • Right-click on the J2EE Preview at localhost
  • Click to Add and Remove... Click Remove all

Then run the project on the server

The Error is gone!

You will have to stop the server before deploying another project because it will not be found by the server. Otherwise you will get a 404 error

Full examples of using pySerial package

import serial
ser = serial.Serial(0)  # open first serial port
print ser.portstr       # check which port was really used
ser.write("hello")      # write a string
ser.close()             # close port

use for more examples

Best way to detect Mac OS X or Windows computers with JavaScript or jQuery

It's as simple as that:

function isMacintosh() {
  return navigator.platform.indexOf('Mac') > -1

function isWindows() {
  return navigator.platform.indexOf('Win') > -1

You can do funny things then like:

var isMac = isMacintosh();
var isPC = !isMacintosh();

Calendar date to yyyy-MM-dd format in java

Your code is wrong. No point of parsing date and keep that as Date object.

You can format the calender date object when you want to display and keep that as a string.

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();             
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");          
String inActiveDate = null;
try {
    inActiveDate = format1.format(date);
    System.out.println(inActiveDate );
} catch (ParseException e1) {
    // TODO Auto-generated catch block

CFLAGS, CCFLAGS, CXXFLAGS - what exactly do these variables control?

As you noticed, these are Makefile {macros or variables}, not compiler options. They implement a set of conventions. (Macros is an old name for them, still used by some. GNU make doc calls them variables.)

The only reason that the names matter is the default make rules, visible via make -p, which use some of them.

If you write all your own rules, you get to pick all your own macro names.

In a vanilla gnu make, there's no such thing as CCFLAGS. There are CFLAGS, CPPFLAGS, and CXXFLAGS. CFLAGS for the C compiler, CXXFLAGS for C++, and CPPFLAGS for both.

Why is CPPFLAGS in both? Conventionally, it's the home of preprocessor flags (-D, -U) and both c and c++ use them. Now, the assumption that everyone wants the same define environment for c and c++ is perhaps questionable, but traditional.

P.S. As noted by James Moore, some projects use CPPFLAGS for flags to the C++ compiler, not flags to the C preprocessor. The Android NDK, for one huge example.

How to get HttpClient returning status code and response body?

You can avoid the BasicResponseHandler, but use the HttpResponse itself to get both status and response as a String.

HttpResponse response = httpClient.execute(get);

// Getting the status code.
int statusCode = response.getStatusLine().getStatusCode();

// Getting the response body.
String responseBody = EntityUtils.toString(response.getEntity());

jQuery - checkbox enable/disable

$(document).ready(function() {_x000D_
  $('#InventoryMasterError').click(function(event) { //on click_x000D_
    if (this.checked) { // check select status_x000D_
      $('.checkerror').each(function() { //loop through each checkbox_x000D_
        $('#selecctall').attr('disabled', 'disabled');_x000D_
    } else {_x000D_
      $('.checkerror').each(function() { //loop through each checkbox_x000D_
        $('#selecctall').removeAttr('disabled', 'disabled');_x000D_
$(document).ready(function() {_x000D_
  $('#selecctall').click(function(event) { //on click_x000D_
    if (this.checked) { // check select status_x000D_
      $('.checkbox1').each(function() { //loop through each checkbox_x000D_
        $('#InventoryMasterError').attr('disabled', 'disabled');_x000D_
    } else {_x000D_
      $('.checkbox1').each(function() { //loop through each checkbox_x000D_
        $('#InventoryMasterError').removeAttr('disabled', 'disabled');_x000D_
<script src=""></script>_x000D_
<input type="checkbox" id="selecctall" name="selecctall" value="All" />_x000D_
<input type="checkbox" name="data[InventoryMaster][error]" label="" value="error" id="InventoryMasterError" />_x000D_
<input type="checkbox" name="checkid[]" class="checkbox1" value="1" id="InventoryMasterId" />_x000D_
<input type="checkbox" name="checkid[]" class="checkbox1" value="2" id="InventoryMasterId" />

How to extract request http headers from a request using NodeJS connect

Check output of console.log(req) or console.log(req.headers);

Create zip file and ignore directory structure

Retain the parent directory so unzip doesn't spew files everywhere

When zipping directories, keeping the parent directory in the archive will help to avoid littering your current directory when you later unzip the archive file

So to avoid retaining all paths, and since you can't use -j and -r together ( you'll get an error ), you can do this instead:

cd path/to/parent/dir/;
zip -r ../ ../$(basename $PWD)
cd -;

The ../$(basename $PWD) is the magic that retains the parent directory.

So now unzip will give a folder containing all your files:

+-- file1
+-- file2
+-- dir1
¦   +-- file3
¦   +-- file4

Instead of littering the current directory with the unzipped files:

+-- file3
+-- file4

How to change maven logging level to display only warning and errors?


mvn validate clean install | egrep -v "(^\[INFO\])"


mvn validate clean install | egrep -v "(^\[INFO\]|^\[DEBUG\])"


mvn validate clean install | findstr /V /R "^\[INFO\] ^\[DEBUG\]"

MS Access VBA: Sending an email through Outlook

Add a reference to the Outlook object model in the Visual Basic editor. Then you can use the code below to send an email using outlook.

Sub sendOutlookEmail()
Dim oApp As Outlook.Application
Dim oMail As MailItem
Set oApp = CreateObject("Outlook.application")

Set oMail = oApp.CreateItem(olMailItem)
oMail.Body = "Body of the email"
oMail.Subject = "Test Subject"
oMail.To = "[email protected]"
Set oMail = Nothing
Set oApp = Nothing

End Sub

How can I detect the touch event of an UIImageView?

In practical terms, don't do that.

Instead add a button with Custom style (no button graphics unless you specify images) over the UIImageView. Then attach whatever methods you want called to that.

You can use that technique for many cases where you really want some area of the screen to act as a button instead of messing with the Touch stuff.

How to get browser width using JavaScript code?

var w = window.innerWidth;
var h = window.innerHeight;
var ow = window.outerWidth; //including toolbars and status bar etc.
var oh = window.outerHeight;

Both return integers and don't require jQuery. Cross-browser compatible.

I often find jQuery returns invalid values for width() and height()

How to change angular port from 4200 to any other

In angular.json:

"serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
          "browserTarget": "projectname:build",
          "port": 5000

I am using angular-cli. This worked for me.

The calling thread cannot access this object because a different thread owns it

You need to do it on the UI thread. Use:

Dispatcher.BeginInvoke(new Action(() => {GetGridData(null, 0)})); 

What causes imported Maven project in Eclipse to use Java 1.5 instead of Java 1.6 by default and how can I ensure it doesn't?

The m2eclipse plugin doesn't use Eclipse defaults, the m2eclipse plugin derives the settings from the POM. So if you want a Maven project to be configured to use Java 1.6 settings when imported under Eclipse, configure the maven-compiler-plugin appropriately, as I already suggested:


If your project is already imported, update the project configuration (right-click on the project then Maven V Update Project Configuration).

JQuery or JavaScript: How determine if shift key being pressed while clicking anchor tag hyperlink?

    $(document).on('keyup keydown', function(e){shifted = e.shiftKey} );

Install tkinter for Python

for python3 user, install python3-tk package by following command sudo apt-get install python3-tk

What does it mean with bug report captured in android tablet?

It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.

Edit: This is what the forums say:

By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.

To disable:

/system/bin/ must be deleted/renamed.

There should be a folder on your SD card called "bug reports".

Have a look at this thread:

And this one:

Downloading and unzipping a .zip file without writing to disk

I'd like to offer an updated Python 3 version of Vishal's excellent answer, which was using Python 2, along with some explanation of the adaptations / changes, which may have been already mentioned.

from io import BytesIO
from zipfile import ZipFile
import urllib.request
url = urllib.request.urlopen("")

with ZipFile(BytesIO( as my_zip_file:
    for contained_file in my_zip_file.namelist():
        # with open(("unzipped_and_read_" + contained_file + ".file"), "wb") as output:
        for line in
            # output.write(line)

Necessary changes:

  • There's no StringIO module in Python 3 (it's been moved to io.StringIO). Instead, I use io.BytesIO]2, because we will be handling a bytestream -- Docs, also this thread.
  • urlopen:


  • In Python 3, the printed output lines will look like so: b'some text'. This is expected, as they aren't strings - remember, we're reading a bytestream. Have a look at Dan04's excellent answer.

A few minor changes I made:

  • I use with ... as instead of zipfile = ... according to the Docs.
  • The script now uses .namelist() to cycle through all the files in the zip and print their contents.
  • I moved the creation of the ZipFile object into the with statement, although I'm not sure if that's better.
  • I added (and commented out) an option to write the bytestream to file (per file in the zip), in response to NumenorForLife's comment; it adds "unzipped_and_read_" to the beginning of the filename and a ".file" extension (I prefer not to use ".txt" for files with bytestrings). The indenting of the code will, of course, need to be adjusted if you want to use it.
    • Need to be careful here -- because we have a byte string, we use binary mode, so "wb"; I have a feeling that writing binary opens a can of worms anyway...
  • I am using an example file, the UN/LOCODE text archive:

What I didn't do:

  • NumenorForLife asked about saving the zip to disk. I'm not sure what he meant by it -- downloading the zip file? That's a different task; see Oleh Prypin's excellent answer.

Here's a way:

import urllib.request
import shutil

with urllib.request.urlopen("") as response, open("downloaded_file.pdf", 'w') as out_file:
    shutil.copyfileobj(response, out_file)

MySQL Query to select data from last week?

select id from tbname
where date between date_sub(now(),INTERVAL 1 WEEK) and now();

How to edit .csproj file

Here is my option to Edit the project file without the need to Unload the project:

  1. Open Solution Explorer and switch to folder view: enter image description here

  2. Navigate to the Project which you want to edit inside the Solution folders and right-click on it.

  3. Choose Open from the Context Menu. enter image description here

That is it!

You will see the *.csproj file opened inside Visual Studio Editor.
After you can switch back to a Solution/Project view (see step 1).

enter image description here

How to import existing Git repository into another?

This function will clone remote repo into local repo dir, after merging all commits will be saved, git log will be show the original commits and proper paths:

function git-add-repo
    dir="$(echo "$2" | sed 's/\/$//')"

    tmp="$(mktemp -d)"
    remote="$(echo "$tmp" | sed 's/\///g'| sed 's/\./_/g')"

    git clone "$repo" "$tmp"
    cd "$tmp"

    git filter-branch --index-filter '
        git ls-files -s |
        sed "s,\t,&'"$dir"'/," |
        GIT_INDEX_FILE="$" git update-index --index-info &&
        mv "$" "$GIT_INDEX_FILE"
    ' HEAD

    cd "$path"
    git remote add -f "$remote" "file://$tmp/.git"
    git pull "$remote/master"
    git merge --allow-unrelated-histories -m "Merge repo $repo into master" --edit "$remote/master"
    git remote remove "$remote"
    rm -rf "$tmp"

How to use:

cd current/package
git-add-repo dir/to/save

If make a little changes you can even move files/dirs of merged repo into different paths, for example:


tmp="$(mktemp -d)"
remote="$(echo "$tmp" | sed 's/\///g' | sed 's/\./_/g')"

git clone "$repo" "$tmp"
cd "$tmp"


function git-mv-store
    from="$(echo "$1" | sed 's/\./\\./')"
    to="$(echo "$2" | sed 's/\./\\./')"


# NOTICE! This paths used for example! Use yours instead!
git-mv-store 'public/index.php' 'public/admin.php'
git-mv-store 'public/data' 'public/x/_data'
git-mv-store 'public/.htaccess' '.htaccess'
git-mv-store 'core/config' 'config/config'
git-mv-store 'core/defines.php' 'defines/defines.php'
git-mv-store '' 'doc/'
git-mv-store '.gitignore' 'unneeded/.gitignore'

git filter-branch --index-filter '
    git ls-files -s |
    sed "'"$GIT_ADD_STORED"'" |
    GIT_INDEX_FILE="$" git update-index --index-info &&
    mv "$" "$GIT_INDEX_FILE"


cd "$path"
git remote add -f "$remote" "file://$tmp/.git"
git pull "$remote/master"
git merge --allow-unrelated-histories -m "Merge repo $repo into master" --edit "$remote/master"
git remote remove "$remote"
rm -rf "$tmp"

Paths replaces via sed, so make sure it moved in proper paths after merging.
The --allow-unrelated-histories parameter only exists since git >= 2.9.

Maven – Always download sources and javadocs

Not sure, but you should be able to do something by setting a default active profile in your settings.xml



What is a predicate in c#?

The following code can help you to understand some real world use of predicates (Combined with named iterators).

namespace Predicate
    class Person
        public int Age { get; set; }
    class Program
        static void Main(string[] args)
            foreach (Person person in OlderThan(18))

        static IEnumerable<Person> OlderThan(int age)
            Predicate<Person> isOld = x => x.Age > age;
            Person[] persons = { new Person { Age = 10 }, new Person { Age = 20 }, new Person { Age = 19 } };

            foreach (Person person in persons)
                if (isOld(person)) yield return person;

Beautiful way to remove GET-variables with PHP?

just use echo'd javascript to rid the URL of any variables with a self-submitting, blank form:

    if (isset($_GET['your_var'])){
    //blah blah blah code
    echo "<script type='text/javascript'>unsetter();</script>"; 

Then make this javascript function:

    function unsetter() {
    $('<form id = "unset" name = "unset" METHOD="GET"><input type="submit"></form>').appendTo('body');
    $( "#unset" ).submit();

Creating Scheduled Tasks

This works for me

It is nicely designed Fluent API.

//This will create Daily trigger to run every 10 minutes for a duration of 18 hours
SchedulerResponse response = WindowTaskScheduler
    .CreateTask("TaskName", "C:\\Test.bat")
    .RunDurationFor(new TimeSpan(18, 0, 0))
    .SetStartDate(new DateTime(2015, 8, 8))
    .SetStartTime(new TimeSpan(8, 0, 0))

How can I rename a project folder from within Visual Studio?

Note: This fix is for Visual Studio 2008, but it should work here.

  1. Using Windows Explorer, rename both the solution folders (the parent folder and the child folder) to the new solution name.
  2. Delete the .sln file located in the parent folder.
  3. In Visual Studio, select menu File ? Open Project.
  4. Drill into the new folder you just renamed and open the .csproj file (located in the child folder).
  5. Right-click the project name and rename it to what you want. (It should be the same name as the folder in step 1.)
  6. Select menu File ? Close Solution. A dialog will ask if you want to save changes to the .sln file. Click Yes.
  7. In the Save File As dialog, point to the newly renamed parent folder and click Save. (Note: Make sure the .sln file has the same name as the folder. It is not required, but it maintains consistency.)


Python, add items from txt file into a list

Names = []
for line in open('names.txt','r').readlines():

strip() cut spaces in before and after string...

Permission is only granted to system app

To ignore this error for one instance only, add the tools:ignore="ProtectedPermissions" attribute to your permission declaration. Here is an example:

<uses-permission android:name="android.permission.READ_PRIVILEGED_PHONE_STATE"
    tools:ignore="ProtectedPermissions" />

You have to add tools namespace in the manifest root element

<manifest xmlns:android=""

What is the most efficient/quickest way to loop through rows in VBA (excel)?

For Each is much faster than for I=1 to X, for some reason. Just try to go through the same dictionary,

once with for each Dkey in dDict,

and once with for Dkey = lbound(dDict.keys) to ubound(dDict.keys)

=>You will notice a huge difference, even though you are going through the same construct.

Replace Line Breaks in a String C#

Use the .Replace() method

Line.Replace("\n", "whatever you want to replace with");

Make Frequency Histogram for Factor Variables

The reason you are getting the unexpected result is that hist(...) calculates the distribution from a numeric vector. In your code, table(animalFactor) behaves like a numeric vector with three elements: 1, 3, 7. So hist(...) plots the number of 1's (1), the number of 3's (1), and the number of 7's (1). @Roland's solution is the simplest.

Here's a way to do this using ggplot:

ggp <- ggplot(data.frame(animals),aes(x=animals))
# counts
ggp + geom_histogram(fill="lightgreen")
# proportion
ggp + geom_histogram(fill="lightblue",aes(y=..count../sum(..count..)))

You would get precisely the same result using animalFactor instead of animals in the code above.

Android: Access child views from a ListView

A quick search of the docs for the ListView class has turned up getChildCount() and getChildAt() methods inherited from ViewGroup. Can you iterate through them using these? I'm not sure but it's worth a try.

Found it here

How can I revert a single file to a previous version?

Git doesn't think in terms of file versions. A version in git is a snapshot of the entire tree.

Given this, what you really want is a tree that has the latest content of most files, but with the contents of one file the same as it was 5 commits ago. This will take the form of a new commit on top of the old ones, and the latest version of the tree will have what you want.

I don't know if there's a one-liner that will revert a single file to the contents of 5 commits ago, but the lo-fi solution should work: checkout master~5, copy the file somewhere else, checkout master, copy the file back, then commit.

Controlling mouse with Python

Another option is to use the cross-platform AutoPy package. This package has two different options for moving the mouse:

This code snippet will instantly move the cursor to position (200,200):

import autopy

If you instead want the cursor to visibly move across the screen to a given location, you can use the smooth_move command:

import autopy

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

from Tools>>NuGet Package Manager>>Manage Package for solution update Newtonsoft.Json of all solutions to latest Version

Dynamically add event listener

Here's my workaround:

I created a library with Angular 6. I added a common component commonlib-header which is used like this in an external application.

Note the serviceReference which is the class (injected in the component constructor(public serviceReference: MyService) that uses the commonlib-header) that holds the stringFunctionName method:

    [logo]="{ src: 'assets/img/logo.svg', alt: 'Logo', href: '#' }"
    [buttons]="[{ index: 0, innerHtml: 'Button', class: 'btn btn-primary', onClick: [serviceReference, 'stringFunctionName', ['arg1','arg2','arg3']] }]">

The library component is programmed like this. The dynamic event is added in the onClick(fn: any) method:

export class HeaderComponent implements OnInit {

 _buttons: Array<NavItem> = []

  set buttons(buttons: Array<any>) {
    buttons.forEach(navItem => {
      let _navItem = new NavItem(navItem.href, navItem.innerHtml)

      _navItem.class = navItem.class

      _navItem.onClick = navItem.onClick // this is the array from the component @Input properties above

      this._buttons[navItem.index] = _navItem

  constructor() {}

  ngOnInit() {}

  onClick(fn: any){
    let ref = fn[0]
    let fnName = fn[1]
    let args = fn[2]

    ref[fnName].apply(ref, args)

The reusable header.component.html:

<div class="topbar-right">
  <button *ngFor="let btn of _buttons"
    class="{{ btn.class }}"
    [innerHTML]="btn.innerHtml | keepHtml"></button>

Make a number a percentage

The best solution, where en is the English locale:

fraction.toLocaleString("en", {style: "percent"})

Replace an element into a specific position of a vector

See an example here: eg.:

vector::iterator iterator1;

  iterator1= vec1.begin();
  vec1.insert ( iterator1+i , vec2[i] );

// This means that at position "i" from the beginning it will insert the value from vec2 from position i

Your first approach was replacing the values from vec1[i] with the values from vec2[i]

Calculating frames per second in a game


// Set the end and start times
var start = (new Date).getTime(), end, FPS;
  /* ...
   * the loop/block your want to watch
   * ...
end = (new Date).getTime();
// since the times are by millisecond, use 1000 (1000ms = 1s)
// then multiply the result by (MaxFPS / 1000)
// FPS = (1000 - (end - start)) * (MaxFPS / 1000)
FPS = Math.round((1000 - (end - start)) * (60 / 1000));

Easiest way to make lua script wait/pause/sleep/block for a few seconds?

You want  win.Sleep(milliseconds), methinks.

Yeah, you definitely don't want to do a busy-wait like you describe.

string.split - by multiple character delimiter

Another option:

Replace the string delimiter with a single character, then split on that character.

string input = "abc][rfd][5][,][.";
string[] parts1 = input.Replace("][","-").Split('-');

php Replacing multiple spaces with a single space

Use preg_replace() and instead of [ \t\n\r] use \s:

$output = preg_replace('!\s+!', ' ', $input);

From Regular Expression Basic Syntax Reference:

\d, \w and \s

Shorthand character classes matching digits, word characters (letters, digits, and underscores), and whitespace (spaces, tabs, and line breaks). Can be used inside and outside character classes.

Yii2 data provider default sorting

defaultOrder contain a array where key is a column name and value is a SORT_DESC or SORT_ASC that's why below code not working.

$dataProvider = new ActiveDataProvider([
        'query' => $query,
        'sort' => ['defaultOrder'=>'topic_order asc']

Correct Way

$dataProvider = new ActiveDataProvider([
    'query' => $query,
    'sort' => [
        'defaultOrder' => [
            'topic_order' => SORT_ASC,

Note: If a query already specifies the orderBy clause, the new ordering instructions given by end users (through the sort configuration) will be appended to the existing orderBy clause. Any existing limit and offset clauses will be overwritten by the pagination request from end users (through the pagination configuration).

You can detail learn from Yii2 Guide of Data Provider

Sorting By passing Sort object in query

 $sort = new Sort([
        'attributes' => [
            'name' => [
                'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
                'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
                'default' => SORT_DESC,
                'label' => 'Name',

    $models = Article::find()
        ->where(['status' => 1])

MongoDB: update every document on one field

Regardless of the version, for your example, the <update> is:

{  $set: { lastLookedAt: / 1000 }  }

However, depending on your version of MongoDB, the query will look different. Regardless of version, the key is that the empty condition {} will match any document. In the Mongo shell, or with any MongoDB client:

$version >= 3.2: {}, <update> )
  • {} is the condition (the empty condition matches any document)

3.2 > $version >= 2.2: {}, <update>, { multi: true } )
  • {} is the condition (the empty condition matches any document)
  • {multi: true} is the "update multiple documents" option

$version < 2.2: {}, <update>, false, true )
  • {} is the condition (the empty condition matches any document)
  • false is for the "upsert" parameter
  • true is for the "multi" parameter (update multiple records)

Python code to remove HTML tags from a string

global temp

temp =''

s = ' '

def remove_strings(text):

    global temp 

    if text == '':

        return temp

    start = text.find('<')

    end = text.find('>')

    if start == -1 and end == -1 :

        temp = temp + text

    return temp

newstring = text[end+1:]

fresh_start = newstring.find('<')

if newstring[:fresh_start] != '':

    temp += s+newstring[:fresh_start]


return temp

How to compile and run a C/C++ program on the Android system

You can compile your C programs with an ARM cross-compiler:

arm-linux-gnueabi-gcc -static -march=armv7-a test.c -o test

Then you can push your compiled binary file to somewhere (don't push it in to the SD card):

adb push test /data/local/tmp/test

How to iterate over arguments in a Bash script

Use "$@" to represent all the arguments:

for var in "$@"
    echo "$var"

This will iterate over each argument and print it out on a separate line. $@ behaves like $* except that when quoted the arguments are broken up properly if there are spaces in them:

sh 1 2 '3 4'
3 4

initialize a vector to zeros C++/C++11

Initializing a vector having struct, class or Union can be done this way

std::vector<SomeStruct> someStructVect(length);
memset(, 0, sizeof(SomeStruct)*length);

Rounding integer division (instead of truncating)

If you're dividing positive integers you can shift it up, do the division and then check the bit to the right of the real b0. In other words, 100/8 is 12.5 but would return 12. If you do (100<<1)/8, you can check b0 and then round up after you shift the result back down.

How to get the cookie value in website

FormsAuthentication.Decrypt takes the actual value of the cookie, not the name of it. You can get the cookie value like


and decrypt that.

Remove all child nodes from a parent?

You can use .empty(), like this:


From the docs:

Remove all child nodes of the set of matched elements from the DOM.

How to get a enum value from string in C#?

With some error handling...

uint key = 0;
string s = "HKEY_LOCAL_MACHINE";
   key = (uint)Enum.Parse(typeof(baseKey), s);
   //unknown string or s is null


You did the right thing by checking from query plans. But I have 100% confidence in version 2. It is faster when the number off records are on the very high side.

My database has around 1,000,000 records and this is exactly the scenario where the query plan shows the difference between both the queries. Further, instead of using a where clause, if you use it in the join itself, it makes the query faster :
SELECT p.Name, s.OrderQty
FROM Product p
INNER JOIN (SELECT ProductID, OrderQty FROM SalesOrderDetail) s on p.ProductID = s.ProductID WHERE p.isactive = 1

The better version of this query is :

SELECT p.Name, s.OrderQty
FROM Product p
INNER JOIN (SELECT ProductID, OrderQty FROM SalesOrderDetail) s on p.ProductID = s.ProductID AND p.isactive = 1

(Assuming isactive is a field in product table which represents the active/inactive products).

How to execute cmd commands via Java

Each of your exec calls creates a process. You second and third calls do not run in the same shell process you create in the first one. Try putting all commands in a bat script and running it in one call: rt.exec("cmd myfile.bat"); or similar

how to get the value of a textarea in jquery?

You don't need to use textarea#message

var message = $('textarea#message').val();

You can directly use

var message = $('#message').val();

Button text toggle in jquery

Use a custom ID if possible if you would like to apply the action to only that button.


<button class="pushDontpush">PUSH ME</button>


$("#pushDontpush").click(function() { 
    if ($(this).text() == "PUSH ME") { 
        $(this).text("DON'T PUSH ME"); 
    } else { 
        $(this).text("PUSH ME"); 

Working CodePen: Toggle text in button

Node.js: Python not found exception due to node-sass and node-gyp

Node-sass tries to download the binary for you platform when installing. Node 5 is supported by 3.8 If your Jenkins can't download the prebuilt binary, then you need to follow the platform requirements on Node-gyp README (Python2, VS or MSBuild, ...) If possible I'd suggest updating your Node to at least 6 since 5 isn't supported by Node anymore. If you want to upgrade to 8, you'll need to update node-sass to 4.5.3

Return value in a Bash function

Although bash has a return statement, the only thing you can specify with it is the function's own exit status (a value between 0 and 255, 0 meaning "success"). So return is not what you want.

You might want to convert your return statement to an echo statement - that way your function output could be captured using $() braces, which seems to be exactly what you want.

Here is an example:

function fun1(){
  echo 34

function fun2(){
  local res=$(fun1)
  echo $res

Another way to get the return value (if you just want to return an integer 0-255) is $?.

function fun1(){
  return 34

function fun2(){
  local res=$?
  echo $res

Also, note that you can use the return value to use boolean logic like fun1 || fun2 will only run fun2 if fun1 returns a non-0 value. The default return value is the exit value of the last statement executed within the function.

how to pass variable from shell script to sqlplus

You appear to have a heredoc containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING

or if BUILDING is $2 in your script:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2

If your file.sql had an exit at the end then it would be even simpler as you wouldn't need the heredoc:

sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2

In your SQL you can then refer to the position parameters using substitution variables:


The &1 will be replaced with the first value passed to the SQL script, BUILDING; because that is a string it still needs to be enclosed in quotes. You might want to set verify off to stop if showing you the substitutions in the output.

You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1, the second is &2, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING


sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2

If total_count is being passed to your shell script then just use its positional parameter, $4 or whatever. And your SQL would then be:

        ?s rdf:type :ProcessSpec .
        ?s ?p ?o

If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:

define MY_ALIAS = &1
define MY_MODEL = &2

        ?s rdf:type :ProcessSpec .
        ?s ?p ?o

From your separate question, maybe you just wanted:

        ?s rdf:type :ProcessSpec .
        ?s ?p ?o

... so the alias will be the same value you're querying on (the value in $2, or BUILDING in the original part of the answer). You can refer to a substitution variable as many times as you want.

That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:


If you set pages 0 and set heading off, your repeated calls might appear in a neat list. You might also need to set tab off and possibly use rpad('&1', 20) or similar to make that column always the same width. Or get the results as CSV with:

select '&1' ||','|| COUNT(*)

Depends what you're using the results for...

How to clear the canvas for redrawing

If you use clearRect only, if you have it in a form to submit your drawing, you'll get a submit instead the clearing, or maybe it can be cleared first and then upload a void drawing, so you'll need to add a preventDefault at the beggining of the function:

   function clearCanvas(canvas,ctx) {
        ctx.clearRect(0, 0, canvas.width, canvas.height);

<input type="button" value="Clear Sketchpad" id="clearbutton" onclick="clearCanvas(canvas,ctx);">

Hope it helps someone.

Using regular expression in css?

First of all, there are many, many ways of matching items within a HTML document. Start with this reference to see some of the available selectors/patterns which you can use to apply a style rule to an element(s).

Match all divs which are direct descendants of #main.

#main > div

Match all divs which are direct or indirect descendants of #main.

#main div

Match the first div which is a direct descendant of #sections.

#main > div:first-child

Match a div with a specific attribute.

#main > div[foo="bar"]

Get selected text from a drop-down list (select box) using jQuery

$("#DropDownID").val() will give the selected index value.

Bulk Insert Correctly Quoted CSV File in SQL Server

I know this is an old topic but this feature has now been implemented since SQL Server 2017. The parameter you're looking for is FIELDQUOTE= which defaults to '"'. See more on

Are there any worse sorting algorithms than Bogosort (a.k.a Monkey Sort)?

There's always the Bogobogosort (Bogoception!). It performs Bogosort on increasingly large subsets of the list, and then starts all over again if the list is ever not sorted.

for (int n=1; n<sizeof(list); ++n) {
  while (!isInOrder(list, 0, n)) {
    shuffle(list, 0, n);
  if (!isInOrder(list, 0, n+1)) { n=0; }

Efficient iteration with index in Scala

Some more ways to iterate:

scala>  xs.foreach (println) 

foreach, and similar, map, which would return something (the results of the function, which is, for println, Unit, so a List of Units)

scala> val lens = for (x <- xs) yield (x.length) 
lens: Array[Int] = Array(5, 6, 5)

work with the elements, not the index

scala> ("" /: xs) (_ + _) 
res21: java.lang.String = firstsecondthird


for(int i=0, j=0; i+j<100; i+=j*2, j+=i+2) {...}

can be done with recursion:

def ijIter (i: Int = 0, j: Int = 0, carry: Int = 0) : Int =
  if (i + j >= 100) carry else 
    ijIter (i+2*j, j+i+2, carry / 3 + 2 * i - 4 * j + 10) 

The carry-part is just some example, to do something with i and j. It needn't be an Int.

for simpler stuff, closer to usual for-loops:

scala> (1 until 4)
res43: scala.collection.immutable.Range with scala.collection.immutable.Range.ByOne = Range(1, 2, 3)

scala> (0 to 8 by 2)   
res44: scala.collection.immutable.Range = Range(0, 2, 4, 6, 8)

scala> (26 to 13 by -3)
res45: scala.collection.immutable.Range = Range(26, 23, 20, 17, 14)

or without order:

List (1, 3, 2, 5, 9, 7).foreach (print) 

How to get Chrome to allow mixed content?

Chrome 46 and newer should be showing mixed content without any warning, just without the green lock in address bar.

Source: Simplifying the Page Security Icon in Chrome at Google Online Security Blog.

Struct memory layout in C

It's implementation-specific, but in practice the rule (in the absence of #pragma pack or the like) is:

  • Struct members are stored in the order they are declared. (This is required by the C99 standard, as mentioned here earlier.)
  • If necessary, padding is added before each struct member, to ensure correct alignment.
  • Each primitive type T requires an alignment of sizeof(T) bytes.

So, given the following struct:

struct ST
   char ch1;
   short s;
   char ch2;
   long long ll;
   int i;
  • ch1 is at offset 0
  • a padding byte is inserted to align...
  • s at offset 2
  • ch2 is at offset 4, immediately after s
  • 3 padding bytes are inserted to align...
  • ll at offset 8
  • i is at offset 16, right after ll
  • 4 padding bytes are added at the end so that the overall struct is a multiple of 8 bytes. I checked this on a 64-bit system: 32-bit systems may allow structs to have 4-byte alignment.

So sizeof(ST) is 24.

It can be reduced to 16 bytes by rearranging the members to avoid padding:

struct ST
   long long ll; // @ 0
   int i;        // @ 8
   short s;      // @ 12
   char ch1;     // @ 14
   char ch2;     // @ 15
} ST;

Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cruncher *some file* failed, see logs

Ok, I just faced this problem and tried all of the steps mentioned above but didn't help. So what I did, I checked what image extension it was before I renamed it to .png. In my case it was .jpeg. So I renamed it back to .jpeg and kept the same original file in drawable. And bingo, it just worked fine.

So the solution is, use the file without changing extension, be it .png or .jpeg, keep it the original way.

Thought to share if it helps anyone. Thanks.

Check if file is already open

(The Q&A is about how to deal with Windows "open file" locks ... not how implement this kind of locking portably.)

This whole issue is fraught with portability issues and race conditions:

  • You could try to use FileLock, but it is not necessarily supported for your OS and/or filesystem.
  • It appears that on Windows you may be unable to use FileLock if another application has opened the file in a particular way.
  • Even if you did manage to use FileLock or something else, you've still got the problem that something may come in and open the file between you testing the file and doing the rename.

A simpler though non-portable solution is to just try the rename (or whatever it is you are trying to do) and diagnose the return value and / or any Java exceptions that arise due to opened files.


  1. If you use the Files API instead of the File API you will get more information in the event of a failure.

  2. On systems (e.g. Linux) where you are allowed to rename a locked or open file, you won't get any failure result or exceptions. The operation will just succeed. However, on such systems you generally don't need to worry if a file is already open, since the OS doesn't lock files on open.

Convert SVG image to PNG with PHP

That's funny you asked this, I just did this recently for my work's site and I was thinking I should write a tutorial... Here is how to do it with PHP/Imagick, which uses ImageMagick:

$usmap = '/path/to/blank/us-map.svg';
$im = new Imagick();
$svg = file_get_contents($usmap);

/*loop to color each state as needed, something like*/ 
$idColorArray = array(
     "AL" => "339966"
    ,"AK" => "0099FF"
    ,"WI" => "FF4B00"
    ,"WY" => "A3609B"

foreach($idColorArray as $state => $color){
//Where $color is a RRGGBB hex value
    $svg = preg_replace(
         '/id="'.$state.'" style="fill:#([0-9a-f]{6})/'
        , 'id="'.$state.'" style="fill:#'.$color
        , $svg


/*png settings*/
$im->resizeImage(720, 445, imagick::FILTER_LANCZOS, 1);  /*Optional, if you need to resize*/

$im->adaptiveResizeImage(720, 445); /*Optional, if you need to resize*/

$im->writeImage('/path/to/colored/us-map.png');/*(or .jpg)*/

the steps regex color replacement may vary depending on the svg path xml and how you id & color values are stored. If you don't want to store a file on the server, you can output the image as base 64 like

<?php echo '<img src="data:image/jpg;base64,' . base64_encode($im) . '"  />';?>

(before you use clear/destroy) but ie has issues with PNG as base64 so you'd probably have to output base64 as jpeg

you can see an example here I did for a former employer's sales territory map:


Finish: enter image description here


Since writing the above, I've come up with 2 improved techniques:

1) instead of a regex loop to change the fill on state , use CSS to make style rules like

<style type="text/css">
#Al, #NY, #NM{

and then you can do a single text replace to inject your css rules into the svg before proceeding with the imagick jpeg/png creation. If the colors don't change, check to make sure you don't have any inline fill styles in your path tags overriding the css.

2) If you don't have to actually create a jpeg/png image file (and don't need to support outdated browsers), you can manipulate the svg directly with jQuery. You can't access the svg paths when embedding the svg using img or object tags, so you'll have to directly include the svg xml in your webpage html like:

<?php echo file_get_contents('/path/to/blank/us-map.svg');?>

then changing the colors is as easy as:

<script type="text/javascript" src="/path/to/jquery.js"></script>
<script type="text/javascript">
    $('#CA').css('fill', 'blue');
    $('#NY').css('fill', '#ff0000');

Magento - Retrieve products with a specific attribute value

This is a follow up to my original question to help out others with the same problem. If you need to filter by an attribute, rather than manually looking up the id you can use the following code to retrieve all the id, value pairs for an attribute. The data is returned as an array with the attribute name as the key.

function getAttributeOptions($attributeName) {
    $product = Mage::getModel('catalog/product');
    $collection = Mage::getResourceModel('eav/entity_attribute_collection')
              ->addFieldToFilter('attribute_code', $attributeName);

    $_attribute = $collection->getFirstItem()->setEntity($product->getResource());
    $attribute_options  = $_attribute->getSource()->getAllOptions(false);
    foreach($attribute_options as $val) {
        $attrList[$val['label']] = $val['value'];

    return $attrList;

Here is a function you can use to get products by their attribute set id. Retrieved using the previous function.

function getProductsByAttributeSetId($attributeSetId) {
   $products = Mage::getModel('catalog/product')->getCollection();


   foreach($products as $val) {
     $productsArray[] = $val->getData();

  return $productsArray;

PHP - define constant inside a class

class Foo {
    const BAR = 'baz';

echo Foo::BAR;

This is the only way to make class constants. These constants are always globally accessible via Foo::BAR, but they're not accessible via just BAR.

To achieve a syntax like Foo::baz()->BAR, you would need to return an object from the function baz() of class Foo that has a property BAR. That's not a constant though. Any constant you define is always globally accessible from anywhere and can't be restricted to function call results.

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

It would be better to use jQuery,

$(document).ready(function() {
    $("a").css("cursor", "pointer");

and omit both href="#" and href="javascript:void(0)".

The anchor tag markup will be like

<a onclick="hello()">Hello</a>

Simple enough!

Check if value already exists within list of dictionaries?

Following works out for me.

    #!/usr/bin/env python
    a = [{ 'main_color': 'red', 'second_color':'blue'},
    { 'main_color': 'yellow', 'second_color':'green'},
    { 'main_color': 'yellow', 'second_color':'blue'}]

    found_event = next(
                lambda x: x['main_color'] == 'red',
      #return this dict when not found

    if found_event:

    $python  /tmp/x
    {'main_color': 'red', 'second_color': 'blue'}

java.util.NoSuchElementException - Scanner reading user input

The problem is

When a Scanner is closed, it will close its input source if the source implements the Closeable interface.

Thus scan.close() closes

To fix it you can make

Scanner scan static and do not close it in PromptCustomerQty. Code below works.

public static void main (String[] args) {   

// Create a customer
// Future proofing the possabiltiies of multiple customers
Customer customer = new Customer("Will");

// Create object for each Product
// (Name,Code,Description,Price)
// Initalize Qty at 0
Product Computer = new Product("Computer","PC1003","Basic Computer",399.99); 
Product Monitor = new Product("Monitor","MN1003","LCD Monitor",99.99);
Product Printer = new Product("Printer","PR1003x","Inkjet Printer",54.23);

// Define internal variables 
ArrayList<Product> ProductList = new ArrayList<Product>(); // List to store Products
String formatString = "%-15s %-10s %-20s %-10s %-10s %n"; // Default format for output

// Add objects to list

// Ask users for quantities 
PromptCustomerQty(customer, ProductList);

// Ask user for payment method

// Create the header
PrintHeader(customer, formatString);

// Create Body
PrintBody(ProductList, formatString);   

static Scanner scan;

public static void PromptCustomerQty(Customer customer, ArrayList<Product> ProductList)               {
// Initiate a Scanner
scan = new Scanner(;

// **** VARIABLES ****
int qty = 0;

// Greet Customer
System.out.println("Hello " + customer.getName());

// Loop through each item and ask for qty desired
for (Product p : ProductList) {

    do {
    // Ask user for qty
    System.out.println("How many would you like for product: " +;
    System.out.print("> ");

    // Get input and set qty for the object
    qty = scan.nextInt();

    while (qty < 0); // Validation

    p.setQty(qty); // Set qty for object
    qty = 0; // Reset count

// Cleanup


public static void PromptCustomerPayment (Customer customer) {
// Variables
String payment = "";

// Prompt User
do {
System.out.println("Would you like to pay in full? [Yes/No]");
System.out.print("> ");

payment =;

} while ((!payment.toLowerCase().equals("yes")) && (!payment.toLowerCase().equals("no")));

// Check/set result
if (payment.toLowerCase() == "yes") {
else {

On a side note, you shouldn't use == for String comparision, use .equals instead.

JPanel vs JFrame in Java

You should not extend the JFrame class unnecessarily (only if you are adding extra functionality to the JFrame class)


JFrame extends Component and Container.

It is a top level container used to represent the minimum requirements for a window. This includes Borders, resizability (is the JFrame resizeable?), title bar, controls (minimize/maximize allowed?), and event handlers for various Events like windowClose, windowOpened etc.


JPanel extends Component, Container and JComponent

It is a generic class used to group other Components together.

  • It is useful when working with LayoutManagers e.g. GridLayout f.i adding components to different JPanels which will then be added to the JFrame to create the gui. It will be more manageable in terms of Layout and re-usability.

  • It is also useful for when painting/drawing in Swing, you would override paintComponent(..) and of course have the full joys of double buffering.

A Swing GUI cannot exist without a top level container like (JWindow, Window, JFrame Frame or Applet), while it may exist without JPanels.

issue ORA-00001: unique constraint violated coming in INSERT/UPDATE

The error message will include the name of the constraint that was violated (there may be more than one unique constraint on a table). You can use that constraint name to identify the column(s) that the unique constraint is declared on

SELECT column_name, position
  FROM all_cons_columns
 WHERE constraint_name = <<name of constraint from the error message>>
   AND owner           = <<owner of the table>>
   AND table_name      = <<name of the table>>

Once you know what column(s) are affected, you can compare the data you're trying to INSERT or UPDATE against the data already in the table to determine why the constraint is being violated.

How can I return the current action in an ASP.NET MVC view?

I saw different answers and came up with a class helper:

using System;
using System.Web.Mvc;

namespace MyMvcApp.Helpers {
    public class LocationHelper {
        public static bool IsCurrentControllerAndAction(string controllerName, string actionName, ViewContext viewContext) {
            bool result = false;
            string normalizedControllerName = controllerName.EndsWith("Controller") ? controllerName : String.Format("{0}Controller", controllerName);

            if(viewContext == null) return false;
            if(String.IsNullOrEmpty(actionName)) return false;

            if (viewContext.Controller.GetType().Name.Equals(normalizedControllerName, StringComparison.InvariantCultureIgnoreCase) &&
                viewContext.Controller.ValueProvider.GetValue("action").AttemptedValue.Equals(actionName, StringComparison.InvariantCultureIgnoreCase)) {
                result = true;

            return result;

So in View (or master/layout) you can use it like so (Razor syntax):

            <div id="menucontainer">

                <ul id="menu">
                    <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("home", "index", ViewContext)) {
                        }>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("account","logon", ViewContext)) {
                        }>@Html.ActionLink("Logon", "Logon", "Account")</li>
                    <li @if(MyMvcApp.Helpers.LocationHelper.IsCurrentControllerAndAction("home","about", ViewContext)) {
                        }>@Html.ActionLink("About", "About", "Home")</li>


Hope it helps.

How to yum install Node.JS on Amazon Linux

I had Node.js 6.x installed and wanted to install Node.js 8.x.

Here's the commands I used (taken from Nodejs's site with a few extra steps to handle the yum cached data):

  1. sudo yum remove nodejs: Uninstall Node.js 6.x (I don't know if this was necessary or not)
  2. curl --silent --location | sudo bash -
  3. sudo yum clean all
  4. sudo yum makecache: Regenerate metadata cache (this wasn't in the docs, but yum kept trying to install Node.jx 6.x, unsuccessfully, until I issued these last two commands)
  5. sudo yum install nodejs: Install Node.js 8.x

KERNELBASE.dll Exception 0xe0434352 offset 0x000000000000a49d

0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.

There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.

I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException and Application.ThreadException, as appropriate.

How to handle-escape both single and double quotes in an SQL-Update statement

When SET QUOTED_IDENTIFIER is OFF, literal strings in expressions can be delimited by single or double quotation marks.

If a literal string is delimited by double quotation marks, the string can contain embedded single quotation marks, such as apostrophes.

How can I get name of element with jQuery?

You should use attr('name') like this


you should use an id selector, if you use a class selector you encounter problems because a collection is returned

Bootstrap 3 unable to display glyphicon properly

the icons and the css are now seperated out from bootstrap. here is a fiddle that is from another stackoverflow answer

@import url("//");

Bootstrap 3 Glyphicons CDN

Changing the image source using jQuery

One of the common mistakes people do when change the image source is not waiting for image load to do afterward actions like maturing image size etc. You will need to use jQuery .load() method to do stuff after image load.

$('yourimageselector').attr('src', 'newsrc').load(function(){
    this.width;   // Note: $(this).width() will not work for in memory images


Reason for editing:

Clearfix with twitter bootstrap

clearfix should contain the floating elements but in your html you have added clearfix only after floating right that is your pull-right so you should do like this:

<div class="clearfix">
  <div id="sidebar">
  <div id="main">
      <div class="pull-right">
  <div>MOVED BELOW Z</div>

see this demo

Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden; as you have done in your main.

C# binary literals

Basically, I think the answer is NO, there is no easy way. Use decimal or hexadecimal constants - they are simple and clear. @RoyTinkers answer is also good - use a comment.

int someHexFlag = 0x010; // 000000010000
int someDecFlag = 8;     // 000000001000

The others answers here present several useful work-a rounds, but I think they aren't better then the simple answer. C# language designers probably considered a '0b' prefix unnecessary. HEX is easy to convert to binary, and most programmers are going to have to know the DEC equivalents of 0-8 anyways.

Also, when examining values in the debugger, they will be displayed has HEX or DEC.

How to know Laravel version and where is it defined?

In your Laravel deployment it would be


to see who changed your Laravel version look at what's defined in composer.json. If you have "laravel/framework": "5.4.*", then it will update to the latest after composer update is run. Composer.lock is the file that results from running a composer update, so really see who last one to modify the composer.json file was (hopefully you have that in version control). You can read more about it here

CSS container div not getting height

You are floating the children which means they "float" in front of the container. In order to take the correct height, you must "clear" the float

The div style="clear: both" clears the floating an gives the correct height to the container. see for more info on floats.


<div class="c">
    <div class="l">

    <div class="m">
    <div style="clear: both" />

How to calculate the sentence similarity using word2vec model of gensim with python

I would like to update the existing solution to help the people who are going to calculate the semantic similarity of sentences.

Step 1:

Load the suitable model using gensim and calculate the word vectors for words in the sentence and store them as a word list

Step 2 : Computing the sentence vector

The calculation of semantic similarity between sentences was difficult before but recently a paper named "A SIMPLE BUT TOUGH-TO-BEAT BASELINE FOR SENTENCE EMBEDDINGS" was proposed which suggests a simple approach by computing the weighted average of word vectors in the sentence and then remove the projections of the average vectors on their first principal component.Here the weight of a word w is a/(a + p(w)) with a being a parameter and p(w) the (estimated) word frequency called smooth inverse frequency.this method performing significantly better.

A simple code to calculate the sentence vector using SIF(smooth inverse frequency) the method proposed in the paper has been given here

Step 3: using sklearn cosine_similarity load two vectors for the sentences and compute the similarity.

This is the most simple and efficient method to compute the sentence similarity.

Setting unique Constraint with fluent API?

On EF6.2, you can use HasIndex() to add indexes for migration through fluent API.


    .HasIndex(u => u.Email)

On EF6.1 onwards, you can use IndexAnnotation() to add indexes for migration in your fluent API.

You must add reference to:

using System.Data.Entity.Infrastructure.Annotations;

Basic Example

Here is a simple usage, adding an index on the User.FirstName property

    .Property(t => t.FirstName) 
    .HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute()));

Practical Example:

Here is a more realistic example. It adds a unique index on multiple properties: User.FirstName and User.LastName, with an index name "IX_FirstNameLastName"

    .Property(t => t.FirstName) 
        new IndexAnnotation(
            new IndexAttribute("IX_FirstNameLastName", 1) { IsUnique = true }));

    .Property(t => t.LastName) 
        new IndexAnnotation(
            new IndexAttribute("IX_FirstNameLastName", 2) { IsUnique = true }));

bootstrap 3 tabs not working properly

In my case, I have two elements with the same id. I could not notice the cause of problem for a long time, because the first such element was hidden.

Drop shadow for PNG image in CSS

img {
  -webkit-filter: drop-shadow(5px 5px 5px #222222);
  filter: drop-shadow(5px 5px 5px #222222);

That worked great for me. One thing to note tho in IE you need the full color (#222222) three characters don't work.

Closing Excel Application Process in C# after Data Access

I met the same problems and tried many methods to solve it but doesn't work. Finally , I found the by my way. Some reference enter link description here

Hope my code can help someone future. I have been spent more than two days to solve it. Below is my Code:

//get current in useing excel
            Process[] excelProcsOld = Process.GetProcessesByName("EXCEL");
            Excel.Application myExcelApp = null;
            Excel.Workbooks excelWorkbookTemplate = null;
            Excel.Workbook excelWorkbook = null;
    //DO sth using myExcelApp , excelWorkbookTemplate, excelWorkbook
catch (Exception ex ){
                //Compare the EXCEL ID and Kill it 
                Process[] excelProcsNew = Process.GetProcessesByName("EXCEL");
                foreach (Process procNew in excelProcsNew)
                    int exist = 0;
                    foreach (Process procOld in excelProcsOld)
                        if (procNew.Id == procOld.Id)
                    if (exist == 0)

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

I have encountered this problem twice. First time I used VS 2013 and the second time I used VS 2015 with different solution. The first solution on VS 2013 and python 2.7 is:

  1. Click win+R
  3. Close all windows
  4. Enter pip install again

Now, one year later, I have found an easier method to fix it. This time I use VS 2015 and python 3.4.

  1. Right click on My Computer.
  2. Click Properties
  3. Advanced system settings
  4. Environment variables
  5. Add New system variable
  6. Enter VS100COMNTOOLSto the variable name
  7. Enter the value of VS140COMNTOOLSto the new variable.
  8. Close all windows

Now I'm sure you will ask some question what is the VSXXXCOMNTOOLSand what should I do if I use VS2008 or other compiler.

There is a file python\Lib\distutils\, beginning on line 216 we see

def find_vcvarsall(version):
    """Find the vcvarsall.bat file
    At first it tries to find the productdir of VS 2010 in the registry. If
    that fails it falls back to the VS100COMNTOOLS env var.

It means that you must give the productdir of VS 2010 for it, so if you are using python 2.x and

  • Visual Studio 2010 (VS10):SET VS90COMNTOOLS=%VS100COMNTOOLS%
  • Visual Studio 2012 (VS11):SET VS90COMNTOOLS=%VS110COMNTOOLS%
  • Visual Studio 2013 (VS12):SET VS90COMNTOOLS=%VS120COMNTOOLS%
  • Visual Studio 2015 (VS15):SET VS90COMNTOOLS=%VS140COMNTOOLS%

or if you are using python 3.x and

  • Visual Studio 2010 (VS10):SET VS100COMNTOOLS=%VS100COMNTOOLS%
  • Visual Studio 2012 (VS11):SET VS100COMNTOOLS=%VS110COMNTOOLS%
  • Visual Studio 2013 (VS12):SET VS100COMNTOOLS=%VS120COMNTOOLS%
  • Visual Studio 2015 (VS15):SET VS100COMNTOOLS=%VS140COMNTOOLS%

And it's the same as adding a new system variable. See the second ways.

Update:Sometimes,it still doesn't work.Check your path,ensure that contains VSxxxCOMNTOOLS

How to get content body from a httpclient call?

The way you are using await/async is poor at best, and it makes it hard to follow. You are mixing await with Task'1.Result, which is just confusing. However, it looks like you are looking at a final task result, rather than the contents.

I've rewritten your function and function call, which should fix your issue:

async Task<string> GetResponseString(string text)
    var httpClient = new HttpClient();

    var parameters = new Dictionary<string, string>();
    parameters["text"] = text;

    var response = await httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters));
    var contents = await response.Content.ReadAsStringAsync();

    return contents;

And your final function call:

Task<string> result = GetResponseString(text);
var finalResult = result.Result;

Or even better:

var finalResult = await GetResponseString(text);

JPA entity without id

I guess you can use @CollectionOfElements (for hibernate/jpa 1) / @ElementCollection (jpa 2) to map a collection of "entity properties" to a List in entity.

You can create the EntityProperty type and annotate it with @Embeddable

How to find specified name and its value in JSON-string from Java?

Use a JSON library to parse the string and retrieve the value.

The following very basic example uses the built-in JSON parser from Android.

String jsonString = "{ \"name\" : \"John\", \"age\" : \"20\", \"address\" : \"some address\" }";
JSONObject jsonObject = new JSONObject(jsonString);
int age = jsonObject.getInt("age");

More advanced JSON libraries, such as jackson, google-gson, json-io or genson, allow you to convert JSON objects to Java objects directly.

python capitalize first letter only

a one-liner: ' '.join(sub[:1].upper() + sub[1:] for sub in text.split(' '))

Finding element in XDocument?

You should use Root to refer to the root element:


If you want to find elements anywhere in the document use Descendants instead:


iPhone Safari Web App opens links in new window

I prefer to open all links inside the standalone web app mode except ones that have target="_blank". Using jQuery, of course.

$(document).on('click', 'a', function(e) {
    if ($(this).attr('target') !== '_blank') {
        window.location = $(this).attr('href');

What are the Differences Between "php artisan dump-autoload" and "composer dump-autoload"?

composer dump-autoload

PATH vendor/composer/autoload_classmap.php
  • Composer dump-autoload won’t download a thing.
  • It just regenerates the list of all classes that need to be included in the project (autoload_classmap.php).
  • Ideal for when you have a new class inside your project.
  • autoload_classmap.php also includes the providers in config/app.php

php artisan dump-autoload

  • It will call Composer with the optimize flag
  • It will 'recompile' loads of files creating the huge bootstrap/compiled.php

grep using a character vector with multiple patterns

Good answers, however don't forget about filter() from dplyr:

patterns <- c("A1", "A9", "A6")
  FirstName Letter
1      Alex     A1
2      Alex     A6
3      Alex     A7
4       Bob     A1
5     Chris     A9
6     Chris     A6

result <- filter(your_df, grepl(paste(patterns, collapse="|"), Letter))

  FirstName Letter
1      Alex     A1
2      Alex     A6
3       Bob     A1
4     Chris     A9
5     Chris     A6

How can I add additional PHP versions to MAMP

If you need to be able to switch between more than two versions at a time, you can use the following to change the version of PHP manually.

MAMP automatically rewrites the following line in your /Applications/MAMP/conf/apache/httpd.conf file when it restarts based on the settings in preferences. You can comment out this line and add the second one to the end of your file:

# Comment this out just under all the modules loaded
# LoadModule php5_module        /Applications/MAMP/bin/php/php5.x.x/modules/

At the bottom of the httpd.conf file, you'll see where additional configurations are loaded from the extra folder. Add this to the bottom of the httpd.conf file

# PHP Version Change
Include /Applications/MAMP/conf/apache/extra/httpd-php.conf

Then create a new file here: /Applications/MAMP/conf/apache/extra/httpd-php.conf

# Uncomment the version of PHP you want to run with MAMP
# LoadModule php5_module /Applications/MAMP/bin/php/php5.2.17/modules/
# LoadModule php5_module /Applications/MAMP/bin/php/php5.3.27/modules/
# LoadModule php5_module /Applications/MAMP/bin/php/php5.4.19/modules/
LoadModule php5_module /Applications/MAMP/bin/php/php5.5.3/modules/

After you have this setup, just uncomment the version of PHP you want to use and restart the servers!

How to convert all tables in database to one collation?

If you're using PhpMyAdmin, you can now:

  1. Select the database.
  2. Click the "Operations" tab.
  3. Under "Collation" section, select the desired collation.
  4. Click the "Change all tables collations" checkbox.
  5. A new "Change all tables columns collations" checkbox will appear.
  6. Click the "Change all tables columns collations" checkbox.
  7. Click the "Go" button.

I had over 250 tables to convert. It took a little over 5 minutes.

How to save a figure in MATLAB from the command line?

try plot(var); saveFigure('title'); it will save as a jpeg automatically

PHP, display image with Header()

Browsers make their best guess with the data they receive. This works for markup (which Websites often get wrong) and other media content. A program that receives a file can often figure out what its received regardless of the MIME content type it's been told.

This isn't something you should rely on however. It's recommended you always use the correct MIME content.

Adding a library/JAR to an Eclipse Android project

If you are using the ADT version 22, you need to check the android dependencies and android private libraries in the order&Export tab in the project build path

JNI converting jstring to char *

Here's a a couple of useful link that I found when I started with JNI

concerning your problem you can use this

JNIEXPORT void JNICALL Java_ClassName_MethodName(JNIEnv *env, jobject obj, jstring javaString)   
   const char *nativeString = env->GetStringUTFChars(javaString, 0);

   // use your string

   env->ReleaseStringUTFChars(javaString, nativeString);

Linking static libraries to other static libraries

Alternatively to Link Library Dependencies in project properties there is another way to link libraries in Visual Studio.

  1. Open the project of the library (X) that you want to be combined with other libraries.
  2. Add the other libraries you want combined with X (Right Click, Add Existing Item...).
  3. Go to their properties and make sure Item Type is Library

This will include the other libraries in X as if you ran

lib /out:X.lib X.lib other1.lib other2.lib

How can I remove a child node in HTML using JavaScript?

You have to remove any event handlers you've set on the node before you remove it, to avoid memory leaks in IE

Sublime Text 2: How do I change the color that the row number is highlighted? seems pretty nice.

On the mac, the default theme files are in ~/Library/Application\ Support/Sublime\ Text\ 2/Packages/Color\ Scheme\ -\ Default

On Win7, the default theme files are in %appdata%\Sublime Text 2\Packages\Color Scheme - Default

How many threads is too many?

As Pax rightly said, measure, don't guess. That what I did for DNSwitness and the results were suprising: the ideal number of threads was much higher than I thought, something like 15,000 threads to get the fastest results.

Of course, it depends on many things, that's why you must measure yourself.

Complete measures (in French only) in Combien de fils d'exécution ?.

OpenCV in Android Studio

In your build.gradle

repositories {

implementation 'com.quickbirdstudios:opencv:4.1.0'

More information

Disable Chrome strict MIME type checking

In case you are using node.js (with express)

If you want to serve static files in node.js, you need to use a function. Add the following code to your js file:


Where app is:

const express = require("express");
const app = express();

Then create a folder called public in you project folder. (You could call it something else, this is just good practice but remember to change it from the function as well.)

Then in this file create another folder named css (and/or images file under css if you want to serve static images as well.) then add your css files to this folder.

After you add them change the stylesheet accordingly. For example if it was:




Make them:


That should work

Why does range(start, end) not include end?

It's also useful for splitting ranges; range(a,b) can be split into range(a, x) and range(x, b), whereas with inclusive range you would write either x-1 or x+1. While you rarely need to split ranges, you do tend to split lists quite often, which is one of the reasons slicing a list l[a:b] includes the a-th element but not the b-th. Then range having the same property makes it nicely consistent.

Rendering an in React

Using Stateless Functional Component We will not be using this.state. Like this

               { return
                <tr key={key}>

bash: Bad Substitution

Not relevant to your example, but you can also get the Bad substitution error in Bash for any substitution syntax that Bash does not recognize. This could be:

  • Stray whitespace. E.g. bash -c '${x }'
  • A typo. E.g. bash -c '${x;-}'
  • A feature that was added in a later Bash version. E.g. bash -c '${x@Q}' before Bash 4.4.

If you have multiple substitutions in the same expression, Bash may not be very helpful in pinpointing the problematic expression. E.g.:

$ bash -c '"${x } multiline string
bash: line 1: ${x } multiline string
$y: bad substitution

Android: How to programmatically access the device serial number shown in the AVD manager (API Version 8)

From Android P, defining the READ_PHONE_STATE permission in AndroidManifest only, will not work. We have to actually request for the permission. Below code works for me:

@RequiresApi(api = Build.VERSION_CODES.P)
protected void onCreate(Bundle savedInstanceState) {

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 101);

@RequiresApi(api = Build.VERSION_CODES.O)
protected void onResume() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
@RequiresApi(api = Build.VERSION_CODES.O)
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case 101:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
        } else {
            //not granted
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);

Add this permissions in AndroidManifest.xml

<uses-permission android:name = "android.permission.INTERNET"/>
<uses-permission android:name = "android.permission.READ_PHONE_STATE" />

Hope this helps.

Thank You, MJ

Display current date and time without punctuation

Without punctuation (as @Burusothman has mentioned):

current_date_time="`date +%Y%m%d%H%M%S`";
echo $current_date_time;



With punctuation:

current_date_time="`date "+%Y-%m-%d %H:%M:%S"`";
echo $current_date_time;


2017-01-15 07:25:33

Display a angular variable in my html page

In your template, you have access to all the variables that are members of the current $scope. So, tobedone should be $scope.tobedone, and then you can display it with {{tobedone}}, or [[tobedone]] in your case.

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

When creating the array, why not just skip over the 0s and save yourself the time of having to worry about them later? As mentioned above, arrays are not well-suited for deletion.

How to replace a string in an existing file in Perl?

None of the existing answers here has provided a complete example of how to do this from within a script (not a one-liner). Here is what I did:

rename($file, $file.'.bak');
open(IN, '<'.$file.'.bak') or die $!;
open(OUT, '>'.$file) or die $!;
    $_ =~ s/blue/red/g;
    print OUT $_;

Convert 24 Hour time to 12 Hour plus AM/PM indication Oracle SQL

For the 24-hour time, you need to use HH24 instead of HH.

For the 12-hour time, the AM/PM indicator is written as A.M. (if you want periods in the result) or AM (if you don't). For example:

SELECT invoice_date,
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
  FROM invoices

For more information on the format models you can use with TO_CHAR on a date, see

How to iterate over columns of pandas dataframe to run regression

Based on the accepted answer, if an index corresponding to each column is also desired:

for i, column in enumerate(df):
    print i, df[column]

The above df[column] type is Series, which can simply be converted into numpy ndarrays:

for i, column in enumerate(df):
    print i, np.asarray(df[column])

Wait for a void async method

The best solution is to use async Task. You should avoid async void for several reasons, one of which is composability.

If the method cannot be made to return Task (e.g., it's an event handler), then you can use SemaphoreSlim to have the method signal when it is about to exit. Consider doing this in a finally block.

Create an ArrayList with multiple object types?


   ArrayList<Object> list = new ArrayList <>();`     


 ArrayList arraylist = new ArrayList();

Git diff against a stash

See the most recent stash:

git stash show -p

See an arbitrary stash:

git stash show -p stash@{1}

From the git stash manpages:

By default, the command shows the diffstat, but it will accept any format known to git diff (e.g., git stash show -p stash@{1} to view the second most recent stash in patch form).

Hide element by class in pure Javascript

document.getElementsByClassName returns an HTMLCollection(an array-like object) of all elements matching the class name. The style property is defined for Element not for HTMLCollection. You should access the first element using the bracket(subscript) notation.

document.getElementsByClassName('appBanner')[0].style.visibility = 'hidden';

Updated jsFiddle

To change the style rules of all elements matching the class, using the Selectors API:

[]'.appBanner'), function (el) { = 'hidden';

If for...of is available:

for (let el of document.querySelectorAll('.appBanner')) = 'hidden';

Spring MVC - Why not able to use @RequestBody and @RequestParam together

It's too late to answer this question, but it could help for new readers, It seems version issues. I ran all these tests with spring 4.1.4 and found that the order of @RequestBody and @RequestParam doesn't matter.

  1. same as your result
  2. same as your result
  3. gave body= "name=abc", and name = "abc"
  4. Same as 3.
  5. body ="name=abc", name = "xyz,abc"
  6. same as 5.

Import Error: No module named numpy

For those using python 2.7, should try:

apt-get install -y python-numpy

Instead of pip install numpy

SQL query, if value is null then return 1

a) If you want 0 when value is null

SELECT isnull(PartNum,0) AS PartNumber, PartID

b) If you want 0 when value is null and otherwise 1

    ELSE 1
  END) AS PartNumber,

Questions every good Database/SQL developer should be able to answer

At our company, instead of asking a lot of SQL questions that anyone with a good memory can answer, we created a SQL Developers test. The test is designed to have the candidate put together a solid schema with normalization and RI considerations, check constraints etc. And then be able to create some queries to produce results sets we're looking for. They create all this against a brief design specification we give them. They are allowed to do this at home, and take as much time as they need (within reason).

Font Awesome icon inside text input element

You're right. :before and :after pseudo content is not intended to work on replaced content like img and input elements. Adding a wrapping element and declare a font-family is one of the possibilities, as is using a background image. Or maybe a html5 placeholder text fits your needs:

<input name="username" placeholder="&#61447;">

Browsers that don’t support the placeholder attribute will simply ignore it.


The before content selector selects the input: input[type="text"]:before. You should select the wrapper: .wrapper:before. See . I also added the placeholder suggestion where the wrapper is redundant.

.wrapper input[type="text"] {
    position: relative; 

input { font-family: 'FontAwesome'; } /* This is for the placeholder */

.wrapper:before {
    font-family: 'FontAwesome';
    position: relative;
    left: -5px;
    content: "\f007";

<p class="wrapper"><input placeholder="&#61447; Username"></p>


Font Awesome uses the Unicode Private Use Area (PUA) to store icons. Other characters are not present and fall back to the browser default. That should be the same as any other input. If you define a font on input elements, then supply the same font as fallback for situations where us use an icon. Like this:

input { font-family: 'FontAwesome', YourFont; }

How can I get a list of locally installed Python modules?

This will help

In terminal or IPython, type:



In [1]: import                      #import press-TAB
Display all 631 possibilities? (y or n)
ANSI                   audiodev               markupbase
AptUrl                 audioop                markupsafe
ArgImagePlugin         avahi                  marshal
BaseHTTPServer         axi                    math
Bastion                base64                 md5
BdfFontFile            bdb                    mhlib
BmpImagePlugin         binascii               mimetools
BufrStubImagePlugin    binhex                 mimetypes
CDDB                   bisect                 mimify
CDROM                  bonobo                 mmap
CGIHTTPServer          brlapi                 mmkeys
Canvas                 bsddb                  modulefinder
CommandNotFound        butterfly              multifile
ConfigParser           bz2                    multiprocessing
ContainerIO            cPickle                musicbrainz2
Cookie                 cProfile               mutagen
Crypto                 cStringIO              mutex
CurImagePlugin         cairo                  mx
DLFCN                  calendar               netrc
DcxImagePlugin         cdrom                  new
Dialog                 cgi                    nis
DiscID                 cgitb                  nntplib
DistUpgrade            checkbox               ntpath

JPQL IN clause: Java-Arrays (or Lists, Sets...)?

I had a problem with this kind of sql, I was giving empty list in IN clause(always check the list if it is not empty). Maybe my practice will help somebody.

jQuery select element in parent window

I came across the same problem but, as stated above, the accepted solution did not work for me.

If you're inside a frame or iframe element, an alternative solution is to use


Here's a quick explanation of the differences between window.opener, window.parent and

  • window.opener refers to the window that called ... ) to open the window from which it's called
  • window.parent refers to the parent of a window in a frame or iframe element

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

The way you import a .cer file into the trust store is the same way you'd import a .crt file from say an export from Firefox.

You do not have to put an alias and the password of the keystore, you can just type:

keytool -v -import -file somefile.crt  -alias somecrt -keystore my-cacerts

Preferably use the cacerts file that is already in your Java installation (jre\lib\security\cacerts) as it contains secure "popular" certificates.

Update regarding the differences of cer and crt (just to clarify) According to Apache with SSL - How to convert CER to CRT certificates? and user @Spawnrider

CER is a X.509 certificate in binary form, DER encoded.
CRT is a binary X.509 certificate, encapsulated in text (base-64) encoding.
It is not the same encoding.

JUnit 5: How to assert an exception is thrown?

Now Junit5 provides a way to assert the exceptions

You can test both general exceptions and customized exceptions

A general exception scenario:

public void validateParameters(Integer param ) {
    if (param == null) {
        throw new NullPointerException("Null parameters are not allowed");

@DisplayName("Test assert NullPointerException")
void testGeneralException(TestInfo testInfo) {
    final ExpectGeneralException generalEx = new ExpectGeneralException();

     NullPointerException exception = assertThrows(NullPointerException.class, () -> {
    assertEquals("Null parameters are not allowed", exception.getMessage());

You can find a sample to test CustomException here : assert exception code sample

public String constructErrorMessage(String... args) throws InvalidParameterCountException {
    if(args.length!=3) {
        throw new InvalidParameterCountException("Invalid parametercount: expected=3, passed="+args.length);
    }else {
        String message = "";
        for(String arg: args) {
            message += arg;
        return message;

@DisplayName("Test assert exception")
void testCustomException(TestInfo testInfo) {
    final ExpectCustomException expectEx = new ExpectCustomException();

     InvalidParameterCountException exception = assertThrows(InvalidParameterCountException.class, () -> {
            expectEx.constructErrorMessage("sample ","error");
    assertEquals("Invalid parametercount: expected=3, passed=2", exception.getMessage());

How can I search sub-folders using glob.glob module?

The glob2 package supports wild cards and is reasonably fast

code = '''
import glob2
timeit.timeit(code, number=1)

On my laptop it takes approximately 2 seconds to match >60,000 file paths.

How to name and retrieve a stash by name in git?

Use a small bash script to look up the number of the stash. Call it "gitapply":

if [[ -z "$NAME" ]]; then echo "usage: gitapply [name]"; exit; fi
git stash apply $(git stash list | grep "$NAME" | cut -d: -f1)


gitapply foo

...where foo is a substring of the name of the stash you want.

Copy tables from one database to another in SQL Server

On SQL Server? and on the same database server? Use three part naming.

INSERT INTO bar..tblFoobar( *fieldlist* )
SELECT *fieldlist* FROM foo..tblFoobar

This just moves the data. If you want to move the table definition (and other attributes such as permissions and indexes), you'll have to do something else.

How unique is UUID?

Here's a testing snippet for you to test it's uniquenes. inspired by @scalabl3's comment

Funny thing is, you could generate 2 in a row that were identical, of course at mind-boggling levels of coincidence, luck and divine intervention, yet despite the unfathomable odds, it's still possible! :D Yes, it won't happen. just saying for the amusement of thinking about that moment when you created a duplicate! Screenshot video! – scalabl3 Oct 20 '15 at 19:11

If you feel lucky, check the checkbox, it only checks the currently generated id's. If you wish a history check, leave it unchecked. Please note, you might run out of ram at some point if you leave it unchecked. I tried to make it cpu friendly so you can abort quickly when needed, just hit the run snippet button again or leave the page.

Math.log2 = Math.log2 || function(n){ return Math.log(n) / Math.log(2); }_x000D_
  Math.trueRandom = (function() {_x000D_
  var crypt = window.crypto || window.msCrypto;_x000D_
  if (crypt && crypt.getRandomValues) {_x000D_
      // if we have a crypto library, use it_x000D_
      var random = function(min, max) {_x000D_
          var rval = 0;_x000D_
          var range = max - min;_x000D_
          if (range < 2) {_x000D_
              return min;_x000D_
          var bits_needed = Math.ceil(Math.log2(range));_x000D_
          if (bits_needed > 53) {_x000D_
            throw new Exception("We cannot generate numbers larger than 53 bits.");_x000D_
          var bytes_needed = Math.ceil(bits_needed / 8);_x000D_
          var mask = Math.pow(2, bits_needed) - 1;_x000D_
          // 7776 -> (2^13 = 8192) -1 == 8191 or 0x00001111 11111111_x000D_
          // Create byte array and fill with N random numbers_x000D_
          var byteArray = new Uint8Array(bytes_needed);_x000D_
          var p = (bytes_needed - 1) * 8;_x000D_
          for(var i = 0; i < bytes_needed; i++ ) {_x000D_
              rval += byteArray[i] * Math.pow(2, p);_x000D_
              p -= 8;_x000D_
          // Use & to apply the mask and reduce the number of recursive lookups_x000D_
          rval = rval & mask;_x000D_
          if (rval >= range) {_x000D_
              // Integer out of acceptable range_x000D_
              return random(min, max);_x000D_
          // Return an integer that falls within the range_x000D_
          return min + rval;_x000D_
      return function() {_x000D_
          var r = random(0, 1000000000) / 1000000000;_x000D_
          return r;_x000D_
  } else {_x000D_
      // From
      // Johannes Baagøe <[email protected]>, 2010_x000D_
      function Mash() {_x000D_
          var n = 0xefc8249d;_x000D_
          var mash = function(data) {_x000D_
              data = data.toString();_x000D_
              for (var i = 0; i < data.length; i++) {_x000D_
                  n += data.charCodeAt(i);_x000D_
                  var h = 0.02519603282416938 * n;_x000D_
                  n = h >>> 0;_x000D_
                  h -= n;_x000D_
                  h *= n;_x000D_
                  n = h >>> 0;_x000D_
                  h -= n;_x000D_
                  n += h * 0x100000000; // 2^32_x000D_
              return (n >>> 0) * 2.3283064365386963e-10; // 2^-32_x000D_
          mash.version = 'Mash 0.9';_x000D_
          return mash;_x000D_
      // From
      function Alea() {_x000D_
          return (function(args) {_x000D_
              // Johannes Baagøe <[email protected]>, 2010_x000D_
              var s0 = 0;_x000D_
              var s1 = 0;_x000D_
              var s2 = 0;_x000D_
              var c = 1;_x000D_
              if (args.length == 0) {_x000D_
                  args = [+new Date()];_x000D_
              var mash = Mash();_x000D_
              s0 = mash(' ');_x000D_
              s1 = mash(' ');_x000D_
              s2 = mash(' ');_x000D_
              for (var i = 0; i < args.length; i++) {_x000D_
                  s0 -= mash(args[i]);_x000D_
                  if (s0 < 0) {_x000D_
                      s0 += 1;_x000D_
                  s1 -= mash(args[i]);_x000D_
                  if (s1 < 0) {_x000D_
                      s1 += 1;_x000D_
                  s2 -= mash(args[i]);_x000D_
                  if (s2 < 0) {_x000D_
                      s2 += 1;_x000D_
              mash = null;_x000D_
              var random = function() {_x000D_
                  var t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32_x000D_
                  s0 = s1;_x000D_
                  s1 = s2;_x000D_
                  return s2 = t - (c = t | 0);_x000D_
              random.uint32 = function() {_x000D_
                  return random() * 0x100000000; // 2^32_x000D_
              random.fract53 = function() {_x000D_
                  return random() +_x000D_
                      (random() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53_x000D_
              random.version = 'Alea 0.9';_x000D_
              random.args = args;_x000D_
              return random;_x000D_
      return Alea();_x000D_
Math.guid = function() {_x000D_
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c)    {_x000D_
      var r = Math.trueRandom() * 16 | 0,_x000D_
          v = c == 'x' ? r : (r & 0x3 | 0x8);_x000D_
      return v.toString(16);_x000D_
function logit(item1, item2) {_x000D_
    console.log("Do "+item1+" and "+item2+" equal? "+(item1 == item2 ? "OMG! take a screenshot and you'll be epic on the world of cryptography, buy a lottery ticket now!":"No they do not. shame. no fame")+ ", runs: "+window.numberofRuns);_x000D_
numberofRuns = 0;_x000D_
function test() {_x000D_
   var x = Math.guid();_x000D_
   var y = Math.guid();_x000D_
   var test = x == y || historyTest(x,y);_x000D_
   return test;_x000D_
historyArr = [];_x000D_
historyCount = 0;_x000D_
function historyTest(item1, item2) {_x000D_
    if(window.luckyDog) {_x000D_
       return false;_x000D_
    for(var i = historyCount; i > -1; i--) {_x000D_
        if(item1 == history[i]) {_x000D_
            return true;_x000D_
        if(item2 == history[i]) {_x000D_
            return true;_x000D_
    return false;_x000D_
luckyDog = false;_x000D_
document.body.onload = function() {_x000D_
document.getElementById('runit').onclick  = function() {_x000D_
window.luckyDog = document.getElementById('lucky').checked;_x000D_
var val = document.getElementById('input').value_x000D_
if(val.trim() == '0') {_x000D_
    var intervaltimer = window.setInterval(function() {_x000D_
         var test = window.test();_x000D_
         if(test) {_x000D_
else {_x000D_
   var num = parseInt(val);_x000D_
   if(num > 0) {_x000D_
        var intervaltimer = window.setInterval(function() {_x000D_
         var test = window.test();_x000D_
         if(num < 0 || test) {_x000D_
Please input how often the calulation should run. set to 0 for forever. Check the checkbox if you feel lucky.<BR/>_x000D_
<input type="text" value="0" id="input"><input type="checkbox" id="lucky"><button id="runit">Run</button><BR/>

is there a function in lodash to replace matched item

If you're looking for a way to immutably change the collection (as I was when I found your question), you might take a look at immutability-helper, a library forked from the original React util. In your case, you would accomplish what you mentioned via the following:

var update = require('immutability-helper')
var arr = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}]
var newArray = update(arr, { 0: { name: { $set: 'New Name' } } })
//=> [{id: 1, name: "New Name"}, {id:2, name:"Person 2"}]

Returning a boolean from a Bash function

Use the true or false commands immediately before your return, then return with no parameters. The return will automatically use the value of your last command.

Providing arguments to return is inconsistent, type specific and prone to error if you are not using 1 or 0. And as previous comments have stated, using 1 or 0 here is not the right way to approach this function.


function test_for_cat {
    if [ $1 = "cat" ];

for i in cat hat;
    echo "${i}:"
    if test_for_cat "${i}";
        echo "- True"
        echo "- False"


$ bash

- True
- False

type object 'datetime.datetime' has no attribute 'datetime'

I run into the same error maybe you have already imported the module by using only import datetime so change form datetime import datetime to only import datetime. It worked for me after I changed it back.

Check if value exists in enum in TypeScript

According to sandersn the best way to do this would be:

Object.values(MESSAGE_TYPE).includes(type as MESSAGE_TYPE)

The term 'ng' is not recognized as the name of a cmdlet

I ran the 'ng serve' command in the command prompt. It compiled the project successfully. Then whatever changes are saved in VS Code, are automatically refreshed in the browser.

PS: I have installed angular globally.

An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll

I had this issue when i refereed a library project from a console application, and the library project was using a nuget package which is not refereed in the console application. Referring the same package in the console application helped to resolve this issue.

Seeing the Inner exception can help.

Changing Background Image with CSS3 Animations

This is really fast and dirty, but it gets the job done: jsFiddle

    #img1, #img2, #img3, #img4 {
    animation-name: test;
    animation-duration: 5s;
#img2 {
#img3 {
#img4 {

@-webkit-keyframes test {
    0% {
        opacity: 0;
    50% {
        opacity: 1;
    100% {
@keyframes test {
    0% {
        opacity: 0;
    50% {
        opacity: 1;
    100% {

I'm working on something similar for my site using jQuery, but the transition is triggered when the user scrolls down the page - jsFiddle

PHP check if date between two dates

You cannot compare date-strings. It is good habit to use PHP's DateTime object instead:

$paymentDate = new DateTime(); // Today
echo $paymentDate->format('d/m/Y'); // echos today! 
$contractDateBegin = new DateTime('2001-01-01');
$contractDateEnd  = new DateTime('2015-01-01');

if (
  $paymentDate->getTimestamp() > $contractDateBegin->getTimestamp() && 
  $paymentDate->getTimestamp() < $contractDateEnd->getTimestamp()){
  echo "is between";
   echo "NO GO!";  

How do I print output in new line in PL/SQL?

Most likely you need to use this trick:

dbms_output.put_line('Hi' || chr(10) || 
                     'good' || chr(10) || 
                     'morning' || chr(10) || 
                     'friends' || chr(10));

Pass props to parent component in React.js

Here is a simple 3 step ES6 implementation using function binding in the parent constructor. This is the first way the official react tutorial recommends (there is also public class fields syntax not covered here). You can find all of this information here

Binding Parent Functions so Children Can Call Them (And pass data up to the parent! :D )

  1. Make sure in the parent constructor you bind the function you created in the parent
  2. Pass the bound function down to the child as a prop (No lambda because we are passing a ref to function)
  3. Call the bound function from a child event (Lambda! We're calling the function when the event is fired. If we don't do this the function will automatically run on load and not be triggered on the event.)

Parent Function


Parent Constructor

this.handleFilterApply = this.handleFilterApply.bind(this);

Prop Passed to Child

onApplyClick = {this.handleFilterApply}

Child Event Call

onClick = {() => {props.onApplyClick(filterVals)}

convert datetime to date format dd/mm/yyyy

As everyone else said, but remember CultureInfo.InvariantCulture!

string s = dt.ToString("dd/M/yyyy", CultureInfo.InvariantCulture)

OR escape the '/'.

Adding +1 to a variable inside a function

Move points into test:

def test():
    points = 0
    addpoint = raw_input ("type ""add"" to add a point")

or use global statement, but it is bad practice. But better way it move points to parameters:

def test(points=0):
    addpoint = raw_input ("type ""add"" to add a point")

How can I set a dynamic model name in AngularJS?

To make the answer provided by @abourget more complete, the value of scopeValue[field] in the following line of code could be undefined. This would result in an error when setting subfield:

<textarea ng-model="scopeValue[field][subfield]"></textarea>

One way of solving this problem is by adding an attribute ng-focus="nullSafe(field)", so your code would look like the below:

<textarea ng-focus="nullSafe(field)" ng-model="scopeValue[field][subfield]"></textarea>

Then you define nullSafe( field ) in a controller like the below:

$scope.nullSafe = function ( field ) {
  if ( !$scope.scopeValue[field] ) {
    $scope.scopeValue[field] = {};

This would guarantee that scopeValue[field] is not undefined before setting any value to scopeValue[field][subfield].

Note: You can't use ng-change="nullSafe(field)" to achieve the same result because ng-change happens after the ng-model has been changed, which would throw an error if scopeValue[field] is undefined.

Android: show/hide a view using an animation

First of all get the height of the view yo want to saw and make a boolean to save if the view is showing:

int heigth=0;
boolean showing=false;
LinearLayout layout = (LinearLayout) view.findViewById(;

        proDetailsLL.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

            public void onGlobalLayout() {
                // gets called after layout has been done but before display
                // so we can get the height then hide the view

                proHeight = proDetailsLL.getHeight(); // Ahaha!  Gotcha

                proDetailsLL.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 0));

Then call the method for showing hide the view, and change the value of the boolean:

slideInOutAnimation(showing, heigth, layout);
proShowing = !proShowing;

The method:

     * Method to slide in out the layout
     * @param isShowing
     *            if the layout is showing
     * @param height
     *            the height to slide
     * @param slideLL
     *            the container to show
private void slideInOutAnimation(boolean isShowing, int height, final LinearLayout slideLL, final ImageView arroIV) {

        if (!isShowing) {
        Animation animIn = new Animation() {
        protected void applyTransformation(float interpolatedTime, Transformation t) {
                    super.applyTransformation(interpolatedTime, t);
        // Do relevant calculations here using the interpolatedTime that runs from 0 to 1
        slideLL.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int) (heigth * interpolatedTime)));

        } else {

            Animation animOut = new Animation() {
                protected void applyTransformation(float interpolatedTime, Transformation t) {
                    super.applyTransformation(interpolatedTime, t);
                    // Do relevant calculations here using the interpolatedTime that runs from 0 to 1

                        slideLL.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                                (int) (heigth * (1 - interpolatedTime))));




Convert any object to a byte[]

Using Encoding.UTF8.GetBytes is faster than using MemoryStream. Here, I am using NewtonsoftJson to convert input object to JSON string and then getting bytes from JSON string.

byte[] SerializeObject(object value) =>Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(value));

Benchmark for @Daniel DiPaolo's version with this version

Method                    |     Mean |     Error |    StdDev |   Median |  Gen 0 | Allocated |
ObjectToByteArray         | 4.983 us | 0.1183 us | 0.2622 us | 4.887 us | 0.9460 |    3.9 KB |
ObjectToByteArrayWithJson | 1.548 us | 0.0309 us | 0.0690 us | 1.528 us | 0.3090 |   1.27 KB |

if (select count(column) from table) > 0 then

You cannot directly use a SQL statement in a PL/SQL expression:

SQL> begin
  2     if (select count(*) from dual) >= 1 then
  3        null;
  4     end if;
  5  end;
  6  /
        if (select count(*) from dual) >= 1 then
ERROR at line 2:
ORA-06550: line 2, column 6:
PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:

You must use a variable instead:

SQL> set serveroutput on
SQL> declare
  2     v_count number;
  3  begin
  4     select count(*) into v_count from dual;
  6     if v_count >= 1 then
  7             dbms_output.put_line('Pass');
  8     end if;
  9  end;
 10  /

PL/SQL procedure successfully completed.

Of course, you may be able to do the whole thing in SQL:

update my_table
set x = y
where (select count(*) from other_table) >= 1;

It's difficult to prove that something is not possible. Other than the simple test case above, you can look at the syntax diagram for the IF statement; you won't see a SELECT statement in any of the branches.

Selecting data frame rows based on partial string match in a column

LIKE should work in sqlite:

df <- data.frame(name = c('bob','robert','peter'),id=c(1,2,3))
sqldf("select * from df where name LIKE '%er%'")
    name id
1 robert  2
2  peter  3

cURL equivalent in Node.js?

You can try using POSTMAN Chrome app for your request and you can generate node js code from there

What is the best way to implement a "timer"?

It's not clear what type of application you're going to develop (desktop, web, console...)

The general answer, if you're developing Windows.Forms application, is use of

System.Windows.Forms.Timer class. The benefit of this is that it runs on UI thread, so it's simple just define it, subscribe to its Tick event and run your code on every 15 second.

If you do something else then windows forms (it's not clear from the question), you can choose System.Timers.Timer, but this one runs on other thread, so if you are going to act on some UI elements from the its Elapsed event, you have to manage it with "invoking" access.

Using an array from Observable Object with ngFor and Async Pipe Angular 2

I think what u r looking for is this

<article *ngFor="let news of (news$ | async)?.articles">
<h4 class="head">{{news.title}}</h4>
<div class="desc"> {{news.description}}</div>

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.testing.models.Account

When you use jackson to map from string to your concrete class, especially if you work with generic type. then this issue may happen because of different class loader. i met it one time with below scenarior:

Project B depend on Library A

in Library A:

public class DocSearchResponse<T> {
 private T data;

it has service to query data from external source, and use jackson to convert to concrete class

public class ServiceA<T>{
  private ObjectMapper mapper;
  private ClientDocSearch searchClient;

  public DocSearchResponse<T> query(Criteria criteria){
      String resultInString =;
      return convertJson(resultInString)

public DocSearchResponse<T> convertJson(String result){
     return mapper.readValue(result, new TypeReference<DocSearchResponse<T>>() {});

in Project B:

public class Account{
 private String name;
 //come with other attributes

and i use ServiceA from library to make query and as well convert data

public class ServiceAImpl extends ServiceA<Account> {

and make use of that

public class MakingAccountService {
    private ServiceA service;
    public void execute(Criteria criteria){
        DocSearchResponse<Account> result = service.query(criteria);
        Account acc = result.getData(); //  java.util.LinkedHashMap cannot be cast to com.testing.models.Account

it happen because from classloader of LibraryA, jackson can not load Account class, then just override method convertJson in Project B to let jackson do its job

public class ServiceAImpl extends ServiceA<Account> {
        public DocSearchResponse<T> convertJson(String result){
         return mapper.readValue(result, new TypeReference<DocSearchResponse<T>>() {});

How can I set a proxy server for gem?

In Addition to @Yifei answer. If you have special character like @, &, $

You have to go with percent-encode | encode the special characters. E.g. instead of this:

http://foo:B@[email protected]:80

you write this:

http://foo:B%[email protected]:80

So @ gets replaced with %40.

Android WSDL/SOAP service client

Android doesn't come with SOAP library. However, you can download 3rd party library here:

If you need help using it, you might find this thread helpful:
How to call a .NET Webservice from Android using KSOAP2?

How to get commit history for just one branch?

You can use a range to do that.

git log master..

If you've checked out your my_experiment branch. This will compare where master is at to HEAD (the tip of my_experiment).

How do you synchronise projects to GitHub with Android Studio?

Android Studio 3.0

I love how easy this is in Android Studio.

1. Enter your GitHub login info

In Android Studio go to File > Settings > Version Control > GitHub. Then enter your GitHub username and password. (You only have to do this step once. For future projects you can skip it.)

enter image description here

2. Share your project

With your Android Studio project open, go to VCS > Import into Version Control > Share Project on GitHub.

Then click Share and OK.

enter image description here

That's all!

How to get the full path of the file from a file input

You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:

In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file" field, ostensibly for backward compatibility reasons.

So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.

How to create a button programmatically?

You can add UIButton,UIlable and UITextfield programmatically in this way.

UIButton code

// var button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
let button = UIButton(type: .System) // let preferred over var here
button.frame = CGRectMake(100, 100, 100, 50)
button.backgroundColor = UIColor.greenColor()
button.setTitle("Button", forState: UIControlState.Normal)
button.addTarget(self, action: "Action:", forControlEvents: UIControlEvents.TouchUpInside)

UILabel Code

var label: UILabel = UILabel()
label.frame = CGRectMake(50, 50, 200, 21)
label.backgroundColor = UIColor.blackColor()
label.textColor = UIColor.whiteColor()
label.textAlignment = NSTextAlignment.Center
label.text = "test label"

UITextField code

var txtField: UITextField = UITextField()
txtField.frame = CGRectMake(50, 70, 200, 30)
txtField.backgroundColor = UIColor.grayColor()

Hope this is helpful for you.

How to detect DIV's dimension changed?

There is a very efficient method to determine if a element's size has been changed.

This library has a class ResizeSensor which can be used for resize detection.
It uses an event-based approach, so it's damn fast and doesn't waste CPU time.


new ResizeSensor(jQuery('#divId'), function(){ 
    console.log('content dimension changed');

Please do not use the jQuery onresize plugin as it uses setTimeout() in combination with reading the DOM clientHeight/clientWidth properties in a loop to check for changes.
This is incredible slow and inaccurate since it causes layout thrashing.

Disclosure: I am directly associated with this library.

Open File Dialog, One Filter for Multiple Excel Extensions?

Use a semicolon

OpenFileDialog of = new OpenFileDialog();
of.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";

Build Error - missing required architecture i386 in file

It just happened here to me as well. Thanks to a great partner we found the answer. Your Xcode may be pointing to the simulator ..change it to a IOS device instead ..built smooth after ....

add an onclick event to a div

Everythings works well. You can't use divtag.onclick, becease "onclick" attribute doesn't exist. You need first create this attribute by using .setAttribute(). Look on this . You should read documentations first before you start giving "-".

How to get cell value from DataGridView in VB.Net?

It is working for me


enter image description here

Render Partial View Using jQuery in ASP.NET MVC

I did it like this.


Details Method:

public IActionResult Details()

            return PartialView("Your Partial View");

'No JUnit tests found' in Eclipse

I had this problem too with JUnit 5.4.2. I use Eclipse 2019-09 with gradle 5.3.1.

So I had to add this two dependencies to build.gradle file with right configuration for it (testImplementation and testRuntimeOnly):

apply plugin: "java"

//enabled the Gradle’s native JUnit 5 support  
test {  
testImplementation  group: "org.junit.jupiter", name: "junit-jupiter-api", version: "${junitVer}"
testRuntimeOnly group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: "${junitVer}"

Automatically running a batch file as an administrator

CMD Itself does not have a function to run files as admin, but powershell does, and that powershell function can be exectuted through CMD with a certain command. Write it in command prompt to run the file you specified as admin.

powershell -command start-process -file yourfilename -verb runas

Hope it helped!

How to update a git clone --mirror?

See here: Git doesn't clone all branches on subsequent clones?

If you really want this by pulling branches instead of push --mirror, you can have a look here:

"fetch --all" in a git bare repository doesn't synchronize local branches to the remote ones

This answer provides detailed steps on how to achieve that relatively easily:

current/duration time of html5 video?

// Get the <video> element with id="myVideo"
var vid = document.getElementById("myVideo");

// Assign an ontimeupdate event to the <video> element, and execute a function if the current playback position has changed
vid.ontimeupdate = function() {myFunction()};

function myFunction() {
// Display the current position of the video in a <p> element with id="demo"
    document.getElementById("demo").innerHTML = vid.currentTime;

beyond top level package error in relative import

from package.A import foo

I think it's clearer than

import sys

Are complex expressions possible in ng-hide / ng-show?

ng-show / ng-hide accepts only boolean values.

For complex expressions it is good to use controller and scope to avoid complications.

Below one will work (It is not very complex expression)

ng-show="User=='admin' || User=='teacher'"

Here element will be shown in UI when any of the two condition return true (OR operation).

Like this you can use any expressions.

How to calculate a logistic sigmoid function in Python?

I feel many might be interested in free parameters to alter the shape of the sigmoid function. Second for many applications you want to use a mirrored sigmoid function. Third you might want to do a simple normalization for example the output values are between 0 and 1.


def normalized_sigmoid_fkt(a, b, x):
   Returns array of a horizontal mirrored normalized sigmoid function
   output between 0 and 1
   Function parameters a = center; b = width
   s= 1/(1+np.exp(b*(x-a)))
   return 1*(s-min(s))/(max(s)-min(s)) # normalize function to 0-1

And to draw and compare:

def draw_function_on_2x2_grid(x): 
    fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)

    ax1.plot(x, normalized_sigmoid_fkt( .5, 18, x))

    ax2.plot(x, normalized_sigmoid_fkt(0.518, 10.549, x))

    ax3.plot(x, normalized_sigmoid_fkt( .7, 11, x))

    ax4.plot(x, normalized_sigmoid_fkt( .2, 14, x))
    plt.suptitle('Different normalized (sigmoid) function',size=10 )

    return fig


x = np.linspace(0,1,100)
Travel_function = draw_function_on_2x2_grid(x)

Sigmoid functions graph

How to vertically align label and input in Bootstrap 3?

The problem is that your <label> is inside of an <h2> tag, and header tags have a margin set by the default stylesheet.

Rendering JSON in controller

You'll normally be returning JSON either because:

A) You are building part / all of your application as a Single Page Application (SPA) and you need your client-side JavaScript to be able to pull in additional data without fully reloading the page.


B) You are building an API that third parties will be consuming and you have decided to use JSON to serialize your data.

Or, possibly, you are eating your own dogfood and doing both

In both cases render :json => some_data will JSON-ify the provided data. The :callback key in the second example needs a bit more explaining (see below), but it is another variation on the same idea (returning data in a way that JavaScript can easily handle.)

Why :callback?

JSONP (the second example) is a way of getting around the Same Origin Policy that is part of every browser's built-in security. If you have your API at and you will be serving your application off of your JavaScript will not (by default) be able to make XMLHttpRequest (XHR - aka ajax) requests from services to api. The way people have been sneaking around that limitation (before the Cross-Origin Resource Sharing spec was finalized) is by sending the JSON data over from the server as if it was JavaScript instead of JSON). Thus, rather than sending back:

{"name": "John", "age": 45}

the server instead would send back:

valueOfCallbackHere({"name": "John", "age": 45})

Thus, a client-side JS application could create a script tag pointing at and have the valueOfCallbackHere function (which would have to be defined in the client-side JS) called with the data from this other origin.)

How can I permanently enable line numbers in IntelliJ?

IntelliJ 14 (Ubuntu):

See: how-do-i-turn-on-line-numbers-permanently-in-intellij-14


File > Settings > Editor > General > Appearance > show line numbers


For current Editor:

View > Active Editor > Show Line Numbers


Why should hash functions use a prime number modulus?

Suppose your table-size (or the number for modulo) is T = (B*C). Now if hash for your input is like (N*A*B) where N can be any integer, then your output won't be well distributed. Because every time n becomes C, 2C, 3C etc., your output will start repeating. i.e. your output will be distributed only in C positions. Note that C here is (T / HCF(table-size, hash)).

This problem can be eliminated by making HCF 1. Prime numbers are very good for that.

Another interesting thing is when T is 2^N. These will give output exactly same as all the lower N bits of input-hash. As every number can be represented powers of 2, when we will take modulo of any number with T, we will subtract all powers of 2 form number, which are >= N, hence always giving off number of specific pattern, dependent on the input. This is also a bad choice.

Similarly, T as 10^N is bad as well because of similar reasons (pattern in decimal notation of numbers instead of binary).

So, prime numbers tend to give a better distributed results, hence are good choice for table size.

Creating a Facebook share button with customized url, title and image

This is the code as 2017:

<i class="fa fa-facebook-square"></i>
<a href="#" onclick="''+encodeURIComponent(location.href),'facebook-share-dialog','width=626,height=436');return false;">Share on Facebook</a>

Facebook now takes all data from OG metatags.

NOTE: This code assumes you have OG metatags on in site's code.


Deleting queues in RabbitMQ

There is rabbitmqadmin which is nice to work from console.

If you ssh/log into server where you have rabbit installed, you can download it from:


and save it into /usr/local/bin/rabbitmqadmin

Then you can run

rabbitmqadmin -u {user} -p {password} -V {vhost} delete queue name={name}

Usually it requires sudo.

If you want to avoid typing your user name and password, you can use config

rabbitmqadmin -c /var/lib/rabbitmq/.rabbitmqadmin.conf -V {vhost} delete queue name={name}

All that under assumption that you have file ** /var/lib/rabbitmq/.rabbitmqadmin.conf** and have bare minumum

hostname = localhost
port = 15672
username = {user}
password = {password}

EDIT: As of comment from @user299709, it might be helpful to point out that user must be tagged as 'administrator' in rabbit. (

How should I have explained the difference between an Interface and an Abstract class?

You choose Interface in Java to avoid the Diamond Problem in multiple inheritance.

If you want all of your methods to be implemented by your client you go for interface. It means you design the entire application at abstract.

You choose abstract class if you already know what is in common. For example Take an abstract class Car. At higher level you implement the common car methods like calculateRPM(). It is a common method and you let the client implement his own behavior like
calculateMaxSpeed() etc. Probably you would have explained by giving few real time examples which you have encountered in your day to day job.

How to set the allowed url length for a nginx request (error code: 414, uri too large)


Syntax: large_client_header_buffers number size ;
Default: large_client_header_buffers 4 8k;
Context: http, server

Sets the maximum number and size of buffers used for reading large client request header. A request line cannot exceed the size of one buffer, or the 414 (Request-URI Too Large) error is returned to the client. A request header field cannot exceed the size of one buffer as well, or the 400 (Bad Request) error is returned to the client. Buffers are allocated only on demand. By default, the buffer size is equal to 8K bytes. If after the end of request processing a connection is transitioned into the keep-alive state, these buffers are released.

so you need to change the size parameter at the end of that line to something bigger for your needs.