Programs & Examples On #Message pump

CSS: styled a checkbox to look like a button, is there a hover?

it looks like you need a rule very similar to your checked rule

http://jsfiddle.net/VWBN4/3

#ck-button input:hover + span {
    background-color:#191;
    color:#fff;
}

and for hover and clicked state:

#ck-button input:checked:hover + span {
    background-color:#c11;
    color:#fff;
}

the order is important though.

Get Memory Usage in Android

Since the OP asked about CPU usage AND memory usage (accepted answer only shows technique to get cpu usage), I'd like to recommend the ActivityManager class and specifically the accepted answer from this question: How to get current memory usage in android?

How to debug Ruby scripts

To easily debug Ruby shell script, just change its first line from:

#!/usr/bin/env ruby

to:

#!/usr/bin/env ruby -rdebug

Then every time when debugger console is shown, you can choose:

  • c for Continue (to the next Exception, breakpoint or line with: debugger),
  • n for Next line,
  • w/where to Display frame/call stack,
  • l to Show the current code,
  • cat to show catchpoints.
  • h for more Help.

See also: Debugging with ruby-debug, Key shortcuts for ruby-debug gem.


In case the script just hangs and you need a backtrace, try using lldb/gdb like:

echo 'call (void)rb_backtrace()' | lldb -p $(pgrep -nf ruby)

and then check your process foreground.

Replace lldb with gdb if works better. Prefix with sudo to debug non-owned process.

Unexpected 'else' in "else" error

You need to rearrange your curly brackets. Your first statement is complete, so R interprets it as such and produces syntax errors on the other lines. Your code should look like:

