Q:

D3: two x-axis with independent zoom behavior

I want to have two independent x-axis in my Time-Comparison chart (TimeScale) and have a problem to implement the zoom Behavior for both. I would like that d3 calculates the x-Domain for both axis independently - that would be perfect. But how can I bind (and call) two zoom Behavior for each axis to my one 'g'-Element (.d3-draw-area) ?
I have listener for both axis but only the "Master-Axis" is (logically) being computed:
d3.select(".d3-draw-area").call(d3.behavior.zoom()
            .on('zoom' + ".x" + self._getXAxisMaster().ID, function () { self._zoomX(self._getXAxisMaster()); })
            .on('zoom' + ".x" + self._getXAxisSlave().ID, function () { self._zoomX(self._getXAxisSlave()); })
            .x(self._getXAxisMaster().d3Axis.scale())
            );

thx...!

A:

I'm not able to make the master-slave independent scales work on a single domain (x). In the code above, you have specified masterScale on the domain (x), so only master scale gets triggered. Also I'm not able to understand the kind of data you are plotting, or what is the relation between master/slave scales. Check out below code and see if any of these work for you:
1) For 2 independent scales and 2 independent dimension (properties or attributes) in your data, you can convert y axis to a secondary x-axis.
DEMO
  var data = [];
  for (var i = 0; i < 500; i++) {
    data.push([Math.random(), Math.random()]);
  }
  d3.select('#chart')
  .append("svg").attr("width", window.innerWidth).attr("height",window.innerHeight)
  .datum(data).call(init());

  function init() {
    var svg, margin = {top: 60,bottom: 80,left: 60,right: 0}, width = 500, height = 400,
      xaxis1 = d3.svg.axis(), xaxis2 = d3.svg.axis(),
    scaleOne = d3.scale.linear(), scaleTwo = d3.scale.linear(), zoomable = true,
    zoom = d3.behavior.zoom().x(scaleOne).y(scaleTwo).on("zoom", zoomable ? draw : null);

    svg = d3.select('svg').data([data]);
    svg.enter().append('svg');
    var g = svg.append('g').attr("transform", "translate(" + margin.left + "," + margin.top + ")");

        g.append("defs").append("clipPath")
          .attr("id", "clip")
          .append("rect")
          .attr("width", width - margin.left - margin.right)
          .attr("height", height - margin.top - margin.bottom);

        g.append("svg:rect")
          .attr("class", "border")
          .attr("width", width - margin.left - margin.right)
          .attr("height", height - margin.top - margin.bottom)
          .style("stroke", "black")
          .style("fill", "none");

        g.append("g").attr("class", "axis One")
          .attr("transform", "translate(" + 0 + "," + (height - margin.top - margin.bottom) + ")");

        g.append("g").attr("class", "axis Two")
            .attr("transform", "translate(" + 0 + "," + (height - margin.top - margin.bottom + 60) + ")");

        g.append("g")
          .attr("class", "scatter")
          .attr("clip-path", "url(#clip)");

        g.append("svg:rect")
          .attr("class", "zoom box")
          .attr("width", width - margin.left - margin.right)
          .attr("height", height - margin.top - margin.bottom)
          .style("visibility", "hidden")
          .attr("pointer-events", "all")
          .call(zoom);

        scaleOne.domain(d3.extent(data, function(d) {
          return d[0];
        })).range([0, width - margin.left - margin.right]);

        xaxis1.scale(scaleOne).orient('bottom').tickPadding(10);
        svg.select('g.axis.One').call(xaxis1);

        scaleTwo.domain(d3.extent(data, function(d) {
          return d[1];
        })).range([0, width - margin.left - margin.right]);

        xaxis2.scale(scaleTwo).orient('bottom').tickPadding(10);
        svg.select('g.axis.Two').call(xaxis2);
        draw();

    function update() {
      var gs = svg.select("g.scatter");

      var circle = gs.selectAll("circle")
        .data(function(d) {
          return d;
        });

      circle.enter().append("svg:circle")
        .attr("class", "points")
        .style("fill", "steelblue")
        .attr("cx", function(d) {
          return X1(d);
        }).attr("cy", function(d) {
          return X2(d);
        }).attr("r", 4);

      circle.attr("cx", function(d) {
        return X1(d);
      }).attr("cy", function(d) {
          return X2(d);
        });

      circle.exit().remove();
    }

    function zoom_update() {
      zoom = d3.behavior.zoom()
        .x(scaleOne)
        .y(scaleTwo)
        .on("zoom", zoomable ? draw : null);
      svg.select('rect.zoom.box').call(zoom);
    }

    function draw() {
      svg.select('g.axis.One').call(xaxis1);
      svg.select('g.axis.Two').call(xaxis2);
      update();
      zoom_update();
    };
    function X1(d) {
      return scaleOne(d[0]);
    }
    function X2(d) {
      return scaleTwo(d[1]);
    }
    return chart;
  }

2) Incase you have connected/dependent scales, you can apply same scale on 2 axis and generate the offset correction (even a logarithmic correction) and have dual axis on same domain. This one keeps your y domain/axis available to plot another dimension in your data.
DEMO
  var data = [];
  for (var i = 0; i < 500; i++) {
    data.push([Math.random(), Math.random()]);
  }
  d3.select('#chart')
  .append("svg").attr("width", window.innerWidth).attr("height",window.innerHeight)
  .datum(data).call(init());

  function init() {
    var svg, margin = {top: 60,bottom: 80,left: 60,right: 0}, width = 500, height = 400,
      xaxis1 = d3.svg.axis(), xaxis2 = d3.svg.axis(),
    scaleOne = d3.scale.linear(), scaleTwo = d3.scale.linear(), zoomable = true,
    zoom = d3.behavior.zoom().x(scaleOne).on("zoom", draw)

    svg = d3.select('svg').data([data]);
    svg.enter().append('svg');
    var g = svg.append('g').attr("transform", "translate(" + margin.left + "," + margin.top + ")");

        g.append("defs").append("clipPath")
      .attr("id", "clip")
      .append("rect")
      .attr("width", width - margin.left - margin.right)
      .attr("height", height - margin.top - margin.bottom);

    g.append("svg:rect")
      .attr("class", "border")
      .attr("width", width - margin.left - margin.right)
      .attr("height", height - margin.top - margin.bottom)
      .style("stroke", "black")
      .style("fill", "none");

    g.append("g").attr("class", "axis One")
      .attr("transform", "translate(" + 0 + "," + (height - margin.top - margin.bottom) + ")");

    g.append("g").attr("class", "axis Two")
      .attr("transform", "translate(" + 0 + "," + (height - margin.top - margin.bottom + 60) + ")");

    g.append("g")
      .attr("class", "scatter")
      .attr("clip-path", "url(#clip)");

    g.append("svg:rect")
      .attr("class", "zoom box")
      .attr("width", width - margin.left - margin.right)
      .attr("height", height - margin.top - margin.bottom)
      .style("visibility", "hidden")
      .attr("pointer-events", "all")
      .call(zoom);

    scaleOne.domain(d3.extent(data, function(d) {
      return d[0];
    })).range([0, width - margin.left - margin.right]);

    xaxis1.scale(scaleOne).orient('bottom').tickPadding(10);
    svg.select('g.axis.One').call(xaxis1);

    scaleTwo.domain(d3.extent(data, function(d) {
      return d[1];
    })).range([0, width - margin.left - margin.right]);

    xaxis2.scale(scaleOne)
                .orient('bottom').tickPadding(10)
                .tickFormat(function(d) { return d + 5.5; })
    svg.select('g.axis.Two').call(xaxis2);
    draw();

    function update() {
      var gs = svg.select("g.scatter");
      var circle = gs.selectAll("circle")
        .data(function(d) { return d; });

      circle.enter().append("svg:circle")
        .attr("class", "points")
        .style("fill", "gray")
        .attr("cx", function(d) { return X1(d); })
        .attr("cy", function(d) { return X2(d); })
        .attr("r", 4);

      circle.attr("cx", function(d) { return X1(d); })
              .attr("cy", function(d) { return X2(d); });

      circle.exit().remove();
    }

    function zoom_update() {
      zoom = d3.behavior.zoom()
               .x(scaleOne)
               .on("zoom", draw)
      svg.select('rect.zoom.box').call(zoom);
    }

    function draw() {
        svg.select('g.axis.One').call(xaxis1);
      svg.select('g.axis.Two').call(xaxis2);
      update();
      zoom_update();
    };

    function X1(d) {
      return scaleOne(d[0]);
    }
    function X2(d) {
      return scaleTwo(d[1]);
    }
    return chart;
  }

I took the base code from D3 examples: http://bl.ocks.org/jgbos/9752277


Q:

How do I access an unhandled exception in an MVC Error view?

When the HandleError attribute on a controller detects an unhandled exception and redirects to the Error view, I would like to provide the user with a brief description of the error, and an option to email the error to the application administrator.
I do have a custom HandleError that notifies Elmah to log the error, but having to look up the error in the Elmah log seems a bit of a last resort.  Is there any other way to access the unhandled exception that is 'caught' by HandleError?

A:

HandleErrorAttribute supplies a Model object of type HandleErrorInfo
Your Error page could look like this
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<HandleErrorInfo>" %>

The Model has an Exception property with the details of the exception handled.
I usually use a custom error handler that also logs the exception using log4net and I have an STMP appender that emails me whenever an exception is handled by the filter.


Q:

scrollViewDidEndDecelerating not executing

I can't seem to get scrollViewDidEndDecelerating called.
I have a scrollView with 2 Views inside. Now I need it to set a value to a label in the first view when the scrollview is finished scrolling to the second view.
Header File:
@interface ViewController: UIViewController
{
   UIScrollView *scrollView;
   UIView *view1;
   UIView *view2;
}

@property (strong, nonatomic) IBOutlet UIScrollView *scrollView;
@property (strong, nonatomic) IBOutlet UIView *view1;
@property (strong, nonatomic) IBOutlet UIView *view2;
@property (weak, nonatomic) IBOutlet UILabel *lbl;

Implementation File:
@synthesize scrollView, view1, view2;

-(void)viewDidLoad
{
   self.view1=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
   self.view2=[[UIView alloc] initWithFrame:CGRectMake(320, 0, 320, 480)];

   [self.scrollView addSubView:self.view1];
   [self.scrollView addSubView:self.view2];

   self.scrollView.bounces=NO;
   self.scrollView.contentSize=CGSizeMake(640,460);
   [self.scrollView setShowHorizontalScrollIndicator:NO];
   [self.scrollView scrollRectToVisible:CGRectMake(0, 0, 320, 416) animated:NO];
}

-(void)scrollViewDidEndDecelerating:(UIView *)scrollView
{
   lbl.text=@"0";
}

I don't see anything wrong, it should be working. Can someone help me out? Would appreciate it.

A:

scrollViewDidEndDecelerating is not called if the user is scrolling slowly (i.e. the scroll view does not continue to scroll on touch up). In that case the delegate calls scrollViewDidEndDragging. So to do something when the user has stopped scrolling and the scrollview has stopped you can combine them:
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
   if(!decelerate) [self endOfScroll];
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
  [self endOfScroll];
}

-(void)endOfScroll{
  //Do something
}

And in Swift
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  if !decelerate {
     endOfScroll()
  }
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  endOfScroll()
}

