What's the most efficient way to transfer workers that are mining minerals to mine gas instead?

Question: When my Refinery finishes in the heat of battle, I don't have time to manually find 3 workers that aren't holding any minerals.
What is the optimal way to transfer 3 workers from minerals to gas without sacrificing any minerals?
Comment: Just a note that even if you send 3 workers at the same time, only one probe can be inside the gas building at the same time so the other two will be waiting for a bit.
Answer: I found what I think is actually the best answer while browsing the Team Liquid forums:
The most efficient way is to select any 3 workers, right click on the gas, then immediately hit C (return cargo). Workers that are holding minerals will drop off their minerals, and then proceed to gas. Meanwhile, workers without minerals will head straight for the gas!
Comment: ohhh, nice.  I like that.
Comment: I tried this out today.  It worked wonders.  Best answer to this question.
Comment: OH.. I always thought they will return to mine minerals again!
Comment: Almost 8 years later and this answer is still amazingly helpful!
Answer: It depends on what you mean by "not lose minerals"
If you do it manually, you'll take about 2 seconds, and you can lose zero minerals.
If you don't do it manually, statistically, you'll have one who is walking to gather (A), one who is walking back with minerals in hand (B), and one who is in the middle of gathering (C). (As they spend about a third of their time on each task)
Option 1:
If you're in the middle of the battle and need the absolute most amount of time you just have them all start going to the gas:

(A) will not lose any minerals
(B) will lose 5 minerals (the minerals in his hands at the time)
(C) will "lose" (on average) 2.5 minerals. (it isn't really "lost" because the next guy will get it, but you've lost the time it took for that worker to start, but not finish mining)