if (dsnt<0.05) {
  wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else if (dst<0.05) {
  wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else {
  t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)       
} 

To put it more simply, if you have:

if(condition == TRUE) x <- TRUE
else x <- FALSE

Then R reads the first line and because it is complete, runs that in its entirety. When it gets to the next line, it goes "Else? Else what?" because it is a completely new statement. To have R interpret the else as part of the preceding if statement, you must have curly brackets to tell R that you aren't yet finished:

if(condition == TRUE) {x <- TRUE
 } else {x <- FALSE}

TypeScript error TS1005: ';' expected (II)

I had today a similar error message. What was peculiar is that it did not break the Application. It was running smoothly but the command prompt (Windows machine) indicated there was an error. I did not update the Typescript version but found another culprit. It turned there was a tiny omission of symbol - closing ")", which I believe The Typescript is compensating for. Just for reference the code is the following:

[new Object('First Characteristic','Second Characteristic',
'Third Characteristic'*] 

* notice here the ending ")" is missing.

Once brought back no more issues on the command prompt!

Download all stock symbol list of a market

Exchanges will usually publish an up-to-date list of securities on their web pages. For example, these pages offer CSV downloads:

NASDAQ Updated their site, so you will have to modify the URLS:

NASDAQ

AMEX

NYSE

Depending on your requirement, you could create the map of these URLs by exchange in your own code.

ContractFilter mismatch at the EndpointDispatcher exception

I had a similar error. This could be because you would have changed some contract setting on your config file after it was refrenced into you project. solution - Update the webservice reference on you VSstudio project or create a new proxy using svcutil.exe

What are the JavaScript KeyCodes?

I needed something like this for a game's control configuration UI, so I compiled a list for the standard US keyboard layout keycodes and mapped them to their respective key names.

Here's a fiddle that contains a map for code -> name and visi versa: http://jsfiddle.net/vWx8V/

If you want to support other key layouts you'll need to modify these maps to accommodate for them separately.

That is unless you were looking for a list of keycode values that included the control characters and other special values that are not (or are rarely) possible to input using a keyboard and may be outside of the scope of the keydown/keypress/keyup events of Javascript. Many of them are control characters or special characters like null (\0) and you most likely won't need them.

Notice that the number of keys on a full keyboard is less than many of the keycode values.

"Please try running this command again as Root/Administrator" error when trying to install LESS

I was getting this issue for instaling expo cli and I fixed by just following four steps mentioned in the npm documentation here.

Problem is some version of npm fail to locate folder for global installations of package. Following these steps we can create or modify the .profile file in Home directory of user and give it a proper PATH there so it works like a charm.

Try this it helped me and I spent around an hour for this issue. My node version was 6.0

Steps I follow

Back up your computer. On the command line, in your home directory, create a directory for global installations:

mkdir ~/.npm-global

Configure npm to use the new directory path:

npm config set prefix '~/.npm-global'

In your preferred text editor, open or create a ~/.profile file and add this line:

export PATH=~/.npm-global/bin:$PATH

On the command line, update your system variables:

source ~/.profile

To test your new configuration, install a package globally without using sudo:

npm install -g jshint

How can I create objects while adding them into a vector?

I know the thread is already all, but as I was checking through I've come up with a solution (code listed below). Hope it can help.

#include <iostream>
#include <vector>

class Box
{
    public:

    static int BoxesTotal;
    static int BoxesEver;
    int Id;

    Box()
    {
        ++BoxesTotal;
        ++BoxesEver;
        Id = BoxesEver;
        std::cout << "Box (" << Id << "/" << BoxesTotal << "/" << BoxesEver << ") initialized." << std::endl;
    }

    ~Box()
    {
        std::cout << "Box (" << Id << "/" << BoxesTotal << "/" << BoxesEver << ") ended." << std::endl;
        --BoxesTotal;
    }

};

int Box::BoxesTotal = 0;
int Box::BoxesEver = 0;

int main(int argc, char* argv[])
{
    std::cout << "Objects (Boxes) example." << std::endl;
    std::cout << "------------------------" << std::endl;

    std::vector <Box*> BoxesTab;

    Box* Indicator;
    for (int i = 1; i<4; ++i)
    {
        std::cout << "i = " << i << ":" << std::endl;
        Box* Indicator = new(Box);
        BoxesTab.push_back(Indicator);
        std::cout << "Adres Blowera: " <<  BoxesTab[i-1] << std::endl;
    }

    std::cout << "Summary" << std::endl;
    std::cout << "-------" << std::endl;
    for (int i=0; i<3; ++i)
    {
        std::cout << "Adres Blowera: " <<  BoxesTab[i] << std::endl;
    }

    std::cout << "Deleting" << std::endl;
    std::cout << "--------" << std::endl;
    for (int i=0; i<3; ++i)
    {
        std::cout << "Deleting Box: " << i+1 << " (" <<  BoxesTab[i] << ") " << std::endl;
        Indicator = (BoxesTab[i]);
        delete(Indicator);
    }

    return 0;
}

And the result it produces is:

Objects (Boxes) example.
------------------------
i = 1:
Box (1/1/1) initialized.
Adres Blowera: 0xdf8ca0
i = 2:
Box (2/2/2) initialized.
Adres Blowera: 0xdf8ce0
i = 3:
Box (3/3/3) initialized.
Adres Blowera: 0xdf8cc0
Summary
-------
Adres Blowera: 0xdf8ca0
Adres Blowera: 0xdf8ce0
Adres Blowera: 0xdf8cc0
Deleting
--------
Deleting Box: 1 (0xdf8ca0) 
Box (1/3/3) ended.
Deleting Box: 2 (0xdf8ce0) 
Box (2/2/3) ended.
Deleting Box: 3 (0xdf8cc0) 
Box (3/1/3) ended.

Installing Git on Eclipse

There are two ways of installing the Git plugin in Eclipse

  1. Installing through Help -> Install New Software..., then add the location http://download.eclipse.org/egit/updates/
  2. Installing through Help -> Eclipse Marketplace..., then type Egit and installing it.

Both methods may need you to restart Eclipse in the middle. For the step by step guide on installing and configuring Git plugin in Eclipse, you can also refer to Install and configure git plugin in Eclipse

Declare variable in SQLite and use it

Herman's solution worked for me, but the ... had me mixed up for a bit. I'm including the demo I worked up based on his answer. The additional features in my answer include foreign key support, auto incrementing keys, and use of the last_insert_rowid() function to get the last auto generated key in a transaction.

My need for this information came up when I hit a transaction that required three foreign keys but I could only get the last one with last_insert_rowid().

PRAGMA foreign_keys = ON;   -- sqlite foreign key support is off by default
PRAGMA temp_store = 2;      -- store temp table in memory, not on disk

CREATE TABLE Foo(
    Thing1 INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL
);

CREATE TABLE Bar(
    Thing2 INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    FOREIGN KEY(Thing2) REFERENCES Foo(Thing1)
);

BEGIN TRANSACTION;

CREATE TEMP TABLE _Variables(Key TEXT, Value INTEGER);

INSERT INTO Foo(Thing1)
VALUES(2);

INSERT INTO _Variables(Key, Value)
VALUES('FooThing', last_insert_rowid());

INSERT INTO Bar(Thing2)
VALUES((SELECT Value FROM _Variables WHERE Key = 'FooThing'));

DROP TABLE _Variables;

END TRANSACTION;

How to check for an active Internet connection on iOS or macOS?

  • Step 1: Add the Reachability class in your Project.
  • Step 2: Import the Reachability class
  • Step 3: Create the below function

    - (BOOL)checkNetConnection {
        self.internetReachability = [Reachability reachabilityForInternetConnection];
        [self.internetReachability startNotifier];
        NetworkStatus netStatus = [self.internetReachability currentReachabilityStatus];
        switch (netStatus) {
            case NotReachable:
            {
                return NO;
            }
    
            case ReachableViaWWAN:
            {
                 return YES;
            }
    
            case ReachableViaWiFi:
            {
                 return YES;
            }
        }
    }
    
  • Step 4: Call the function as below:

    if (![self checkNetConnection]) {
        [GlobalFunctions showAlert:@""
                         message:@"Please connect to the Internet!"
                         canBtntitle:nil
                         otherBtnTitle:@"Ok"];
        return;
    }
    else
    {
        Log.v("internet is connected","ok");
    }
    

Git push existing repo to a new and different remote repo server?

Do you really want to simply push your local repository (with its local branches, etc.) to the new remote or do you really want to mirror the old remote (with all its branches, tags, etc) on the new remote? If the latter here's a great blog on How to properly mirror a git repository.

I strongly encourage you to read the blog for some very important details, but the short version is this:

In a new directory run these commands:

git clone --mirror [email protected]/upstream-repository.git
cd upstream-repository.git
git push --mirror [email protected]/new-location.git

Why does the html input with type "number" allow the letter 'e' to be entered in the field?

The best way to force the use of a number composed of digits only:

_x000D_
_x000D_
<input type="number" onkeydown="javascript: return event.keyCode === 8 ||_x000D_
event.keyCode === 46 ? true : !isNaN(Number(event.key))" />
_x000D_
_x000D_
_x000D_

this avoids 'e', '-', '+', '.' ... all characters that are not numbers !

To allow number keys only:

isNaN(Number(event.key))

but accept "Backspace" (keyCode: 8) and "Delete" (keyCode: 46) ...

Failed to serialize the response in Web API with Json

While all these answers above are correct, one may want to check the InnerException > ExceptionMessage.

If it says something like this "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.". This could be an issue because of default behavior of the EF.

By assigning LazyLoadingEnabled = false in your DbContext constructor will do the trick.

public class MyDbContext : DbContext
{
  public MyDbContext()
  {
    this.Configuration.LazyLoadingEnabled = false;
  }
}

For more detailed reading about EagerLoading and LazyLoading behavior of EF refer this MSDN Article.

SQL Stored Procedure: If variable is not null, update statement

Use a T-SQL IF:

IF @ABC IS NOT NULL AND @ABC != -1
    UPDATE [TABLE_NAME] SET XYZ=@ABC

Take a look at the MSDN docs.

jQuery issue in Internet Explorer 8

The solution in my case was to take any special characters out of the URL you're trying to access. I had a tilde (~) and a percentage symbol in there, and the $.get() call failed silently.

Error: vector does not name a type

Also you can add #include<vector> in the header. When two of the above solutions don't work.

How to play a sound using Swift?

Swift 4, 4.2 and 5

Play audio from URL and from your project (Local File)

import UIKit
import AVFoundation

class ViewController: UIViewController{

var audioPlayer : AVPlayer!

override func viewDidLoad() {
        super.viewDidLoad()
// call what ever function you want.
    }

    private func playAudioFromURL() {
        guard let url = URL(string: "https://geekanddummy.com/wp-content/uploads/2014/01/coin-spin-light.mp3") else {
            print("error to get the mp3 file")
            return
        }
        do {
            audioPlayer = try AVPlayer(url: url as URL)
        } catch {
            print("audio file error")
        }
        audioPlayer?.play()
    }

    private func playAudioFromProject() {
        guard let url = Bundle.main.url(forResource: "azanMakkah2016", withExtension: "mp3") else {
            print("error to get the mp3 file")
            return
        }

        do {
            audioPlayer = try AVPlayer(url: url)
        } catch {
            print("audio file error")
        }
        audioPlayer?.play()
    }

}

React JSX: selecting "selected" on selected <select> option

Simply add as first option of your select tag:

<option disabled hidden value=''></option>

This will become default and when you'll select a valid option will be setted on your state

How do I clear my Jenkins/Hudson build history?

If you want to clear the build history of MultiBranchProject (e.g. pipeline), go to your Jenkins home page ? Manage Jenkins ? Script Console and run the following script:

def projectName = "ProjectName"
def project = Jenkins.instance.getItem(projectName)
def jobs = project.getItems().each {
  def job = it
  job.getBuilds().each { it.delete() }
  job.nextBuildNumber = 1
  job.save()
}

Web colors in an Android color xml resource file

I specifically was looking for the XML representation for Android.Graphics.Color. I didn't find these, so here you are. More details are in the help document.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="sysBlack">#FF000000</color>
    <color name="sysBlue">#FF0000FF</color>
    <color name="sysCyan">#FF00FFFF</color>
    <color name="sysDkGray">#FF444444</color>
    <color name="sysGray">#FF888888</color>
    <color name="sysGreen">#FF00FF00</color>
    <color name="sysLtGray">#FFCCCCCC</color>
    <color name="sysMagenta">#FFFF00FF</color>
    <color name="sysRed">#FFFF0000</color>
    <color name="sysTransparent">#00000000</color>
    <color name="sysWhite">#FFFFFFFF</color>
    <color name="sysYellow">#FFFFFF00</color>
</resources>

Of course, this is used like this:

android:textColor="@color/sysGray"

Messages Using Command prompt in Windows 7

"net send" is a command using a background service called "messenger". This service has been removed from Windows 7. ie You cannot use 'net send' on Vista nor Win7 / Win8.

Pity though , I loved using it.

There is alternatives, but that requires you to download and install software on each pc you want to use, this software runs as background services, and i would advise one to be very very very very careful of using these kind of software as they can potentially cause seriously damage one's system or impair the systems securities.

winsent innocenti / winsent messenger

****This command is risky because of what is stated above***

Interfaces vs. abstract classes

The advantages of an abstract class are:

  • Ability to specify default implementations of methods
  • Added invariant checking to functions
  • Have slightly more control in how the "interface" methods are called
  • Ability to provide behavior related or unrelated to the interface for "free"

Interfaces are merely data passing contracts and do not have these features. However, they are typically more flexible as a type can only be derived from one class, but can implement any number of interfaces.

How to run two jQuery animations simultaneously?

That would run simultaneously yes. what if you wanted to run two animations on the same element simultaneously ?

$(function () {
    $('#first').animate({ width: '200px' }, 200);
    $('#first').animate({ marginTop: '50px' }, 200);
});

This ends up queuing the animations. to get to run them simultaneously you would use only one line.

$(function () {
    $('#first').animate({ width: '200px', marginTop:'50px' }, 200);
});

Is there any other way to run two different animation on the same element simultaneously ?

How can I get a list of all values in select box?

It looks like placing the click event directly on the button is causing the problem. For some reason it can't find the function. Not sure why...

If you attach the event handler in the javascript, it does work however.

See it here: http://jsfiddle.net/WfBRr/7/

<button id="display-text" type="button">Display text of all options</button>

document.getElementById('display-text').onclick = function () {
    var x = document.getElementById("mySelect");
    var txt = "All options: ";
    var i;
    for (i = 0; i < x.length; i++) {
        txt = txt + "\n" + x.options[i].value;
    }
    alert(txt);
}

What is the purpose of using WHERE 1=1 in SQL statements?

It's also a common practice when people are building the sql query programmatically, it's just easier to start with 'where 1=1 ' and then appending ' and customer.id=:custId' depending if a customer id is provided. So you can always append the next part of the query starting with 'and ...'.

How do I generate a random int number?

I've tried all of these solutions excluding the COBOL answer... lol

None of these solutions were good enough. I needed randoms in a fast for int loop and I was getting tons of duplicate values even in very wide ranges. After settling for kind of random results far too long I decided to finally tackle this problem once and for all.

It's all about the seed.

I create a random integer by parsing out the non-digits from Guid, then I use that to instantiate my Random class.

public int GenerateRandom(int min, int max)
{
    var seed = Convert.ToInt32(Regex.Match(Guid.NewGuid().ToString(), @"\d+").Value);
    return new Random(seed).Next(min, max);
}

Update: Seeding isn't necessary if you instantiate the Random class once. So it'd be best to create a static class and call a method off that.

public static class IntUtil
{
   private static Random random;

   private static void Init()
   {
      if (random == null) random = new Random();
   }

   public static int Random(int min, int max)
   {
      Init();
      return random.Next(min, max);
   }
}

Then you can use the static class like so..

for(var i = 0; i < 1000; i++)
{
   int randomNumber = IntUtil.Random(1,100);
   Console.WriteLine(randomNumber); 
}

I admit I like this approach better.

Convert string with commas to array

Convert all type of strings

var array = (new Function("return [" + str+ "];")());



var string = "0,1";

var objectstring = '{Name:"Tshirt", CatGroupName:"Clothes", Gender:"male-female"}, {Name:"Dress", CatGroupName:"Clothes", Gender:"female"}, {Name:"Belt", CatGroupName:"Leather", Gender:"child"}';

var stringArray = (new Function("return [" + string+ "];")());

var objectStringArray = (new Function("return [" + objectstring+ "];")());

JSFiddle https://jsfiddle.net/7ne9L4Lj/1/

Result in console

enter image description here

Some practice doesnt support object strings

- JSON.parse("[" + string + "]"); // throw error

 - string.split(",") 
// unexpected result 
   ["{Name:"Tshirt"", " CatGroupName:"Clothes"", " Gender:"male-female"}", "      {Name:"Dress"", " CatGroupName:"Clothes"", " Gender:"female"}", " {Name:"Belt"",    " CatGroupName:"Leather"", " Gender:"child"}"]

Cleaning up old remote git branches

Consider to run :

git fetch --prune

On a regular basis in each repo to remove local branches that have been tracking a remote branch that is deleted (no longer exists in remote GIT repo).

This can be further simplified by

git config remote.origin.prune true

this is a per-repo setting that will make any future git fetch or git pull to automatically prune.

To set this up for your user, you may also edit the global .gitconfig and add

[fetch]
    prune = true

However, it's recommended that this is done using the following command:

git config --global fetch.prune true

or to apply it system wide (not just for the user)

git config --system fetch.prune true

How to maintain page scroll position after a jquery event is carried out?

I had a similar problem getting scrollTop to work after reload of div content. The content scrolled to top each time the procedure below was run. I found that a little delay before setting the new scrolltop solved the issue.

This is cut from wdCalendar where I modified this procedure:

 function BuildDaysAndWeekView(startday, l, events, config)
   ....
        var scrollpos = $("#dvtec").scrollTop();
        gridcontainer.html(html.join(""));
        setTimeout(function() {
            $("#dvtec").scrollTop(scrollpos);
        }, 25);
   ....

Without the delay, it simply did not work.

Dynamic Height Issue for UITableView Cells (Swift)

To make autoresizing of UITableViewCell to work make sure you are doing these changes :

  • In Storyboard your UITableView should only contain Dynamic Prototype Cells (It shouldn't use static cells) otherwise autoresizing won't work.
  • In Storyboard your UITableViewCell's UILabel has configured for all 4 constraints that is top, bottom, leading and trailing constraints.
  • In Storyboard your UITableViewCell's UILabel's number of lines should be 0
  • In your UIViewController's viewDidLoad function set below UITableView Properties :

    self.tableView.estimatedRowHeight = <minimum cell height> 
    self.tableView.rowHeight = UITableViewAutomaticDimension
    

How can I combine hashes in Perl?

Quick Answer (TL;DR)


    %hash1 = (%hash1, %hash2)

    ## or else ...

    @hash1{keys %hash2} = values %hash2;

    ## or with references ...

    $hash_ref1 = { %$hash_ref1, %$hash_ref2 };

Overview

  • Context: Perl 5.x
  • Problem: The user wishes to merge two hashes1 into a single variable

Solution

  • use the syntax above for simple variables
  • use Hash::Merge for complex nested variables

Pitfalls

See also


Footnotes

1 * (aka associative-array, aka dictionary)

How to sort Counter by value? - python

A rather nice addition to @MartijnPieters answer is to get back a dictionary sorted by occurrence since Collections.most_common only returns a tuple. I often couple this with a json output for handy log files:

from collections import Counter, OrderedDict

x = Counter({'a':5, 'b':3, 'c':7})
y = OrderedDict(x.most_common())

With the output:

OrderedDict([('c', 7), ('a', 5), ('b', 3)])
{
  "c": 7, 
  "a": 5, 
  "b": 3
}

What underlies this JavaScript idiom: var self = this?

It should also be noted there is an alternative Proxy pattern for maintaining a reference to the original this in a callback if you dislike the var self = this idiom.

As a function can be called with a given context by using function.apply or function.call, you can write a wrapper that returns a function that calls your function with apply or call using the given context. See jQuery's proxy function for an implementation of this pattern. Here is an example of using it:

var wrappedFunc = $.proxy(this.myFunc, this);

wrappedFunc can then be called and will have your version of this as the context.

Setting Different Bar color in matplotlib Python

Update pandas 0.17.0

@7stud's answer for the newest pandas version would require to just call

s.plot( 
    kind='bar', 
    color=my_colors,
)

instead of

pd.Series.plot(
    s, 
    kind='bar', 
    color=my_colors,
)

The plotting functions have become members of the Series, DataFrame objects and in fact calling pd.Series.plot with a color argument gives an error

How to play only the audio of a Youtube video using HTML 5?

UPDATED FOR 2020

It seems in Septeber 2019, YouTube updated the values that are returned by get_video_info.

Rather than data.url_encoded_fmt_stream_map and data.adaptive_fmts (as used in the other older examples) now we are looking for for data.formats and data.adaptiveFormats.

Anyways here is what you are all here for some code that loads a YouTube video into an <audio> element. Try it on CodePen

_x000D_
_x000D_
// YouTube video ID
var videoID = "CMNry4PE93Y";

// Fetch video info (using a proxy to avoid CORS errors)
fetch('https://cors-anywhere.herokuapp.com/' + "https://www.youtube.com/get_video_info?video_id=" + videoID).then(response => {
  if (response.ok) {
    response.text().then(ytData => {
      
      // parse response to find audio info
      var ytData = parse_str(ytData);
      var getAdaptiveFormats = JSON.parse(ytData.player_response).streamingData.adaptiveFormats;
      var findAudioInfo = getAdaptiveFormats.findIndex(obj => obj.audioQuality);
      
      // get the URL for the audio file
      var audioURL = getAdaptiveFormats[findAudioInfo].url;
      
      // update the <audio> element src
      var youtubeAudio = document.getElementById('youtube');
      youtubeAudio.src = audioURL;
      
    });
  }
});

function parse_str(str) {
  return str.split('&').reduce(function(params, param) {
    var paramSplit = param.split('=').map(function(value) {
      return decodeURIComponent(value.replace('+', ' '));
    });
    params[paramSplit[0]] = paramSplit[1];
    return params;
  }, {});
}
_x000D_
<audio id="youtube" controls></audio>
_x000D_
_x000D_
_x000D_

how to change class name of an element by jquery

Instead of removeClass and addClass, you can also do it like this:

$('.IsBestAnswer').toggleClass('IsBestAnswer bestanswer');

Check whether values in one data frame column exist in a second data frame

Use %in% as follows

A$C %in% B$C

Which will tell you which values of column C of A are in B.

What is returned is a logical vector. In the specific case of your example, you get:

A$C %in% B$C
# [1]  TRUE FALSE  TRUE  TRUE

Which you can use as an index to the rows of A or as an index to A$C to get the actual values:

# as a row index
A[A$C %in% B$C,  ]  # note the comma to indicate we are indexing rows

# as an index to A$C
A$C[A$C %in% B$C]
[1] 1 3 4  # returns all values of A$C that are in B$C

We can negate it too:

A$C[!A$C %in% B$C]
[1] 2   # returns all values of A$C that are NOT in B$C



If you want to know if a specific value is in B$C, use the same function:

  2 %in% B$C   # "is the value 2 in B$C ?"  
  # FALSE

  A$C[2] %in% B$C  # "is the 2nd element of A$C in B$C ?"  
  # FALSE

"Bitmap too large to be uploaded into a texture"

I ran through same problem, here is my solution. set the width of image same as android screen width and then scales the height

Bitmap myBitmap = BitmapFactory.decodeFile(image.getAbsolutePath());
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
Log.e("Screen width ", " "+width);
Log.e("Screen height ", " "+height);
Log.e("img width ", " "+myBitmap.getWidth());
Log.e("img height ", " "+myBitmap.getHeight());
float scaleHt =(float) width/myBitmap.getWidth();
Log.e("Scaled percent ", " "+scaleHt);
Bitmap scaled = Bitmap.createScaledBitmap(myBitmap, width, (int)(myBitmap.getWidth()*scaleHt), true);
myImage.setImageBitmap(scaled);

This is better for any size android screen. let me know if it works for you.

Select multiple columns by labels in pandas

How do I select multiple columns by labels in pandas?

Multiple label-based range slicing is not easily supported with pandas, but position-based slicing is, so let's try that instead:

loc = df.columns.get_loc
df.iloc[:, np.r_[loc('A'):loc('C')+1, loc('E'), loc('G'):loc('I')+1]]

          A         B         C         E         G         H         I
0 -1.666330  0.321260 -1.768185 -0.034774  0.023294  0.533451 -0.241990
1  0.911498  3.408758  0.419618 -0.462590  0.739092  1.103940  0.116119
2  1.243001 -0.867370  1.058194  0.314196  0.887469  0.471137 -1.361059
3 -0.525165  0.676371  0.325831 -1.152202  0.606079  1.002880  2.032663
4  0.706609 -0.424726  0.308808  1.994626  0.626522 -0.033057  1.725315
5  0.879802 -1.961398  0.131694 -0.931951 -0.242822 -1.056038  0.550346
6  0.199072  0.969283  0.347008 -2.611489  0.282920 -0.334618  0.243583
7  1.234059  1.000687  0.863572  0.412544  0.569687 -0.684413 -0.357968
8 -0.299185  0.566009 -0.859453 -0.564557 -0.562524  0.233489 -0.039145
9  0.937637 -2.171174 -1.940916 -1.553634  0.619965 -0.664284 -0.151388

Note that the +1 is added because when using iloc the rightmost index is exclusive.


Comments on Other Solutions

  • filter is a nice and simple method for OP's headers, but this might not generalise well to arbitrary column names.

  • The "location-based" solution with loc is a little closer to the ideal, but you cannot avoid creating intermediate DataFrames (that are eventually thrown out and garbage collected) to compute the final result range -- something that we would ideally like to avoid.

  • Lastly, "pick your columns directly" is good advice as long as you have a manageably small number of columns to pick. It will, however not be applicable in some cases where ranges span dozens (or possibly hundreds) of columns.

check all socket opened in linux OS

You can use netstat command

netstat --listen

To display open ports and established TCP connections,

netstat -vatn

To display only open UDP ports try the following command:

netstat -vaun

How do I syntax check a Bash script without running it?

I also enable the 'u' option on every bash script I write in order to do some extra checking:

set -u 

This will report the usage of uninitialized variables, like in the following script 'check_init.sh'

#!/bin/sh
set -u
message=hello
echo $mesage

Running the script :

$ check_init.sh

Will report the following :

./check_init.sh[4]: mesage: Parameter not set.

Very useful to catch typos

CSV file written with Python has blank lines between each row

Opening the file in binary mode "wb" will not work in Python 3+. Or rather, you'd have to convert your data to binary before writing it. That's just a hassle.

Instead, you should keep it in text mode, but override the newline as empty. Like so:

with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile:

More than 1 row in <Input type="textarea" />

Although <input> ignores the rows attribute, you can take advantage of the fact that <textarea> doesn't have to be inside <form> tags, but can still be a part of a form by referencing the form's id:

<form method="get" id="testformid">
    <input type="submit" />
</form> 
<textarea form ="testformid" name="taname" id="taid" cols="35" wrap="soft"></textarea>

Of course, <textarea> now appears below "submit" button, but maybe you'll find a way to reposition it.

How do I use DateTime.TryParse with a Nullable<DateTime>?

You can't because Nullable<DateTime> is a different type to DateTime. You need to write your own function to do it,

public bool TryParse(string text, out Nullable<DateTime> nDate)
{
    DateTime date;
    bool isParsed = DateTime.TryParse(text, out date);
    if (isParsed)
        nDate = new Nullable<DateTime>(date);
    else
        nDate = new Nullable<DateTime>();
    return isParsed;
}

Hope this helps :)

EDIT: Removed the (obviously) improperly tested extension method, because (as Pointed out by some bad hoor) extension methods that attempt to change the "this" parameter will not work with Value Types.

P.S. The Bad Hoor in question is an old friend :)

jQuery .each() with input elements

You can use:

$(formId).serializeArray();

Hide "NFC Tag type not supported" error on Samsung Galaxy devices

Before Android 4.4

What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.

On a rooted device, you may be able to bypass the message using either

  1. Xposed to modify the behavior of the NFC service, or
  2. the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup> is set to any value but "mifareclassic" or "all". For instance, you could use:

    <CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
    

    You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet> that already exists in that file).

Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).