func endOfScroll() {
  //Do something
}

A:

Either connect the delegate property of the scrollview to the File's Owner object in Interface Builder or just set the delegate manually in your ViewController's ViewDidLoad.
scrollview.delegate = self

A:

This would do:
Header File:
@interface ViewController: UIViewController <UIScrollViewDelegate> //promise that you'll act as scrollView's delegate
{
   UIScrollView *scrollView;
   UIView *view1;
   UIView *view2;
}

@property (strong, nonatomic) IBOutlet UIScrollView *scrollView;
@property (strong, nonatomic) IBOutlet UIView *view1;
@property (strong, nonatomic) IBOutlet UIView *view2;
@property (weak, nonatomic) IBOutlet UILabel *lbl;

Implementation File:
@synthesize scrollView, view1, view2;

-(void)viewDidLoad
{
   self.view1=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
   self.view2=[[UIView alloc] initWithFrame:CGRectMake(320, 0, 320, 480)];

   [self.scrollView addSubView:self.view1];
   [self.scrollView addSubView:self.view2];

   self.scrollView.bounces=NO;
   self.scrollView.contentSize=CGSizeMake(640,460);
   [self.scrollView setShowHorizontalScrollIndicator:NO];
   [self.scrollView scrollRectToVisible:CGRectMake(0, 0, 320, 416) animated:NO];
   [self.scrollView setDelegate:self];//Set delegate
}

-(void)scrollViewDidEndDecelerating:(UIView *)scrollView
{
   lbl.text=@"0";
}


Q:

.htaccess RewriteRule for multiple parameters added in javascript as non slash

This question might be a duplicate. But I did not find any solution for my problem. I try to add RewriteRule to htaccess file that will be combine slashed static parameters with non slashed parameters added in javascript by window.history.replaceState( {} , '', ''); for choosed filters.
I got two static parameters named as 'p' and 'a'. For that i write rule:
RewriteRule ^/?([0-9a-zA-Z\_\-]*)/([0-9a-zA-Z\_\-]*)$ index.php?p=$1&a=$2 [NC,L].
But i need to add non slashed parameters for friendly url, that gonna be create only in js and used for back action in history. I would like to that url looks like:
www.page.com/category/pen.html?colour=green
and that should be as non friendly:
www.page.com/index.php?p=category&a=pen&colour=green
and that parameters after parameter 'a' could be many, but should be after .html extension.
I don't found any solution so far for that problem. Thanks for any help.
EDIT
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^(www\.)?example.com [NC]
RewriteRule ^admin/?$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([A-Za-z0-9\-]+)(/([A-Za-z0-9\-\,]+))?$ /index.php?p=$1&a=$3 [L,NC,QSA]

That works!

A:

You can use the QSA flag in your rule, to get any already existing query string of the original rule merged with the one you are creating yourself.
https://httpd.apache.org/docs/2.4/rewrite/flags.html#flag_qsa:

When the replacement URI contains a query string, the default behavior of RewriteRule is to discard the existing query string, and replace it with the newly generated one. Using the [QSA] flag causes the query strings to be combined.


Q:

Magento product page variables

I'm running Magento CE 1.9 and I have a piece of code that displays the sku on the product page:
template > catalog > product > view.phtml
the php code is:
     < ?php echo $this->getProduct()->getSku() ?>
which works perfectly, but if I try to add the sku somewhere else in the page... such as for a piece of code for PowerReviews where it needs the SKU to be dynamically inserted for tracking... if I add the same php code to get the sku, it breaks the page right there. I am not sure why I can display the sku in the view.phtml, but not in a product page tab for example...
in this example, I need it in a custom tab I made... so it would be: frontend/rwd/default/template/so/reviews.phtml

A:

I think your issue is understanding how Magento blocks are defined. Templates, like app/design/frontend/[DESIGN PACKAGE]/[THEME]/template/catalog/product/view.phtml, have a corresponding PHP block definition. This specific template, for example, has its block defined in app/code/core/Mage/Catalog/Block/Product/View.php--and you should even see that this is commented at the top of the core template file for the product view block:
/**
 * Product view template
 *
 * @see Mage_Catalog_Block_Product_View
 * @see Mage_Review_Block_Product_View
 */

Inside the block definition, you should find a method called getProduct which is why you can access that method from the view.phtml block. The $this variable refers to an instance of the block definition object, so an instance of Mage_Catalog_Block_Product_View, in other words. If the other block definitions (including those from third-party libraries) where you wish to access the product do not define a method like getProduct (or inherit from a block definition that does), then you will not be able to call that method and return a product. What you can do, is define a similar method on the block definition for whatever block you want to use to access product data. As an example, you could copy the getProduct method definition from the core product view block definition into the block definition for the block from your PowerReviews extension.
This resource should give you a decent overview and hopefully a better understanding of the concept:
http://www.magentocommerce.com/knowledge-base/entry/magento-for-dev-part-4-magento-layouts-blocks-and-templates
UPDATE: Here's a bit more direction and some elaboration on my reply in the comments. One way to tackle this is to use an existing block definition for your block in the layout definition, like so:

You could choose to use an existing block definition for your template file, or you could create your own (and possibly inherit that class)
<block type="catalog/product_view" name="my.product.block" template="path/to/custom/template.pthml" />

Notice I'm using the Magento core catalog/product_view block type which corresponds to the PHP file I mentioned previously that defines the block and its getProduct method.
Or if you need some kind of custom functionality in your block but you want to rely on the base functionality of an existing block, define your own block and extend an existing one that has the desired functionality:
class MyPackage_MyExtension_Block_Product_View extends Mage_Catalog_Block_Product_View {
    // add your custom methods
}

Here I'm extending the existing Magento core block definition that has the method you want. Then use your custom block definition in the layout definition:
<block type="mypackage_myextension/product_view" name="my.product.block" template="path/to/custom/template.pthml" />

Hopefully that helps clear it up a bit more.


Q:

open a dropdown-menu toggle on hover - knockout

I am trying to add and close the dropdown on hover using knockout and jquery.
FIDDLE HERE
Here is the simple HTML

    <button type="button" class="btn btn-default dropdown-toggle"
            data-toggle="dropdown" data-bind="event: { mouseover: enableDetails, mouseout: disableDetails }">
        Lists
    </button>

            Sub List 1

            Sub List 2

A:

Ideally $(".dropdown-toggle").dropdown(); should work when placed within the enableDetails method in your fiddle. But this $(".dropdown-toggle").dropdown('toggle'); seems to work. Here is the updated fiddle.
The dropdown function is from the bootstrap documentation.


Q:

Regex to match a string with 2 capital letters only

I want to write a regex which will match a string only if the string consists of two capital letters.
I tried - [A-Z]{2}, [A-Z]{2, 2} and [A-Z][A-Z] but these only match the string 'CAS' while I am looking to match only if the string is two capital letters like 'CA'.

A:

You could use anchors:
^[A-Z]{2}$

^ matches the beginning of the string, while $ matches its end.

Note in your attempts, you used [A-Z]{2, 2} which should actually be [A-Z]{2,2} (without space) to mean the same thing as the others.

A:

You need to add word boundaries,
\b[A-Z]{2}\b

DEMO
Explanation:

\b Matches between a word character and a non-word character.
[A-Z]{2} Matches exactly two capital letters.
\b Matches between a word character and a non-word character.


Q:

How to fix "SSL error: certificate verify failed"

I started a bash code that tries to download a file via axel, but when the script is about to download the file, it crashes and the error SSL error: certificate verify failed.
Can someone please help me with that, like adding an exception via command-line?
Part of the code:
axel ${EXTRAARGS} --alternate "https://build.nethunter.com/kalifs/kalifs-20171013/kalifs-armhf-minimal.tar.xz "

Other variables were already declared.
The result is:
Initializing download: https://build.nethunter.com/kalifs/kalifs-20171013/kalifs-armhf-minimal.tar.xz<br>
SSL error: certificate verify failed

Thanks anyway.

A:

Did you try man axel? From the man page:
   --insecure, -k
          Do not verify the SSL certificate. Only use this if
          you are getting certificate errors and you are sure
          of the sites authenticity.


Q:

How to show Calendar instead of using UIDatePicker in iPhone?

I am using UIDatePicker controller to choose the date in iPhone app. Now, i want to show the Calendar View instead of UIDatePicker Controller. I have searched my level best in google. But, i can't find the exact solution for my problem. Can anyone please help to use the Calendar view for UIDatePicker? Thanks in advance.

A:

Your best bet is to use one of the following -
1) https://github.com/guicocoa/calendar
2) http://github.com/devinross/tapkulibrary
3) http://github.com/klazuka/Kal
There is no ready made solution which will convert UIDatePicker to calender view


Q:

Initializers may only be declared within a type

import UIKit

func Question() {
    var questiontext : String
    var answer : Bool

    init(text: String , correctanswer: Bool ){ //error in this point : Initializers may only be declared within a type
        questiontext = text
        answer = correctanswer
    }
}

How can I solve this problem?

A:

An init  should be inside class / struct type not func
class Question {
    var questiontext : String
    var answer : Bool
    init(text: String , correctanswer: Bool ){
        questiontext = text
        answer = correctanswer
    }
}


Q:

Why the view "I am the owner of my karma" not contradict anatta?

Why did the Buddha advise lay people and monks to think, "I am the owner of my kamma, the heir of my kamma; I have kamma as my origin, kamma as my relative, kamma as my resort; I will be the heir of whatever kamma, good or bad, that I do" when this seems to contradict anatta?
Isn't thinking "I am X" contradicting the teaching of anatta?
There are suttas where the Buddha advised not to associate the five aggregates with the self e.g. SN 22.93. Aren't these two teachings contradictory? Isn't "owner of kamma, heir of kamma" a mental fabrication (sankhara) that we shouldn't associate our self with?
Why didn't the Buddha advise lay people and monks to think, "there's no self in this body and mind doing anything"? What's the consequence of this view?
From AN 5.57:

“And for the sake of what benefit should a woman or a man, a
  householder or one gone forth, often reflect thus: ‘I am the owner of
  my kamma, the heir of my kamma; I have kamma as my origin, kamma as my
  relative, kamma as my resort; I will be the heir of whatever kamma,
  good or bad, that I do’? People engage in misconduct by body, speech,
  and mind. But when one often reflects upon this theme, such misconduct
  is either completely abandoned or diminished.

A:

This is how you practice equanimity (upekkha). It's the one of the four divine abodes. Just like in Metta(loving-kindness) meditation where you say "may I/my parents/relatives/friends be happy, well, free from suffering etc.", Upekkha meditation is also practiced at a conceptual level.
The purpose of Upekkha meditation is to cultivate equanimity in the mind. It does not lead to realization of Anatta nor enlightenment unless you turn it into Vipassana at some point.
Anatta is at the level of ultimate reality. That is for advanced practitioners of Buddhism. Trying to teach Anatta to everyone regardless of their mental maturity will not be productive as many will endup being more confused than they already are. That's why there are teachings in Buddhism that help you develop the mind at a conceptual level where you are familiar and comfortable. It is important not to mix up these teachings with the teachings of ultimate reality.


Q:

Partial rule over footer page numbers

I am using KOMA's scrreprt together with fancyhdr and want my page numbers on the outside of each page. So I use:
\fancyfoot[LE,RO]{\thepage}