Option 2:
If you have a brief instant of reprieve, but need to get back on the battlefield, you can save 5 minerals from option 1, by sending (B) back to the base. The quickest way to do that is by ordering "return with goods". This is better then sending them all back to the base, because only the one with minerals will run back. Immediately after issuing the "return with goods / return cargo" command, shift right click on the geyser, and that will queue a command to the geyser, which for the other two will be executed instantly. This can be done in one instant, because the return with goods command can be issued by the keyboard hand, while the mouse hand will be moving to issue the command to the geyser.
Option 3:
If you have a little bit longer, select only those that are going back to mining, that way you lose no minerals at all, nor even time wasted mining.
It does depend on how urgent you need to get back to the battle, but if the battle is so important that it can't be delayed by a couple seconds, the gas can probably wait.
Comment: What's the hotkey to return the goods?
Comment: it depends on your keybindings, typically "C" "return [C]argo"
Comment: +1 for mentioning `return with goods` menu item.
Comment: @CarlClover... hover over the icon?
Answer: What I usually do is quickly grab the group that is nearest to the gas, shift click the excess workers then shift click my 3 to the Nexus/Command Center/Hatchery then shift click to the gas.  This will tell them to drop off any minerals they have (no wasting) and then go mine gas.
shift + click = queueing commands.  So you are telling the worker to finish mining -> drop off minerals -> mine gas
Comment: This usually, though sometimes I'll come up 1 short have to grab an extra one.
Comment: While you don't actually "lose" minerals using this method, you do lose time on two fronts. See my answer for more details.
Answer: Usually, when your gas is depleted, naturally, you would have idle workers.
Here is what I do: On top of Mark's answer, if you have idle workers then you can press F1 to select an idle worker. However, if you hold CTRL + F1 then it will select ALL idle workers. So assuming you do not have any other idle workers, and when your gas is depleted then you can just press CTRL + F1 and select the 3 idle workers.
Answer: What I do is set the command center's rally point to the refinery and build 3 more.
I don't know if this counts as "sacrificing materials", but in my opinion, you can never have enough workers.
Comment: While I like this option, I tend to forget that I've set the rally point to the geyser, and I end up sending more than 3 workers to the geyser, which results in more wasted time.
Comment: so true.  Full Saturation is 30 workers, and by the time you hit that number you can transfer to an expo
Comment: Juan Manuel, this means that you need to wait for each of those 3 works to be created. I think you'll waste less time using McKay's option 2 and get gas faster. Then, if you need to replenish the workers you took from the mineral fields, you just hotkey your command center and fire off some more workers that are always set to rally to the minerals.
Answer: The easiest manual way to do it would be to just select three workers and get Ctrl+1-9 them. This will then bind them to a key. Quickly click on the nearest base to the workers, this will allow them to drop any minerals that they are carrying. If your battling and cant watch them, when you see the "Workers not working" button appear on the left hand side of your screen press 1-9 depending on what HotKey you selected and then click on your refinery. This would result in no loss in minerals, via them being dropped.
Comment: What is the purpose of binding them to a control group?
Comment: I bind at least one to a control group so that if I'm not on view of my base, I can select one and check through building's and place. At the end of the day it comes down to personal preference and what you can do the quickest.
Answer: I usually just draw a small rectangle close to the command center/hatch/nexus and keep the mouse button down until there are at least workers 3 in it. Then i quickly right-click on the cc/hatch/nexus in case they carried anything and then i send them to the refinery. If i got more than 3 (usually i don't, but sometimes i get a fourth worker) then after sending all to the refinery i pick the excess workers in the selected units list and send them to work on the minerals again. This takes roughly 1-3 seconds, depending on how many workers you have and how good you are at figuring out where the 3 workers will be easiest to capture.
It's easier and faster to rectangle-select more and remove the unnecessary ones than it's to select them one-by-one when they are moving.


UIRefreshControl with transparent background above UISearchController

Question: I have implemented a UIRefreshControl with transparent background in a table, and all was working fine until I added a UIRefreshControl, now I can't remove the gray background behind the RefreshControl as shown in the screenshots.
Screenshot
Anybody knows where could be the issue?
Answer:

Double-check the background color of the TableView:

Double-check the background color of the UIRefreshControl itself:


HTTP 2 Protocol using WebClient

Question: New HTTP 2 Protocol will allow multiple file sent using single request, and it keeps the request open. If like that, a WebClient need to have callback each time a file is received,

Is there any .NET library that do that on HTTP 2?
Or is there any sample using existing WebClient?

Thanks
Answer: HTTP 2 is not yet adopted by .NET Framework. It might require serious API changes, so you need to wait.
If you are willing to contribute you can go to https://github.com/dotnet/corefx.

HTTP 2 Protocol using WebClient


How to combine Multi Map entries based on common entry values

Question: I have a Multimap structure, Map<String, Set<String>> as input. I want to group entries of this map if any two sets of entry values have a common element. Output should be of the format Map<Set<String>, Set<String>>  where each key will be a group of keys from the input map.
eg. given this input:
A -> [1,2]
B -> [3,4]
C -> [5,6]
D -> [1,5]

Output:
[A,C,D] -> [1,2,5,6]
[B] -> [3,4]

Here A & D have 1 as common element, C & D have 5 as common element. So A, C, D are merged into one key.
Comment: Do you have an algorithm in mind? I think the simple solution is to use loops that merge until nothing changes, starting with singleton sets derived directly from the input.
Answer: There are lots of ways you can solve this. One that I like (assuming you are using Java 8) is to implement this as a collector for a Map.Entry stream. Here's a possible implementation:
public class MapCollector {
    private final Map<Set<String>,Set<Integer>> result = new HashMap<>();

    public void accept(Map.Entry<String,Set<Integer>> entry) {
        Set<String> key = new HashSet<>(Arrays.asList(entry.getKey()));
        Set<Integer> value = new HashSet<>(entry.getValue());
        Set<Set<String>> overlapKeys = result.entrySet().stream()
                .filter(e -> e.getValue().stream().anyMatch(value::contains))
                .map(Map.Entry::getKey)
                .collect(Collectors.toSet());
        overlapKeys.stream().forEach(key::addAll);
        overlapKeys.stream().map(result::get).forEach(value::addAll);
        result.keySet().removeAll(overlapKeys);
        result.put(key, value);
    }

    public MapCollector combine(MapCollector other) {
        other.result.forEach(this::accept);
        return this;
    }

    public static Collector<Map.Entry<String, Set<Integer>>, MapCollector, Map<Set<String>,Set<Integer>>> collector() {
        return Collector.of(MapCollector::new, MapCollector::accept, MapCollector::combine, c -> c.result);
    }
}

This can be used as follows:
Map<Set<String>,Set<Integer>> result = input.entrySet().stream()
    .collect(MapCollector.collector());

Most of the work is done in the accept method. It finds all overlapping sets and moves them to the new map entry. It supports parallel streams which could be useful if your map is massive.


Ajax fail in all versions of IE

Question: I have this Ajax post request.  Works great in Crome.  Just opened it in IE and it fails completely.  It is a div with images loaded into a carousel.  The carousel used is http://caroufredsel.dev7studios.com/ (Which I would highly recommend for its easy implementation if anyone is after an image carousel)
When you click a folder
     Folder 1

basically queries a php file and refreshes the div with a new set of images
  $.ajaxSetup ({
    cache: false,
    async: false
});
 function getImages(id)
 {
 $.ajax({

 type: "POST",
 url: 'getImage.php',
 dataType: "json",
 data: "id=" + id,
 success: function(data) {

      $('#scrolimg').html(data);
      $("#car1").carouFredSel({
auto : false,
items   : 4,
scroll  : 4,
circular : false,
infinite : false,
prev : "#foo1_prev",
next : "#foo1_next",
swipe       : {
    onTouch     : true,
    onMouse     : false
}
 });

 }

 });

When I have been reading similar problems on Stack most people say turn cache to false and async but that has not helped.  Another solution was to make POST requests instead of GET but thats does not work for me either.
The code above works perfectly.   The problem is in the getImage.php file.  I have a loop thats running to find the image width and height with php function call getimagesize()
That function is not running in IE but working perfectly in all other browsers.  Is my Ajax blocking this function from running?
   <?php do {
  $image = $_SERVER['DOCUMENT_ROOT']."/images/uploads/".$row_rs_image['thumbfile'];
   list($width, $height)= getimagesize($image);
 ?>
     <img  src="/images/uploads/<?php echo $row_rs_image['thumbfile']; ?>"  width="<?php echo $width;?>" height="<?php echo $height;?>" />
    <?php } while ($row_rs_image = mysql_fetch_assoc($rs_image)); ?>

When I output the source I see the following

Comment: Don't use `async: false`.
Comment: Normally the case for this is a trailing comma in JSON or an object. Check that the last items in all your objects + JSON don't contain any trailing commas.
Comment: @DanielRobinson - to examine HTTP request/response in IE: First, get the page to the point you want to test, then: F12 to open dev tools; Click "Network" tab; Click "start capturing". Then do the action on the page that should trigger the ajax event. If the ajax was called, the dev tools window should now show the request. If so, click it to see the the details about what was sent and recieved.
Comment: You should specify the version of internet explorer in your original post.
Comment: Have you looked at the Dev Tools to see what the actual HTTP request/response look like?
Comment: @Dean all versions of IE fail.
Comment: @SDC how do you look in dev tools in the correct way to test this
Comment: @SLaks I have removed that line as well as data type as that stopped it in all browsers but it still does not work
Comment: @Dean Thanks Dean.  Tried that but to no avail.  Im completely confused as to whats going on.  Why would it work perfectly in other broswers?
Comment: @Dean thanks thats great.  I can now see the ajax call is working fine.  My function in getImage.php called getimagesize() is not working but only in IE
Comment: FYI, `$.ajaxSetup` will need to be `$(document).ajaxSetup` in 1.9+ and 2.0+ versions
Answer: Found the issue.  on get image sizes use this line instead
list($width, $height, $type, $sizes)= getimagesize($image);
then in the getImage.php
  <?php do {
  $image = $_SERVER['DOCUMENT_ROOT'].$row_rs_image['userimagespath'].$row_rs_image['thumbfile'];
   list($width, $height, $type, $sizes)= getimagesize($image);
 ?>
  <img name="<?php echo $row_rs_image['imgname']; ?>" src="/images/uploads/<?php echo $row_rs_image['thumbfile']; ?>"  <?php echo $sizes;?> />

Thanks to everyone for the help
Answer: Just remove the comma, try it, hope it will work :)
$.ajaxSetup ({
    cache: false,
    async: false
});
 function getImages(id)
 {
 $.ajax({
type: "POST",
 url: 'getImage.php',
 dataType: "json",
 data: "id=" + id
 success: function(data) {
  $('#scrolimg').html(data);
  $("#car1").carouFredSel({

auto : false,
items   : 4,
scroll  : 4,
circular : false,
infinite : false,
prev : "#foo1_prev",
next : "#foo1_next"
swipe       : {
    onTouch     : true,
    onMouse     : false
}
 });
}
});
Comment: in which version if IE are u trying?
Comment: I have now tried all of them.  Its completely fine in Chrome.  When you click the link the images currently loaded disappear and no new ones are loaded in all IE versions.

Ajax fail in all versions of IE


Values in try/except available after execution

Question: I have a question about try/except in python3.
I wondered if you have code like:
#1
try:
    #do something here
    var = 'some value here'

except:
    #do something if it fails

#2
try:
    #do something here
    newvar = var    #var from above

except:
    #do something if it fails

Can I use var from #1 in #2 like Im using it or is the value of var no longer after it goes into the #1 try or except block?
Thank you
Comment: Note, you should always catch *specific* exceptions, like `except IndexError:`
Answer: It depends.
If the code in #1 fails while calculating the value to store into variable var, the assignment will never happen and var will be as it was before that code block. The Python documentation explicitly says that the value on the right side of the equal sign is calculated first, and when and if that calculation is done, the resulting value is then bound to the variable name that is on the left side of the equals sign. If var was undefined, it will still be undefined; if it was defined and had a value, it will still have that value. It will not lose its definition or its value.
So if var is undefined, you will get an exception in code block #2. If var has an old value, it will still have it and that's what will be used on code block #2.
Whether or not that is what you want depends on other factors.
As @Chris_Rands points out in a comment, your style is not very good. You should catch specific exceptions and deal with them. Unexpected exceptions should be raised and dealt with at a higher level. The exception to this is when your code is used in a long-running program that you do not want to stop for any reason other than the user shutting it down. And in that case, you should still catch and handle the specific exception you expect, and log the unexpected ones along with their complete tracebacks into some file so that you, the programmer, can examine it later to fix the problem. Never catch all exceptions and just continue on without some kind of logging.
Answer: If an exception occurs in the try block before you have assigned your variable, it won't be declared.
In order to safely use your variable later, you also have to set it in the event of an exception (ie in your except block).


Are some things (RCI demand, commuters, unlocks, etc.) shared only by "cluster" instead of region?

Question: The new SimCity allows cities to share benefits such as RCI demand, commuters, unlocks, and utility and safety services. What is not clear is whether certain things are always shared region-wide, or if some things are shared only within the cluster.
Are some things (RCI demand, commuters, unlocks, etc.) shared only by "cluster" instead of region? If so,

What is shared across the entire region, no matter what?
What is
    shared across the entire region if appropriate connections exist
    (road, rail, sea)?
What is shared only among cities in the same
    cluster?

I am playing with some friends the new Maxis game. We created a 16 city region, but with  disappointment, we've noticed that the city does not share the RCI demands, benefits etc. (even if they are connected by the same highway and railroad) with all the region but only with the adjacent 3-4 cities (we call cluster).
Is it working as intended? The region with 7 cities has a unique cluster?
Thanks
Answer: What you are seeing is working as intended. Not all cities within a region will be able to share all things but they are eventually able to share most things. The most limited of what can and can not be shared are going to be water, sewage, power and garbage. These are limited by physical roads. This is where you get your cluster or sub-region as you have noted. The best way to tell which cities will be able to share these resources is to see which ones are connected by road as roads are needed to transport these materials.
In the early game this can also hinder almost all resource transfer. You can eventually unlock things like a trade port that can use roads or rail or water to transfer resources locally or globally. There are also additional methods for the transportation of people and such via ferries and the like. The last thing, that jumps the final gap, is an air port.
These things together will let other cities be more connected but it should be noted that anything that requires a road, as mentioned above, will never be able to get to another city that does not have a road connecting to it.
EDIT: Found out last night that gifting also requires a connection between the cities. Even the act of sending money from city to city required at least a rail connection between the regions. I have not seen if ferries or air ports will fulfill this requirement and will update here when I figure that out!
Great Works are region wide as well. If you unlock a great work like the solar farm in one sub-region you are then capable of building that great work at any site on the map. However note that getting resources to a remote location may be a bit of a challenge.
This also works with other unlocks that claim 'region wide' like the upgrades to City Hall. Even though the cities are not connected in any manner people starting up cities in other sub-regions or clusters have access to 100,000 bonds for instance.. Smelting plants and the like. So it does appear that development unlocks also jump over the bounds of a solid (or even liquid) connection.
Answer: It looks like regions with multiple Great Work sites are actually divided into multiple city groupings.
My biggest tip for the game, however, is to be very wary of the the RCI demand in regional play. For example, if you build a mine + trade depot your Industrial demand will go through the roof (I think these specialist buildings also higher a ton of workers). If you build to meet that demand your city will be absolutely swamped with commuters (even with a rail connection + streetcars) and your city will be fubared.


Can wardens detect players walking on wool?

Question: If sculk sensors can't detect me when I walk on wool, so do Wardens too?
Comment: I'm voting to close this question because it is asking about unreleased content.
Comment: Hello! To add to what my mod collegue has said: Here at arqade we try to not work on theories and things that cannot be proven 100% that it is as the answer says. And well, with unrelesed content, the best we can do is theorize as to how it will work. So this question will be considered as off-topic for the moment. It could be reopened when the content will be released on at least a public beta channel (I dont know Minecraft much, but basically, when someone not at mojang can freely get and test the update). Have a nice day!
Comment: Voting to reopen, since 1.19 version the Warden was officially released.
Comment: @pinckerman [Unreleased content questions shouldn't be retroactively reopened once the game is released](https://gaming.meta.stackexchange.com/q/6971/185203)
Comment: @pppery didn't know that, thanks
Answer: Unfortunately as of yet no one knows how the Warden mob is actually going to work in-game.
This is because the Warden does not currently exist on any official update releases or snapshots.
Answer: One of Mojang developer, Kingbdogz, has confirmed that the Warden has a larger radius for hearing vibrations than the sculk sensor.
He also confirmed in another tweet that the Warden and the skulk sensor act the exact same (other than their radius).

Source, Minecraft wikia.


Unable to pass image to another UIViewController over present modally segue

Question: I tried to pass an image to another imageView of destination UIView which is connected to source UIView over present Modally segue.
I tried to pass data through segue and as well set image (i.e. NSData - Core Data) in source UIView through Outlet but I got an error image description in console -

"fatal error: unexpectedly found nil while unwrapping an Optional
  value"

  //Code of destination UIView
   import UIKit
   import CoreData
   class ReviewViewController: UIViewController {

   @IBOutlet var backgroundImageView:UIImageView!
   var subject:Semester!

    override func viewDidLoad() {
    super.viewDidLoad()
    backgroundImageView?.image = UIImage(data: subject.image!)
    let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    blurEffectView.frame = view.bounds
    backgroundImageView.addSubview(blurEffectView)

   // Code of Source UIView
  import UIKit
  import CoreData

  class SubjectDetailViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
  @IBOutlet var facultyImageView:UIImageView!
  var subject:Semester!

  override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "destinationidentifier"
    {
            let destinationController = segue.destinationViewController as! ReviewViewController
            destinationController.backgroundImageView?.image = self.facultyImageView.image
     }
}

Answer: You are doing wrong as you are setting image directly inside outlet without passing value using var or property.
1) Declare variable first
var backgroundImage : UIImage!

2) Set the value inside that variable while push
destinationController.backgroundImage = self.facultyImageView.image

Comment: Actually not. Thats why i am tired of this
Comment: Still you are facing issue?
Answer: Your problem is backgroundImageView object is nil because destinationController is not currently in window hierarchy.
So Change your prepareForSegue like this
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "destinationidentifier"
    {
        let destinationController = segue.destinationViewController as! ReviewViewController
        destinationController.image = self.facultyImageView.image
    }
}

Now create one image object in ReviewViewController like below and add one line in viewDidLoad
var image: UIImage!

override func viewDidLoad() {
    super.viewDidLoad()
    self.backgroundImageView?.image = self.image
}

Hope this will help you
Answer: Modify your code like this, Try to send image using UIImage rather then ImageView,
//Code of destination UIView
import UIKit
import CoreData
class ReviewViewController: UIViewController {

@IBOutlet var backgroundImageView:UIImageView!
var backgroundImage : UIImage!
var subject:Semester!

override func viewDidLoad() {
super.viewDidLoad()
//backgroundImageView?.image = UIImage(data: subject.image!)
backgroundImageView?.image = self. backgroundImage
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = view.bounds
backgroundImageView.addSubview(blurEffectView)

// Code of Source UIView
import UIKit
import CoreData

class SubjectDetailViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var facultyImageView:UIImageView!
var subject:Semester!

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)        {
if segue.identifier == "destinationidentifier"
{
        let destinationController = segue.destinationViewController as! ReviewViewController
        destinationController.backgroundImage = self.facultyImageView.image
 }
}

Hope this will help you.


Unable to set a fixed width and center custom scrollbar

Question: I am working on some kind of carousel with items aligned horizontally.
Each of the child elements (there will be about a dozen of them) should stretch one third of the parent's width. Three items should be visible at any one time.
I have used Bootstrap 4, some custom CSS and the Perfect-scrollbar plugin.

var ps = new PerfectScrollbar('#carousel');
html,
body {
  padding: 0;
  margin: 0;
  height: 100%;
}
.page-wrapper {
  min-height: 100%;
}
.hero {
  height: 100vh;
  background: #212121;
  justify-content: center;
  align-items: center;
}

#carousel {
  display: flex;
  list-style-type: none;
  position: relative;
  margin: 0;
  padding: 0;
  justify-content: left;
  align-items: center;
}
#carousel li {
  padding: 0 0 70px 0;
}
#carousel a {
  text-decoration: none;
  color: #fff;
}
#carousel img {
  display: block;
  width: 100%;
}
#carousel .caption {
  padding: 20px 20px 0 20px;
}
#carousel h2 {
  font-size: 20px;
  line-height: 1;
  margin: 0;
  padding: 0;
}
#carousel p {
  font-size: 10px;
  padding: 0;
  margin: 5px 0 0 0;
}
#carousel .ps__rail-x {
  background: #5C5C5C;
  height: 3px;
  margin: 0 auto;
}
#carousel .ps__thumb-x {
  height: 3px;
  margin-bottom: -2px;
  border-radius: 0;
  background: #fff;
}
<link href="//stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<link href="//rawgit.com/utatti/perfect-scrollbar/master/css/perfect-scrollbar.css" rel="stylesheet"/>