Since Android 4.4

This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK.

'and' (boolean) vs '&' (bitwise) - Why difference in behavior with lists vs numpy arrays?

For the first example and base on the django's doc
It will always return the second list, indeed a non empty list is see as a True value for Python thus python return the 'last' True value so the second list

In [74]: mylist1 = [False]
In [75]: mylist2 = [False, True, False,  True, False]
In [76]: mylist1 and mylist2
Out[76]: [False, True, False, True, False]
In [77]: mylist2 and mylist1
Out[77]: [False]

What is the default Jenkins password?

The password is present in the log generated by docker run image as shown in the example below.

Jenkins Docker run log

Additionally you can check the directory /var/jenkins_home/secrets/ Its in the file name initialAdminPassword

You can use cat /var/jenkins_home/secrets/initialAdminPassword to read it.

How can I delete one element from an array by value

Another option:

a = [2,4,6,3,8]

a -= [3]

which results in

=> [2, 4, 6, 8] 

How do I display a wordpress page content?

@Marc B Thanks for the comment. Helped me discover this:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post();
the_content();
endwhile; else: ?>
<p>Sorry, no posts matched your criteria.</p>
<?php endif; ?>

NoClassDefFoundError in Java: com/google/common/base/Function

It looks like you're trying to import some google code:

import com.google.common.base.Function;

And it's not finding it the class Function. Check to make sure all the required libraries are in your build path, and that you typed the package correctly.

How to return a value from try, catch, and finally?

Here is another example that return's a boolean value using try/catch.

private boolean doSomeThing(int index){
    try {
        if(index%2==0) 
            return true; 
    } catch (Exception e) {
        System.out.println(e.getMessage()); 
    }finally {
        System.out.println("Finally!!! ;) ");
    }
    return false; 
}

How to use concerns in Rails 4

In concerns make file filename.rb

For example I want in my application where attribute create_by exist update there value by 1, and 0 for updated_by

module TestConcern 
  extend ActiveSupport::Concern

  def checkattributes   
    if self.has_attribute?(:created_by)
      self.update_attributes(created_by: 1)
    end
    if self.has_attribute?(:updated_by)
      self.update_attributes(updated_by: 0)
    end
  end

end

If you want to pass arguments in action

included do
   before_action only: [:create] do
     blaablaa(options)
   end
end

after that include in your model like this:

class Role < ActiveRecord::Base
  include TestConcern
end

Count distinct value pairs in multiple columns in SQL

You can also do something like:

SELECT COUNT(DISTINCT id + name + address) FROM mytable

Does MySQL ignore null values on unique constraints?

I am unsure if the author originally was just asking whether or not this allows duplicate values or if there was an implied question here asking, "How to allow duplicate NULL values while using UNIQUE?" Or "How to only allow one UNIQUE NULL value?"

The question has already been answered, yes you can have duplicate NULL values while using the UNIQUE index.

Since I stumbled upon this answer while searching for "how to allow one UNIQUE NULL value." For anyone else who may stumble upon this question while doing the same, the rest of my answer is for you...

In MySQL you can not have one UNIQUE NULL value, however you can have one UNIQUE empty value by inserting with the value of an empty string.

Warning: Numeric and types other than string may default to 0 or another default value.

How to programmatically set style attribute in a view

For anyone looking for a Material answer see this SO post: Coloring Buttons in Android with Material Design and AppCompat

I used a combination of this answer to set the default text color of the button to white for my button: https://stackoverflow.com/a/32238489/3075340

Then this answer https://stackoverflow.com/a/34355919/3075340 to programmatically set the background color. The code for that is:

ViewCompat.setBackgroundTintList(your_colored_button,
 ContextCompat.getColorStateList(getContext(),R.color.your_custom_color));

your_colored_button can be just a regular Button or a AppCompat button if you wish - I tested the above code with both types of buttons and it works.

EDIT: I found that pre-lollipop devices do not work with the above code. See this post on how to add support for pre-lollipop devices: https://stackoverflow.com/a/30277424/3075340

Basically do this:

Button b = (Button) findViewById(R.id.button);
ColorStateList c = ContextCompat.getColorStateList(mContext, R.color.your_custom_color;
Drawable d = b.getBackground();
if (b instanceof AppCompatButton) {
    // appcompat button replaces tint of its drawable background
    ((AppCompatButton)b).setSupportBackgroundTintList(c);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    // Lollipop button replaces tint of its drawable background
    // however it is not equal to d.setTintList(c)
    b.setBackgroundTintList(c);
} else {
    // this should only happen if 
    // * manually creating a Button instead of AppCompatButton
    // * LayoutInflater did not translate a Button to AppCompatButton
    d = DrawableCompat.wrap(d);
    DrawableCompat.setTintList(d, c);
    b.setBackgroundDrawable(d);
}

AngularJS - Does $destroy remove event listeners?

Event listeners

First off it's important to understand that there are two kinds of "event listeners":

  1. Scope event listeners registered via $on:

    $scope.$on('anEvent', function (event, data) {
      ...
    });
    
  2. Event handlers attached to elements via for example on or bind:

    element.on('click', function (event) {
      ...
    });
    

$scope.$destroy()

When $scope.$destroy() is executed it will remove all listeners registered via $on on that $scope.

It will not remove DOM elements or any attached event handlers of the second kind.

This means that calling $scope.$destroy() manually from example within a directive's link function will not remove a handler attached via for example element.on, nor the DOM element itself.


element.remove()

Note that remove is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.

When element.remove() is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on.

It will not destroy the $scope associated with the element.

To make it more confusing there is also a jQuery event called $destroy. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:

element.on('$destroy', function () {
  scope.$destroy();
});

What to do when a directive is "destroyed"

This depends on how the directive is "destroyed".

A normal case is that a directive is destroyed because ng-view changes the current view. When this happens the ng-view directive will destroy the associated $scope, sever all the references to its parent scope and call remove() on the element.

This means that if that view contains a directive with this in its link function when it's destroyed by ng-view:

scope.$on('anEvent', function () {
 ...
});

element.on('click', function () {
 ...
});

Both event listeners will be removed automatically.

However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references.

Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.

For example if you have registered a listener on $rootScope:

var unregisterFn = $rootScope.$on('anEvent', function () {});

scope.$on('$destroy', unregisterFn);

This is needed since $rootScope is never destroyed during the lifetime of the application.

The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.

Another situation would be to cancel $interval/$timeout:

var promise = $interval(function () {}, 1000);

scope.$on('$destroy', function () {
  $interval.cancel(promise);
});

If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:

var windowClick = function () {
   ...
};

angular.element(window).on('click', windowClick);

scope.$on('$destroy', function () {
  angular.element(window).off('click', windowClick);
});

These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view or ng-if.

If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.

How do I trap ctrl-c (SIGINT) in a C# console app

This question is very similar to:

Capture console exit C#

Here is how I solved this problem, and dealt with the user hitting the X as well as Ctrl-C. Notice the use of ManualResetEvents. These will cause the main thread to sleep which frees the CPU to process other threads while waiting for either exit, or cleanup. NOTE: It is necessary to set the TerminationCompletedEvent at the end of main. Failure to do so causes unnecessary latency in termination due to the OS timing out while killing the application.

namespace CancelSample
{
    using System;
    using System.Threading;
    using System.Runtime.InteropServices;

    internal class Program
    {
        /// <summary>
        /// Adds or removes an application-defined HandlerRoutine function from the list of handler functions for the calling process
        /// </summary>
        /// <param name="handler">A pointer to the application-defined HandlerRoutine function to be added or removed. This parameter can be NULL.</param>
        /// <param name="add">If this parameter is TRUE, the handler is added; if it is FALSE, the handler is removed.</param>
        /// <returns>If the function succeeds, the return value is true.</returns>
        [DllImport("Kernel32")]
        private static extern bool SetConsoleCtrlHandler(ConsoleCloseHandler handler, bool add);

        /// <summary>
        /// The console close handler delegate.
        /// </summary>
        /// <param name="closeReason">
        /// The close reason.
        /// </param>
        /// <returns>
        /// True if cleanup is complete, false to run other registered close handlers.
        /// </returns>
        private delegate bool ConsoleCloseHandler(int closeReason);

        /// <summary>
        ///  Event set when the process is terminated.
        /// </summary>
        private static readonly ManualResetEvent TerminationRequestedEvent;

        /// <summary>
        /// Event set when the process terminates.
        /// </summary>
        private static readonly ManualResetEvent TerminationCompletedEvent;

        /// <summary>
        /// Static constructor
        /// </summary>
        static Program()
        {
            // Do this initialization here to avoid polluting Main() with it
            // also this is a great place to initialize multiple static
            // variables.
            TerminationRequestedEvent = new ManualResetEvent(false);
            TerminationCompletedEvent = new ManualResetEvent(false);
            SetConsoleCtrlHandler(OnConsoleCloseEvent, true);
        }

        /// <summary>
        /// The main console entry point.
        /// </summary>
        /// <param name="args">The commandline arguments.</param>
        private static void Main(string[] args)
        {
            // Wait for the termination event
            while (!TerminationRequestedEvent.WaitOne(0))
            {
                // Something to do while waiting
                Console.WriteLine("Work");
            }

            // Sleep until termination
            TerminationRequestedEvent.WaitOne();

            // Print a message which represents the operation
            Console.WriteLine("Cleanup");

            // Set this to terminate immediately (if not set, the OS will
            // eventually kill the process)
            TerminationCompletedEvent.Set();
        }

        /// <summary>
        /// Method called when the user presses Ctrl-C
        /// </summary>
        /// <param name="reason">The close reason</param>
        private static bool OnConsoleCloseEvent(int reason)
        {
            // Signal termination
            TerminationRequestedEvent.Set();

            // Wait for cleanup
            TerminationCompletedEvent.WaitOne();

            // Don't run other handlers, just exit.
            return true;
        }
    }
}

How to convert an Array to a Set in Java

In Eclipse Collections, the following will work:

Set<Integer> set1 = Sets.mutable.of(1, 2, 3, 4, 5);
Set<Integer> set2 = Sets.mutable.of(new Integer[]{1, 2, 3, 4, 5});
MutableSet<Integer> mutableSet = Sets.mutable.of(1, 2, 3, 4, 5);
ImmutableSet<Integer> immutableSet = Sets.immutable.of(1, 2, 3, 4, 5);

Set<Integer> unmodifiableSet = Sets.mutable.of(1, 2, 3, 4, 5).asUnmodifiable();
Set<Integer> synchronizedSet = Sets.mutable.of(1, 2, 3, 4, 5).asSynchronized();
ImmutableSet<Integer> immutableSet = Sets.mutable.of(1, 2, 3, 4, 5).toImmutable();

Note: I am a committer for Eclipse Collections

what innerHTML is doing in javascript?

innerHTML explanation with example:

The innerHTML manipulates the HTML content of an element(get or set). In the example below if you click on the Change Content link it's value will be updated by using innerHTML property of anchor link Change Content

Example:

_x000D_
_x000D_
<a id="example" onclick='testFunction()'>Change Content</a>_x000D_
_x000D_
<script>_x000D_
  function testFunction(){_x000D_
    // change the content using innerHTML_x000D_
    document.getElementById("example").innerHTML = "This is dummy content";_x000D_
_x000D_
    // get the content using innerHTML_x000D_
    alert(document.getElementById("example").innerHTML)_x000D_
_x000D_
  }_x000D_
</script>_x000D_
    
_x000D_
_x000D_
_x000D_

How do I center a Bootstrap div with a 'spanX' class?

Define the width as 960px, or whatever you prefer, and you're good to go!

#main {
 margin: 0 auto !important;
 float: none !important;
 text-align: center;
 width: 960px;
}

(I couldn't figure this out until I fixed the width, nothing else worked.)

Intersection and union of ArrayLists in Java

If the number matches than I am checking it's occur first time or not with help of "indexOf()" if the number matches first time then print and save into in a string so, that when the next time same number matches then it's won't print because due to "indexOf()" condition will be false.

class Intersection
{
public static void main(String[] args)
 {
  String s="";
    int[] array1 = {1, 2, 5, 5, 8, 9, 7,2,3512451,4,4,5 ,10};
    int[] array2 = {1, 0, 6, 15, 6, 5,4, 1,7, 0,5,4,5,2,3,8,5,3512451};


       for (int i = 0; i < array1.length; i++)
       {
           for (int j = 0; j < array2.length; j++)
           {
               char c=(char)(array1[i]);
               if(array1[i] == (array2[j])&&s.indexOf(c)==-1)
               {    
                System.out.println("Common element is : "+(array1[i]));
                s+=c;
                }
           }
       }    
}

}

What is LD_LIBRARY_PATH and how to use it?

LD_LIBRARY_PATH is the default library path which is accessed to check for available dynamic and shared libraries. It is specific to linux distributions.

It is similar to environment variable PATH in windows that linker checks for possible implementations during linking time.

Java Swing revalidate() vs repaint()

revalidate is called on a container once new components are added or old ones removed. this call is an instruction to tell the layout manager to reset based on the new component list. revalidate will trigger a call to repaint what the component thinks are 'dirty regions.' Obviously not all of the regions on your JPanel are considered dirty by the RepaintManager.

repaint is used to tell a component to repaint itself. It is often the case that you need to call this in order to cleanup conditions such as yours.

Get file size before uploading

Best solution working on all browsers ;)

function GetFileSize(fileid) {
    try {
        var fileSize = 0;
        // for IE
        if(checkIE()) { //we could use this $.browser.msie but since it's deprecated, we'll use this function
            // before making an object of ActiveXObject, 
            // please make sure ActiveX is enabled in your IE browser
            var objFSO = new ActiveXObject("Scripting.FileSystemObject");
            var filePath = $("#" + fileid)[0].value;
            var objFile = objFSO.getFile(filePath);
            var fileSize = objFile.size; //size in b
            fileSize = fileSize / 1048576; //size in mb 
        }
        // for FF, Safari, Opeara and Others
        else {
            fileSize = $("#" + fileid)[0].files[0].size //size in b
            fileSize = fileSize / 1048576; //size in mb 
        }
        alert("Uploaded File Size is" + fileSize + "MB");
    }
    catch (e) {
        alert("Error is :" + e);
    }
}

from http://www.dotnet-tricks.com/Tutorial/jquery/HHLN180712-Get-file-size-before-upload-using-jquery.html

UPDATE : We'll use this function to check if it's IE browser or not