which works as expected. Now, how do I add a short horizontal line (rule) above the page number? The rule should cover about one third of the page width.

A:

I would suggest to use package scrlayer-scrpage which is part of the KOMA-Script bundle. Then you can enable the footsepline and adjust its layer:
\documentclass[
  twoside
]{scrreprt}
\usepackage{blindtext}% only for dummy text

\usepackage{scrlayer-scrpage}% sets pagestyle scrheadings automatically
\clearpairofpagestyles
\ofoot*{\pagemark}

\KOMAoptions{
  footsepline=1pt:.3333\paperwidth,% syntax: footsepline=<thickness>:<length>
  plainfootsepline,
  olines
}
\ModifyLayer[
  hoffset=0pt,
  width=\paperwidth,
  addvoffset=-5pt% move the line up
]{scrheadings.foot.above.line}
\RedeclareLayer[
  clone=scrheadings.foot.above.line
]{plain.scrheadings.foot.above.line}

\usepackage{xcolor}
\addtokomafont{footsepline}{\color{red!50!black}}

\begin{document}
\blinddocument
\end{document}


Q:

How does a fuel tank fire self-extinguish in an A380?

On Qantas Flight 32 there was...

...an undetected fire in the left inner wing fuel tank that eventually
  self-extinguished

How does a fire in a nearly full fuel tank self-extinguish?

A:

The Australian Transportation Safety Board's Final Report gives a couple of possible reasons that the reaction was not sustained in Appendix D on page 257:

The flash fire initially consumed the oxygen inside the tank; reducing the oxygen concentration level to below the threshold required for sustained combustion of Jet A-1.
The general temperature rise associated with the initial combustion was low and insufficient to increase the temperature of the fuel inside the tank to at least the lower flammability limit of Jet A-1. Quenching of the flame by the cool fuel tank walls (evident from the sooting) and the entry of cooling air through the tank perforations may have promoted this.

Note that Jet-A requires quite a bit of activation energy to vaporize and burn. If the burning of what fuel did burn didn't produce enough energy to provide activation energy for the surrounding fuel, the fire would not be sustained. The fire was likely very brief as the turbine disc fragment passed through the tank.
From what I've heard (I haven't tried this myself,) you can drop a lit match in a bucket of Jet-A and it won't ignite. Using fuel that doesn't easily burst into flames in a vehicle designed to carry tens of thousands of gallons of fuel at several hundred miles per hour is desirable and intentional for obvious reasons.
To illustrate just how hard it is to burn Jet-A, the fuel tanks in Asiana 214 never ignited. The entire fuselage was burned out, but the fuel tanks never burned.

Remnants of Asiana 214's hull Source: Wikipedia


Q:

Get Matching Xpath Count Keyword does not return all matching Xpaths

I am trying to store a list of all radiobuttons within the page I am working on. The Radio Button amount will change depending on what pagination number I am on.
Right now I am using the code below to find all matching Xpaths and store it within a variable.
*** Keywords ***
Count How Many RadioButtons On Page
    ${Count}    Get Matching Xpath Count    //tr
    ${CountList}    Create List
    : FOR    ${INDEX}    IN RANGE    1    ${Count}
    \    Append To List    ${CountList}    xpath=//tr[${INDEX}]
    log    ${CountList}
    Set Global Variable    ${CountList}

This only stores 11 entries. When the page actually contains 20. For some reason it is missing the other 9 and I cannot figure out why.
At the end, the CountList variable looks like this:
u'xpath=//tr[1]', u'xpath=//tr[2]', u'xpath=//tr[3]', u'xpath=//tr[4]', u'xpath=//tr[5]', u'xpath=//tr[6]', u'xpath=//tr[7]', u'xpath=//tr[8]', u'xpath=//tr[9]', u'xpath=//tr[10]', u'xpath=//tr[11]'

This list should go all the way up to //tr[20]
I can also confirm that using (for example) //tr[12] or onwards, will work correctly. It is just that Get Matching Xpath Count is not pulling all 20 of them for some reason.
Can anyone shine light onto this?
EDIT:
Below is part of the HTML of the page I am trying to count:

 P-DAC-15-790

DATA

..DATA

15

i9

DATA

26-06-2015 14:50

EDIT2:
Ive updated the Get Matching Xpath Count to //div[4]/table/tbody/tr to be a little more specific, and it still only counts 11, not 20
EDIT3:
If I perform the same test on the 2nd page, it works completely fine (returns 20, and loops through 20 rows) But there is no difference between page 1 and 2...

A:

Turns out, RF didn't really understand what was going on within the page. So what I did was as I arrive to the page (via the nav bar) to then refresh the current page. It then saw all 20 entries and continued through the for loop as expected.
I don't know if this is a bug within RF for Selenium2Library, But I shouldn't have needed to basically re-initialise the web page when trying to complete logic tasks.
If someone else runs into a similar issue like this - comment below and ill try to assist you :)


Q:

Unequal Cost Load Balancing via MPLS TE

Given the following network, with all sites' network routing tables built via OSPF:
   Site_A
      |
Site_A_router
  |           \
  |      Intermediate_site_C_router -- Other_sites
  |                       |
  |      Intermediate_site_D_router
  |                       |
Site_B_router_1     Site_B_router_2
             \       /
            Site_B_LAN
                 |
              Site_B
                 |
          Site_B_router_3
                 |
             Internet

Currently, there is no link between Site A and Site C. I'm looking at adding that in place and seting up unequal cost load balancing between Site A and Site B to provide some redundancy as well as get more effective bandwidth between Site A and hosts on the Internet and at Site B. From a significant amount of Googling, it appears I want to set up MPLS TE tunnels between the Site A router and one of the Site B routers to direct all traffic between the two sites over one of the two routes.
I'm stuck at trying to wrap my head around how the MPLS tunnels will fit into the scheme of the routed network. From my reading, MPLS TE layers on top of the OSPF derived routes and simply defines paths to take between two routers.
Do I need to advertise their existence at all via OSPF? I wouldn't think so, as I suspect that'd just end up routing all traffic from anywhere on the network destined to Site A through Site B then back across one of the two paths to Site A.
Alternately, would I just set the tunnels up on a Site B router but not advertise their existence and just allow them to sort any trafifc that arrives into one of the two tunnels paths? If this works in this manner, I'd expect hosts in site D, site C, and the other sites connected via site C to just route the traffic over the shortest OSPF route, ignoring the tunnels.
Complicating this is that many of the hosts in Site B build their routing tables via OSPF and thus there is no single gateway router that the hosts use to determine the next hop. Which of the three routers should I be setting the Site B -> Site A direction of the MPLS TE tunnel up on in order to get the appropriate load balancing?
If I set it up on router 3, I suspect only Internet-sourced traffic would be load balanced, as hosts in site B are going to be sending site A-destined packets through to either router 1 or 2 directly. Alternately, I could set it up on router 1, as that's almost certain to be the OSPF shortest route. However, then traffic is going to be routed from router 1 through to router 2 somewhat needlessly as traffic takes the alternate tunnel. I suspect this is overthinking things somewhat and is propably premature optimization.
Given this situation, what's the best practice way for doing what I'm trying to do?

A:

Yes, you can create MPLS tunnels between the routers to make OSPF load balance between them (the tunnels) as OSPF does not support UCLB itself.
You do need to add a few mpls commands to your ospf config. See here
You ought to be able to create two tunnels between the site A router and the "main" router at site B (probably router 1) One tunnel would be between A-1 and B-1 directly and the other - through router B-2. Routers A-1 and B-1 will perform the load balancing of traffic
In this scenario, the hosts would need to be configured to use router B-1 as their default gateway in site B.
*Edited for correct router names.


Q:

protractor - issues with scrolling into infinite scroller

I have a protractor test looking for a record in my infinite scroller component like this.
 searchPage.searchEntitlement('search criteria');
    var myHiddenElementInScroller = element(by.repeater('result in ctrl.results track by $index').row(12));
    browser.driver.executeScript(function () { arguments[0].scrollIntoView(); }, myHiddenElementInScroller .getWebElement());

myHiddenElementInScroller.click();

This is supposed to scroll to the element and click it. Instead its throwing me element not visible error.
Has anyone come across this situation? Any help greatly appreciated.

A:

Thanks for all the responses. I was able to resolve this issue by using element(by.CssContainingText(cssSelector, searchText)) locator.


Q:

AS3 object rotation issues

I'll ask a more simple question. Let's say no matter how but I have calculated the rotation of a line between an object center and a mouse (angle). Starting at North aka 0, going a CW circle to 359 near North. I ask AS3 to "object.rotation = angle;" every frame . I have 2 text areas that show the values "angle" and "object.rotation". After 180 object.rotation becomes -180 and goes backwards to 0. Why so?
Even more simple. I get value A, then say A = B. Then ask computer to show A and show B. At 180 to 360, B=B-360.
Rotation is satisfactory, but the numbers are wrong. Need explanation why numbers misfit. Need an advice on how to make object rotation range 0-360 and be directly determined by a number I input. "angle" in my case.
Meaning if I input rotation 2892 it should be it(yes,8*360+12), not 12, not -348... even though these represent the same rotation visually.

A:

It looks like you're stuck with it.  From the documentation:

Values from 0 to 180 represent clockwise rotation; values from 0 to
  -180 represent counterclockwise rotation. Values outside this range are added to or subtracted from 360 to obtain a value within the
  range. For example, the statement my_video.rotation = 450 is the same
  as my_video.rotation = 90.

If you want to store 2892 instead of 12, you'll have to track it manually.
When you enter something nonstandard, they standardize it for you.  I would assume this is to make it easier on people using the designer, though maybe some graphical optimization relies on it as well.

A:

I expect this is the result of Flash's overflow protection. Imagine a movie clip that's turning for an hour, each frame its rotation gets increased by 50. Without such clipping, its rotation value will end up in millions, which will cause loss of precision and performance (in some cases) if one would take a sinus of 10000000*PI/180. So, in order to prevent undesired or different behavior, the devs of Flash player made it so that the actual rotation is returned in interval -180...180.
You might attempt to override rotation setter/getter functions, in order to preserve the passed result as is.
class RotationTest extends Sprite {
    private var myRotation:Number;
    public override function set rotation(value:Number):void {
        super.rotation=value;
        myRotation=value;
    }
    public override function get rotation():Number { return myRotation; }
}


Q:

How do you run gulp if gulp is installed(node_modules) in different folder than gulpfile.js

I have gulpfile.js in one directory and node_modules in another.
When I run gulp, i get the error -
'Local gulp not found in '..(the directory)..
Try running: npm install gulp'
The thing is - I cannot install gulp in the directory of gulpfile.js and so I need a way to tell the gulp to refere to the other directory i have gulp installed in.

A:

You don't need to install gulp globally if you don't want to. What you can do is run your gulp executable (from your node_modules) and then pass in the location of your gulpfile using the --gulpfile parameter. Also, if you want to control where your gulp is running, make use of the --cwd parameter.
Here's an example:
 <NODE_MODULES DIR>/gulp/bin/gulp.js --gulpfile <GULP FILE> --cwd <SOME DIR>

A:

There is no need to install gulp globally.
First install gulp (ideally on dev dependencies)
npm install gulp --save-dev
Then in the package.json add the line you want to run
"scripts" : {
    "gulp" : "gulp"}
}