Lorem

A true story

Lorem ipsum

Lorem ipsum. Dolor sit amet.

Lorem

Lorem ipsum. Dolor sit amet

Into the wild

Lorem ipsum dolor sit amet, consectetur

It came out pretty nice, except I have been struggling to find a way to set a fixed width (of 300px) for the rail and centering it. How can I do that?
Comment: you can set `max-width to 300px` since the js keep changing the width to 1280px.
Comment: doesnt look possible with the current scrollBar plugin. maybe use something else like http://gromo.github.io/jquery.scrollbar/demo/advanced.html or smth
Answer: You can pass maxScrollbarLength to the PerfectScrollbar instance and set it's value to your desired width for the thumb.
like this:
var ps = new PerfectScrollbar('#carousel', {
  // set this for 300px width thumb
  maxScrollbarLength: 300
});

Have a look at this demo: https://jsfiddle.net/Towkir/wkoyy0uf/
Comment: I want the gray part (div with class `ps__rail-x`) to be 300px wide AND centered.
Answer: I got the desired effect adding
.ps__rail-x {margin: 0 35%;}

and
var ps = new PerfectScrollbar('#carousel', {
  maxScrollbarLength: 150
});

var ps = new PerfectScrollbar('#carousel', {
  maxScrollbarLength: 150
});
html,
body {
  padding: 0;
  margin: 0;
  height: 100%;
}
.page-wrapper {
  min-height: 100%;
}
.hero {
  height: 100vh;
  background: #212121;
  justify-content: center;
  align-items: center;
}
#carousel {
  display: flex;
  list-style-type: none;
  position: relative;
  margin: 0;
  padding: 0;
  justify-content: left;
  align-items: center;
}
#carousel li {
  padding: 0 0 70px 0;
}
#carousel a {
  text-decoration: none;
  color: #fff;
}
#carousel img {
  display: block;
  width: 100%;
}
#carousel .caption {
  padding: 20px 20px 0 20px;
}
#carousel h2 {
  font-size: 20px;
  line-height: 1;
  margin: 0;
  padding: 0;
}
#carousel p {
  font-size: 10px;
  padding: 0;
  margin: 5px 0 0 0;
}
#carousel .ps__rail-x {
  background: #5C5C5C;
  height: 3px;
  margin: 0 35%;
}
#carousel .ps__thumb-x {
  height: 3px;
  margin-bottom: -2px;
  border-radius: 0;
  background: #fff;
}
<link href="//stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<link href="//rawgit.com/utatti/perfect-scrollbar/master/css/perfect-scrollbar.css" rel="stylesheet"/>

Lorem

A true story

Lorem ipsum

Lorem ipsum. Dolor sit amet.

Lorem

Lorem ipsum. Dolor sit amet

Into the wild

Lorem ipsum dolor sit amet, consectetur


Prove that $5 \times 5 \times 5$ tic-tac-toe ends in a draw

Question: I am pretty sure that when played perfectly, $5 \times 5 \times 5$ tic-tac-toe will end in a draw. Is anyone able to prove this?
Comment: you need to get $5$ in a row right?
Comment: Yes you need to get 5 in a row
Comment: so it's in $3$d ?
Comment: Yes it is in 3d
Comment: Anyone have any ideas?
Comment: According to http://library.msri.org/books/Book42/files/golomb.pdf, the answer was unknown as of 2002. For $n=5,k=3$, it is conjectured that the second player can force a draw ("region 4"), but it has not been ruled out whether the first placer can force a win ("region 3").
Answer: This seems to be an open problem. At any rate, it was stated as an open problem in József Beck's 2008 book Combinatorial Games: Tic-Tac-Toe Theory, on p. 55:

Open Problem 3.2 Is it true that $5^3$ Tic-Tac-Toe is a draw game? Is it true that $5^4$ Tic-Tac-Toe is a first player win?
Very little is known about the $n^d$ games when $d\ge3,$ especially about winning. We know that the first player can achieve a $4$-in-a-row first in the $3$-space ($4^3$ Tic-Tac-Toe); how about achieving a $5$-in-a-row? In other words, the first player wants a winning strategy in some $5^d$ Tic-Tac-Toe. Let $d_0$ denote the smallest dimension $d$ when the first player has a forced win in the $5^d$ game; how small is $d_0?$ (A famous result in Ramsey Theory, called the Hales–Jewett Theorem, see Section 7, guarantees that $d_0$ is finite.) The second question in Open Problem 3.2 suggests that $d_0=4,$ but what can we actually prove? Can we prove that $d_0\le1000?$ No, we cannot. Can we prove that $d_0\le1000^{1000}?$ No, we cannot. Can we prove that $d_0\le1000^{1000^{1000}}?$ No, we cannot prove that either. Even if we iterate this $1000$ times, we still cannot prove that this "$1000$-tower" is an upper bound on $d_0.$ Unfortunately, the best-known upper bound on $d_0$ is embarrassingly poor. For more about $d_0,$ see Section 7.