function checkIE() {
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)){  
        // If Internet Explorer, return version number
        alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
    } else {
        // If another browser, return 0
        alert('otherbrowser');
    }

    return false;
}

How to connect to SQL Server from command prompt with Windows authentication

Try This :

--Default Instance

SQLCMD -S SERVERNAME -E

--OR
--Named Instance

SQLCMD -S SERVERNAME\INSTANCENAME -E

--OR

SQLCMD -S SERVERNAME\INSTANCENAME,1919 -E

More details can be found here

How to initialize an array in one step using Ruby?

You can do

array = ['1', '2', '3']

As others have noted, you can also initialize an array with %w notation like so:

array = %w(1 2 3)

or

array = %w[1 2 3]

Please note that in both cases each element is a string, rather than an integer. So if you want an array whose elements are integers, you should not wrap each element with apostrophes:

array_of_integers = [1, 2, 3]

Also, you don't need to put comma in between the elements (which is necessary when creating an array without this %w notation). If you do this (which I often did by mistake), as in:

wrong_array = %w(1, 2, 3)

its elements will be three strings ---- "1,", "2,", "3". So if you do:

puts wrong_array

the output will be:

1,
2,
3
=>nil

which is not what we want here.

Hope this helps to clarify the point!

AngularJS toggle class using ng-class

Add more than one class based on the condition:

<div ng-click="AbrirPopUp(s)" 
ng-class="{'class1 class2 class3':!isNew, 
           'class1 class4': isNew}">{{ isNew }}</div>

Apply: class1 + class2 + class3 when isNew=false,

Apply: class1+ class4 when isNew=true

getResourceAsStream() is always returning null

To my knowledge the file has to be right in the folder where the 'this' class resides, i.e. not in WEB-INF/classes but nested even deeper (unless you write in a default package):

net/domain/pkg1/MyClass.java  
net/domain/pkg1/abc.txt

Putting the file in to your java sources should work, compiler copies that file together with class files.

TypeError: unsupported operand type(s) for -: 'str' and 'int'

  1. The reason this is failing is because (Python 3) input returns a string. To convert it to an integer, use int(some_string).

  2. You do not typically keep track of indices manually in Python. A better way to implement such a function would be

    def cat_n_times(s, n):
        for i in range(n):
            print(s) 
    
    text = input("What would you like the computer to repeat back to you: ")
    num = int(input("How many times: ")) # Convert to an int immediately.
    
    cat_n_times(text, num)
    
  3. I changed your API above a bit. It seems to me that n should be the number of times and s should be the string.

How do I convert speech to text?

Dragon NaturallySpeaking seems to support MP3 input.

If you want an open source version (I think there are some Asterisk integration projects based on this one).

Razor View Engine : An expression tree may not contain a dynamic operation

Before using (strongly type html helper into view) this line

@Html.TextBoxFor(p => p.Product.Name)

You should include your model into you page for making strongly type view.

@model SampleModel

Omit rows containing specific column of NA

Use 'subset'

DF <- data.frame(x = c(1, 2, 3), y = c(0, 10, NA), z=c(NA, 33, 22))
subset(DF, !is.na(y))

EOL conversion in notepad ++

Depending on your project, you might want to consider using EditorConfig (https://editorconfig.org/). There's a Notepad++ plugin which will load an .editorconfig where you can specify "lf" as the mandatory line ending.

I've only started using it, but it's nice so far, and open source projects I've worked on have included .editorconfig files for years. The "EOL Conversion" setting isn't changed, so it can be a bit confusing, but if you "View > Show Symbol > Show End of Line", you can see that it's adding LF instead of CRLF, even when "EOL Conversion" and the lower bottom corner shows something else (e.g. Windows (CR LF)).

Can an abstract class have a constructor?

package Test1;

public class AbstractClassConstructor {

public AbstractClassConstructor() {

}

    public static void main(String args[]) {
       Demo obj = new Test("Test of code has started");
       obj.test1();
    }

}

abstract class Demo{
    protected final String demoValue;

    public Demo(String testName){
        this.demoValue = testName;
    }

    public abstract boolean test1();
}

class Test extends Demo{

    public Test(String name){
        super(name);
    }

    @Override
    public boolean test1() {
       System.out.println( this.demoValue + " Demo test started");
       return true;
    }

}

JIRA JQL searching by date - is there a way of getting Today() (Date) instead of Now() (DateTime)

In case you want to search for all the issues updated after 9am previous day until today at 9AM, please try: updated >= startOfDay(-15h) and updated <= startOfDay(9h). (explanation: 9AM - 24h/day = -15h)

You can also use updated >= startOfDay(-900m) . where 900m = 15h*60m

Reference: https://confluence.atlassian.com/display/JIRA/Advanced+Searching

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

The accepted answer to this question is awesome and should remain the accepted answer. However I ran into an issue with the code where the read stream was not always being ended/closed. Part of the solution was to send autoClose: true along with start:start, end:end in the second createReadStream arg.

The other part of the solution was to limit the max chunksize being sent in the response. The other answer set end like so:

var end = positions[1] ? parseInt(positions[1], 10) : total - 1;

...which has the effect of sending the rest of the file from the requested start position through its last byte, no matter how many bytes that may be. However the client browser has the option to only read a portion of that stream, and will, if it doesn't need all of the bytes yet. This will cause the stream read to get blocked until the browser decides it's time to get more data (for example a user action like seek/scrub, or just by playing the stream).

I needed this stream to be closed because I was displaying the <video> element on a page that allowed the user to delete the video file. However the file was not being removed from the filesystem until the client (or server) closed the connection, because that is the only way the stream was getting ended/closed.

My solution was just to set a maxChunk configuration variable, set it to 1MB, and never pipe a read a stream of more than 1MB at a time to the response.

// same code as accepted answer
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;

// poor hack to send smaller chunks to the browser
var maxChunk = 1024 * 1024; // 1MB at a time
if (chunksize > maxChunk) {
  end = start + maxChunk - 1;
  chunksize = (end - start) + 1;
}

This has the effect of making sure that the read stream is ended/closed after each request, and not kept alive by the browser.

I also wrote a separate StackOverflow question and answer covering this issue.

What does 'useLegacyV2RuntimeActivationPolicy' do in the .NET 4 config?

Here's an explanation I wrote recently to help with the void of information on this attribute. http://www.marklio.com/marklio/PermaLink,guid,ecc34c3c-be44-4422-86b7-900900e451f9.aspx (Internet Archive Wayback Machine link)

To quote the most relevant bits:

[Installing .NET] v4 is “non-impactful”. It should not change the behavior of existing components when installed.

The useLegacyV2RuntimeActivationPolicy attribute basically lets you say, “I have some dependencies on the legacy shim APIs. Please make them work the way they used to with respect to the chosen runtime.”

Why don’t we make this the default behavior? You might argue that this behavior is more compatible, and makes porting code from previous versions much easier. If you’ll recall, this can’t be the default behavior because it would make installation of v4 impactful, which can break existing apps installed on your machine.

The full post explains this in more detail. At RTM, the MSDN docs on this should be better.

PKIX path building failed in Java application

I ran into similar issues whose cause and solution turned out both to be rather simple:

Main Cause: Did not import the proper cert using keytool

NOTE: Only import root CA (or your own self-signed) certificates

NOTE: don't import an intermediate, non certificate chain root cert

Solution Example for imap.gmail.com

  1. Determine the root CA cert:

    openssl s_client -showcerts -connect imap.gmail.com:993
    

    in this case we find the root CA is Equifax Secure Certificate Authority

  2. Download root CA cert.
  3. Verify downloaded cert has proper SHA-1 and/or MD5 fingerprints by comparing with info found here
  4. Import cert for javax.net.ssl.trustStore:

    keytool -import -alias gmail_imap -file Equifax_Secure_Certificate_Authority.pem
    
  5. Run your java code

How to get thread id from a thread pool?

Using Thread.currentThread():

private class MyTask implements Runnable {
    public void run() {
        long threadId = Thread.currentThread().getId();
        logger.debug("Thread # " + threadId + " is doing this task");
    }
}

Test for array of string type in TypeScript

Another option is Array.isArray()

if(! Array.isArray(classNames) ){
    classNames = [classNames]
}

Running an outside program (executable) in Python?

Your usage is correct. I bet that your external program, flow.exe, needs to be executed in its directory, because it accesses some external files stored there.

So you might try:

import sys, string, os, arcgisscripting
os.chdir('c:\\documents and settings\\flow_model')
os.system('"C:\\Documents and Settings\\flow_model\\flow.exe"')

(Beware of the double quotes inside the single quotes...)

Java NIO FileChannel versus FileOutputstream performance / usefulness

If the thing you want to compare is performance of file copying, then for the channel test you should do this instead:

final FileInputStream inputStream = new FileInputStream(src);
final FileOutputStream outputStream = new FileOutputStream(dest);
final FileChannel inChannel = inputStream.getChannel();
final FileChannel outChannel = outputStream.getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
inChannel.close();
outChannel.close();
inputStream.close();
outputStream.close();

This won't be slower than buffering yourself from one channel to the other, and will potentially be massively faster. According to the Javadocs:

Many operating systems can transfer bytes directly from the filesystem cache to the target channel without actually copying them.

How to set image width to be 100% and height to be auto in react native?

"resizeMode" isn't style property. Should move to Image component's Props like below code.

const win = Dimensions.get('window');

const styles = StyleSheet.create({
    image: {
        flex: 1,
        alignSelf: 'stretch',
        width: win.width,
        height: win.height,
    }
});

...
    <Image 
       style={styles.image}
       resizeMode={'contain'}   /* <= changed  */
       source={require('../../../images/collection-imag2.png')} /> 
...

Image's height won't become automatically because Image component is required both width and height in style props. So you can calculate by using getSize() method for remote images like this answer and you can also calculate image ratio for static images like this answer.

There are a lot of useful open source libraries -

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

Please check the fields value you are passing, are valid and according to database fields. For example number of characters passed in a particular field are less than the characters defined in database table field.

jquery - How to determine if a div changes its height or any css attribute?

For future sake I'll post this. If you do not need to support < IE11 then you should use MutationObserver.

Here is a link to the caniuse js MutationObserver

Simple usage with powerful results.

    var observer = new MutationObserver(function (mutations) {
        //your action here
    });

    //set up your configuration
    //this will watch to see if you insert or remove any children
    var config = { subtree: true, childList: true };

    //start observing
    observer.observe(elementTarget, config);

When you don't need to observe any longer just disconnect.

    observer.disconnect();

Check out the MDN documentation for more information

How to update maven repository in Eclipse?

You can right-click on your project then Maven > Update Project..., then select Force Update of Snapshots/Releases checkbox then click OK.

How do I force Postgres to use a particular index?

Assuming you're asking about the common "index hinting" feature found in many databases, PostgreSQL doesn't provide such a feature. This was a conscious decision made by the PostgreSQL team. A good overview of why and what you can do instead can be found here. The reasons are basically that it's a performance hack that tends to cause more problems later down the line as your data changes, whereas PostgreSQL's optimizer can re-evaluate the plan based on the statistics. In other words, what might be a good query plan today probably won't be a good query plan for all time, and index hints force a particular query plan for all time.

As a very blunt hammer, useful for testing, you can use the enable_seqscan and enable_indexscan parameters. See:

These are not suitable for ongoing production use. If you have issues with query plan choice, you should see the documentation for tracking down query performance issues. Don't just set enable_ params and walk away.

Unless you have a very good reason for using the index, Postgres may be making the correct choice. Why?

  • For small tables, it's faster to do sequential scans.
  • Postgres doesn't use indexes when datatypes don't match properly, you may need to include appropriate casts.
  • Your planner settings might be causing problems.

See also this old newsgroup post.

Angularjs -> ng-click and ng-show to show a div

Very simple just do this:

<button ng-click="hideShow=(hideShow ? false : true)">Toggle</button>

<div ng-if="hideShow">hide and show content ...</div>

Why doesn't Java offer operator overloading?

Well you can really shoot yourself in the foot with operator overloading. It's like with pointers people make stupid mistakes with them and so it was decided to take the scissors away.

At least I think that's the reason. I'm on your side anyway. :)

.NET: Simplest way to send POST with data and read response

Given other answers are a few years old, currently here are my thoughts that may be helpful:

Simplest way

private async Task<string> PostAsync(Uri uri, HttpContent dataOut)
{
    var client = new HttpClient();
    var response = await client.PostAsync(uri, dataOut);
    return await response.Content.ReadAsStringAsync();
    // For non strings you can use other Content.ReadAs...() method variations
}

A More Practical Example

Often we are dealing with known types and JSON, so you can further extend this idea with any number of implementations, such as:

public async Task<T> PostJsonAsync<T>(Uri uri, object dtoOut)
{
    var content = new StringContent(JsonConvert.SerializeObject(dtoOut));
    content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

    var results = await PostAsync(uri, content); // from previous block of code

    return JsonConvert.DeserializeObject<T>(results); // using Newtonsoft.Json
}

An example of how this could be called:

var dataToSendOutToApi = new MyDtoOut();
var uri = new Uri("https://example.com");
var dataFromApi = await PostJsonAsync<MyDtoIn>(uri, dataToSendOutToApi);

Objective-C declared @property attributes (nonatomic, copy, strong, weak)

nonatomic property means @synthesized methods are not going to be generated threadsafe -- but this is much faster than the atomic property since extra checks are eliminated.

strong is used with ARC and it basically helps you , by not having to worry about the retain count of an object. ARC automatically releases it for you when you are done with it.Using the keyword strong means that you own the object.

weak ownership means that you don't own it and it just keeps track of the object till the object it was assigned to stays , as soon as the second object is released it loses is value. For eg. obj.a=objectB; is used and a has weak property , than its value will only be valid till objectB remains in memory.

copy property is very well explained here

strong,weak,retain,copy,assign are mutually exclusive so you can't use them on one single object... read the "Declared Properties " section

hoping this helps you out a bit...

MySQL Insert query doesn't work with WHERE clause

You can't combine a WHERE clause with a VALUES clause. You have two options as far as I am aware-

  1. INSERT specifying values

    INSERT INTO Users(weight, desiredWeight) 
    VALUES (160,145)
    
  2. INSERT using a SELECT statement

    INSERT INTO Users(weight, desiredWeight) 
    SELECT weight, desiredWeight 
    FROM AnotherTable 
    WHERE id = 1
    

How to check if a number is a power of 2

I see many answers are suggesting to return n && !(n & (n - 1)) but to my experience if the input values are negative it returns false values. I will share another simple approach here since we know a power of two number have only one set bit so simply we will count number of set bit this will take O(log N) time.

while (n > 0) {
    int count = 0;
    n = n & (n - 1);
    count++;
}
return count == 1;

Check this article to count no. of set bits

Loop over array dimension in plpgsql

Since PostgreSQL 9.1 there is the convenient FOREACH:

DO
$do$
DECLARE
   m   varchar[];
   arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
   FOREACH m SLICE 1 IN ARRAY arr
   LOOP
      RAISE NOTICE 'another_func(%,%)',m[1], m[2];
   END LOOP;
END
$do$

Solution for older versions:

DO
$do$
DECLARE
   arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
   FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
   LOOP
      RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
   END LOOP;
END
$do$

Also, there is no difference between varchar[] and varchar[][] for the PostgreSQL type system. I explain in more detail here.

The DO statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql is the default (so you can omit the declaration).

R - test if first occurrence of string1 is followed by string2

I think it's worth answering the generic question "R - test if string contains string" here.

For that, use the grep function.

# example:
> if(length(grep("ab","aacd"))>0) print("found") else print("Not found")
[1] "Not found"
> if(length(grep("ab","abcd"))>0) print("found") else print("Not found")
[1] "found"

How do I change the font size and color in an Excel Drop Down List?

I created a custom view that is at 100%. Use the dropdowns then click to view page layout to go back to a smaller view.

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

import the HttpClientModule in your app.module.ts

import {HttpClientModule} from '@angular/common/http';

...
@NgModule({
...
  imports: [
    //other content,
    HttpClientModule
  ]
})

How to set limits for axes in ggplot2 R plots?

Basically you have two options

scale_x_continuous(limits = c(-5000, 5000))

or

coord_cartesian(xlim = c(-5000, 5000)) 

Where the first removes all data points outside the given range and the second only adjusts the visible area. In most cases you would not see the difference, but if you fit anything to the data it would probably change the fitted values.

You can also use the shorthand function xlim (or ylim), which like the first option removes data points outside of the given range:

+ xlim(-5000, 5000)

For more information check the description of coord_cartesian.

The RStudio cheatsheet for ggplot2 makes this quite clear visually. Here is a small section of that cheatsheet:

enter image description here

Distributed under CC BY.

Oracle PL/SQL : remove "space characters" from a string

To remove any whitespaces you could use:

myValue := replace(replace(replace(replace(replace(replace(myValue, chr(32)), chr(9)),  chr(10)), chr(11)), chr(12)), chr(13));

Example: remove all whitespaces in a table:

update myTable t
    set t.myValue = replace(replace(replace(replace(replace(replace(t.myValue, chr(32)), chr(9)), chr(10)), chr(11)), chr(12)), chr(13))
where
    length(t.myValue) > length(replace(replace(replace(replace(replace(replace(t.myValue, chr(32)), chr(9)), chr(10)), chr(11)), chr(12)), chr(13)));

or

update myTable t
    set t.myValue = replace(replace(replace(replace(replace(replace(t.myValue, chr(32)), chr(9)), chr(10)), chr(11)), chr(12)), chr(13))
where
    t.myValue like '% %'

Cause of No suitable driver found for

As some answered before, this line of code solved the problem

Class.forName("org.hsqldb.jdbcDriver");

But my app is running in some tomcats but only in one installation I had to add this code.

How to split a string in Ruby and get all items except the first one?

Try this:

first, *rest = ex.split(/, /)

Now first will be the first value, rest will be the rest of the array.

How do you delete an ActiveRecord object?

It's destroy and destroy_all methods, like

user.destroy
User.find(15).destroy
User.destroy(15)
User.where(age: 20).destroy_all
User.destroy_all(age: 20)

Alternatively you can use delete and delete_all which won't enforce :before_destroy and :after_destroy callbacks or any dependent association options.

User.delete_all(condition: 'value') will allow you to delete records without a primary key

Note: from @hammady's comment, user.destroy won't work if User model has no primary key.

Note 2: From @pavel-chuchuva's comment, destroy_all with conditions and delete_all with conditions has been deprecated in Rails 5.1 - see guides.rubyonrails.org/5_1_release_notes.html

CodeIgniter Disallowed Key Characters

Step1. Search for function _clean_input_keys on /system/core/Input.php

Step2. Modify this line

exit(‘Disallowed Key Characters.’);

to

exit(‘Disallowed Key Characters.’ . $str);

Step3. Refresh page to see the characters which generate the error

Step4. If you need to add those characters into the exception list, just add to this line

if ( ! preg_match(“/^[a-z0-9:_/-]+$|/i”, $str))

I add | (pipe) character on the example above

Check if String / Record exists in DataTable

Something like this

 string find = "item_manuf_id = 'some value'";
 DataRow[] foundRows = table.Select(find);

javascript multiple OR conditions in IF statement

This is an example:

false && true || true   // returns true
false && (true || true) // returns false
(true || true || true)  // returns true
false || true           // returns true
true || false           // returns true

How to select min and max values of a column in a datatable?

var answer = accountTable.Aggregate(new { Min = int.MinValue, Max = int.MaxValue }, 
                                        (a, b) => new { Min = Math.Min(a.Min, b.Field<int>("AccountLevel")),
                                                        Max = Math.Max(a.Max, b.Field<int>("AccountLevel")) });
int min = answer.Min;
int max = answer.Max;

1 iteration, linq style :)

How can I set multiple CSS styles in JavaScript?

Your best bet may be to create a function that sets styles on your own:

var setStyle = function(p_elem, p_styles)
{
    var s;
    for (s in p_styles)
    {
        p_elem.style[s] = p_styles[s];
    }
}

setStyle(myDiv, {'color': '#F00', 'backgroundColor': '#000'});
setStyle(myDiv, {'color': mycolorvar, 'backgroundColor': mybgvar});

Note that you will still have to use the javascript-compatible property names (hence backgroundColor)

Set a persistent environment variable from cmd.exe

Use the SETX command (note the 'x' suffix) to set variables that persist after the cmd window has been closed.

For example, to set an env var "foo" with value of "bar":

setx foo bar

Though it's worth reading the 'notes' that are displayed if you print the usage (setx /?), in particular:

2) On a local system, variables created or modified by this tool will be available in future command windows but not in the current CMD.exe command window.

3) On a remote system, variables created or modified by this tool will be available at the next logon session.

In PowerShell, the [Environment]::SetEnvironmentVariable command.

Mercurial — revert back to old version and continue from there

IMHO, hg strip -r 39 suits this case better.

It requires the mq extension to be enabled and has the same limitations as the "cloning repo method" recommended by Martin Geisler: If the changeset was somehow published, it will (probably) return to your repo at some point in time because you only changed your local repo.

What is cURL in PHP?

cURL is a library that lets you make HTTP requests in PHP. Everything you need to know about it (and most other extensions) can be found in the PHP manual.

In order to use PHP's cURL functions you need to install the » libcurl package. PHP requires that you use libcurl 7.0.2-beta or higher. In PHP 4.2.3, you will need libcurl version 7.9.0 or higher. From PHP 4.3.0, you will need a libcurl version that's 7.9.8 or higher. PHP 5.0.0 requires a libcurl version 7.10.5 or greater.

You can make HTTP requests without cURL, too, though it requires allow_url_fopen to be enabled in your php.ini file.

// Make a HTTP GET request and print it (requires allow_url_fopen to be enabled)
print file_get_contents('http://www.example.com/');

Mixed mode assembly is built against version ‘v2.0.50727' of the runtime

Enabling the legacy from app.config didn't work for me. For unknown reasons, my application wasn't activating V2 runtime policy. I found a work around here.

Enabling the legacy from app.config is a recommended approach but in some cases it doesn't work as expected. Use the following code with in your main application to force Legacy V2 policy:

public static class RuntimePolicyHelper
{
public static bool LegacyV2RuntimeEnabledSuccessfully { get; private set; }

static RuntimePolicyHelper()
{
    ICLRRuntimeInfo clrRuntimeInfo =
        (ICLRRuntimeInfo)RuntimeEnvironment.GetRuntimeInterfaceAsObject(
            Guid.Empty, 
            typeof(ICLRRuntimeInfo).GUID);
    try
    {
        clrRuntimeInfo.BindAsLegacyV2Runtime();
        LegacyV2RuntimeEnabledSuccessfully = true;
    }
    catch (COMException)
    {
        // This occurs with an HRESULT meaning 
        // "A different runtime was already bound to the legacy CLR version 2 activation policy."
        LegacyV2RuntimeEnabledSuccessfully = false;
    }
}

[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("BD39D1D2-BA2F-486A-89B0-B4B0CB466891")]
private interface ICLRRuntimeInfo
{
    void xGetVersionString();
    void xGetRuntimeDirectory();
    void xIsLoaded();
    void xIsLoadable();
    void xLoadErrorString();
    void xLoadLibrary();
    void xGetProcAddress();
    void xGetInterface();
    void xSetDefaultStartupFlags();
    void xGetDefaultStartupFlags();

    [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
    void BindAsLegacyV2Runtime();
}
}

How to read a value from the Windows registry

Since Windows >=Vista/Server 2008, RegGetValue is available, which is a safer function than RegQueryValueEx. No need for RegOpenKeyEx, RegCloseKey or NUL termination checks of string values (REG_SZ, REG_MULTI_SZ, REG_EXPAND_SZ).

#include <iostream>
#include <string>
#include <exception>
#include <windows.h>

/*! \brief                          Returns a value from HKLM as string.
    \exception  std::runtime_error  Replace with your error handling.
*/
std::wstring GetStringValueFromHKLM(const std::wstring& regSubKey, const std::wstring& regValue)
{
    size_t bufferSize = 0xFFF; // If too small, will be resized down below.
    std::wstring valueBuf; // Contiguous buffer since C++11.
    valueBuf.resize(bufferSize);
    auto cbData = static_cast<DWORD>(bufferSize * sizeof(wchar_t));
    auto rc = RegGetValueW(
        HKEY_LOCAL_MACHINE,
        regSubKey.c_str(),
        regValue.c_str(),
        RRF_RT_REG_SZ,
        nullptr,
        static_cast<void*>(valueBuf.data()),
        &cbData
    );
    while (rc == ERROR_MORE_DATA)
    {
        // Get a buffer that is big enough.
        cbData /= sizeof(wchar_t);
        if (cbData > static_cast<DWORD>(bufferSize))
        {
            bufferSize = static_cast<size_t>(cbData);
        }
        else
        {
            bufferSize *= 2;
            cbData = static_cast<DWORD>(bufferSize * sizeof(wchar_t));
        }
        valueBuf.resize(bufferSize);
        rc = RegGetValueW(
            HKEY_LOCAL_MACHINE,
            regSubKey.c_str(),
            regValue.c_str(),
            RRF_RT_REG_SZ,
            nullptr,
            static_cast<void*>(valueBuf.data()),
            &cbData
        );
    }
    if (rc == ERROR_SUCCESS)
    {
        cbData /= sizeof(wchar_t);
        valueBuf.resize(static_cast<size_t>(cbData - 1)); // remove end null character
        return valueBuf;
    }
    else
    {
        throw std::runtime_error("Windows system error code: " + std::to_string(rc));
    }
}

int main()
{
    std::wstring regSubKey;
#ifdef _WIN64 // Manually switching between 32bit/64bit for the example. Use dwFlags instead.
    regSubKey = L"SOFTWARE\\WOW6432Node\\Company Name\\Application Name\\";
#else
    regSubKey = L"SOFTWARE\\Company Name\\Application Name\\";
#endif
    std::wstring regValue(L"MyValue");
    std::wstring valueFromRegistry;
    try
    {
        valueFromRegistry = GetStringValueFromHKLM(regSubKey, regValue);
    }
    catch (std::exception& e)
    {
        std::cerr << e.what();
    }
    std::wcout << valueFromRegistry;
}

Its parameter dwFlags supports flags for type restriction, filling the value buffer with zeros on failure (RRF_ZEROONFAILURE) and 32/64bit registry access (RRF_SUBKEY_WOW6464KEY, RRF_SUBKEY_WOW6432KEY) for 64bit programs.

Read data from SqlDataReader

For a single result:

if (reader.Read())
{
    Response.Write(reader[0].ToString());
    Response.Write(reader[1].ToString());
}

For multiple results:

while (reader.Read())
{
    Response.Write(reader[0].ToString());
    Response.Write(reader[1].ToString());
}

port 8080 is already in use and no process using 8080 has been listed

PID is the process ID - not the port number. You need to look for an entry with ":8080" at the end of the address/port part (the second column). Then you can look at the PID and use Task Manager to work out which process is involved... or run netstat -abn which will show the process names (but must be run under an administrator account).

Having said that, I would expect the find "8080" to find it...

Another thing to do is just visit http://localhost:8080 - on that port, chances are it's a web server of some description.

How to repeat a string a variable number of times in C++?

I know this is an old question, but I was looking to do the same thing and have found what I think is a simpler solution. It appears that cout has this function built in with cout.fill(), see the link for a 'full' explanation

http://www.java-samples.com/showtutorial.php?tutorialid=458

cout.width(11);
cout.fill('.');
cout << "lolcat" << endl;

outputs

.....lolcat

How to use java.String.format in Scala?

In Scala 2.10

val name = "Ivan"
val weather = "sunny"

s"Hello $name, it's $weather today!"

Where does Chrome store cookies?

For Google chrome Version 56.0.2924.87 (Latest Release) cookies are found inside profile1 folder.

If you browse that you can find variety of information.

There is a separate file called "Cookies". Also the Cache folder is inside this folder.

Path : C:\Users\user_name\AppData\Local\Google\Chrome\User Data\Profile 1

Remember to replace user_name.

For Version 61.0.3163.100
Path : C:\Users\user_name\AppData\Local\Google\Chrome\User Data\Default

Inside this folder there is Cookies file and Cache folder.

How to get the version of ionic framework?

You can use command ionic info to get details of ionic CLI , angular CLI , Node JS version and NPM version

Programmatically close aspx page from code behind

You would typically do something like:

protected void btnClose_Click(object sender, EventArgs e)
{
    ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
}

However, keep in mind that different things will happen in different scenerios. Firefox won't let you close a window that wasn't opened by you (opened with window.open()).

IE7 will prompt the user with a "This page is trying to close (Yes | No)" dialog.

In any case, you should be prepared to deal with the window not always closing!

One fix for the 2 above issues is to use:

protected void btnClose_Click(object sender, EventArgs e) {
    ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.open('close.html', '_self', null);", true);
}

And create a close.html:

<html><head>
 <title></title>
 <script language="javascript" type="text/javascript">
     var redirectTimerId = 0;
     function closeWindow()
     {
         window.opener = top;
         redirectTimerId = window.setTimeout('redirect()', 2000);
         window.close(); 
     }

     function stopRedirect()
     {
         window.clearTimeout(redirectTimerId);
     }