Finally in the command line use
npm run gulp
npm will use the binary from the node modules without any need to install it globally or to write down the whole path


Q:

Constructive proof of decidability of finite Halting-problem-style set that does not use table lookup

I tried to prove that the following language is recursive: for $\Sigma=\{0,1\}$, $k$ a positive integer:
$$
L_k= H_{\mathrm{TM},\varepsilon}\cap \Sigma^k
$$
where $H_{\mathrm{TM},\varepsilon}=\{\langle M\rangle\mid M \text{ is a TM that halts on an empty input}\}$
It is easy to prove because $L_k$ is finite, but I didn't notice this and tried to prove it by finding a decider TM for it.
I thought that since the encoding of the TM is of length $k$ then it can't have more than $2^k$ states, and by running it on epsilon for $2^k$ steps, if it halts by then than accept otherwise reject.
I was told that it's incorrect - is it a wrong solution. How can I prove this using this method (and not the way I mentioned about $L_k$ being finite)?

A:

There is no general way to find a decider TM for $L_k$
You are correct that $L_k$ is recursive because, being a subset of the
finite set $\Sigma^k$, it is also finite.
You would like to rather find a decider TM for $L_k$, and you suggest
some techniques. Without even going into the details of these
techniques and why they do not work, you do not stand any chance of
ever succeeding.
The first thing you should notice is that the finiteness argument
tells you that there exists a decider TM $M_k$ for the language $L_k$,
but it does not tell you what this TM is. It is an example of a
non-constructive proof: you prove that a decider exists, but you
cannot tell which it is.
Now, suppose that, given $k$, you have a procedure $\mathcal P(k)$ to
find such a decider $M_k$ for the language $L_k$ (rather than just
prove it exist). Then, given any Turing machine $M$, then there is an
integer $k'$ such that $|\langle M\rangle|=k'$, so that $\langle
M\rangle\in \Sigma^{k'}$. Then you can use the procedure $\mathcal P$
to find a decider TM $M_{k'}$ that can determine whether $\langle
M\rangle\in L_{k'}$. So you have a way to decide whether the TM $M$
halts on empty input. And this works for any TM $M$. However, this is
not possible, because it is undecidable whether a given TM $M$ halts
on empty input.
So the procedure $\mathcal P$ cannot exist.
Since you are looking for a general way to find the decider TM
$M_{k'}$, you cannot succeed because that method would be precisely a
procedure such as $\mathcal P$.
Note that this proof could still leave the (very remote) possibility
of finding a decider for some specific values of $k$, but you would
have to identify precisely the concerned values, and the method would
not work for all values of $k$. I am not advising you to try.

A:

You can "fix" your proof using the busy beaver function. Let $B_k$ be the maximal number of steps that a Turing machine of description size at most $k$ performs before halting, when given the empty input. If you know $B_k$ (or even just an upper bound on $B_k$, that is, some $T_k \geq B_k$) then you can solve the halting problems for Turing machines of description size $k$ (and the empty input) by running the given machine for up to $B_k$ (or $T_k$) steps. If it doesn't halt by that point, then you know that it never halts.
Since the halting problem isn't decidable, we know that the function $B_k$ cannot be computable. Indeed, no computable function $T_k$ satisfies $T_k \geq B_k$ for all $k$. In other words, for any computable function $f(k)$, it is the case that $B_k > f(k)$ for infinitely many $k$. Roughly speaking, $B_k$ grows faster than every computable function.
In fact, using diagonalization one can show that $B_k$ does grow faster than every computable function: for every computable $f(k)$ there exists $K$ such that $B_k > f(k)$ for all $k \geq K$. This was first proved by Rado.

A:

The core fallacy is that you assume that the number of states a TM has limits its runtime (before termination) in some way. This is false.
Case in point, there are universal Turing machines, that is finitely described TMs that can exhibit any behaviour, from terminating quickly over running arbitrarily long to looping, given the right input.
On a technical note, universal TMs are usually described as taking two parameters, one TM encoding and the input to simulate it on. It is easy to merge them into one parameter, so there are indeed unary universal TMs.
More specifically, you ignore the input of the encoded TM, which can be arbitrarily large (and convoluted). The actual state of a TM is the product of control state and tape content, so a simple combinatorial argument based on the number of control states alone is not sufficient. In particular, a TM is not in an unescapable loop when it visits some state for the second time.


Q:

how to print cross mark (✕) or check mark ✓ in TCL

I would like to print either crossmark (✕) or right (check) symbol (✓) in TCL either using echo or puts.
Is there anyway to do it?

A:

Use their unicode escape sequences:
puts \u2713 ;# check mark

puts \u2717 ;# cross mark

There are several different cross marks you can use:
✗ = \u2717  BALLOT X
✘ = \u2718  HEAVY BALLOT X
❌ = \u274c CROSS MARK
× = \u00D7  MULTIPLICATION SIGN
╳ = \u2573  BOX DRAWINGS LIGHT DIAGONAL CROSS
☓ = \u2613  SALTIRE (St. Andrew's Cross)
✕ = \u2715  MULTIPLICATION X
✖ = \u2716  HEAVY MULTIPLICATION X
⨉ = \u2A09  N-ARY TIMES OPERATOR

There are also several alternatives for check marks:
✓ = \u2713  CHECK MARK
✔ = \u2714  HEAVY CHECK MARK


Q:

Lynx is stopping loop?

I'll just apologize beforehand; this is my first ever post, so I'm sorry if I'm not specific enough, if the question has already been answered and I just didn't look hard enough, and if I use incorrect formatting of some kind.
That said, here is my issue:  In bash, I am trying to create a script that will read a file that lists several dozen URL's.  Once it reads each line, I need it to run a set of actions on that, the first being to use lynx to navigate to the website.  However, in practice, it will run once perfectly on the first line.  Lynx goes, the download works, and then the subsequent renaming and organizing of that file go through as well.  But then it skips all the other lines and acts like it has finished the whole file.
I have tested to see if it was lynx causing the issue by eliminating all the other parts of the code, and then by just eliminating lynx.  It works without Lynx, but, of course, I need lynx for the rest of the output to be of any use to me.  Let me just post the code:
!#/bin/bash

while read line; do
echo $line
  lynx -accept_all_cookies  $line
echo "lynx done"
  od -N 2 -h *.zip | grep "4b50"
echo "od done, if 1 starting..."
    if [[ $? -eq 0 ]]
    then ls *.*>>logs/zips.log
    else
    od -N 2 -h *.exe | grep "5a4d"
echo "if 2 starting..."
      if [[ $? -eq 0 ]]
      then ls *.*>>logs/exes.log
      else
      od -N 2 -h *.exe | grep "5a4d, 4b50"
echo "if 3 starting..."
        if [[ $? -eq 1 ]]
        then
        ls *.*>>logs/failed.log
        fi
echo "if 3 done"
      fi
echo "if 2 done"
    fi
echo "if 1 done..."
  FILE=`(ls -tr *.* | head -1)`
  NOW=$(date +"%m_%d_%Y")
echo "vars set"
  mv $FILE "criticalfreepri/${FILE%%.*}(ZCH,$NOW).${FILE#*.}" -u
echo "file moved"
  rm *.zip *.exe
echo "file removed"
done < "lynx"

$SHELL

Just to be sure, I do have a file called "lynx" that contains the urls separated by a return each.  Also, I used all those "echo"s to do my own sort of debugging, but I have tried it with and without the echo's.  When I execute the script, the echo's all show up...
Any help is appreciated, and thank you all so much!  Hope I didn't break any rules on this post!
PS:  I'm on Linux Mint running things through the "terminal" program. I'm scripting with bash in Gedit, if any of that info is relevant.  Thanks!
EDIT:  Actually, the echo tests repeat for all three lines.  So it would appear that lynx simply can't start again in the same loop?
Here is a simplified version of the script, as requested:
!#/bin/bash

while read -r line; do
echo $line
lynx $line
echo "lynx done"
done < "ref/url"
read "lynx"

$SHELL

Note that I have changed the sites the "url" file goes to:
`www.google.com
www.majorgeeks.com
http://www.sophos.com/en-us/products/free-tools/virus-removal-tool.aspx`

A:

I should have answered this question a long time ago. I got the program working, it's now on Github!
Anyway, I simply had to wrap the loop inside a function. Something like this:
progdownload () {
  printlog "attmpting download from ${URL}"
  if echo "${URL}" | grep -q "http://www.majorgeeks.com/" ; then
lynx -cmd_script="${WORKINGDIR}/support/mgcmd.txt" --accept-all-cookies ${URL}
  else wget ${URL}
  fi
  }
URL="something.com"
progdownload


Q:

Add title in addition to data description in JS file

I am working on a jquery gallery and each image has a data description. I want to add a title above each data description. How can I do this? I cannot figure it out. Thanks. I am suspecting the variables need to be changed in the code snippet I posted below.
var $loader = $rgGallery.find('div.rg-loading').show();

                $items.removeClass('selected');
                $item.addClass('selected');

                var $thumb      = $item.find('img'),
                    largesrc    = $thumb.data('large'),
                    title       = $thumb.data('description');

                $('').load( function() {

                    $rgGallery.find('div.rg-image').empty().append('');

                    if( title )
                        $rgGallery.find('div.rg-caption').show().children('p').empty().text( title );

                    $loader.hide();

                    if( mode === 'carousel' ) {
                        $esCarousel.elastislide( 'reload' );
                        $esCarousel.elastislide( 'setCurrent', current );
                    }

                    anim    = false;

                }).attr( 'src', largesrc );

            };

        return { init : init };

    })();

    Gallery.init();
});

Here's my html code in a js fiddle file: jsfiddle.net/amw312/tq86nv7z/62/

A:

I think this should set you on the correct path. Of course, I do not know if you want some special formatting. I see in your example, you already added data-title attribute. I just put the title inside the description block. You can seperate it out (remember to also make elem available. I just reduced typing by creating a local elem var).
        var $thumb      = $item.find('img'),
            largesrc    = $thumb.data('large'),
            description = $thumb.data('description');
            title       = $thumb.data('title');

        $('').load( function() {

            $rgGallery.find('div.rg-image').empty().append('');

            if( description ){
                 var elem =  $rgGallery.find('div.rg-caption').show().children('p')
                 elem.empty().text( description );

                 if(title)
                     elem.prepend(title + "
");
             }

            $loader.hide();


Q:

Why does my test try to render a different & invalid route?

I have a test that tries to view a subscription that doesn't exist. I run this test with a bunch of users from my fixtures. In the case of the user in the admin role when the app gets to the point of trying to render the response it has changed the action from :show to :edit and dropped the id param. Yet when I try and use byebug to trace the execution I never seem to be able to pinpoint when it happens.
my test is:
test "#{u.role} can not view subscriptions that don't exist" do
  self.send('sign_in_' + u.role)
  get :show, id:1234567890
  assert_redirected_to root_path
  assert_includes flash[:alert], "That subscription doesn't exist"
end

where u is a user loaded from my fixtures.
The error I get is:
SubscriptionsControllerTest#test_admin_can_not_view_subscriptions_that_don't_exist:
ActionView::Template::Error: No route matches {:action=>"edit", :controller=>"subscriptions", :id=>nil} missing required keys: [:id]
    app/views/subscriptions/show.html.erb:13:in `_app_views_subscriptions_show_html_erb__1518678276755260966_70268849069860'
    test/controllers/subscriptions_controller_test.rb:58:in `block (2 levels) in <class:SubscriptionsControllerTest>'

my controller looks like this:
class SubscriptionsController < ApplicationController
  load_and_authorize_resource except: [:create,:new]
  before_action :set_subscription
  def show
  end
  def edit
  end
...
  private
    def subscription_params
      params.require(:subscription).permit(:email,:confirmed)
    end
    def set_subscription
      #byebug if user_signed_in? && current_user.role == 'admin' && self.action_name == 'show'
        begin
          if (params.has_key? :id) && (controller_name == 'subscriptions')
            @subscription = Subscription.find(params[:id])
          elsif user_signed_in?
            @subscription = current_user.subscription || Subscription.new(email: current_user.email)
          else
            @subscription = Subscription.new
          end
        rescue ActiveRecord::RecordNotFound
          @subscription = Subscription.new
          flash.alert = "That subscription doesn't exist"
        end
    end
end

load_and_authorize_resource comes from cancancan.
my routes related to this test are:
  resources :subscriptions do
    member do
      get 'confirm'
    end
  end

I don't really know where to go from here, so any advice would be appreciated.

A:

Take a look at the stack trace for this exception:
SubscriptionsControllerTest#test_admin_can_not_view_subscriptions_that_don't_exist:
ActionView::Template::Error: No route matches {:action=>"edit", :controller=>"subscriptions", :id=>nil} missing required keys: [:id]
    app/views/subscriptions/show.html.erb:13:in `_app_views_subscriptions_show_html_erb__1518678276755260966_70268849069860'
    test/controllers/subscriptions_controller_test.rb:58:in `block (2 levels) in <class:SubscriptionsControllerTest>'

app/views/subscriptions/show.html.erb, line 13. Are you calling link_to (or a similar helper method) with a nil ID, maybe?


Q:

Передача void* параметра в функцию

Имеется функция:
void MyFun(void *Array){...}

Как определить какой тип данных получен, для последующего вычисления его размера (sizeof())

A:

Угу.
void * - просто указатель на что-то. Непонятно что.
Число ли это, строка, массив, структура - компилятор знать не будет. Потому и применяют типы "указатель на что-то известное", если это надо.
Если же нужно в одну функцию передавать разные штуки (а надо ли так делать?), то нужно функцию как-то уведомлять, что же ей дали на переваривание.


Q:

How do I get a float/double bits without doing undefined behavour?

In C++ I want to get the bits of double myval = 1.3; It's 0x3FF4CCCCCCCCCCCC however how do I get it without breaking alias rules and doing undefined behavior?

A:

You can copy the bits into an integer object byte by byte. Aliasing with char is allowed. Then you can shift and mask the bits of that integer to get values of individual bits.
The easiest way to copy byte by byte is std::memcpy. You'll need to make sure that your integer type is large enough.
double myval = 1.3;
unsigned long long myval_int = 0;
static_assert(sizeof myval_int == sizeof myval);
std::memcpy(&myval_int, &myval, sizeof myval);
std::cout << std::hex << myval_int;

For a better way to make sure that you've got appropriately sized integer type, see http://www.boost.org/doc/libs/1_65_1/libs/integer/doc/html/boost_integer/integer.html
Note that copying to into the beginning of the integer works only if the integer has the same size - or if integer is larger, then CPU has to be little endian. If integer is larger, and CPU is big endian, then you need to copy with an offset.


Q:

Ponteiros e matrizes pegando algo não esperado

#include <stdio.h>

int main()
{
    int vetor[][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
    int valor= *(vetor[1] + 1) + **(vetor + 3);
    printf("%d", valor);
}

O código acima foi retirado de exercícios teóricos, porém não possuo o gabarito, mas verifiquei que compila e imprime o valor 15. Entretanto minhas dúvidas são as seguintes:

Por que o array foi declarado com o 'subscrito' da linha vazio  int vetor[][3] e qual a diferença entre  int vetor[0][3]?

Entendi que o trecho vetor[1]+1 retorna o valor 5 do array, mas
por que o trecho **(vetor+3) retorna o valor 10?

Por que o ponteiro para ponteiro **(vetor+3)
funciona mas o ponteiro *(vetor+3) não funciona?

A:

Primeiro vamos combinar que este código está potencialmente errado. Ele compila em compiladores ruins ou mal configurados. Eu não tentaria aprender por ele.

Por que o array foi declarado com o 'subscrito' da linha vazio int vetor[][1] e qual a diferença entre int vetor[0][1]?

Porque ele pega do tamanho informado no literal logo à frente na atribuição, ele conta que tem 12 e como uma das dimensões é 3 ele adota 4 e usa este número.
Se usar 0 terá um tamanho de 0, não é o que você quer, não faz sentido ter um array que cabe 0 elementos. Em bom compilador nem aceitaria.
Desnecessário fazer estas maluquices, melhor escrever um código legível e conforme.

Entendi que o trecho vetor[1] + 1 retorna o valor 5 do array, mas por que o trecho **(vetor+3) retorna o valor 10?

Pelo mesmo motivo que o trecho anterior pegou 4 e somou com 1 (primeiro elemento da segunda dimensão dentro do elemento 1 da primeira dimensão). Ele pegou o primeiro elemento da segunda dimensão dentro do elemento 3 da primeira dimensão, que é 10.

Por que o ponteiro para ponteiro **(vetor+3) funciona mas o ponteiro *(vetor+3) não funciona?

Porque você está pegando o valor da segunda dimensão e não da primeira, então há duas indireções.
Este código faz a mesma coisa com os mesmos compromissos e é muito mais legível:
#include <stdio.h>

int main() {
    int vetor[4][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}};
    printf("%d", vetor[1][0] + 1 + vetor[3][0]);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.

A:

Por que o array foi declarado com o 'subscrito' da linha vazio  int
  vetor[][3] e qual a diferença entre  int vetor[0][3]?

Nessa linha você está criando uma matriz. Quando você deixa de especificar a quantidade de elementos em um vetor ele é gerado com base na quantidade de elementos que você coloca na inicialização dele. Por exemplo:
int v[] = {1, 2, 3};

Nesse caso o vetor v será gerado com 3 elementos. Já no seu caso, foi definido apenas a quantidade de colunas da matriz. Como na inicialização temos 12 elementos, o programa irá criar uma matriz de 4 linhas por 3 colunas. Seria uma prática melhor definir previamente a quantidade de elementos, dessa maneira:
int vetor[4][3] = {{1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}};

O código acima deixa claro como a matriz será organizada, além de definir previamente a quantidade de elementos.

Entendi que o trecho vetor[1]+1 retorna o valor 5 do array, mas por
  que o trecho **(vetor+3) retorna o valor 10 ?

Vamos analisar primeiramente o caso *(vetor[1]+1). Lembrando que o vetor é um ponteiro para o primeiro elemento e os elementos seguintes são armazenados em sequência. Como a variável vetor é uma matriz (ou seja, um vetor de vetores) quando se coloca vetor[1] é retornado o endereço à linha 1 da matriz (ou seja, o endereço para o elemento 0 da linha 1). Ao adicionar 1 a esse endereço pegamos o endereço do elemento seguinte (elemento 1 da linha 1 da matriz, lembrando que as linhas e colunas são contadas a partir de 0). Ao colocar o * antes de vetor, que está armazenando o endereço, pegamos o valor que está armazenado naquele endereço, portanto 5.
Na parte **(vetor+3) o que acontece é que pegamos vetor (que é um ponteiro para um ponteiro, pois é um vetor de vetores e cada vetor é um ponteiro) e adicionamos 3 a ele. O que acontece então é que pegamos o ponteiro que contém o endereço para vetor[3].
vetor é um ponteiro para ponteiro. Então quando você usa *vetor[3] você está acessando o conteúdo de v[3], que será um ponteiro, e então acessando o conteúdo desse outro ponteiro.

Por que o ponteiro para ponteiro **(vetor+3) funciona mas o ponteiro
  *(vetor+3) não funciona?

Como dito na resposta anterior, *(vetor+3) é apenas o endereço para o conteúdo que você quer acessar. Para acessá-lo você deverá usar **(vetor+3).


Q:

Suggest editing to upvoters of unclear questions

While I was trying to understand some question, it got a few upvotes.
So it got me thinking - these upvoters probably understood it and thought it was good. So it would be great if they edited it in addition!
I think this can be programmed in the following way:

If the question has a close-vote (or two) as "unclear"
and the user is upvoting it
and the user has editing privileges

then make a popup window that says:

Some users thought that this question is unclear. Please consider improving it.

I remember that similar UI is used for:

You have been voting only on answers - please consider voting on questions too.

And for downvoting:

Please consider adding a comment to explain what is wrong with this question.

(I don't remember the exact wording, because I haven't gotten them for a while.)
So, would such a popup help? If yes, maybe it would be good in additional situations (e.g. close-voted for being opinion-based - the wording in the popup properly adjusted)?

A:

I support this basic idea, although it seems to reveal a bit of extra information about the CV process that low-rep users don't necessarily have, normally. Is that intended, or should we perhaps limit displaying this only to those who can normally see close votes anyway?
I would say we should not limit it, since a large source of careless upvotes is generally from users with 15-3000 rep, whether because they are less experienced with moderation, because there are so many of them, or both. Exposing the existence of 1+ close votes of a specific type under certain circumstances is not terribly dangerous. (For that matter, we already do expose the existence of dupe-votes/flags, as well as custom freeform close reasons, to all and sundry without any restrictions at all.)

A:

I might be a pessimist, but this is my explanation of your observation.

Confused Guy (posts question): I want to model a nuclear reactor using expression templates. It has to be very fast because I'm going to model a lot of very complicated processes. According to Donald Knuth's The Art of Computer Programming, I should use a prime number for my hashing but I don't understand how that works in the context of nuclear reactors and expression templates. Can anybody please explain? PS: I need code by tomorrow.

Long Term User (votes to close):  Unclear what you're asking. Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question.

Happy User (up-votes in excitement): Oh my God, he is modeling a nuclear reactor! Nuclear reactors are awesome! Also, he is using expression templates and reads TAOCP, he must be a very smart guy.

In the status quo, the story ends here. The last two actions may be repeated a few times but eventually, enough “Long Term User”s will come by and the question be finally closed.
Now, this is what I fear might happen in the future.

System (to Happy User): Some users thought that this question is unclear. Please consider improving it.

Happy User (edits in eager to fulfill his mission): You can find more information about nuclear reactors on Wikipedia.

As I've said, I might be a pessimist.

A:

While I think this is a good idea, I'm a little concerned that it won't help much...
I strongly suspect that many of these upvotes have more to do with misguided lines of thought when it comes to voting:

downvotes are mean...

have a sympathy vote

I know the answer, so the question can't be that bad...

upvotes wildly off-topic question about baking cookies

and so on...

This is a step in the right direction, but I'm thinking that adding a little more guidance may be in order. Something like:

Some users thought that this question is unclear.
Are you sure that it shows research effort and that it is clear and useful?
  If not, please consider improving it.

Still not sure if it would help much, most users who exhibit these behaviors are notorious for not reading the docs/tour/help pages...


Q:

Java URL Connection blank input stream

The application I am working on has a terribly slow loading web page.  If I run the following code it works fine but only because of the call to sleep.  If I don't sleep then the InputStream is just a bunch of spaces, probably due to the application it is calling from.  Is there any non-hack way around this?
public class PublishTool extends Thread {

  private URL publishUrl;

  private String filerLocation;

  public PublishTool() {
  }

  public PublishTool(String publishUrl, String filerLocation) throws NibException {

    try {
      this.publishUrl = new URL(publishUrl);
    } catch (MalformedURLException e) {
      throw new NibException("Publish Url :" + publishUrl + " is not valid. ");
    }

    this.filerLocation = filerLocation;

  }

  public void run() {

    File filerFile = new File(filerLocation);
    BufferedWriter writer = null;

    try {
      URLConnection conn = publishUrl.openConnection();
      BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(conn.getInputStream())));

      writer = new BufferedWriter(new FileWriter(filerLocation));

      Thread.sleep(1000l);

      while (reader.ready()) {
        writer.write(reader.readLine() + "\n");
      }

    } catch (MalformedURLException e) {
      throw new IllegalStateException("Malformed URL for : " + publishUrl + " " + filerLocation, e);
    } catch (IOException e) {
      throw new IllegalStateException("IO Exception for  : " + publishUrl + " " + filerLocation, e);
    } catch (InterruptedException e) {
      throw new IllegalStateException("Thread was interrupted early... publishing might have failed.");
    } catch (NibException e) {
      throw new IllegalStateException("Publishing File Copy failed : " + filerLocation + ".bak" + " to " + filerLocation);
    } finally {
      try {
        writer.flush();
        writer.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

A:

Don't use reader.ready(). Just call readLine() and let readLine() block until the data's ready. The end of the data will generally be signalled with a null line.
In case its helpful, a couple of code examples on my web site: reading from a URL.


Q:

Can we parallel shift a vector from one plane to another plane

When 2 vectors are in a plane ,we can parallel shift them so that they have same intial point such that they have same direction and magnitude as intial , but when 2 vectors are in different planes say one in X-Z plane and other in Y-Z plane  how can we parallel shift them to add ? Or simply can we shift the vectors from one plane to another?
If yes,
We know that each vector has a unique direction given by r=xi^+ yj^+zk^ where x y z are it's components in X Yand Z direction respectively. Then if we shift (parallel shift) then it's components may change, this will give us another vector ? Though this new vector has same direction as r but it's components may be different (like the new vector may r'=-xi+yj-zk). I am not getting this . Please help

A:

An operator that transports vectors from one plane to another is sometimes called a “discrete connection” and has been studied in the context of simplicial complexes etc.
One canonical way to transport a vector from one plane to another: rotate the first plane about the edge common to both planes until the first plane is parallel to the second. Then slide the vector onto the second plane.


Q:

Extending a program to count line frequency

I have this simple program to count the word frequency:
#include <iostream>
#include <map>
#include <cctype>
#include <string>
using namespace std;
int main(void) {
  map<string, int> words;
  map<string, int>::iterator i;
string s;
while (cin >> s) {
    transform(s.begin(), s.end(), s.begin(), ::tolower);
words[s]++;
  }
for (i=words.begin(); i != words.end(); i++)
    cout << i->first << " " << i->second << endl;
return 0;

Now how do I make it to count line frequency instead of word frequency. Each line is separated by '\n' new line character in the input.

A:

If you want to count the total lines, then its very simple:
 size_t countLine = 0;
 while(std::getline(std::cin, s)) countLine++;

But if you really want to count frequency of same line, then in your code, replace
string s;

with
line s;

where line is defined as:
struct line : std::string
{
    friend std::istream & operator >> (std::istream &in, line &ln)
    {
        return std::getline(in, ln);
    }
};

Or, you can make it generic:
template<typename CharT, typename Traits = std::char_traits<CharT>, typename Allocator = std::allocator<CharT>>
struct basic_line : public std::basic_string<CharT, Traits, Allocator>
{
    friend std::basic_istream<CharT, Traits> & operator >> (std::basic_istream<CharT, Traits > &in, basic_line<CharT, Traits, Allocator> &ln)
    {
        return std::getline(in, ln);
    }
};

then define these typedefs:
typedef basic_line<char>    line;
typedef basic_line<wchar_t> wline;


Q:

assertNotEquals static import causing compile error

I have a file Foo.java which compiles with no errors.  But when I add the single line
import static org.junit.Assert.assertNotEquals;

This causes the following error from my ant build:
compileTests:
[javac] Compiling 27 source files to C:\example\bin
[javac] C:\example\src\Foo.java:7: error: cannot find symbol
[javac] import static org.junit.Assert.assertNotEquals;
[javac] ^
[javac]   symbol:   static assertNotEquals
[javac]   location: class
[javac] 1 error

I am using JUnit 4.4. junit-4.4.jar is included in the classpath for the javac task.
I have tried running different compiler versions with the flags -Dbuild.compiler=javac1.7 and -Dbuild.compiler=javac1.8 but it makes no difference.  I still get the exact same error.
assertNotEquals is the only static import from Assert that causes this error.
I have already seen this post Java static import causing compile error. Probable compiler bug?
and I tried importing Assert on its own and prepending each assert statement with Assert. like this post suggested.  I got the same error, this time at the method call for Assert.assertNotEquals()instead of the import statement.
The import successfully compiles and runs on Eclipse, however.
Does anyone have any ideas about the cause of this? I'd like to get to the bottom of this instead of having to implement a workaround solution.

A:

You are using Junit 4.4.  AssertNotEquals wasn't added until 4.11
JUnit 4.11 release Notes
If you update to the latest JUnit jar. the compiler error should go away.  Eclipse is probably using its own built in version that has the latest methods.


Q:

R: nested groupings and total counts via dplyr?

I'm trying to practice using the dplyr package in R with a data frame called
fruit_eaten like so:
person,fruit
Alice,apple
Alice,apple
Alice,apple
Alice,orange
Bob,apple
Bob,banana
Bob,grape
Bob,grape
Bob,grape
Cheryl,orange
Cheryl,orange
Cheryl,kiwi
Donald,apple
Donald,apple
Donald,grape
Donald,grape

I would like to do the following with dplyr:
For each type of fruit, calculate who ate the most of it (so this is not a simple count, I want to find the maximum count) and how many to produce this table:
| fruit  | who_ate_most | how_many |
|--------|--------------|----------|
| apple  | Alice        | 3        |
| orange | Cheryl       | 2        |
| banana | Bob          | 1        |
| grape  | Bob          | 3        |
| kiwi   | Cheryl       | 1        |

In addition, I'm not sure how to deal with situations where two or more people all ate the same maximum number of a fruit.
Similarly, I'm trying to make a table that lists each person and the fruit that they ate the most of and how many:
| person | ate_most_of | how_many |
|--------|-------------|----------|
| Alice  | apple       | 3        |
| Bob    | grape       | 3        |
| Cheryl | orange      | 2        |
| Donald | apple       | 2        |

Of course a similar problem for this second output table is what to do if a person ate the same maximum number of more than one fruit?
I am aware of the group_by() function in dplyr, but looks like I have more than one "group" here. And how do I get that maximum count for the "how_many" columns in both tables?
P.S. The original data in comma delimited format (pastebin link here).

A:

For each type of fruit, calculate who ate the most of it (this is not a simple count, rather, a maximum count):
df %>%
  count(fruit, person) %>%
  top_n(1)

#    fruit person     n
#   (fctr) (fctr) (int)
# 1  apple  Alice     3
# 2 banana    Bob     1
# 3  grape    Bob     3
# 4   kiwi Cheryl     1
# 5 orange Cheryl     2

df %>%
  count(person, fruit) %>%
  top_n(1)

#   person  fruit     n
#   (fctr) (fctr) (int)
# 1  Alice  apple     3
# 2    Bob  grape     3
# 3 Cheryl orange     2
# 4 Donald  apple     2
# 5 Donald  grape     2

Noting that count is a wrapper for tally|summarise|n which does the group_by for you. Notice the difference in the ordering of the underlying group_by. Also note that each summary (the underlying n() summarization) peels off one level of grouping.

Per the comments about getting one record per tie, we can use toString as suggested by @Frank. In addition, we can "keep" n by extracting the first() value from its vector:
df %>%
  count(person, fruit) %>%
  top_n(1) %>%
  summarise(     n = first(n),
            fruits = toString(fruit))

#   person     n       fruits
#   (fctr) (int)        (chr)
# 1  Alice     3        apple
# 2    Bob     3        grape
# 3 Cheryl     2       orange
# 4 Donald     2 apple, grape


Q:

Get, or calculate the entropy of an image with Ruby and imagemagick

How to find the "entropy" with imagemagick, preferably mini_magic, in Ruby? I need this as part of a larger project, finding "interestingness" in an image so to crop it.
I found a good example in Python/Django, which gives the following pseudo-code:
image = Image.open('example.png')
histogram = image.histogram() # Fetch a list of pixel counts, one for each pixel value in the source image

#Normalize, or average the result.
for each histogram as pixel
  histogram_recalc << pixel / histogram.size
endfor

#Place the pixels on a logarithmic scale, to enhance the result.
for each histogram_recalc as pixel
  if pixel != 0
    entropy_list << log2(pixel)
  endif
endfor

#Calculate the total of the enhanced pixel-values and invert(?) that.
entropy = entroy_list.sum * -1

This would translate to the formula entropy = -sum(p.*log2(p)).
My questions: Did I interprete the Django/Python code correct? How can I fetch a histogram in ruby's mini_magick if at all?
Most important question: is this algorithm any good in the first place? Would you suggest a better one to find the "entropy" or "amount of changing pixels" or "gradient depth" in (parts of) images?
Edit: Using a.o. the resources provided by the answer below, I came up with the working code:
# Compute the entropy of an image slice.
def entropy_slice(image_data, x, y, width, height)
  slice = image_data.crop(x, y, width, height)
  entropy = entropy(slice)
end

# Compute the entropy of an image, defined as -sum(p.*log2(p)).
# Note: instead of log2, only available in ruby > 1.9, we use
# log(p)/log(2). which has the same effect.
def entropy(image_slice)
  hist = image_slice.color_histogram
  hist_size = hist.values.inject{|sum,x| sum ? sum + x : x }.to_f

  entropy = 0
  hist.values.each do |h|
    p = h.to_f / hist_size
    entropy += (p * (Math.log(p)/Math.log(2))) if p != 0
  end
  return entropy * -1
end

Where image_data is an RMagick::Image.
This is used in the smartcropper gem, which allows smart slicing and cropping for images with e.g. paperclip.

A:

Entropy is explained here (with MATLAB source, but hopefully the qualitative explanation helps):
Introduction to Entropy (Data Mining in MATLAB)
For a more formal explanation, see:
"Elements of Information Theory" (Chapter 2), by Cover and Thomas


Q:

How can I add Zurb Foundation as a library?

I'm trying to add Zurb Foundation framework to my theme library file. However, when I add the following code to my library, I'm not getting any result.
I would be grateful to hear what is the problem with the code and what is the right way to load a library?
This is my theme folder structure (Zurb Foundation folder location):
|-Theme Name
|  |-includes
|  |  |-foundation
|  |  |  |-css
|  |  |  |-js

Library file:
foundation:
  version: 6.x
  css:
    includes/foundation/css/app.css: {}
    includes/foundation/css/foundation.css: {}
    includes/foundation/css/foundation.min.css: {}
  js:
    includes/foundation/js/app.js: {}
    includes/foundation/js/foundation.js: {}
    includes/foundation/js/foundation.min.js: {}
    includes/foundation/js/jquery.js: {}
    includes/foundation/js/what-input.js: {}

A:

You created the library, alright, but you need to call the library.
In [theme_name].info.yml add the following:
libraries:
  - '[theme_name]/foundation'

Also you need to modify your [theme_name].libraries.yml file and add dependencies:
foundation:
  version: 6.x
  css:
    base:
      includes/foundation/css/app.css: {}
      includes/foundation/css/foundation.css: {}
      includes/foundation/css/foundation.min.css: {}
  js:
    includes/foundation/js/app.js: {}
    includes/foundation/js/jquery.js: {}
    includes/foundation/js/foundation.js: {}
    includes/foundation/js/foundation.min.js: {}
    includes/foundation/js/what-input.js: {}
  dependencies:
    - core/drupal
    - core/jquery
    - core/jquery.once

As per Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme


Q:

Upcasting not to real base class

I'm a bit stuck with such awful problem of bad class hierarchy.
class A {...}; // abstract
class B : public A {...}; // abstract
class C {...}; // abstract

class a1 : public B, public C {...}; // indirect inheritance of A
class c1 : public A, public C {...};

The question: is it possible convert a pointer(reference) to C into pointer(reference) to class A.
I understand that best solution is to make just class C inherited from A, but still it can cause some problems with class a1 (two base A).

A:

The question: is it possible convert a pointer(reference) to C into pointer(reference) to class A.

Not unless the classes are polymorphic i.e. have at least one virtual member function. In that case dynamic_cast can be used to side cast, as shown in StoryTeller's answer.
However, if that C pointer(reference) points to a child that inherits A, then you can first cast down to that child pointer, and then to A.
c1 c;
C& cref = c;
A& aref = static_cast<c1&>(cref);

That's of course not necessarily ideal because you cannot convert just any arbitrary C pointer whose concrete type is unknown.

I understand that best solution is to make just class C inherited from A

If you did this, then all C pointers would be implicitly convertible to A pointers.

but still it can cause some problems with class a1 (two base A).

To work around the problems, you need shared bases i.e virtual inheritance.
struct A {}; // abstract
struct B : virtual A {}; // abstract
struct C : virtual A {}; // abstract

struct a1 : B, C {}; // indirect inheritance of A
struct c1 : C {};

int main() {
    c1 c;
    C& cref = c;
    A& aref = cref;
}

A:

What you are trying to do is called a "side-cast". And the built-in dynamic_cast expression can do that. But it isn't cheap, and you better not have turned off support for RTTI in your project (you already mentioned your classes are abstract, so that entails virtual functions, whose declarations are needed for RTTI to be generated along).
See it Live
#include <cassert>

struct A {
    virtual ~A() = default;
};

struct B : public A {
    virtual ~B() = default;
};

struct C {
    virtual ~C() = default;
};

struct a1 : public B, public C {
    a1() = default;
    virtual ~a1() = default;

}; // indirect inheritance of A

int main() {
    a1 a;

    C* c = &a;

    assert(dynamic_cast<A*>(c) != nullptr);

    return 0;
}

But your sentiments about needing to re-design your classes are in my opinion highly warranted. The need to do a side cast should not arise.


Q:

In mysql How can I multiply two tables?

Basically what I want is cross product of two tables.
t1 is :
    +------------+
    | student    |
    +------------+
    | 1234567890 |
    | 1234567890 |
    | 1234567890 |
    | 000000001  |
    +------------+
t2 is:
    +--------+
    | number |
    +--------+
    |      1 |
    |      3 |
    +--------+

How can I get a table which has two columns and 8 entries which are crosss product of values in t1 and t2 ?

A:

I think you need a CROSS JOIN.
It'll join both tables on all rows.
SELECT * FROM t1 CROSS JOIN t2

A:

Select student, number, from t1, t2;


Q:

XNA HLSL Shader Glow

I have googled this to death, and I still don't quite understand it.
I'm trying to create a glow effect in XNA using HLSL. A long time ago I was able to do it the way most people suggest which is by sampling the pixels from a texture, however I've always been curious about how you can make it more advanced so that you could do things like set the glow distance and stuff. If I recall from back when I was creating something like this in a similar project, there was always a limit as to how much I could sample before the computer couldn't handle it, hence limiting the glow distance. I wanted to know if there was a more sophisticated way of doing it, one that would have no glow distance limit? And I'm not referring to lighting ground textures either, the idea I have in my head is to have a set of vertices that all join together to create a LineList (for this example lets say they create a cube), so you have very thin lines creating a shape, and then you can set a glow on this object that has no limit to its distance, kinda like how Photoshop works I guess.
Thanks

A:

You can create arbitrary blur effects by first fourier transforming the image, applying the blurring and then transforming it back. This is how Futuremark's 3DMark 11 does it (Whitepaper) and possibly some other modern 3D engines as well. There is also a video of the effect here and explanation of the process.
Unfortunately I didn't find any ready-made implementation of this with source code, but you can try searching for FFT bloom.


Q:

How can I force a program to open in a specific desktop?

I've created an environment where I use 3 different desktop configurations, but every time I reboot, I have to manually open each program in that target desktop to make it look like it did before.
So, I'd like to write a .bat file that can get all my programs running in their appropriate desktops. I'm wondering if something like this is possible:
"C:\Program Files (x86)\Mozilla Firefox\firefox.exe" -desktop:2
"C:\Program Files\My\Other\Software.exe" -desktop:3
...etc.

Obviously, this example is not real, but I hope there's something similar. I don't care if it's hacky :)

A:

You can use the program VDesk to achieve this functionality.

VDesk for Windows 10: launch programs on virtual desktops
Vdesk is a portable program for Windows that adds the feature to
  Windows 10. It is a command line program but ships with an option to
  integrate its functionality in File Explorer.
The main command looks like this: vdesk [n] [command [args]]

n sets the index of the virtual desktop you want to launch the program on.
[command [args]] specifies the program and arguments that you want it to start.

The command vdesk notepad.exe launches Notepad on a new virtual
  desktop, while vdesk 3 notepad c:\text.txt opens Notepad on virtual
  desktop 3 and uses an argument to load text.txt automatically.
You can run the application on start of Windows 10 to always load
  programs on virtual desktops when the operating system starts by
  creating simple batch files, and adding them to one of the many
  startup locations of the operating system.
The option to launch a program on a new virtual desktop can be added
  to File Explorer as well. You need to run vdesk -install for that on
  the command line, and will notice afterwards that a new "open in new
  virtual desktop" option is available when you right-click on
  executable files in File Explorer.
The command vdesk -uninstall removes the entry from File Explorer
  again.


Q:

SUM giving incorrect output

For my mySQL course, we're creating a database that manages customer orders. One of the questions is asking for me to list all customers and the total revenue per customer.
My issue is that some orders have ordered more than one of the same item, and so when I introduced quantity into the SUM, any order that had multiples of an individual item ordered were summed out incorrectly, but I have no idea how to fix this issue.
This is the code that I have right now:
SELECT customers.customer_name, customers.customer_id,
SUM(items.retail_price*orderline.order_qty) AS 'Total Retail Price'
FROM customers
INNER JOIN orders on customers.customer_id = orders.customer_id
INNER JOIN orderline on orders.order_id = orderline.order_id
INNER JOIN items on orderline.item_id = items.item_id
GROUP BY customers.customer_name;

I realize it's a bit of a mess as well, so any advice on cleaning it up would be appreciated as well; I've only been working with mySQL for about a month now so its still new to me.
Thanks in advance!
Sample Data:
item_id: 300, unit_cost: 156.00, order_qty: 2
item_id: 600, unit_cost:  92.00, order_qty: 2
item_id: 450, unit_cost:  79.98, order_qty: 6
item_id: 600, unit_cost:  92.00, order_qty: 8
item_id: 200, unit_cost: 241.98, order_qty: 4

If I did the math right, I'm supposed to get 2,727.80, but my output for this customer in question is listed as 2,679.80.
Link to Code

A:

I have re-written the query with another logic and here are the results:
My query:
SELECT c.customer_name, c.customer_id, SUM(o_price.total) as 'Total Retail Price'
    FROM customers c JOIN orders o
    ON c.customer_id = o.customer_id
    JOIN
        (
            SELECT
                order_id,
                SUM(i.retail_price * ol.order_qty) as 'total'
            FROM
                orderline ol
            JOIN items i ON ol.item_id = i.item_id
            GROUP BY
                ol.order_id
        ) o_price
    ON o.order_id = o_price.order_id
    GROUP BY c.customer_id
ORDER BY c.customer_id;

My result set:
Cora Blanca     1000    280.80
Yash Reed       1100    1723.88
John Mills      1200    363.24
Tina Evans      1400    4974.32
Will Allen      1500    1444.00
James Boyd      1600    173.58
Ann Damian      1900    271.24
Jane Brown      2100    1213.52
Betty Draper    2200    2679.80

Your result set:
Cora Blanca     1000    280.80
Yash Reed       1100    1723.88
John Mills      1200    363.24
Tina Evans      1400    4974.32
Will Allen      1500    1444.00
James Boyd      1600    173.58
Ann Damian      1900    271.24
Jane Brown      2100    1213.52
Betty Draper    2200    2679.80

Conclusion:
Both results are exactly same. Your query is absolutely fine and well written. And now you have 2 queries for same purpose, apply the best one :)


Q:

How to prevent food absorbing smells from other food?

I want to bake cakes to take into work tomorrow. But I also have a broccoli and half an onion that need eating soon, and was thinking of having broccoli and sausages with onion for dinner. Is there a way of baking the cakes and cooking the dinner on the same evening without the cakes absorbing broccoli/ onion smell, or do these activities need to be done on different days? Which is it better to cook first?
Possibly relevant information about this specific situation (though I think more general answers would be better):

There is an extractor fan which can be used if necessary (though it's very noisy and annoying).
The cakes would be cupcakes/butterfly buns with buttercream.
I prefer to do the sausages and onions in the oven rather than the frying pan, but don't have to.

A:

To people saying it's not an issue... um.. yes it bloody is! If I cook a smelly oniony meal in the oven and then bake cake or something in it (even the next) it absolutely absorbs smells and really ruins it!


Q:

Is there a good way to separate categories from subcategories in wp

Here are my costume functions that I wrote for the menu and submenu in my wordpress theme, but after I tested it the submenu disappeared when I clicked on a submenu, because wordpress doesnt separate categories from subcategories, so the parameter for them is "cat", which means that when I click on a submenu then the function that creates the submenu checks if cat=id in the url has child categories but it doesnt becasue it is a child category, I am new into wordpress and I dont know how to deal with it:
function costume_menu() {
$categories =  get_categories('hide_empty=0&style=none&parent=0');
  foreach ($categories as $category) {
    (is_category($category->term_id)) ? $active = 'class="active_menu"' : $active = '';
    $nav = '
';
    $nav .= 'term_id).'">'.strtoupper($category->cat_name).'';
    $nav .= '
';

    echo $nav;
  }

}

function costume_submenu($cat) {

$categories =  get_categories("child_of=$cat&hide_empty=0");
  foreach ($categories as $category) {
    (is_category($category->term_id)) ? $active = 'class="active_menu"' : $active = '';
    $nav = '
';
    $nav .= 'term_id).'">'.strtoupper($category->cat_name).'';
    $nav .= '
';

    echo $nav;
  }
}

A:

Try the function like this:
function costume_submenu($cat) {
    $current_cat=get_category($cat);
    if($current_cat->parent==0)
        $parent_cat=$cat;
    else
        $parent_cat=$current_cat->parent;

    $categories =  get_categories("child_of=$parent_cat&hide_empty=0");
    foreach ($categories as $category) {
        (is_category($category->term_id)) ? $active = 'class="active_menu"' : $active = '';
        $nav = '
';
        $nav .= 'term_id).'">'.strtoupper($category->cat_name).'';
        $nav .= '
';

        echo $nav;
    }
}


Q:

managing solutions/references

I would like to create utils class library (eg, logging, etc).
I want to use the utils solution in several indepandent applications.
I'm using source control of course...

does that mean I should manage utils solution (holding the utils class library)
and also seperate solution for each application ?
what do I have to do to use the utils class library from ApplicationA solution
can ApplicationA solution also include the utils solution (eg, go to definition works ?)
if that is possible, does that mean that any change proggrammerA apply to utils library via ApplicatioA solution, also affects ApplicationB solution using the same utils class libray
what do we to do when we fix a bug in utils solution ?
how does the fix bubbles to ApplicationA and B .

A:

It sounds like you have the possible approaches identified already:

Develop and manage your utility library independent of any specific application.

Advantages: no need to manage multiple versions, updates done in one solution don't impact/break other solutions
Disadvantages: the Utilities assembly is essentially a closed box, a component your applications are consuming, the same as any third-party or .NET framework assembly.

Put your Utilities library project into source control, and have the solution to each of your applications include it as a project reference (this is possible, to answer your question above).

Advantages: Utilities library is kept up to date in all projects, and can be stepped into during debugging, etc.
Disadvantages: Changes made to Utilities as part of development in one project may  break it for another.  Also, this may add issues with versioning, you may need to roll back changes for patch builds, etc.

Create a new copy of the Utilities library for each project

Advantages: no issues with build, debug, deployment or versioning
Disadvantages: changes made to the Utilities in one project are not reflected in others, and must be manually copied over if needed.

At the end of the day, there is no one correct answer; it depends on the stability of your utility methods, how often they need to be changed, and how often you will want/need to debug into them.
In most cases, I find that it is more convenient to just create a new copy of the Utilities class library for each project.  They end up being somewhat different eventually, but the ease of maintenance makes up for the lack of consistency across all projects.  If you had a very complex set of utility classes that encapsulated some portion of your business, you would probably want to go the other way and maintain it independently.


Q:

Get multiple column ranges from one row in Cassandra via Hector

Given I have one row in Cassandra with multiple columns that have an Integer as key and some value. Using SliceQuery in Hector gives me the ability to get one range of this columns. Is there a possibility to get multiple ranges with one query?
Example cassandra row:
columns 3, 7, 12, 34, 45, 46, 59, 98, 99
----------------------------------------
values  a, f,  e,  v,  a,  r,  r,  o,  k

How do I use Hector to get all columns with keys from 20 to 30 and 50 to 90 in one query?

A:

To solve that on PlayOrm open source project we do this...
Does Hector have the async calls like astyanax does so that you can do this
for(Query q : queryList) {
// this next call is non-blocking..sends requests and returns immediately not waiting for response
   Future f = q.executeAsycn();
   futures.add(f);
}

//Now, both column slices are happening in parallel at the SAME time

for(Future f : futures) {
   Result r = f.get(); //this will block for the first result
}

In this way, it is just as fast as if the api had ONE single api call anyways so no need for one call.
Dean

A:

I don't think so.  To keep it in one query you'll have to use a single slice that includes all of the slices of interest and then on the client side decide on a column by column basis whether the columns fall into one of the ranges you're interested in.
You should note that if there's too much data to handle all of the columns in that one big slice in a single call, then you can use pagination to reduce the footprint of the data on the client side, but then you might as well just make individual calls for each of your original slices.


Q:

Given a finite list of prime factors, what is the fastest way to find all numbers that can be formed from them

$$ \text{Let} \ S = \{p_1,p_2,p_3,...,p_n\} $$
$$ \text{where} \ p_i \in \Bbb P$$
What is the fastest known method method/algorithm to generate all unique numbers through product operation on $S$?
$\text{Ex}: S= \{3,5,2\} $
Soln:
$3\times5 = 15$
$3\times2 = 6$
$3\times5\times2 = 30$
$5\times2 = 10$
Currently, my ideas hover around generating all subsets of $S$, multiplying all the members in each of them and eliminating the duplicates from the list of numbers so generated. This is $O(2^n)$.

A:

If the primes are distinct and repetitions (e.g. $3\times3\times 5$) are forbidden, then going through the whole list of subsets will yield no duplicates, because the fundamental theorem of arithemetic says prime factorizations are unique.
(If unlimited numbers of repetitions are allowed, you get an infinite list.  It is a somewhat edifying exercise to prove that the sum of the reciprocals of those infinitely many numbers will be finite if you had only finitely many primes in your initial list.)

A:

Given your example solution I saw a very nice solution (the answer by @Arturo Magidin) that may be relevant to you.


Q:

how to use linprog to calculate f(x) with a constant in Matlab?

I know the linprog can deal with questions like this
Find x that minimizes

f(x) = –5x1 – 4x2 –6x3,

subject to

x1 – x2 + x3 ≤ 20
3x1 + 2x2 + 4x3 ≤ 42
3x1 + 2x2 ≤ 30
0 ≤ x1, 0 ≤ x2, 0 ≤ x3.

However, if I add a constant to f(x) so that change it into something like f(x) = -5x1 -4x2  + 2, it seems that the linprog can't work it out. Could anybody please give me any ideas about how to deal with this problem?
Thanks a lot!

A:

f(x) = -5x1 -4x2 - 6x3 + 2 , suppose g(x)= -5x1 -4x2 - 6x3 , f(x) can  be formalized as f(x) = g(x) +2 ,it is obvious that min(f(x)) = min(g(x)) +2 , so  minimize g(x) instead


Q:

How do you get a document ID in the success callback when using jquery.couch.saveDoc?

Example code is:
$db.saveDoc(doc, {
    success: function () {
        // Do something with the ID.
    },
    error: function () {
        alert("Cannot save the thread.");
    }
});

In the success callback function, how do you get the ID of the doc that's just been saved?

A:

Pretty much all jquery.couch functions call the success callback with the data returned from the http request, when you sent a POST /db/doc request,
{"ok":true,"id":"ad5c9fc93ae3b6f5f9809357a30003fe","rev":"1-2a91bdd9ee1e3e5e6302741132d7c415"}

is returned, so
$db.saveDoc(doc, {
  success: function (data) {
    var id = data.id;
  },
  error: function () {
    alert("Cannot save the thread.");
  }
});


Q:

Django Rest Framework - How to nest several fields in a serializer?

I have several a base model with several control fields. Among them a location fields compound from lat, lon, accuracy, provider and client time. Most of my writable models (and hence resources) are inheriting from this base model.
I'm trying to make DRF serialize the location related fields in a nested "location" field. For example,
{
 "id": 1,
 "name": "Some name",
 "location": {
   "lat": 35.234234,
   "lon": 35.234234,
   "provider": "network",
   "accuracy": 9.4,
 }
}

I'ts important to remember that these fields are regular (flat) fields on the base model.
I've investigated and found several options

Create a custom field and by overriding "get_attribute" create the nested representation. I don't like this solution because i lose some of the benefits of the model serializer such as validation.
Create a nested resource called Location. I guess i could make it work by adding a property by the same name on the model but again, no validations.

So my question is, What is the best way to nest ( or group ) several fields in a DRF serializer ?
DRF 3.0.0, Django 1.7
EDIT:
Building on top of @Tom Christie answer this is what i came up with (simplified)
# models.py
class BaseModel(models.Model):
  id = models.AutoField(primary_key=True)
  lat = models.FloatField(blank=True, null=True)
  lon = models.FloatField(blank=True, null=True)
  location_time = models.DateTimeField(blank=True, null=True)
  location_accuracy = models.FloatField(blank=True, null=True)
  location_provider = models.CharField(max_length=50, blank=True, null=True)

  @property
  def location(self):
    return {
      'lat': self.lat,
      'lon': self.lon,
      'location_time': self.location_time,
      'location_accuracy': self.location_accuracy,
      'location_provider': self.location_provider
    }

class ChildModel(BaseModel):
  name = models.CharField(max_lengtg=10)

# serializers.py
class LocationSerializer(serializers.Serializer):
  lat = serializers.FloatField(allow_null=True, required=False)
  lon = serializers.FloatField(allow_null=True, required=False)
  location_time = serializers.DateTimeField(allow_null=True, required=False)
  location_accuracy = serializers.FloatField(allow_null=True, required=False)
  location_provider = serializers.CharField(max_length=50,allow_null=True, required=False)

class BaseSerializer(serializers.ModelSerializer):

  def create(self,validated_data):
    validated_data.update(validated_data.pop('location',{}))
    return super(BaseSerializer,self).create(validated_data)

  def update(self, instance, validated_data):
    location = LocationSerializer(data=validated_data.pop('location',{}), partial=True)
    if location.is_valid():
      for attr,value in location.validated_data.iteritems():
        setattr(instance,attr,value)
    return super(BaseSerializer,self).update(instance, validated_data)

class ChildSerializer(BaseSerializer):
    location = LocationSerializer()

    class meta:
      model = ChildModel
      fields = ('name','location',)

I've tested with valid/invalid post/patch and it worked perfectly.
Thanks.

A:

I'd suggest simply using explicit serializer classes, and writing the fields explicitly. It's a bit more verbose, but it's simple, obvious and maintainable.
class LocationSerializer(serializers.Serializer):
    lat = serializers.FloatField()
    lon = serializers.FloatField()
    provider = serializers.CharField(max_length=100)
    accuracy = serializers.DecimalField(max_digits=3, decimal_places=1)

class FeatureSerializer(serializers.Serializer):
    name = serializers.CharField(max_length=100)
    location = LocationSerializer()

    def create(self, validated_data):
        return Feature.objects.create(
            name=validated_data['name'],
            lat=validated_data['location']['lat'],
            lon=validated_data['location']['lat'],
            provider=validated_data['location']['provider'],
            accuracy=validated_data['location']['accuracy']
        )

    def update(self, instance, validated_data):
        instance.name = validated_data['name']
        instance.lat = validated_data['location']['lat']
        instance.lon = validated_data['location']['lat']
        instance.provider = validated_data['location']['provider']
        instance.accuracy = validated_data['location']['accuracy']
        instance.save()
        return instance

There's a bunch of ways you could use a ModelSerializer instead, or ways to keep the create and update methods a little shorter, but it's not clear that the extra indirection you'd be giving yourself is at all worth it.
We almost always use completely explicit serializer classes for APIs that we're building.