(See this old answer for a few more quotations from Professor Beck's book.)
If the answer to your question is known, it must have been found within the last few years. You might try asking Professor Beck himself.
Comment: Nice answer +1. Wondering if any other users may know more about this.


The ProxyFactoryFactory was not configured

Question: We have recently upgraded our windows forms C# project from NHibernate 2.0 to 2.1. We updated our app.config to include the "proxyfactory.factory_class" to point to the chosen proxy ("NHibernate.ByteCode.Castle" in our case). After the upgrade the program builds and runs as expected, with no issues. Our problem is when attempting to open any forms that have references to NHibernate upon load within the Visual Studio 2008 designer, now give us the following error (as if we hadn't configured the proxy):

The ProxyFactoryFactory was not
  configured. Initialize
  'proxyfactory.factory_class' property
  of the session-factory configuration
  section with one of the available
  NHibernate.ByteCode providers.

Stack trace:
   at NHibernate.Bytecode.AbstractBytecodeProvider.get_ProxyFactoryFactory()
   at NHibernate.Cfg.Configuration.Validate()
   at NHibernate.Cfg.Configuration.BuildSessionFactory()
   at DAL.NHibernateHelper..cctor() in ...\DAL\NHibernateHelper.cs:line 62

Line 62 from NHibernateHelper:
    static NHibernateHelper()
    {
        var cfg = new Configuration();
        cfg.Configure();
        cfg.AddAssembly("DAL");
        sessionFactory = cfg.BuildSessionFactory(); // <-- line 62
    }

Here is our app.config configuration for NHibernate:
<configuration>
  <configSections>

  </configSections>
  <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
      <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
      <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
      <property name="connection.connection_string">Server=ourserver;initial catalog=ourdb;Integrated Security=SSPI</property>
      <property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
      <property name="show_sql">true</property>
    </session-factory>
  </hibernate-configuration>
</configuration>

Anyone have any clues on how to remedy this issue? Thanks!
Answer: I just worked out the same error.
My data access assembly had a proper reference to Nhibernate.ByteCode.Castle.Dll and it appeared in its bin/release folder.  Everything worked fine within the data access assembly.
The error was thrown when I tried to use data access code from my test assembly.  It turned out that even though my test assembly referenced the data access project, it did not get a copy of the Nhibernate.ByteCode.Castle.dll.  Adding a reference to Nhibernate.ByteCode.Castle.dll in the test assembly solved the problem.
Comment: For those using Castle ActiveRecord and getting the same error, as well as adding the reference to NHibernate.ByteCode.Castle.dll, you'll need to add this to your XML configuration file:
Comment: @Kyralessa. Thanks a million, I've been trying to get Castle ActiveRecord working, and you're comment fixed the issue I was having!
Comment: I had same error in my project, adding reference to Nhibernate.ByteCode.Castle.dll solved my problem.
Answer: I had the same problem.  To fix it, I had to not only explicitly reference the DLL, but add a method to the test DLL that explicitly created NHibernate.ByteCode.Castle.ProxyFactoryFactory.
That did the trick.
Comment: This worked for me too.  Just somewhere put a method you'll never call and create a new NHibernate.ByteCode.Castle.ProxyFactory().
Answer: It seems that the Designer somehow initializes your SessionFactory. Have you tried to add the ByteCodeProvider dll as a reference to your Project?
[EDIT]
Ok..., the fact that the Application runs when deployed implies that everything is configured correctly. So your problem is a VS DesignMode problem. Why (the heck) are you using NHibernate in designmode?
If you really need it try setting the ByteCodeProvider in your code. If you don't need it and just want a quick workarround you could check the current VS mode with this Hack preventing Nhibernate from building the SessionFactory:
static NHibernateHelper()
{
    if(System.Diagnostics.Process.GetCurrentProcess().ProcessName != "devenv")
    {
        var cfg = new Configuration();
        cfg.Configure();
        cfg.AddAssembly("DAL");
        sessionFactory = cfg.BuildSessionFactory(); // <-- line 62
    }
}

If i were you i'd try to find the control or whatever needs this static NHibernateHelper and try to decouple.
Comment: NHibernate.ByteCode.Castle.dll (as well as other dependent dlls) have been referenced.
Comment: We're not (at least intentionally) trying to use NHibernate in design mode. Simply opening a form in the designer triggers VS 2008 to try to initialize any objects associated with the form_load function (one of which being NHibernate). The line of code you provided looks like a viable option however. I'll give that a shot and post a reply on how that worked.
Comment: Consider this as a Hack. I am not sure wheather this would also block SessionFactory creation in Debug mode. I think a better solution would be refactoring your NHibernateHelper. What about initializing the SessionFactory in Program.cs?
Answer: Make sure that in the properties of your Nhibernate.ByteCode.Castle reference, you set it to "Copy Always" so that it gets copied to your \bin folder.
Comment: There is no "Copy Always" option for the reference. However, Copy Local is set to True.


Ionic 3, Angular 4 and prepopulated database

Question: After follow several tutorials, I find imposible to use a prepopulated SqlLite in Ionic 3 and Angular 4..
I try this plugins, all with the same result..
cordova-plugin-dbcopy
nativescript-sqlite
Cordova-sqlite-storage
cordova-sqlite-ext
Anyone here did it?.. if so.. how? I only find tutorials with ionic 2 or 1..
Answer: Ionic 3 and 2 are basically the same framework.
You can follow the tutorial.
What you need is clearly this plugin: https://ionicframework.com/docs/native/sqlite/
Its show how to install "Cordova-sqlite-storage" for ionic 2/3.
Comment: It only works if you are going to create a new database and you populate from the app..


How to rollback commands in Spring Roo?

Question: I realise that this has been asked before but the thread seems about 9 months old. Just want to check if the newer versions have added this capability.
I seemed to have goofed up with one command and desperately want to rollback.
Answer: They are still working on this: https://jira.springsource.org/browse/ROO-911
This feature will solve this problem by optionally keeping everything in a local git repo (so you can always roll back to the last version).
Update: From the JIRA comments, it seems like a first working version is available
Comment: Thanks Sean - just checked the JIRA link. Its been outstanding for a while!
Comment: @Nilesh I know, but that's the status. Other similar requests have been closed as dupes: https://jira.springsource.org/browse/ROO-1015 , https://jira.springsource.org/browse/ROO-1124
Comment: @MikeR perhaps. haven't looked at roo in more than 3 years
Answer: OK- I have used Refactoring from STS to make the change and ROO Shell did pick this up and made corresponding changes to ROO artifacts.
I was running ROO shell from within STS.
If that helps anyone.
Answer: As @sean-patrick-floyd mentioned, this is now available as a Spring Roo 'addon'.
Description: Offers GIT Integration in the project. Each successfully executed command will be automatically committed to a local GIT repository.
<code>roo > addon search git
roo > addon install id --searchResult 1
</code>
Then you can use the built in commands to rollback:
<code>* git revert commit
* git revert last
</code>

How to rollback commands in Spring Roo?


Firefox contenteditable image selected after drop - can't remove selection

Question: If you drag-and-drop around an image in Firefox in a contenteditable area, sometimes the images will end up being selected like this:

Fiddle here: http://jsfiddle.net/zupa/qg5Qh/
You may need to drag-drop it a few times, I have this bug in like 20+% of the time.
I am using Firefox 13.0.1 on Windows 7
How to remove that selection? Any help is appreciated.
Ps:

It is not available as a range via document.getselection().getRangeAt(..)
Firefox does NOT add any HTML attributes, still if I hit save (custom CMS), and reload the page in contenteditable mode, the selection comes back. Seems to be an annoying bug.
Comment: What platform are you using?
I created a demonstration video as well: http://youtu.be/dXCWjjJ1HGY (there I have 13% error rate)
Comment: Replicated on Windows XP Firefox 13.0.1 as well (close to 50% error rate)
Comment: Ah, it's happening on my home PC.
Answer: It does it reliably when the image is within a word that is marked by Firefox as a spelling error. For example, here's your jsFiddle with the image moved into the middle of the word "Lorem": http://jsfiddle.net/timdown/qg5Qh/1/
It seems to be something to do with the styling applied to misspelled words. Add the word "Lorem" to the browser's dictionary and the image styling goes away.
You could switch spellchecking off using the spellcheck attribute. From what I can gather, you have to do this at the  level in Firefox  because it doesn't seem to work on single contenteditable elements as it does for textareas.
Demo: http://jsfiddle.net/timdown/qg5Qh/2/
Comment: I am totally amazed that you spot this. Wow. Thank you Tim!


Implementing SSH Server in C#/.Net

Question: A project we're working on just got a new requirement added to it: it has to be able to receive files through SFTP (SSH) using key/pair authentication. We've been able to find an interesting collection of SSH client libraries (such as SSH.Net), but no server ones. The closest we've found so far is a Python library that we're debating implementing through IronPython.
How should we go about doing this? Are we missing any libraries, or should we work on implementing it ourselves?
Comment: You don't want to implement one yourself - it's too easy to get the security protocol wrong.  OpenSSH itself has had it share of issues: http://www.openssh.org/security.html
Comment: Any reason why you can't just run a separate SSH server?
Comment: We can run a separate SSH server, and that's our fallback at the moment, but it means added complexity to the solution.
Answer: Also, FxSsh is a pure C# implementing SSH server side. In this stage, supported EXEC method and return stream.
you are welcome Fork and Contribute on https://github.com/Aimeast/FxSsh
Answer: Rebex Tiny SFTP Server is a minimalist SFTP server written in C#. You can find sources at https://github.com/rebexnet/RebexTinySftpServer. It depends on a commercial component though.
The list of SFTP server components which will enable you to write your own server application can be found at https://www.sftp.net/server-libraries. I am aware of only two of them: one is from nSoftware (originaly from Eldos) and one from Rebex.

Implementing SSH Server in C#/.Net


Assist with JS app where formula result has a bunch of 9s on the end

Question: Hello I built a very simple Js app to have a cash register on a webpage...
Just experimenting and learning about JS...
anyways, basically there are 4 items (eggs, milk etc) loaded in with prices etc...
using dropdowns you can select an item and quantity and hit the "clickme8 button".
this updates the total and also i am working on creating a table that shows all of the items with all details for each line; everything is working fine; but something bizarre is happening if I input eggs with quantity of "7"; i calculate the extended price for that line by taking the quantity times the unit price
var extend1=gman3[i][1]*gman3[i][2];

this mostly works fine; but if i enter eggs with quantity of 7; the extended price calculated ends with a bunch of 9s...
I have no idea what is causing this, I am sure I am missing something or have something wrong.  I have tried finding an answer but can find nothing like this out there.  Here is the entire app:
<?php
?>

Select the quantity:

<select id="quantity">
<?php
for ($i=1;$i<=10;$i++) {
    ?>
    <option value="<?php echo $i; ?>">
        <?php echo $i; ?>

    </option>
    <?php

}
?>
</select>

Select the item:

<select id="item">
    <option value="eggs">Eggs</option>
    <option value="milk">Milk</option>
    <option value="magazine">Magazine</option>
    <option value="chocolate">Chocolate</option>
</select>

<button onclick="myFunction2()">Click me8</button>

Comment: Possible duplicate of [How to deal with floating point number precision in JavaScript?](https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript)
Comment: thanks for your input and the link, this helped me understand to some extent what is going on...
Answer: Some math results will have a bunch of 9's in the end.
You can do this:

add: function(itemCost){
    itemCost = (itemCost).toFixed(2); //This makes a number have 2 decimals places. For example: 9.99999 comes to 9.99
    this.total += (itemCost || 0);
    this.lastTransactionAmount = itemCost;
},
Comment: thanks, this answer pointed me in the right direction, I was not able to get it to work at first, but when I applied the "toFixed" directly to the extended price that worked fine...
Comment: :D
If that helped you, I'd be glad if you accepted my answer! Thanks.


Can I add a 120v branch for a washer to a 240v dryer circuit?

Question: I'm running 10-3 Romex for a 240v electric dryer in our garage. It would be very convenient to tap into one hot leg and add a 120v outlet for the washer (they will be stacked). Is this allowed per NEC code?
Also, can I add an additional 240v outlet to this circuit to future proof the garage for such things as a table saw or welder? Or does the dryer require a dedicated circuit with no other outlets?
Comment: No you can't combine the washer and dryer circuits.  You wouldn't want to either, the washer is a large enough load that you couldn't run the dryer at the same time.
Answer: You can't tap a cable like that - NEC has a whole section called the "tap rules" which describe when you can do that, and this is not one of those times. Even if you could, it would be a lost cause:  Since a washer must be provisioned for 20A, that plus the 30A dryer puts you at 50A, and you'd need to run the expensive 6/3 cable.
Here's what you can do:
Pull a 12/2 cable alongside the 10/3 cable
That may seem stupidly obvious, but for the cost of a 12/2 cable, you are done. It will take an additional breaker space.
Run 6/3 and install a subpanel
You can run 6/3 cable instead of 10/3, terminate at a small subpanel, then have a 2-pole 30A breaker for the dryer and a 1-pole 20A breaker for the washer.  I believe the subpanel would need to be at least 50A.
Run 10/3 to a subpanel with a "generator" interlock
Use the interlock so you can only operate the 30A breaker for the dryer, OR, the 20A breaker for the washer.  You would have to throw the breaker every time.  Very tedious. This will get old fast.
Buy a washer-dryer set that's designed for that
Large housing complexes are typically out to minimize the utility work they must put in laundry rooms.  Industry caters to them with washer-dryers designed to run together off a 30A/240V receptacle only.  They are either sized correctly, or have logic to manage electricity usage so they can't overload the 30A circuit. They make combo units (washer + dryer in one unit) which tend to be tenant-tier cheap in their feature set... or they make matched set washers + dryers which can be deluxe, but expensive.
Answer: This would not be allowed for several reasons one being the dryer will be protected by a 30 amp breaker the other is that the last 2 code cycles require a 120 v 20 amp dedicated circuit for the laundry.
Comment: I believe there is no rule about adding additional 120v circuits to the dedicated laundry circuit as long as they are in the laundry room, is that correct?  If so, would my garage be considered the laundry room and can the washer share the circuit with the other garage outlets? I have limited breaker box space and would rather not use one for a single 120v outlet to run the washer if I can avoid it.


ActiveResource Caching

Question: How would you cache an ActiveResource model? Preferably in memcached. Right now it's pulling a model from my REST API fine but it pulls dozens of records each time. Would be best to cache them.
Comment: forgive my completely noobish question but what is an "ActiveResource model"? I think of ActiveRecord classes as model classes and ActiveResource as controller classes. I see this phrase all over the place and don't fully understand it. sorry to piggy back on your question :(
Comment: Does this mean a model that is backed by the RESTful requests/api rather than a database?
Comment: An ActiveResource model is just a different way of retrieving data. ActiveRecord is to database, as ActiveResource is to external data (API's for example). ActiveResource doesn't have a lot of the niceties of ActiveRecord, however.
Answer: I've been playing around with the same thing and I think I've found a pretty simple way to check redis for the cached object first.  This will only work when you use the find method, but for my needs, I think this is sufficient.
By overriding find, I can check the checksum of the arguments to see if I already have the response saved in redis.  If I do, I can pull the JSON response out of redis and create a new object right there.  If I don't, I'll pass the find through to ActiveResource::Base's find and the normal action will happen.
I haven't implemented the saving of the responses into redis with ActiveResource yet, but my plan is to populate those caches elsewhere.  This way, normally I can rely on my caches being there, but if they aren't, I can fall back to the API.
class MyResource < ActiveResource::Base
  class << self
    def find(*arguments)
      checksum = Digest::MD5.hexdigest(arguments.md5key)
      cached = $redis.get "cache:#{self.element_name}:#{checksum}"
      if cached
        return self.new JSON.parse(cached)
      end

      scope   = arguments.slice!(0)
      options = arguments.slice!(0) || {}
      super scope, options
    end
  end
end

and a little patch so we can get an md5key for our array:
require 'digest/md5'

class Object
  def md5key
    to_s
  end
end

class Array
  def md5key
    map(&:md5key).join
  end
end

class Hash
  def md5key
    sort.map(&:md5key).join
  end
end

Does that help?
Answer: Caching in rails is configurable.  You can configure the cache to be backed by memcached.  Typically you can cache when you retrieve.  It's unclear if you are a rest consumer or service but it's really not relevant.  If you cache on read (or retrieve) and then read the cache the next time, everything will work just fine.  If you are pulling the data from a database, serve up the cache and if no cache is available then cache the read from the database.
I wrote a blog post about it here:
http://squarism.com/2011/08/30/memcached-with-rails-3/
However what I wrote about is really pretty simple.  Just showing how to avoid an expensive operation with what is sort of similar to the ||= operator.  For a better example, new relic has a scaling rails episode.  For example, they show how to cache the latest 10 posts:
def self.recent
  Rails.cache.fetch("recent_posts", :expires_in => 30.minutes) do
    self.find(:all, :limit => 10)
  end
end

Rails.cache has been configured to be a memcached cache, this is the configurable part I was talking about.
Answer: I would suggest looking into https://github.com/Ahsizara/cached_resource, almost all of the work is done for you through the gem.

ActiveResource Caching


Conflict between Featherlight.js and Contact Form 7?

Question: I'm trying to get a Contact Form 7 form to work in a Featherlight.js lightbox. I've created a page at mydomain.com/contact and set the link to open mydomain.com/contact #main article.
Featherlight does open the form, but when I submit the form, the lightbox closes and the url resolves to mydomain.com/contact/#wpcf7-f262-p11-o1. It doesn't matter if it's successfully submitted or there are validation errors, the lightbox still closes (to be clear, the form does actually work—I receive the email).
If I open the entire page (mydomain.com/contact/), the lightbox doesn't close on submission, which leads me to believe that perhaps there's an AJAX conflict.
That said, I don't receive any errors in the console.
Any help in resolving the issue would be appreciated!
Thanks.
Answer: I've got it working, thanks to the second part of the accepted answer here (the Documentation example from the jQuery website).
jQuery's submit() function didn't work for me—I'm guessing it's a version issue? In any case, this is my final code:
   /* attach a submit handler to the form */
   $( "body" ).on( "submit", ".wpcf7-form", function(event) {

        /* stop form from submitting normally */
        event.preventDefault();

        /* get some values from elements on the page: */
        var $form = $( this ),
          url = $form.attr( 'action' );

        /* Send the data using post */
        var posting = $.post( url, $form.serialize() );

        /* Put the results in a div */
        posting.done(function(data) {
            var content = $(data).find('.wpcf7-form');
            $('.featherlight .wpcf7').empty().append(content);
        });
    });


Tensorflow Object Dectection API : how to create tfrecords with images not containing any labels (hard negatives)?

Question: Hello.
I am currently using tensorflow object detection API(with Faster Rcnn)on my own dataset, for some of my labels, i've identified objects that are very likely to be detected as false positives, and i know that the API uses hard exemples mining, so what i'am trying to do it is to introduce images that contain these hard objects into the training , so that the miner can take them as hard negatives.
following this conversation on
  github  https://github.com/tensorflow/models/issues/2544 I was told that it's possible

You can have purely negative images and faster_rcnn models will sample
  from anchors from them.

So my question is : how do i create tfrecords with some images not having any bounding boxes ? What do i put in the associated .xml files?
Comment: have you had the answer?
Comment: Unfortunately, no
Answer: In your tfrecords generation script make sure you add the metadata of the hard negative image to tf record like this -
tf_example = tf.train.Example(features=tf.train.Features(feature={
            'image/height': dataset_util.int64_feature(height),
            'image/width': dataset_util.int64_feature(width),
            'image/filename': dataset_util.bytes_feature(filename),
            'image/source_id': dataset_util.bytes_feature(filename),
            'image/encoded': dataset_util.bytes_feature(encoded_jpg),
            'image/format': dataset_util.bytes_feature(image_format)
            }))

For an image with objects you must add the bounding boxes and label information as well -
tf_example = tf.train.Example(features=tf.train.Features(feature={
            'image/height': dataset_util.int64_feature(height),
            'image/width': dataset_util.int64_feature(width),
            'image/filename': dataset_util.bytes_feature(filename),
            'image/source_id': dataset_util.bytes_feature(filename),
            'image/encoded': dataset_util.bytes_feature(encoded_jpg),
            'image/format': dataset_util.bytes_feature(image_format),
            'image/object/bbox/xmin': dataset_util.float_list_feature(xmins),
            'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs),
            'image/object/bbox/ymin': dataset_util.float_list_feature(ymins),
            'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs),
            'image/object/class/text': dataset_util.bytes_list_feature(classes_text),
            'image/object/class/label': dataset_util.int64_list_feature(classes),
        }))

Also make sure you set min_negatives_per_image to a positive number in your pipeline.config file otherwise it won't train with negative images
Comment: yeah, I will point out the exact same thing -- one has to properly set the training config, i.e. `min_negatives_per_image`, to invoke the expected hard negative sampling behavior
Comment: I used this piece of code and my train behavior didn't change at all. I had to pass an empty list to the boxes keys so it could actually be used on training as a negative sample (image without annotations). Using faster_rcnn_resnet101_coco.config.
Answer: I adapted my dataset to add a dummy annotation for images that doesn't had any real annotations and changed the tfrecord producer code to:
def create_tf_example(group, path, label_map):
    with tf.gfile.GFile(os.path.join(path, '{}'.format(group.filename)), 'rb') as fid:
        encoded_jpg = fid.read()
    encoded_jpg_io = io.BytesIO(encoded_jpg)
    image = Image.open(encoded_jpg_io)
    width, height = image.size

    filename = group.filename.encode('utf8')
    image_format = b'jpg'

    xmins = []
    xmaxs = []
    ymins = []
    ymaxs = []
    classes_text = []
    classes = []

    for index, row in group.object.iterrows():
        if not pd.isnull(row.xmin):
            if not row.xmin == -1:
                xmins.append(row['xmin'] / width)
                xmaxs.append(row['xmax'] / width)
                ymins.append(row['ymin'] / height)
                ymaxs.append(row['ymax'] / height)
                classes_text.append(row['class'].encode('utf8'))
                classes.append(label_map[row['class']])

    tf_example = tf.train.Example(features=tf.train.Features(feature={
        'image/height': dataset_util.int64_feature(height),
        'image/width': dataset_util.int64_feature(width),
        'image/filename': dataset_util.bytes_feature(filename),
        'image/source_id': dataset_util.bytes_feature(filename),
        'image/encoded': dataset_util.bytes_feature(encoded_jpg),
        'image/format': dataset_util.bytes_feature(image_format),
        'image/object/bbox/xmin': dataset_util.float_list_feature(xmins),
        'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs),
        'image/object/bbox/ymin': dataset_util.float_list_feature(ymins),
        'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs),
        'image/object/class/text': dataset_util.bytes_list_feature(classes_text),
        'image/object/class/label': dataset_util.int64_list_feature(classes),
    }))
    return tf_example

So, when an dummy annotation 'xmin == -1' appears, it creates a tfrecord with empty list of bounding boxes (class, xmin, xmax, ymin, ymax).
Besides the messy train loss behavior, my model successfully learned the negative samples pattern, thus decreasing to zero the false positives I got, on my scenario.
Answer: You don't have to do anything specific for that. Just leave the list of associated bounding boxes empty, whatever the source format is. I did so for my experiments, did not get any gain though.


TypeError: Cannot read property 'username' of undefined in passportjs

Question:   app.get('/getUser', function(req, res) {

     console.log(req.user.username);

         res.json({'user':req.user.username});
    });

When I login to passportjs, this does not return any error, but when I am not logged in, it shows TypeError: Cannot read property 'username' of undefined error, I need to send res.json only if it is defined,
     app.get('/getUser', function(req, res) {

         console.log(req.user.username);
    if(typeof req.user.username!="undefined")
             res.json({'user':req.user.username});
           else
     res.json({'user':"Anonymous"});
                    });

but it gives error for conditional statement, How do I error handle it?
Comment: if(typeof req.user !="undefined")
Answer: Passport places user on the req object.  If you have not performed authentication with Passport, there will be no user object on the request object.  Therefore, req.user will be undefined.  As you can probably imagine, undefined does not have a property named username, causing your error.
You probably want something like:
username = req.user ? req.user.username : "Anonymous"
res.json({'user':username});


How to prove $\left(\frac{4}{3-\sqrt{5}}\right)^2 - \left(\frac{6 - 5 \sqrt{6}}{5 - \sqrt{6}}\right)^2 = 2\sqrt{61+24\sqrt{5}}$?

Question: How to prove the following identity?
$$\left(\frac{4}{3-\sqrt{5}}\right)^2 - \left(\frac{6 - 5 \sqrt{6}}{5 - \sqrt{6}}\right)^2 = 2\sqrt{61+24\sqrt{5}}$$
I come up with $\dfrac{16}{14-6\sqrt{5}}-6=2\sqrt{61+24\sqrt{5}}$, but still can't get it to the obvious equality.
Any ideas?
Comment: Please write something descriptive in the title of a question.
Comment: @hey, Suggestion: change title to "How to prove an algebraic numerical equality with radicals?"
Comment: @hey, why don't you put as many close brackets as open brackets? I added them so that the question makes sense.
Comment: LaTeX conversion of (16 / (14 - 6*sqrt(5))) - 6 = 2 * sqrt(61 + 24*sqrt(5)) : $\dfrac{16}{14-6\sqrt{5}}-6=2\sqrt{61+24\sqrt{5}}$
Comment: Technically it is an equality, not an identity, because there is no variables such as $(a+b)^2=a^2+2ab+b^2$
Answer: Simplify both sides to $8+6\sqrt{5}$, as they are both equal to this.
Just square the RHS to see this and rationalise the denominators on the LHS.
After the rationalisation of the denominators on the LHS (which is very quick) you obtain $(3+\sqrt{5})^2-6,$ and hence the $8+6\sqrt{5}.$
Answer: Since
$$\dfrac{4^{2}}{\left( 3-\sqrt{5}\right) ^{2}}-\dfrac{\left( 6-5\sqrt{6}%
\right) ^{2}}{\left( 5-\sqrt{6}\right) ^{2}}=\dfrac{4^{2}\left( 5-\sqrt{6}%
\right) ^{2}-\left( 6-5\sqrt{6}\right) ^{2}\left( 3-\sqrt{5}\right) ^{2}}{%
\left( 3-\sqrt{5}\right) ^{2}\left( 5-\sqrt{6}\right) ^{2}}$$
and
$$\dfrac{1}{\left( 3-\sqrt{5}\right) ^{2}\left( 5-\sqrt{6}\right) ^{2}}=\dfrac{%
\left( 3+\sqrt{5}\right) ^{2}\left( 5+\sqrt{6}\right) ^{2}}{5776},$$
to prove
$$\left( \dfrac{4}{3-\sqrt{5}}\right) ^{2}-\dfrac{\left( 6-5\sqrt{6}\right)
^{2}}{\left( 5-\sqrt{6}\right) ^{2}}=2\sqrt{61+24\sqrt{5}}\quad (1)$$
it is enough to show that
$\left( 16\left( 5-\sqrt{6}\right) ^{2}-\left( 6-5\sqrt{6}\right) ^{2}\left(
3-\sqrt{5}\right) ^{2}\right) \left( 3+\sqrt{5}\right) ^{2}\left( 5+\sqrt{6}%
\right) ^{2}$
$=11552\sqrt{61+24\sqrt{5}}$.
But (see addendum)
$$\left( 16\left( 5-\sqrt{6}\right) ^{2}-\left( 6-5\sqrt{6}\right) ^{2}\left(
3-\sqrt{5}\right) ^{2}\right) \left( 3+\sqrt{5}\right) ^{2}\left( 5+\sqrt{6}%
\right) ^{2}=3656\sqrt{5}+46208.$$
It remains to prove
$$\left( 34656\sqrt{5}+46208\right) ^{2}=11552^{2}\left( 61+24\sqrt{5}%
\right) \quad (2).$$
The left hand side is
$$\left( 3656\sqrt{5}+46208\right) ^{2}=3202768896\sqrt{5}+8140370944$$
and the right hand side is equal:
$$11552^{2}\left( 61+24\sqrt{5}\right) =3202768896\sqrt{5}+8140370944,$$
which proves your equality.

Addendum:
$$\left( 16\left( 5-\sqrt{6}\right) ^{2}-\left( 6-5\sqrt{6}\right) ^{2}\left(
3-\sqrt{5}\right) ^{2}\right) \left( 3+\sqrt{5}\right) ^{2}\left( 5+\sqrt{6}\right) ^{2}$$
$$=16\left( 3+\sqrt{5}\right) ^{2}\left( 5+\sqrt{6}\right) ^{2}\left( 5-\sqrt{%
6}\right) ^{2}-\left( 3+\sqrt{5}\right) ^{2}\left( 5+\sqrt{6}\right)
^{2}\left( 6-5\sqrt{6}\right) ^{2}\left( 3-\sqrt{5}\right) ^{2}$$
$$=5776\left( 3+\sqrt{5}\right) ^{2}-34656=34656\sqrt{5}+46208$$

Addendum 2: The second equality stated in the question
$$\dfrac{16}{14-6\sqrt{5}}-6=2\sqrt{61+24\sqrt{5}}\quad (3)$$
is equivalent to
$$\dfrac{8}{14-6\sqrt{5}}-3=\sqrt{61+24\sqrt{5}}=\sqrt{61+\sqrt{2880}}.$$
The LHS can be transformed into
$$\dfrac{8}{14-6\sqrt{5}}-3=\dfrac{18\sqrt{5}-34}{14-6\sqrt{5}}$$
$$=\dfrac{18\sqrt{5}-34}{14-6\sqrt{5}}\times \dfrac{14+6\sqrt{5}}{14+6\sqrt{5}%
}=\dfrac{64+48\sqrt{5}}{16}=4+3\sqrt{5}.$$
Then we have to prove
$$\sqrt{61+\sqrt{2880}}=4+3\sqrt{5}.\quad (4)$$
Now we apply to the LHS the following general transformation involving radicals:
$$\sqrt{A+\sqrt{B}}=\sqrt{\dfrac{A+\sqrt{A^{2}-B}}{2}}+\sqrt{\dfrac{A-\sqrt{%
A^{2}-B}}{2}}$$
If $A=61,B=2880$, then $\sqrt{A^{2}-B}=\sqrt{61^{2}-2880}=29$ and
$$\sqrt{\dfrac{A+\sqrt{A^{2}-B}}{2}}=3\sqrt{5},$$
$$\sqrt{\dfrac{A-\sqrt{A^{2}-B}}{2}}=4,$$
which completes the proof.
Comment: You're working too hard, Américo: simplify before you take all those squares!  If we write the equation as a^2 - b^2 = 2Sqrt(c), begin by finding (as Derek Jennings suggests) that a = 3 + Sqrt(5) and b = -Sqrt(6).  You should also suspect that c itself is a perfect square of the form x + y Sqrt(5); you easily find x = 4 and y = 3.
Comment: @Américo Tavares: Just to be clear, my proposal is not a "clever trick;" it's a standard way to proceed. One is guided in such problems by seeking simplification early and often.  This tends to limit the work that must be done.  In fact, you could halve the length of your addendum by following this principle: simplify the arguments of the squares (and of the square root) *before* performing the squaring.
Comment: whuber: I made an alternative "standard" algebraic computation (without any clever trick).
Comment: @whuber: I agree with you that seeking **simplification early and often is better than rarely and later**. I also tend to do it, as opposed to what I did here. I am from a generation and a country where algebraic manipulation was very stressed, and we  learned (as a problem) transformations of radicals such as the one I wrote in Addendum 2, no longer taught. I know that quite often all these manipulations are seen as boring and tedious, apart from being very time consuming. Also in trigonometry we studied many more formulae than now. In the future I will try more concise approaches.
Comment: @whuber, only a final comment: The OP did not select my answer, which is a clear evidence to me that my answer was not good.
Comment: @Américo: I wouldn't take that to be the case in general.  Only one answer can be selected and you're free to disagree with the OP!  The important thing is that one usually learns more by risking an answer, even if it can be improved or is wrong, than by not answering at all.
Answer: You want to show:
$$\left(\frac{4}{3-\sqrt{5}}\right)^2 - \left(\frac{6 - 5 \sqrt{6}}{5 - \sqrt{6}}\right)^2 = 2\sqrt{61+24\sqrt{5}}$$
First multiply out the squares
$$\frac{16}{14-6\sqrt{5}} - \frac{186-60\sqrt{6}}{31-10\sqrt{6}} = 2\sqrt{61+24\sqrt{5}}$$
Then simplify it
$$\frac{16}{14-6\sqrt{5}} - 6 = 2\sqrt{61+24\sqrt{5}}$$
now we can start getting rid of the square roots on the right hand side by squaring both sides
$$\frac{256}{376-168\sqrt{5}} - \frac{192}{14-6\sqrt{5}} + 36 = 244 + 96 \sqrt{5}$$
at this point it makes sense to rationalize the denominators of the fractions
$$\left(\frac{256}{376-168\sqrt{5}}\right)\left(\frac{376+168\sqrt{5}}{376+168\sqrt{5}}\right) - \left(\frac{192}{14-6\sqrt{5}}\right)\left(\frac{14+6\sqrt{5}}{14+6\sqrt{5}}\right) + 36 = 244 + 96 \sqrt{5}$$
which simplifies to
$$376 + 168\sqrt{5} - 168 - 72\sqrt{5} + 36 = 244 + 96 \sqrt{5}$$
collecting like terms now gives
$$(376 - 168 + 36) + (168 - 72)\sqrt{5} = 244 + 96 \sqrt{5}$$
which is easily seem to be equal.

Another approach is, using the fact that algebraic numbers cannot be too close together - compute the first few digits of both sides of the original identity and compare them.
Comment: You probably want to make sure both sides have the same sign before you square them.
Comment: How did you conclude the correct result $\frac{\left(186-60\sqrt{6}\right)}{\left(31-10\sqrt{6}\right)}=6$ - I mean did you actually tested it or is there a theory?
Answer: Specialize $\rm\ \ \ b=3,\ \ c = 5,\ \ d = 6 \ \Rightarrow\ a = 4\ \ $ in this simple derivation:
$\rm\quad\quad\quad\quad\displaystyle \bigg(\frac{b^2-c}{b-\sqrt{c}}\bigg)^2 - \bigg(\frac{d -5\sqrt{d}}{5-\sqrt d}\bigg)^2$
$\rm\quad\quad =\quad \:(\: b \ \: + \:   \sqrt{c}\ )^{\:2} \ \ \:-\ \ \ (\:-\:\sqrt{d}\:)^{2} $
$\rm\quad\quad =\ \  2\ (\:a + b \sqrt{c}\ )\:, \quad 2\ a\ =\ b^2+c-d $
$\rm\quad\quad =\ \ 2\:\sqrt{a^2+b^2\:c+2\:a\:b\sqrt{c} } $
NOTE $\:$ Replacing numbers by functions makes  the proof both simpler and more general - similar to your recently asked question
Comment: Very clean solution.
Answer: Trivial. Lets simplify the left part:
multiply first fraction to the sum of expressions in its denominator, and get whole part in second fraction and do with second fraction the same that we did with first:
$(\frac{4(3+\sqrt{5})}{9-5})^2 - (\frac{25-19 - \sqrt{6}}{5-\sqrt{6}}) = (3+\sqrt{5})^2 - (5-\frac{19(5+\sqrt{6})}{25-6})^2 = (3+\sqrt{5})^2 - 6 = 8 + 6\sqrt{5}$
Now lets prove this:
$8+6\sqrt{5}=2\sqrt{61+24\sqrt{5}}$
divide by two and square:
$4+3\sqrt{5} = \sqrt{61+24\sqrt{5}}$
$16+45+24\sqrt{5}=61+24\sqrt{5}$
Thats all.


Migrate MySQL database to Oracle 11g with SQL Developer 3

Question: I try to migrate a sample database from mysql to Oracle 11g using SQL developer. I go through some online tutorial and follow each steps but I don't know why there is no data show up in the target database.
Here is what I did:

Connect to MySQL(connection name "MySQL") using SQL Developer with JConnector, log on as root.
Create a empty schema for "Repository" during migration named "TEMPBUFFER"
Create a target schema for holding the data in Oracle, named "DEVELOPER"
Follow migration wizard:

Migration Repository = TEMPBUFFER
  Third party database for migration = MySQL
  Target schema in Oracle = DEVELOPER
  Only one database called "classmodels" is chosen to be immigrated from MySQL

So here are my questions:

On top of everything, why there is no table/data show up on DEVELOPER schema, how to fix it?
What is a Migration Repository and why we need it? It seems hold a few tables with config information, so is it very common we should use the target schema as Migration Repository?

Thanks in advance.
Comment: I'm struggling with same issue. Did you find what's wrong? if you do, please share it.
Answer: i know this is old but the last step is to do copy to oracle when right click the tables on the source scheme
step 27 in this tut
http://taliphakanozturken.wordpress.com/tag/db-migration-using-sql-developer/


Outlook auto forward set replyto to orginal sender rather than forwarder

Question: I have VBA code to forward email to a specific account. It works except email being forwarded has the forwarder's email address.
How can I keep the original sender email address as the replyto after an email is forwarded?
Sub AutoForwardAllSentItems(Item As Outlook.MailItem)
    Dim strMsg As String
    Dim autoFwd  As Outlook.MailItem

    Set autoFwd = Item.Forward

    autoFwd.Recipients.Add "email@example.com"

    autoFwd.Send

    Set autoFwd = Nothing
End Sub

Answer:
so there is no way? really? – Mike 7 hours ago

Riking is correct when he mentioned that Outlook will not let you modify the headers included in the email. I am guessing that he is refering to .SenderEmailAddress property. You cannot modify the .SenderEmailAddressas this property is readonly.
Having said that there is another property that you may like to use. .SentOnBehalfOfName More details here
Topic: SentOnBehalfOfName Property
Link: http://msdn.microsoft.com/en-us/library/aa171998%28v=office.11%29.aspx
Quote from the above link

Returns a String indicating the display name for the intended sender of the mail message. This property corresponds to the MAPI property PR_SENT_REPRESENTING_NAME. Read/write.
expression.SentOnBehalfOfName
expression     Required. An expression that returns a MailItem object.

Also see this link
Topic: Automatically setting the 'From' address of a new Outlook message
Link: http://benchristian.wordpress.com/2005/12/18/automatically-setting-the-from-address-of-a-new-outlook-message/
Quote from the above link

Setting an alternate reply address is particularly useful if you are using a mail enabled public folder or distribution list for a group of users and would like the replies to messages that they send to go to the group smtp address instead of the sender's mailbox.

HTH
Answer: Everything I've seen so far supports the conclusion that Outlook will not
let you modify the headers included in the email.
Sorry. I'd suggest managing the forwards at the email provider, if that is an option for you.
Comment: + 1 Yup you cannot change the `.SenderEmailAddress property` as it is readonly.


neo4j requires more space than expected

Question: I have a neo4j server including 10 million nodes.
I'm trying to create 1 billion relationships, by adding each node 100 relationships.
I wrote a java embedded program and it updates the relationships.
So far, the execution time looks not bad: approximately 15 million relationships per hour. (using 3GB heap size);
But, the disk usage is increasing far more than expected : appr. 6 GB per hour .(15 m relationships..)
For my understanding, relationship takes 33B. So, when adding 15 million relationships (with no properties at all except for the name), it should take about 0.5 GB . instead it takes 10 times more!
Why relationships take so much disk usage?
Comment: Are you using the bulk inserter or the normal transactional method for your creation? When you say it's taking up all that space, is it just the `relationshipstore` or is it the entire neo4j directory?
Comment: below post might help:::

http://stackoverflow.com/questions/15074593/how-does-neo4j-perform-in-time-and-space-complexity-for-given-type-of-nodes-rel
Answer: You probably need to clean up your logical log (to be sure, check which files are growing fast). You can configure this via a configuration parameter: keep_logical_logs=false
Comment: Hi Wes. You're right, the logical files took increased up to 40 GB. I stopped the service, cleaned the files, changed in `neo4j.properties` file to `keep_logical_logs="2G size"`. But, when started it again, got the same problem, it got much over 2G... How can I change configuration?
Comment: It should keep "more than 2G", depending on your transactions and the files they're in... for heavy insert load I would just do `false`.
Answer: See Code:
int number = (int) parseLongWithUnit( numberWithUnit );

More than "2G size" can not set by bytes,but you can set XXX files/XXX hours/XXX days/XXX txs
keep_logical_logs for backup/HA sync etc.

neo4j requires more space than expected


Send HTML Mail from Cocoa with Mail.app

Question: I'm trying to send html email from Cocoa app, through Mail.app. I want to open new message in Mail.app, include subject, recipient and add HTML Body with links and other content. But can't find the way to do this.
I already tried Scripting Bridge, but MailOutgoingMessage class doesn't have content type i can add content in plaintext.
tried AppleScript, something like this:
set htmlContent to read "/Path/index.html"
set recipientList to {"email@example.com"}

tell application "Mail"
    set newMessage to make new outgoing message with properties {subject:"qwerty", visible:true}
    tell newMessage
        make new to recipient at end of to recipients with properties {address:"firstname.lastname@example.com"}
            set html content to htmlContent
        --send
    end tell
end tell

this code send email with html, only if I'm changing --send to send. But i need to send letter later, after user made some changes.
Answer: To recap the problem: Using AppleScript to create a message with HTML content for interactive editing does not work (as of OS X 10.9.2): the new-message form comes up with an empty body.
This should be considered a bug and I encourage everyone to let Apple know at http://bugreport.apple.com - caveat: the html content message class property is not defined in Mail.sdef, Mail.app's AppleScript dictionary, so assigning HTML may not be officially supported.
There is a workaround, but it ain't pretty:

Create the message invisibly.
Save it as a draft.
Open the draft message, at which point the HTML content will appear.

Implementing this robustly is challenging, because several workarounds are required. The following code tries its hardest, though:
Note: Since the code uses GUI scripting, Access for Assistive Devices must be enabled (via System Preferences > Security & Privacy > Accessibility) for the application running this code (e.g., AppleScript Editor or, if run via osascript, Terminal.app).
# Example values; use `read someFile` to read HTML from a file.
set htmlContent to "
Hello,

world.
"
set recipientList to {"firstname.lastname@example.com", "email@example.com"}
set msgSubject to "qwerty"

tell application "Mail"

    # Create the message *invisibly*, and assign subject text
    # as well as the HTML content.
    set newMessage to make new outgoing message with properties ¬
        {visible:false, subject:msgSubject, html content:htmlContent}

    # Add recipients.
    # !! Given the workaround below, this is currently pointless.
    tell newMessage
        repeat with toRcpt in recipientList
            make new to recipient at end of to recipients with properties {address:toRcpt}
        end repeat
    end tell

    # Save the current number of drafts messages.
    set draftCountBefore to count messages of drafts mailbox

    # !! Save the new message as a *draft* - this is necessary
    # for the HTML content to actually appear in the message
    # body when we open the message interactively later.
    save newMessage

    # !! Sadly, it takes a little while for the new message
    # !! to appear in the drafts mailbox, so we must WAIT.
    set newMessageAsDraft to missing value
    repeat with i from 1 to 30 # give up after n * 0.1 secs.
        set draftCountNow to (count messages of drafts mailbox)
        if draftCountNow > draftCountBefore then
            set newMessageAsDraft to message 1 of drafts mailbox
            exit repeat
        end if
        delay 0.1 # sleep a little
    end repeat

    # Abort, if the draft never appeared.
    if newMessageAsDraft is missing value then error "New message failed to appear in the drafts mailbox within the timeout period."

    # Open the new message as a *draft* message - this ensures that
    # the HTML content is displayed and editable in the message body.
    # !! The ONLY solution I found is to use `redirect`, which, unfortunately,
    # !! *wipes out the recipients*.
    # !! It does, however, ensure that the draft is deleted once the message is sent.
    redirect newMessageAsDraft with opening window

    # Activate Mail.app and thus the draft message's window.
    activate

    # !! Since the recipients have been wiped out, we need to
    # !! add them again - unfortunately, the only way we can do that is to
    # !! *GUI scripting* - simulating invocation of a menu command or
    # !! sending keystrokes.
    tell application "System Events"

        # We must make sure that the target window is active before
        # we can perform GUI scripting on it.
        set newMessageWindow to missing value
        repeat with i from 1 to 30 # give up after n * 0.1 secs.
            tell (first window of (first process whose frontmost is true) whose subrole is not "AXFloatingWindow")
                if name is msgSubject then
                    set newMessageWindow to it
                    exit repeat
                end if
            end tell
            delay 0.1 # sleep a little
        end repeat
        if newMessageWindow is missing value then error "New message failed to become the active window within the timeout period."

        # Turn the list of recipients into comma-delimited *string* for pasting into the To field.
        set {orgTIDs, AppleScript's text item delimiters} to {AppleScript's text item delimiters, {","}}
        set recipientListString to (recipientList as text)
        set AppleScript's text item delimiters to orgTIDs

        # Save the current clipboard content.
        set prevClipboardContents to the clipboard

        # Cursor is in the  "To:" field, so use GUI scripting to send the Edit > Paste command now.
        # NOTE: Access for assistive devices must be enabled via System Preferences > Security & Privacy > Accessibility.
        set the clipboard to recipientListString
        my pasteFromClipboard("")

        # Restore the previous clipboard content.
        # !! We mustn't do this instantly, as our temporary content may not have
        # !! finished pasting yet. It would be non-trivial to determine
        # !! when pasting has finished (examining `count of to recipients` doesn't work),
        # !! so we take our chances with a fixed, small delay.
        delay 0.1
        set the clipboard to prevClipboardContents

        # Place the cursor in the message *body*.
        # !! This works as of Mail.app on OS X 10.9.2, but may break in the future.
        try
            tell newMessageWindow
                tell UI element 1 of scroll area 1
                    set value of attribute "AXFocused" to true
                end tell
            end tell
        end try

    end tell

end tell

(*
 Pastes form the clipboard into the active window of the specified application (process) using GUI scripting
 rather than keyboard shortcuts so as to avoid conflicts with keyboard shortcuts used to invoke this handler.
 Specify "" or `missing value` to paste into the currently active (frontmost) application.
 The target process may be specified by either name or as a process object.

 CAVEAT: While this subroutine IS portable across *UI languages*, it does make an assumption that will hopefully hold for
 all applications: that the "Edit" menu is the *4th* menu from the left (Apple menu, app menu, File, Edit).

 Examples:
     my pasteFromClipboard("") # paste into frontmost app
     my pasteFromClipboard("TextEdit")
*)
on pasteFromClipboard(targetProcess)
    tell application "System Events"
        if targetProcess is missing value or targetProcess = "" then
            set targetProcess to first process whose frontmost is true
        else
            if class of targetProcess is text then
                set targetProcess to process targetProcess
            end if
            -- Activate the application (make it frontmost), otherwise pasting will not work.
            set frontmost of targetProcess to true
        end if
        tell menu 1 of menu bar item 4 of menu bar 1 of targetProcess
            -- Find the menu item whose keyboard shortcut is Cmd-V
            set miPaste to first menu item whose value of attribute "AXMenuItemCmdChar" is "V" and value of attribute "AXMenuItemCmdModifiers" is 0
            click miPaste
        end tell
    end tell
end pasteFromClipboard

Answer: I didn't see that you needed to edit the message before sending, so my previous answer was wrong. This time it should be correct.
It basically

takes a preformatted RTF file,
renders it & puts it into the clipboard,
creates a new message,
fills in the fields,
moves the focus to the message body,
pastes the formatted clipboard

Here is the code:
set textSubject to "HTML Test"
set toAddress to "firstname.lastname@example.com"
set toName to "John Doe"

tell application "Mail"
    do shell script "cat ~/Documents/RTF\\ File.rtf | textutil -stdin -stdout -convert rtf | pbcopy"

    set refMessage to make new outgoing message with properties {name:toName, address:toAddress, subject:textSubject, visible:true}
    tell refMessage
        make new to recipient at end of to recipients with properties {name:toName, address:toAddress}
    end tell
end tell

tell application "System Events"
    tell application process "Mail"
        set frontmost to true
        set value of attribute "AXFocused" of scroll area 4 of window textSubject to true
    end tell
    keystroke "v" using {command down}
end tell

Again, this worked fine on Snow Leopard
Hope that helped.
Comment: Normally [Link only responses](http://meta.stackexchange.com/questions/65277/are-link-only-answers-poor-practice) are frowned upon.
Comment: Ack. Thx for heads up.
Comment: getting an error cannot set outgoing message on your code.. can you please confirm ?
Comment: Compiles and runs fine for me. I did find that the scroll area needed to be 4, I don't know why I had 3 originally but I changed it now. FYI this is Mail app v4.6 on 10.6.8
Answer: It isn't clear what your are looking for, but I'll do my best to offer some help.
If you leave send commented, then the message should already be open in Mail.app, waiting for further editing and sending.
By adding the line save newMessage, it will be saved to the drafts folder. The user can open it and continue editing whenever they please. If you want to actually send the draft from your application, use:
set sendMessage to first message of drafts mailbox
send sendMessage

Good luck!
Answer: If the HTML file's contents is a real HTML, then following script will create in Mail.app outgoing message with its contents. No GUI scripting involved. After sending to yourself you can confirm that the links and other rich content is preserved.
use framework "Foundation"
use framework "AppKit"
use scripting additions

-- classes, constants, and enums used
property NSUTF8StringEncoding : a reference to 4
property NSSharingServiceNameComposeEmail : a reference to current application's NSSharingServiceNameComposeEmail
property NSAttributedString : a reference to current application's NSAttributedString
property NSString : a reference to current application's NSString
property NSSharingService : a reference to current application's NSSharingService

set messageSubject to "Sending the message with html file contents."
set recipientAddresses to {"firstname.lastname@example.com"} -- I will send to myself, to test

set htmlContent to read (POSIX path of (choose file))

set theSource to NSString's stringWithString:htmlContent
set theData to theSource's dataUsingEncoding:NSUTF8StringEncoding
set anAttributedString to NSAttributedString's alloc()'s initWithHTML:theData documentAttributes:{}

-- USE THE MAIL SHARING SERVICE TO CREATE A NEW MAIL MESSAGE
set aSharingService to NSSharingService's sharingServiceNamed:(NSSharingServiceNameComposeEmail)
if aSharingService's canPerformWithItems:recipientAddresses then
    set aSharingService's subject to messageSubject
    set aSharingService's recipients to recipientAddresses
    tell aSharingService to performSelectorOnMainThread:"performWithItems:" withObject:{anAttributedString} waitUntilDone:false
end if

Send HTML Mail from Cocoa with Mail.app


C++ if (false) condition evaluated?

Question: I'm learning about template in C++, and my set of C++ terminology is somewhat limited, so I couldn't google this problem.I'm trying to implement a custom dict type based on std::unordered_map. My goal is to be able to instantiate the class dict in ways like the following:
dict<std::string, long> d; // OR
dict<std::string, std::set<std::string>> d; // OR
dict<std::string, std::map<char, float>> d; // OR
dict<std::string, std::vector<std::string>> d; // OR
dict<std::string, std::vector<double>> d;

So here's the code, I'm using:
utils.h
#include <fstream>
#include <unordered_map>
#include <set>
#include <vector>
#include <algorithm>
#include <type_traits>

// for bravity
using namespace std;

// to check for stl vector
// slightly modified version of: https://stackoverflow.com/a/31105859
namespace is_container {
    template <typename T> struct stl_vector : false_type{};
    template <typename T> struct stl_vector<std::vector<T>> : true_type{};
}

namespace StringOps {
    // generaic function to split based on many delimiters:
    // source: https://stackoverflow.com/a/9676623
    vector<string> split(const string& str, const string& delimiters = " ,") {
        vector<string> v;
        unsigned start = 0;
        auto pos = str.find_first_of(delimiters, start);
        while(pos != string::npos) {
            if(pos != start) // ignore empty tokens
                v.emplace_back(str, start, pos - start);
            start = pos + 1;
            pos = str.find_first_of(delimiters, start);
        }
        if(start < str.length()) // ignore trailing delimiter
            v.emplace_back(str, start, str.length() - start); // add what's left of the string
        return v;
    }
}

template<class Key, template <class...> class Value, typename T, class = void>
class dict {
    public:
        Value<T> t;
};

template<class Key, template <class...> class Value, typename T> // detect container types with ::iterator
class dict<Key, Value, T, void_t<typename Value<T>::iterator>> : true_type {
    private:
        unordered_map<Key, Value<T>> content;
        bool is_vector = false;
        string line;
        unordered_map<Key, Value<T>> load(ifstream& file) {
            while (getline(file, line)) {
                if (!line.empty()) {
                    // remove trailling \n if exists
                    if (line[line.length()-1] == '\n')
                        line.erase(line.length() - 1);

                    vector<string> tokens = StringOps::split(line);
                    Value<T> result;
(tokens[i]));

                    if (is_vector) {
                        for (unsigned i = 1; i < tokens.size(); i++) {
                            result.emplace_back(static_cast<T>(tokens[i]));
                        }
                    }
                    if(false) { // should never be looked into
                        auto it = result.cend();
                        for (unsigned i = 1; i < tokens.size(); i++) {
                            result.emplace_hint(it, static_cast<T>(tokens[i]));
                        }
                    }
                    content[static_cast<Key>(tokens[0])] = result;
                }
            }
            return content;
        }

    public:
        constexpr Value<T>& operator[](Key k) {
            return content[k];
        }

        dict(const string& path) {
            // detect vector type
            if(is_container::stl_vector<decay_t<Value<T>>>::value)
                is_vector = true;
            ifstream file(path);
            content = load(file);
        }

        constexpr unsigned size() {
            return content.size();
        }
};

template<class Key, template <class...T> class Value, typename T> // detect arithmatic types
class dict<Key, Value, T, typename enable_if<is_arithmetic<Value<T>>::value>::type> {
    public:
        dict() {
            // we'll come to you later..
        }
};

main.cpp
#include <iostream>
#include "utils.h"

int main() {
    dict<string, vector, string> d("/home/path/to/some/file");
    cout << d.size();
}

results:
error: no member named 'emplace_hint' in 'std::vector<std::__cxx11::basic_string<char>, std::allocator<std::__cxx11::basic_string<char> > >'
                        result.emplace_hint(it, static_cast<T>(tokens[i]));

questions:
1 - why on earth if (false) condition is reached in the first place?
2 - how could this be tweaked to achieve the desired instantiation style?
Comment: Whether you mention it or not, that's what `if (false) {}` means. It means "don't execute this block when the program runs". It doesn't mean "don't even look at the code within this block".
Comment: The condition is not reached. In fact, nothing is "reached"; execution doesn't even start because the code doesn't compile.
Comment: The program must be well-formed in order to compile - including parts of it that will not be executed at run time. You cannot write `if (false) { random garbage }` and expect the code to compile. One way to achieve what (I think) you are trying to achieve is via a traits class, with a uniform interface and a specialization for every container you want to support.
Comment: "Unreachable" is a runtime thing. Before code can run, it has to be compiled. In order to be compiled, it must (among other things) be syntactically valid and pass type checking. `if (false) { int x = "apples" * 1.5; }` is a type error, so it doesn't pass compilation. `if (false) { fjakslfkdjfaklsdfjkalskdjf(); }` uses an undeclared identifier, so it doesn't pass compilation.
Comment: I don't understand that comment. Wrong code doesn't suddenly compile just because you move it around.
Comment: You can't write `if (true){} else { random garbage }` either. Basically, you can't write `random garbage`, period. Whether that spot is reachable at run time or not is irrelevant. In fact, it's meaningless to even talk about "reachable at runtime" - there won't be any runtime when the code fails to compile in the first place. If you want to hide a piece of code from compilation, turn it into a comment, or surround with `#if 0' / `#endif`
Comment: @IgorTandetnik you can swap `if (false)` for `else` ... and still get the same error; when you clearly pass `vector`
Comment: @melpomene why then g++ is complaining about `.emplace_hint` when it's inside an "unreachable" condition?? I'd appreciate any insight.
Comment: also,from your comments, I may figure out a better title, but feel free to suggest a better more informative title or description of the problem.
Comment: @melpomene okay. But even if `if (flase)` is changed to `else` so that it compiles (I think) the same error message will appear in both g++ and clang++
Comment: @IgorTandetnik easy bro. I didn't mention the word runtime at all. The word appeared on CLion, and it stuck in my head.
Comment: @melpomene I get your point .. the code doesn't compile. I hope you both can see why I'm asking, the error message is not informative at all (at least to me) and a proper way to achieve my intended behaviour is greatly appreciated.
Comment: I don't understand the question. You never mentioned any intended behavior. Why can't you just use a `std::map`?
Comment: As I mentioned earlier, you probably want a traits class. See e.g. [here](https://erdani.com/publications/traits.html) and [here](http://www.gotw.ca/publications/mxc++-item-4.htm)
Comment: Why do you consider the error message as not helpful? It tells you that a certain class does not have a certain member which you are trying to access. Which is exactly the problem.
Answer: if (false) doesn't mean the code isn't compiled; it simply means the code inside is not executed at runtime, but it still has to be valid.
There are (at least) three kinds of conditional constructs in C++:

Preprocessor conditions.  This tells the preprocessor not to pass the code to the compiler if if the condition is not met.  Therefore, the code can be completely gibberish as long as it consists of valid preprocessor tokens.  For example, the following is a well-formed C++ program with defined behavior:
#include <iostream>

int main()
{
#if 0
    YYMJBNvOldLdK8rC0PTXH8DHJ58FQpP0MisPZECDuYHDJ7xL9G
#else
    std::cout << "Hello world!\n";
#endif
}

Runtime selection statements.  Such code is still parsed by the compiler and must still be valid code regardless of whether the compiler is capable of proving unreachable code — the compiler cannot even find the terminating } if it doesn't parse the code.  This is partly because compilers cannot evaluate arbitrary expressions at runtime — if you don't specify explicitly (see next bullet), then evaluation defaults to be runtime.  Therefore, the code above becomes ill-formed if you replace #if 0 – #else – #endif with if (false) { – } else { – }.  However, runtime errors (i.e., undefined behavior) within unreachable code are fine.  Therefore, the following is a well-formed C++ program with defined behavior: (some compilers may generate warnings, but that's irrelevant)
#include <iostream>
#include <climits>

int main()
{
    if (false) {
        volatile int x = 42/0;
        x = *static_cast<int*>(nullptr);
        const int y = INT_MAX + 1;
    } else {
        std::cout << "Hello world!\n";
    }
}

(Since C++17)  if constexpr.  The rule for this one is a bit complex.  The condition has to be known at compile time, and the false branch is discarded.  The discarded branch is still required to be valid, except that it is not instantiated.  Therefore, the code above is still valid code if you change if to if constexpr.  The following is also a well-formed C++ program with defined behavior:
#include <iostream>
#include <type_traits>

template <typename T>
void print(T x)
{
    if constexpr (std::is_same_v<T, int>) {
        std::cout << static_cast<typename T::template stack<T>::overflow>(x);
    } else {
        std::cout << x;
    }
}

int main()
{
    print("Hello world!\n");
}

The typename and template are still necessary to make the code syntactically valid, but the nonexistent type const char*::stack<const char*>::overflow is not formed.

In your case, you can write a trait class to determine whether a type is a specialization of the class template std::vector: (here I use the standard traits convention)
template <typename C>
struct is_std_vector :std::false_type {};
template <typename T, typename A>
struct is_std_vector<std::vector<T, A>> :std::true_type {};
template <typename C>
inline constexpr bool is_std_vector_v = is_std_vector<C>::value;

Then use it in if constexpr to dispatch: (don't forget to replace Container with the container type you are examining)
if constexpr (is_std_vector_v<Container>) {
    // do std::vector specific things
} else {
    // do other things
}

Comment: @7kemZmani I have updated to include an example of the trait class.
Comment: @7kemZmani In your case, it seems that you can remove the `if (is_vector) { /* ... */ }` part altogether.  Am I missing something?
Comment: the `load` method is trying to populate the container with data from the file, and tries to detect if the container `is_vector` for which it uses `emplace_back` .. and `emplace_hint` for others (I'm assuming stl containers only)

C++ if (false) condition evaluated?