     function redirect()
     {
         window.location = 'default.aspx';
     }
 </script>
 </head>
 <body onload="closeWindow()" onunload="stopRedirect()" style="">
     <center><h1>Please Wait...</h1></center>
 </body></html>

Note that close.html will redirect to default.aspx if the window does not close after 2 sec for some reason.

Registry key Error: Java version has value '1.8', but '1.7' is required

I didn't delete any of the java.exe files, but changed the ordering of my System - "path" variable - so that it reflected %JAVA_HOME%\bin as the first entry. That did the trick.

How to search for file names in Visual Studio?

I'd recommend PhatStudio if you're using upto VS 2012. Works pretty fast, and supports multi-word search by using "space". So to search for LoginController, you could press Alt+O and search using "Lo Con".

enter image description here

You could also use ReSharper (paid) and CodeMaid (free) to do this.

Hide text using css

I don't recall where I picked this up, but have been using it successfully for ages.

  =hide-text()
    font: 0/0 a
    text-shadow: none
    color: transparent

My mixin is in sass however you can use it any way you see fit. For good measure I generally keep a .hidden class somewhere in my project to attach to elements to avoid duplication.

List of enum values in java

It is possible but you should use EnumSet instead

enum MyEnum {
    ONE, TWO;
    public static final EnumSet<MyEnum> all = EnumSet.of(ONE, TWO);
}

How to Set/Update State of StatefulWidget from other StatefulWidget in Flutter?

1.On Child Widget : add parameter Function paramter

class ChildWidget extends StatefulWidget {
  final Function() notifyParent;
  ChildWidget({Key key, @required this.notifyParent}) : super(key: key);
}

2.On Parent Widget : create a Function for the child to callback

refresh() {
  setState(() {});
}

3.On Parent Widget : pass parentFunction to Child Widget

new ChildWidget( notifyParent: refresh );  

4.On Child Widget : call the Parent Function

  widget.notifyParent();

PHP include relative path

While I appreciate you believe absolute paths is not an option, it is a better option than relative paths and updating the PHP include path.

Use absolute paths with an constant you can set based on environment.

if (is_production()) {
    define('ROOT_PATH', '/some/production/path');
}
else {
    define('ROOT_PATH', '/root');
}

include ROOT_PATH . '/connect.php';

As commented, ROOT_PATH could also be derived from the current path, $_SERVER['DOCUMENT_ROOT'], etc.

Is it possible to modify a registry entry via a .bat/.cmd script?

@Franci Penov - modify is possible in the sense of overwrite with /f, eg

reg add "HKCU\Software\etc\etc" /f /v "value" /t REG_SZ /d "Yes"

How do I select last 5 rows in a table without sorting?

There is a handy trick that works in some databases for ordering in database order,

SELECT * FROM TableName ORDER BY true

Apparently, this can work in conjunction with any of the other suggestions posted here to leave the results in "order they came out of the database" order, which in some databases, is the order they were last modified in.

How to bind Close command to a button

I think that in real world scenarios a simple click handler is probably better than over-complicated command-based systems but you can do something like that:

using RelayCommand from this article http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

public class MyCommands
{
    public static readonly ICommand CloseCommand =
        new RelayCommand( o => ((Window)o).Close() );
}
<Button Content="Close Window"
        Command="{X:Static local:MyCommands.CloseCommand}"
        CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, 
                           AncestorType={x:Type Window}}}"/>

Remove folder and its contents from git/GitHub's history

The best and most accurate method I found was to download the bfg.jar file: https://rtyley.github.io/bfg-repo-cleaner/

Then run the commands:

git clone --bare https://project/repository project-repository
cd project-repository
java -jar bfg.jar --delete-folders DIRECTORY_NAME
git reflog expire --expire=now --all && git gc --prune=now --aggressive
git push --mirror https://project/new-repository

If you want to delete files then use the delete-files option instead:

java -jar bfg.jar --delete-files *.pyc

Sorting a vector in descending order

bool comp(int i, int j) { return i > j; }
sort(numbers.begin(), numbers.end(), comp);

Escape string for use in Javascript regex

Short 'n Sweet

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

Example

escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");

>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "

(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)

Install

Available on npm as escape-string-regexp

npm install --save escape-string-regexp

Note

See MDN: Javascript Guide: Regular Expressions

Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.

.

.

.

.

Test Case: A typical url

escapeRegExp("/path/to/resource.html?search=query");

>>> "\/path\/to\/resource\.html\?search=query"

The Long Answer

If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.

var escapeRegExp;

(function () {
  // Referring to the table here:
  // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
  // these characters should be escaped
  // \ ^ $ * + ? . ( ) | { } [ ]
  // These characters only have special meaning inside of brackets
  // they do not need to be escaped, but they MAY be escaped
  // without any adverse effects (to the best of my knowledge and casual testing)
  // : ! , = 
  // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)

  var specials = [
        // order matters for these
          "-"
        , "["
        , "]"
        // order doesn't matter for any of these
        , "/"
        , "{"
        , "}"
        , "("
        , ")"
        , "*"
        , "+"
        , "?"
        , "."
        , "\\"
        , "^"
        , "$"
        , "|"
      ]

      // I choose to escape every character with '\'
      // even though only some strictly require it when inside of []
    , regex = RegExp('[' + specials.join('\\') + ']', 'g')
    ;

  escapeRegExp = function (str) {
    return str.replace(regex, "\\$&");
  };

  // test escapeRegExp("/path/to/res?search=this.that")
}());

Any shortcut to initialize all array elements to zero?

declare the array as instance variable in the class i.e. out of every method and JVM will give it 0 as default value. You need not to worry anymore

Send File Attachment from Form Using phpMailer and PHP

Try:

if (isset($_FILES['uploaded_file']) &&
    $_FILES['uploaded_file']['error'] == UPLOAD_ERR_OK) {
    $mail->AddAttachment($_FILES['uploaded_file']['tmp_name'],
                         $_FILES['uploaded_file']['name']);
}

Basic example can also be found here.

The function definition for AddAttachment is:

public function AddAttachment($path,
                              $name = '',
                              $encoding = 'base64',
                              $type = 'application/octet-stream')

The current .NET SDK does not support targeting .NET Standard 2.0 error in Visual Studio 2017 update 15.3

make sure you download the x86 SDK instead of only the x64 SDK for visual studio.

How to continue a Docker container which has exited

If you want to do it in multiple, easy-to-remember commands:

  1. list stopped containers:

docker ps -a

  1. copy the name or the container id of the container you want to attach to, and start the container with:

docker start -i <name/id>

The -i flag tells docker to attach to the container's stdin.

If the container wasn't started with an interactive shell to connect to, you need to do this to run a shell:

docker start <name/id>
docker exec -it <name/id> /bin/sh

The /bin/sh is the shell usually available with alpine-based images.

HTML SELECT - Change selected option by VALUE using JavaScript

If you are using jQuery:

$('#sel').val('bike');

How do I use cx_freeze?

  • Add import sys as the new topline
  • You misspelled "executables" on the last line.
  • Remove script = on last line.

The code should now look like:

import sys
from cx_Freeze import setup, Executable

setup(
    name = "On Dijkstra's Algorithm",
    version = "3.1",
    description = "A Dijkstra's Algorithm help tool.",
    executables = [Executable("Main.py", base = "Win32GUI")])

Use the command prompt (cmd) to run python setup.py build. (Run this command from the folder containing setup.py.) Notice the build parameter we added at the end of the script call.

Could not resolve Spring property placeholder

the following property must be added in the gradle.build file

processResources {
    filesMatching("**/*.properties") {
        expand project.properties
    }
}

Additionally, if working with Intellij, the project must be re-imported.

How to convert Blob to File in JavaScript

This problem was bugg me for hours. I was using Nextjs and trying to convert canvas to an image file.

I just use the other guy's solution but the created file was empty.

So if this is your problem you should mention the size property in the file object.

new File([Blob], `my_image${new Date()}.jpeg`, {
  type: "image/jpeg",
  lastModified: new Date(),
  size: 2,
});

just add it, the value it's not important.

Node.js: for each … in not working

for those used to php:

//add this function
function foreach(arr, func){
  for(var i in arr){
    func(i, arr[i]);
  }
}

usage:

foreach(myArray, function(i, v){
  //run code here
});

similar to php version:

foreach(myArray as i=>v){
  //run code here
}

How to change fontFamily of TextView in Android

The easiest way to add the font programatically to a TextView is to, first, add the font file in your Assets folder in the project. For example your font path is looking like this: assets/fonts/my_font.otf

And add it to a TextView as:

Kotlin

val font_path = "fonts/my_font.otf"  

myTypeface = Typeface.createFromAsset(MyApplication.getInstance().assets, font_path)

textView.typeface = myTypeface

Java

String font_path = "fonts/my_font.otf";
Typeface myTypeface = Typeface.createFromAsset(MyApplication.getInstance().assets, font_path)
textView.setTypeface(myTypeface);

How to have stored properties in Swift, the same way I had on Objective-C?

Here is simplified and more expressive solution. It works for both value and reference types. The approach of lifting is taken from @HepaKKes answer.

Association code:

import ObjectiveC

final class Lifted<T> {
    let value: T
    init(_ x: T) {
        value = x
    }
}

private func lift<T>(_ x: T) -> Lifted<T>  {
    return Lifted(x)
}

func associated<T>(to base: AnyObject,
                key: UnsafePointer<UInt8>,
                policy: objc_AssociationPolicy = .OBJC_ASSOCIATION_RETAIN,
                initialiser: () -> T) -> T {
    if let v = objc_getAssociatedObject(base, key) as? T {
        return v
    }

    if let v = objc_getAssociatedObject(base, key) as? Lifted<T> {
        return v.value
    }

    let lifted = Lifted(initialiser())
    objc_setAssociatedObject(base, key, lifted, policy)
    return lifted.value
}

func associate<T>(to base: AnyObject, key: UnsafePointer<UInt8>, value: T, policy: objc_AssociationPolicy = .OBJC_ASSOCIATION_RETAIN) {
    if let v: AnyObject = value as AnyObject? {
        objc_setAssociatedObject(base, key, v, policy)
    }
    else {
        objc_setAssociatedObject(base, key, lift(value), policy)
    }
}

Example of usage:

1) Create extension and associate properties to it. Let's use both value and reference type properties.

extension UIButton {

    struct Keys {
        static fileprivate var color: UInt8 = 0
        static fileprivate var index: UInt8 = 0
    }

    var color: UIColor {
        get {
            return associated(to: self, key: &Keys.color) { .green }
        }
        set {
            associate(to: self, key: &Keys.color, value: newValue)
        }
    }

    var index: Int {
        get {
            return associated(to: self, key: &Keys.index) { -1 }
        }
        set {
            associate(to: self, key: &Keys.index, value: newValue)
        }
    }

}

2) Now you can use just as regular properties:

    let button = UIButton()
    print(button.color) // UIExtendedSRGBColorSpace 0 1 0 1 == green
    button.color = .black
    print(button.color) // UIExtendedGrayColorSpace 0 1 == black

    print(button.index) // -1
    button.index = 3
    print(button.index) // 3

More details:

  1. Lifting is needed for wrapping value types.
  2. Default associated object behavior is retain. If you want to learn more about associated objects, I'd recommend checking this article.

Can we write our own iterator in Java?

Sure. An iterator is just an implementation of the java.util.Iterator interface. If you're using an existing iterable object (say, a LinkedList) from java.util, you'll need to either subclass it and override its iterator function so that you return your own, or provide a means of wrapping a standard iterator in your special Iterator instance (which has the advantage of being more broadly used), etc.

Shell equality operators (=, ==, -eq)

It's the other way around: = and == are for string comparisons, -eq is for numeric ones. -eq is in the same family as -lt, -le, -gt, -ge, and -ne, if that helps you remember which is which.

== is a bash-ism, by the way. It's better to use the POSIX =. In bash the two are equivalent, and in plain sh = is the only one guaranteed to work.

$ a=foo
$ [ "$a" = foo ]; echo "$?"       # POSIX sh
0
$ [ "$a" == foo ]; echo "$?"      # bash specific
0
$ [ "$a" -eq foo ]; echo "$?"     # wrong
-bash: [: foo: integer expression expected
2

(Side note: Quote those variable expansions! Do not leave out the double quotes above.)

If you're writing a #!/bin/bash script then I recommend using [[ instead. The doubled form has more features, more natural syntax, and fewer gotchas that will trip you up. Double quotes are no longer required around $a, for one:

$ [[ $a == foo ]]; echo "$?"      # bash specific
0

See also:

How to resolve the C:\fakepath?

Use file readers:

$(document).ready(function() {
        $("#input-file").change(function() {
            var length = this.files.length;
            if (!length) {
                return false;
            }
            useImage(this);
        });
    });

    // Creating the function
    function useImage(img) {
        var file = img.files[0];
        var imagefile = file.type;
        var match = ["image/jpeg", "image/png", "image/jpg"];
        if (!((imagefile == match[0]) || (imagefile == match[1]) || (imagefile == match[2]))) {
            alert("Invalid File Extension");
        } else {
            var reader = new FileReader();
            reader.onload = imageIsLoaded;
            reader.readAsDataURL(img.files[0]);
        }

        function imageIsLoaded(e) {
            $('div.withBckImage').css({ 'background-image': "url(" + e.target.result + ")" });

        }
    }

Reading settings from app.config or web.config in .NET

web.config is used with web applications. web.config by default has several configurations required for the web application. You can have a web.config for each folder under your web application.

app.config is used for Windows applications. When you build the application in Visual Studio, it will be automatically renamed to <appname>.exe.config and this file has to be delivered along with your application.

You can use the same method to call the app settings values from both configuration files: System.Configuration.ConfigurationSettings.AppSettings["Key"]

How do you run your own code alongside Tkinter's event loop?

The solution posted by Bjorn results in a "RuntimeError: Calling Tcl from different appartment" message on my computer (RedHat Enterprise 5, python 2.6.1). Bjorn might not have gotten this message, since, according to one place I checked, mishandling threading with Tkinter is unpredictable and platform-dependent.

The problem seems to be that app.start() counts as a reference to Tk, since app contains Tk elements. I fixed this by replacing app.start() with a self.start() inside __init__. I also made it so that all Tk references are either inside the function that calls mainloop() or are inside functions that are called by the function that calls mainloop() (this is apparently critical to avoid the "different apartment" error).

Finally, I added a protocol handler with a callback, since without this the program exits with an error when the Tk window is closed by the user.

The revised code is as follows:

# Run tkinter code in another thread

import tkinter as tk
import threading

class App(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        self.start()

    def callback(self):
        self.root.quit()

    def run(self):
        self.root = tk.Tk()
        self.root.protocol("WM_DELETE_WINDOW", self.callback)

        label = tk.Label(self.root, text="Hello World")
        label.pack()

        self.root.mainloop()


app = App()
print('Now we can continue running code while mainloop runs!')

for i in range(100000):
    print(i)

How do I find and replace all occurrences (in all files) in Visual Studio Code?

I'm using Visual Studio Code 1.8, and this feature is available. But it's a little tricky to understand at first, and (at the time of writing) the docs don't explain clearly how to use it, so here's how it works, step by step:

Invoke Replace in Files (under the Edit menu, or with shortcut Ctrl+Shift+H)

You'll see a standard Find/Replace input replacing the files pane on the left:

enter image description here

Enter your search string and the replace string, then press enter. It may churn for a second searching all files, then it'll show the proposed changes in all your project files -- but note, these changes haven't been made yet! Here's what it looks like:

enter image description here

Now you need to make the changes (and even after that, you have to save the modified files.)

You can make those changes in various ways:

1) Make all changes to all files at once.

Click the replace icon next to your replace string (note: you'll get a dialog to confirm this bulk action.)

enter image description here

2) Make all changes in a single file at once.

Click the replace icon next to the filename (note: the icon only shows up when you hover over the filename row)

enter image description here

3) Make a single change in a single file.

Click the replace icon next to the individual change: (note: the icon only shows up when you hover over the change row)

enter image description here

Finally, don't forget to save!

All those files are now modified in the editor and not yet saved to disk.

Use File -> Save All (or Ctrl+Alt+S)

Update: I'm not sure when this was added, but if you click the "Replace all" button and see this dialog, clicking "Replace" will change and save all files in one click:

enter image description here

jQuery preventDefault() not triggered

Update

And there's your problem - you do have to click event handlers for some a elements. In this case, the order in which you attach the handlers matters since they'll be fired in that order.

Here's a working fiddle that shows the behaviour you want.

This should be your code:

$(document).ready(function(){


    $('#tabs div.tab').hide();
    $('#tabs div.tab:first').show();
    $('#tabs ul li:first').addClass('active');

    $("div.subtab_left li.notebook a").click(function(e) {
        e.stopImmediatePropagation();
        alert("asdasdad");
        return false;
    });

    $('#tabs ul li a').click(function(){
        alert("Handling link click");
        $('#tabs ul li').removeClass('active');
        $(this).parent().addClass('active');
        var currentTab = $(this).attr('href');
        $('#tabs div.tab').hide();
        $(currentTab).show();
        return false;
    });

});

Note that the order of attaching the handlers has been exchanged and e.stopImmediatePropagation() is used to stop the other click handler from firing while return false is used to stop the default behaviour of following the link (as well as stopping the bubbling of the event. You may find that you need to use only e.stopPropagation).

Play around with this, if you remove the e.stopImmediatePropagation() you'll find that the second click handler's alert will fire after the first alert. Removing the return false will have no effect on this behaviour but will cause links to be followed by the browser.

Note

A better fix might be to ensure that the selectors return completely different sets of elements so there is no overlap but this might not always be possible in which case the solution described above might be one way to consider.


  1. I don't see why your first code snippet would not work. What's the default action that you're seeing that you want to stop?

    If you've attached other event handlers to the link, you should look into event.stopPropagation() and event.stopImmediatePropagation() instead. Note that return false is equivalent to calling both event.preventDefault and event.stopPropagation()ref

  2. In your second code snippet, e is not defined. So an error would thrown at e.preventDefault() and the next lines never execute. In other words

    $("div.subtab_left li.notebook a").click(function() {
        e.preventDefault();
        alert("asdasdad");
        return false;   
    });
    

    should be

    //note the e declared in the function parameters now
    $("div.subtab_left li.notebook a").click(function(e) {
        e.preventDefault();
        alert("asdasdad");
        return false;   
    });
    

Here's a working example showing that this code indeed does work and that return false is not really required if you only want to stop the following of a link.

Reading in double values with scanf in c

Use the %lf format specifier to read a double:

double a;
scanf("%lf",&a);

Wikipedia has a decent reference for available format specifiers.

You'll need to use the %lf format specifier to print out the results as well:

printf("%lf %lf",a,b);

Lock screen orientation (Android)

I had a similar problem.

When I entered

<activity android:name="MyActivity" android:screenOrientation="landscape"></activity>

In the manifest file this caused that activity to display in landscape. However when I returned to previous activities they displayed in lanscape even though they were set to portrait. However by adding

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

immediately after the OnCreate section of the target activity resolved the problem. So I now use both methods.

How to set the image from drawable dynamically in android?

Try this Dynamic code

String fnm = "cat"; //  this is image file name
String PACKAGE_NAME = getApplicationContext().getPackageName();
int imgId = getResources().getIdentifier(PACKAGE_NAME+":drawable/"+fnm , null, null);
System.out.println("IMG ID :: "+imgId);
System.out.println("PACKAGE_NAME :: "+PACKAGE_NAME);
//    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),imgId);
your_image_view.setImageBitmap(BitmapFactory.decodeResource(getResources(),imgId));

In above code you will need Image-file-Name and Image-View object which both you are having.

Xcode 4 - "Archive" is greyed out?

see the picture. but I have to type enough chars to post the picture.:)

enter image description here

How to find MySQL process list and to kill those processes?

Here is the solution:

  1. Login to DB;
  2. Run a command show full processlist;to get the process id with status and query itself which causes the database hanging;
  3. Select the process id and run a command KILL <pid>; to kill that process.

Sometimes it is not enough to kill each process manually. So, for that we've to go with some trick:

  1. Login to MySQL;
  2. Run a query Select concat('KILL ',id,';') from information_schema.processlist where user='user'; to print all processes with KILL command;
  3. Copy the query result, paste and remove a pipe | sign, copy and paste all again into the query console. HIT ENTER. BooM it's done.

Rounded table corners CSS only

You can try this if you want the rounded corners on each side of the table without touching the cells : http://jsfiddle.net/7veZQ/3983/

<table>
    <tr class="first-line"><td>A</td><td>B</td></tr>
    <tr class="last-line"><td>C</td><td>D</td></tr>
</table>

Handle Button click inside a row in RecyclerView

You need to return true inside onInterceptTouchEvent() when you handle click event.

Excel VBA Run-time Error '32809' - Trying to Understand it

I exported the VBA Module - resaved the file, then imported the module again and all is well

Android refresh current activity

You can use this to refresh an Activity from within itself.

finish();
startActivity(getIntent());

ASP.Net Download file to client browser

Just a slight addition to the above solution if you are having problem with downloaded file's name...

Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");

This will return the exact file name even if it contains spaces or other characters.

What can cause a “Resource temporarily unavailable” on sock send() command

Let'e me give an example:

  1. client connect to server, and send 1MB data to server every 1 second.

  2. server side accept a connection, and then sleep 20 second, without recv msg from client.So the tcp send buffer in the client side will be full.

Code in client side:

#include <arpa/inet.h>
#include <sys/socket.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#define exit_if(r, ...)                                                                          \
    if (r) {                                                                                     \
        printf(__VA_ARGS__);                                                                     \
        printf("%s:%d error no: %d error msg %s\n", __FILE__, __LINE__, errno, strerror(errno)); \
        exit(1);                                                                                 \
    }

void setNonBlock(int fd) {
    int flags = fcntl(fd, F_GETFL, 0);
    exit_if(flags < 0, "fcntl failed");
    int r = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
    exit_if(r < 0, "fcntl failed");
}

void test_full_sock_buf_1(){
    short port = 8000;
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof addr);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = INADDR_ANY;


    int fd = socket(AF_INET, SOCK_STREAM, 0);
    exit_if(fd<0, "create socket error");

    int ret = connect(fd, (struct sockaddr *) &addr, sizeof(struct sockaddr));
    exit_if(ret<0, "connect to server error");
    setNonBlock(fd);

    printf("connect to server success");

    const int LEN = 1024 * 1000;
    char msg[LEN];  // 1MB data
    memset(msg, 'a', LEN);

    for (int i = 0; i < 1000; ++i) {
        int len = send(fd, msg, LEN, 0);
        printf("send: %d, erron: %d, %s \n", len, errno, strerror(errno));
        sleep(1);
    }

}

int main(){
    test_full_sock_buf_1();

    return 0;
}

Code in server side:

    #include <arpa/inet.h>
    #include <sys/socket.h>
    #include <stdio.h>
    #include <errno.h>
    #include <fcntl.h>
    #include <stdlib.h>
    #include <string.h>
    #define exit_if(r, ...)                                                                          \
        if (r) {                                                                                     \
            printf(__VA_ARGS__);                                                                     \
            printf("%s:%d error no: %d error msg %s\n", __FILE__, __LINE__, errno, strerror(errno)); \
            exit(1);                                                                                 \
        }
void test_full_sock_buf_1(){

    int listenfd = socket(AF_INET, SOCK_STREAM, 0);
    exit_if(listenfd<0, "create socket error");

    short port = 8000;
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof addr);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = INADDR_ANY;

    int r = ::bind(listenfd, (struct sockaddr *) &addr, sizeof(struct sockaddr));
    exit_if(r<0, "bind socket error");

    r = listen(listenfd, 100);
    exit_if(r<0, "listen socket error");

    struct sockaddr_in raddr;
    socklen_t rsz = sizeof(raddr);
    int cfd = accept(listenfd, (struct sockaddr *) &raddr, &rsz);
    exit_if(cfd<0, "accept socket error");

    sockaddr_in peer;
    socklen_t alen = sizeof(peer);
    getpeername(cfd, (sockaddr *) &peer, &alen);

    printf("accept a connection from %s:%d\n", inet_ntoa(peer.sin_addr), ntohs(peer.sin_port));

    printf("but now I will sleep 15 second, then exit");
    sleep(15);
}

Start server side, then start client side.

server side may output:

accept a connection from 127.0.0.1:35764
but now I will sleep 15 second, then exit
Process finished with exit code 0

enter image description here

client side may output:

connect to server successsend: 1024000, erron: 0, Success 
send: 1024000, erron: 0, Success 
send: 1024000, erron: 0, Success 
send: 552190, erron: 0, Success 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 11, Resource temporarily unavailable 
send: -1, erron: 104, Connection reset by peer 
send: -1, erron: 32, Broken pipe 
send: -1, erron: 32, Broken pipe 
send: -1, erron: 32, Broken pipe 
send: -1, erron: 32, Broken pipe 
send: -1, erron: 32, Broken pipe 

enter image description here

You can see, as the server side doesn't recv the data from client, so when the client side tcp buffer get full, but you still send data, so you may get Resource temporarily unavailable error.

phpmailer: Reply using only "Reply To" address

At least in the current versions of PHPMailers, there's a function clearReplyTos() to empty the reply-to array.

    $mail->ClearReplyTos();
    $mail->addReplyTo([email protected], 'EXAMPLE');

Pandas join issue: columns overlap but no suffix specified

The .join() function is using the index of the passed as argument dataset, so you should use set_index or use .merge function instead.

Please find the two examples that should work in your case:

join_df = LS_sgo.join(MSU_pi.set_index('mukey'), on='mukey', how='left')

or

join_df = df_a.merge(df_b, on='mukey', how='left')

IIS7 - The request filtering module is configured to deny a request that exceeds the request content length

I had similar issue, I resolved by changing the requestlimits maxAllowedContentLength ="40000000" section of applicationhost.config file, located in "C:\Windows\System32\inetsrv\config" directory

Look for security Section and add the sectionGroup.

<sectionGroup name="requestfiltering">
    <section name="requestlimits" maxAllowedContentLength ="40000000" />
</sectionGroup>

*NOTE delete;

<section name="requestfiltering" overrideModeDefault="Deny" />

How to make link not change color after visited?

Simply give it a css color

like :

a
{
 color:red;
}

ALTER TABLE DROP COLUMN failed because one or more objects access this column

When you alter column datatype you need to change constraint key for every database

  alter table CompanyTransactions drop constraint [df__CompanyTr__Creat__0cdae408];

When is "java.io.IOException:Connection reset by peer" thrown?

java.io.IOException: Connection reset by peer

In my case, the problem was with PUT requests (GET and POST were passing successfully).

Communication went through VPN tunnel and ssh connection. And there was a firewall with default restrictions on PUT requests... PUT requests haven't been passing throughout, to the server...

Problem was solved after exception was added to the firewall for my IP address.

What does the SQL Server Error "String Data, Right Truncation" mean and how do I fix it?

I got around the issue by using a convert on the "?", so my code looks like convert(char(50),?) and that got rid of the truncation error.

Running an Excel macro via Python?

I tried the win32com way and xlwings way but I didn't get any luck. I use PyCharm and didn't see the .WorkBook option in the autocompletion for win32com. I got the -2147352567 error when I tried to pass a workbook as variable.

Then, I found a work around using vba shell to run my Python script. Write something on the XLS file you are working with when everything is done. So that Excel knows that it's time to run the VBA macro.

But the vba Application.wait function will take up 100% cpu which is wierd. Some people said that using the windows Sleep function would fix it.

 Import xlsxwriter


 Shell "C:\xxxxx\python.exe 
 C:/Users/xxxxx/pythonscript.py"

 exitLoop = 0

wait for Python to finish its work.

  Do

  waitTime = TimeSerial(Hour(Now), Minute(Now), Second(Now) + 30)
  Application.Wait waitTime
  Set wb2 = Workbooks.Open("D:\xxxxx.xlsx", ReadOnly:=True)
  exitLoop = wb2.Worksheets("blablabla").Cells(50, 1)
  wb2.Close exitLoop

  Loop While exitLoop <> 1




  Call VbaScript

Could not create work tree dir 'example.com'.: Permission denied

Turns out the problem was in the permission. I fix it with the following command

sudo chown -R $USER /var/www

Please make sure with the $USER variable. I tested and worked on Ubuntu Distro

What is an attribute in Java?

Attribute is a synonym of field for array.length

Make Iframe to fit 100% of container's remaining height

Here are a few modern approaches:


  • Approach 1 - Combination of viewport relative units / calc().

    The expression calc(100vh - 30px) represents the remaining height. Where 100vh is the height of the browser and the usage of calc() effectively displaces the height of the other element.

    Example Here

    _x000D_
    _x000D_
    body {_x000D_
        margin: 0;_x000D_
    }_x000D_
    .banner {_x000D_
        background: #f00;_x000D_
        height: 30px;_x000D_
    }_x000D_
    iframe {_x000D_
        display: block;_x000D_
        background: #000;_x000D_
        border: none;_x000D_
        height: calc(100vh - 30px);_x000D_
        width: 100%;_x000D_
    }
    _x000D_
    <div class="banner"></div>_x000D_
    <iframe></iframe>
    _x000D_
    _x000D_
    _x000D_

    Support for calc() here; support for viewport relative units here.


  • Approach 2 - Flexbox approach

    Example Here

    Set the display of the common parent element to flex, along with flex-direction: column (assuming you want the elements to stack on top of each other). Then set flex-grow: 1 on the child iframe element in order for it to fill the remaining space.

    _x000D_
    _x000D_
    body {_x000D_
        margin: 0;_x000D_
    }_x000D_
    .parent {_x000D_
        display: flex;_x000D_
        flex-direction: column;_x000D_
        min-height: 100vh;_x000D_
    }_x000D_
    .parent .banner {_x000D_
        background: #f00;_x000D_
        width: 100%;_x000D_
        height: 30px;_x000D_
    }_x000D_
    .parent iframe {_x000D_
        background: #000;_x000D_
        border: none;_x000D_
        flex-grow: 1;_x000D_
    }
    _x000D_
    <div class="parent">_x000D_
        <div class="banner"></div>_x000D_
        <iframe></iframe>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    Since this approach has less support1, I'd suggest going with the aforementioned approach.

1Though it seems to work in Chrome/FF, it doesn't work in IE (the first method works in all current browsers).

How to display (print) vector in Matlab?

To print a vector which possibly has complex numbers-

fprintf('Answer: %s\n', sprintf('%d ', num2str(x)));

Colors in JavaScript console

You can try console.log("%cI am red %cI am green", "color: red", "color: green"); enter image description here

How do I run all Python unit tests in a directory?

I have used the discover method and an overloading of load_tests to achieve this result in a (minimal, I think) number lines of code:

def load_tests(loader, tests, pattern):
''' Discover and load all unit tests in all files named ``*_test.py`` in ``./src/``
'''
    suite = TestSuite()
    for all_test_suite in unittest.defaultTestLoader.discover('src', pattern='*_tests.py'):
        for test_suite in all_test_suite:
            suite.addTests(test_suite)
    return suite

if __name__ == '__main__':
    unittest.main()

Execution on fives something like

Ran 27 tests in 0.187s
OK

Use async await with Array.map

You can use:

for await (let resolvedPromise of arrayOfPromises) {
  console.log(resolvedPromise)
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of

If you wish to use Promise.all() instead you can go for Promise.allSettled() So you can have better control over rejected promises.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled

How can you create multiple cursors in Visual Studio Code

https://code.visualstudio.com/Updates

New version (Visual Studio 0.3.0) support more multi cursor feature.

Multi-cursor
Here's multi-cursor improvements that we've made.

?D selects the word at the cursor, or the next occurrence of the current selection.
?K ?D moves the last added cursor to next occurrence of the current selection.
The two actions pick up the matchCase and matchWholeWord settings of the find widget.
?U undoes the last cursor action, so if you added one cursor too many or made a mistake, press ?U to return to the previous cursor state.
Insert cursor above (???) and insert cursor below (???) now reveals the last added cursor, making it easier to work with multi-cursors spanning more than one screen height (i.e., working with 300 lines while only 80 fit in the screen).

And short cut of select multi cursor change into cmd + d(it's same as Sublime Text. lol)

We can expect that next version supports more convenient feature about multi cursor ;)

jQuery If DIV Doesn't Have Class "x"

How about instead of using an if inside the event, you unbind the event when the select class is applied? I'm guessing you add the class inside your code somewhere, so unbinding the event there would look like this:

$(element).addClass( 'selected' ).unbind( 'hover' );

The only downside is that if you ever remove the selected class from the element, you have to subscribe it to the hover event again.

jQuery: Wait/Delay 1 second without executing code

delay() doesn't halt the flow of code then re-run it. There's no practical way to do that in JavaScript. Everything has to be done with functions which take callbacks such as setTimeout which others have mentioned.

The purpose of jQuery's delay() is to make an animation queue wait before executing. So for example $(element).delay(3000).fadeIn(250); will make the element fade in after 3 seconds.

Find and replace with a newline in Visual Studio Code

  • Control F for search, or Control Shift F for global search
  • Replace >< by >\n< with Regular Expressions enabled

enter image description here

z-index not working with position absolute

Opacity changes the context of your z-index, as does the static positioning. Either add opacity to the element that doesn't have it or remove it from the element that does. You'll also have to either make both elements static positioned or specify relative or absolute position. Here's some background on contexts: http://philipwalton.com/articles/what-no-one-told-you-about-z-index/

How can I keep a container running on Kubernetes?

In order to keep a POD running it should to be performing certain task, otherwise Kubernetes will find it unnecessary, therefore it stops. There are many ways to keep a POD running.

I have faced similar problems when I needed a POD just to run continuously without doing any useful operation. The following are the two ways those worked for me:

  1. Firing up a sleep command while running the container.
  2. Running an infinite loop inside the container.

Although the first option is easier than the second one and may suffice the requirement, it is not the best option. As, there is a limit as far as the number of seconds you are going to assign in the sleep command. But a container with infinite loop running inside it never exits.

However, I will describe both the ways(Considering you are running busybox container):

1. Sleep Command

apiVersion: v1
kind: Pod
metadata:
  name: busybox
  labels:
    app: busybox
spec:
  containers:
  - name: busybox
    image: busybox
    ports:
    - containerPort: 80
    command: ["/bin/sh", "-ec", "sleep 1000"]
  nodeSelector:
    beta.kubernetes.io/os: linux

2. Infinite Loop

apiVersion: v1
kind: Pod
metadata:
  name: busybox
  labels:
    app: busybox
spec:
  containers:
  - name: busybox
    image: busybox
    ports:
    - containerPort: 80
    command: ["/bin/sh", "-ec", "while :; do echo '.'; sleep 5 ; done"]
  nodeSelector:
    beta.kubernetes.io/os: linux

Run the following command to run the pod:

kubectl apply -f <pod-yaml-file-name>.yaml

Hope it helps!

jQuery Set Cursor Position in Text Area

I had to get this working for contenteditable elements and jQuery and tought someone might want it ready to use:

$.fn.getCaret = function(n) {
    var d = $(this)[0];
    var s, r;
    r = document.createRange();
    r.selectNodeContents(d);
    s = window.getSelection();
    console.log('position: '+s.anchorOffset+' of '+s.anchorNode.textContent.length);
    return s.anchorOffset;
};

$.fn.setCaret = function(n) {
    var d = $(this)[0];
    d.focus();
    var r = document.createRange();
    var s = window.getSelection();
    r.setStart(d.childNodes[0], n);
    r.collapse(true);
    s.removeAllRanges();
    s.addRange(r);
    console.log('position: '+s.anchorOffset+' of '+s.anchorNode.textContent.length);
    return this;
};

Usage $(selector).getCaret() returns the number offset and $(selector).setCaret(num) establishes the offeset and sets focus on element.

Also a small tip, if you run $(selector).setCaret(num) from console it will return the console.log but you won't visualize the focus since it is established at the console window.

Bests ;D

How Do I Make Glyphicons Bigger? (Change Size?)

Increase the font-size of glyphicon to increase all icons size.

.glyphicon {
    font-size: 50px;
}

To target only one icon,

.glyphicon.glyphicon-globe {
    font-size: 75px;
}

How to check if an alert exists using WebDriver?

public static void handleAlert(){
    if(isAlertPresent()){
        Alert alert = driver.switchTo().alert();
        System.out.println(alert.getText());
        alert.accept();
    }
}
public static boolean isAlertPresent(){
      try{
          driver.switchTo().alert();
          return true;
      }catch(NoAlertPresentException ex){
          return false;
      }
}

Using C# to read/write Excel files (.xls/.xlsx)

**Reading the Excel File:**

string filePath = @"d:\MyExcel.xlsx";
Excel.Application xlApp = new Excel.Application();  
Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(filePath);  
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);  

Excel.Range xlRange = xlWorkSheet.UsedRange;  
int totalRows = xlRange.Rows.Count;  
int totalColumns = xlRange.Columns.Count;  

string firstValue, secondValue;   
for (int rowCount = 1; rowCount <= totalRows; rowCount++)  
{  
    firstValue = Convert.ToString((xlRange.Cells[rowCount, 1] as Excel.Range).Text);  
    secondValue = Convert.ToString((xlRange.Cells[rowCount, 2] as Excel.Range).Text);  
    Console.WriteLine(firstValue + "\t" + secondValue);  
}  
xlWorkBook.Close();  
xlApp.Quit(); 


**Writting the Excel File:**

Excel.Application xlApp = new Excel.Application();
object misValue = System.Reflection.Missing.Value;  

Excel.Workbook xlWorkBook = xlApp.Workbooks.Add(misValue);  
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);  

xlWorkSheet.Cells[1, 1] = "ID";  
xlWorkSheet.Cells[1, 2] = "Name";  
xlWorkSheet.Cells[2, 1] = "100";  
xlWorkSheet.Cells[2, 2] = "John";  
xlWorkSheet.Cells[3, 1] = "101";  
xlWorkSheet.Cells[3, 2] = "Herry";  

xlWorkBook.SaveAs(filePath, Excel.XlFileFormat.xlOpenXMLWorkbook, misValue, misValue, misValue, misValue,  
Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);  



xlWorkBook.Close();  
xlApp.Quit();  

Very simple C# CSV reader

This fixed version of code above remember the last element of CVS row ;-)

(tested with a CSV file with 5400 rows and 26 elements by row)

   public static string[] CSVRowToStringArray(string r, char fieldSep = ',', char stringSep = '\"')  {
            bool bolQuote = false;
            StringBuilder bld = new StringBuilder();
            List<string> retAry = new List<string>();

            foreach (char c in r.ToCharArray())
                if ((c == fieldSep && !bolQuote))
                {
                    retAry.Add(bld.ToString());
                    bld.Clear();
                }
                else
                    if (c == stringSep)
                        bolQuote = !bolQuote;
                    else
                        bld.Append(c);

            /* to solve the last element problem */
            retAry.Add(bld.ToString()); /* added this line */
            return retAry.ToArray();
        }

Getting all names in an enum as a String[]

Another way to do it in Java 7 or earlier would be to use Guava:

public static String[] names() {
    return FluentIterable.from(values()).transform(Enum::name).toArray(String.class);
}

Javascript Click on Element by Class

I'd suggest:

document.querySelector('.rateRecipe.btns-one-small').click();

The above code assumes that the given element has both of those classes; otherwise, if the space is meant to imply an ancestor-descendant relationship:

document.querySelector('.rateRecipe .btns-one-small').click();

The method getElementsByClassName() takes a single class-name (rather than document.querySelector()/document.querySelectorAll(), which take a CSS selector), and you passed two (presumably class-names) to the method.

References:

Converts scss to css

First of all, you have to install Ruby if it is not on your machine.

1.Open a terminal window. 2.Run the command which ruby.

If you see a path such as /usr/bin/ruby, Ruby is installed. If you don't see any response or get an error message, Ruby is not installed. To verify that you have a current version of Ruby, run the command ruby -v.

If ruby is not installed on your machine then

sudo apt-get install ruby2.0
sudo apt-get install ruby2.0-dev
sudo update-alternatives --install /usr/bin/gem gem /usr/bin/gem2.0 1 

After then install Sass gem by running this command

sudo gem install sass --no-user-install

Then copy or add any .sass file and go to that file path and then

sass --watch style.scss:style.css 

When ever it notices a change in the .scss file it will update your .css

This only works when your .scss is on your local machine. Try copying the code to a file and running it locally.

How to synchronize a static variable among threads running different instances of a class in Java?

If you're simply sharing a counter, consider using an AtomicInteger or another suitable class from the java.util.concurrent.atomic package:

public class Test {

    private final static AtomicInteger count = new AtomicInteger(0); 

    public void foo() {  
        count.incrementAndGet();
    }  
}

How do I get the MAX row with a GROUP BY in LINQ query?

This can be done using GroupBy and SelectMany in LINQ lamda expression

var groupByMax = list.GroupBy(x=>x.item1).SelectMany(y=>y.Where(z=>z.item2 == y.Max(i=>i.item2)));

How to use andWhere and orWhere in Doctrine?

$q->where("a = 1")
  ->andWhere("b = 1 OR b = 2")
  ->andWhere("c = 2 OR c = 2")
  ;

Notepad++: Multiple words search in a file (may be in different lines)?

If you are using Notepad++ editor (like the tag of the question suggests), you can use the great "Find in Files" functionality.

Go to SearchFind in Files (Ctrl+Shift+F for the keyboard addicted) and enter:

  • Find What = (cat|town)

  • Filters = *.txt

  • Directory = enter the path of the directory you want to search in. You can check Follow current doc. to have the path of the current file to be filled.

  • Search mode = Regular Expression

How to export collection to CSV in MongoDB?

@karoly-horvath has it right. Fields are required for csv.

According to this bug in the MongoDB issue tracker https://jira.mongodb.org/browse/SERVER-4224 you MUST provide the fields when exporting to a csv. The docs are not clear on it. That is the reason for the error.

Try this:

mongoexport --host localhost --db dbname --collection name --csv --out text.csv --fields firstName,middleName,lastName

UPDATE:

This commit: https://github.com/mongodb/mongo-tools/commit/586c00ef09c32c77907bd20d722049ed23065398 fixes the docs for 3.0.0-rc10 and later. It changes

Fields string `long:"fields" short:"f" description:"comma separated list of field names, e.g. -f name,age"`

to

Fields string `long:"fields" short:"f" description:"comma separated list of field names (required for exporting CSV) e.g. -f \"name,age\" "`

VERSION 3.0 AND ABOVE:

You should use --type=csv instead of --csv since it has been deprecated.

More details: https://docs.mongodb.com/manual/reference/program/mongoexport/#export-in-csv-format

Full command:

mongoexport --host localhost --db dbname --collection name --type=csv --out text.csv --fields firstName,middleName,lastName

How to get last items of a list in Python?

Here are several options for getting the "tail" items of an iterable:

Given

n = 9
iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Desired Output

[2, 3, 4, 5, 6, 7, 8, 9, 10]

Code

We get the latter output using any of the following options:

from collections import deque
import itertools

import more_itertools


# A: Slicing
iterable[-n:]


# B: Implement an itertools recipe
def tail(n, iterable):
    """Return an iterator over the last *n* items of *iterable*.

        >>> t = tail(3, 'ABCDEFG')
        >>> list(t)
        ['E', 'F', 'G']

    """
    return iter(deque(iterable, maxlen=n))
list(tail(n, iterable))


# C: Use an implemented recipe, via more_itertools
list(more_itertools.tail(n, iterable))


# D: islice, via itertools
list(itertools.islice(iterable, len(iterable)-n, None))


# E: Negative islice, via more_itertools
list(more_itertools.islice_extended(iterable, -n, None))

Details

  • A. Traditional Python slicing is inherent to the language. This option works with sequences such as strings, lists and tuples. However, this kind of slicing does not work on iterators, e.g. iter(iterable).
  • B. An itertools recipe. It is generalized to work on any iterable and resolves the iterator issue in the last solution. This recipe must be implemented manually as it is not officially included in the itertools module.
  • C. Many recipes, including the latter tool (B), have been conveniently implemented in third party packages. Installing and importing these these libraries obviates manual implementation. One of these libraries is called more_itertools (install via > pip install more-itertools); see more_itertools.tail.
  • D. A member of the itertools library. Note, itertools.islice does not support negative slicing.
  • E. Another tool is implemented in more_itertools that generalizes itertools.islice to support negative slicing; see more_itertools.islice_extended.

Which one do I use?

It depends. In most cases, slicing (option A, as mentioned in other answers) is most simple option as it built into the language and supports most iterable types. For more general iterators, use any of the remaining options. Note, options C and E require installing a third-party library, which some users may find useful.