text:
Q: How to create 3 columns in the drop-down list using jQuery UI selectMenu widget? I was given a task for creating a drop-down list consisting of 3 columns (in each row) as shown in the below image.

Now, I realized that the Selectmenu widget of the jQuery UI will fulfill my requirement and therefore, I used the following code (as given on their official documentation page).
<!doctype html>

<meta charset="utf-8">

<title>selectmenu demo</title>

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">

Select a number:

<select name="number" id="number">

<option value="1">1</option>

<option value="2" selected>2</option>

<option value="3">3</option>

<option value="4">4</option>

<option value="5">5</option>

<option value="6">6</option>

<option value="7">7</option>

<option value="8">8</option>

<option value="9">9</option>

<option value="10">10</option>

<option value="11">11</option>

<option value="12">12</option>

<option value="13">13</option>

<option value="14">14</option>

<option value="15">15</option>

<option value="16">16</option>

<option value="17">17</option>

<option value="18">18</option>

<option value="19">19</option>

</select>

The problem was that I was looking to create 3 columns instead of the 1 default column. So, I tried two options for aligning the text content inside the option tag.

*

*Putting the text inside the span tag.

*Putting the text inside a table made of one row and three columns (cells).

Given below is the code which I tried.
<option value="1">
        Apple
        Mango
        Orange
        </option>
      <option value="2" selected>

          1
          2
          3

      </option>

But this didn't fix my problem as I was getting the Output as shown in the below image.

Since I'm a beginner in HTML, CSS, and jQuery, therefore, I have no idea of what to do next for creating a drop-down list containing 3 columns in each row. Please note that I'll select the whole row consisting of all the 3 columns (as shown in the below image) and not any cell of any particular column.Can anyone kindly suggest what can be done to fix this problem and create the dropdown list as shown in the first image?

A: Firstly, we will want to create a proper HTML Structure. There is an element of select you will want to learn about: <optgroup>. Here is a basic suggested structure.

Select an Option:
<select id="options">
  <optgroup label="PREFERRED OPTIONS">
    <option value="L">Standard Screw Adjustment</option>
  </optgroup>
  <optgroup label="STANDARD OPTIONS">
    <option value="C">Tamper Resistant - Factory Set</option>
    <option value="K">Handknob</option>
  </optgroup>
  <optgroup label="ADDITIONAL OPTIONS">
    <option value="F">Hex Head Screw with Locknut</option>
  </optgroup>
</select>

This is just the start. You can use $("#options").selectmenu(); and you get a lot closer to what you want. We still need to add more elements and incorporate the extra data.

The selectmenu widget is built with the widget factory and can be extended. When extending widgets, you have the ability to override or add to the behavior of existing methods.

This is exactly what we will do, taking an example from .autocomplete(). See this example here: http://jqueryui.com/autocomplete/#categories
We will perform the same type of override within .selectmenu(). The widget factory and it's code can be a bit advanced and a bit hard to understand sometimes, so you'll have to dig through this more on your own.
HTML
Select an Option:
<select id="options">
  <optgroup label="PREFERRED OPTIONS">
    <option data-short="L" data-price="$0.00" value="L">Standard Screw Adjustment</option>
  </optgroup>
  <optgroup label="STANDARD OPTIONS">
    <option data-short="C" data-price="$5.00" value="C">Tamper Resistant - Factory Set</option>
    <option data-short="K" data-price="$6.00" value="K">Handknob</option>
  </optgroup>
  <optgroup label="ADDITIONAL OPTIONS">
    <option data-short="F" data-price="-$4.00" value="F">Hex Head Screw with Locknut</option>
  </optgroup>
</select>

What you see above is sort of extended from what we built first. I have added data attributes. They do not mean much to our HTML yet they can be useful for our jQuery. the benefit here is that if we encounter a browser that does not support JavaScript (and hence cannot load the jQuery library), the code will fall back to basic HTML Markup and still be a similar experience for the user.
CSS
.ui-selectmenu-category {
  color: #5F5F5F;
  padding: .5em .25em;
}
.ui-menu-item {
}
.ui-menu-item .ui-menu-item-wrapper {
  display: inline-block;
  padding: 1em 2px;
}

.ui-menu-item .ui-menu-item-wrapper.ui-state-active {
  border-width: 1px 0 1px 0;
  border-color: #CCCCCC;
  background-color: #E4EBF1;
  color: #000;
}

.ui-menu-item .ui-menu-item-wrapper.ui-state-active.short {
  color: #2E6D99;
}

.ui-menu-item div.ui-menu-item-wrapper {
  width: 295px;
}

.ui-menu-item .short {
  color: #2E6D99;
  font-weight: strong;
  width: 30px;
  padding-left: .5em;
}

.ui-menu-item .price {
  font-weight: strong;
  width: 75px;
  margin-right: -6px;
}

We're going to override and extend a number of theme elements for the .selectmenu(). this is all just to help make it fit the look and feel desired.
JavaScript
$(function() {
  $.widget("custom.mySelectMenu", $.ui.selectmenu, {
    _renderMenu: function(ul, items) {
      var that = this,
        currentCategory = "";
      $.each(items, function(index, item) {
        var li, name, short, price;
        if (item.optgroup != currentCategory) {
          ul.append("
" + item.optgroup + "
");
          currentCategory = item.optgroup;
        }
        li = that._renderItemData(ul, item);
        console.log(ul);
        name = li.text();
        short = item.element.data("short");
        price = item.element.data("price");
        console.log(li, short, price);
        li.prepend($("", {
          class: "short"
        }).html(short));
        li.append($("", {
          class: "price"
        }).html(price));
        if (item.optgroup) {
          li.attr("aria-label", item.optgroup + " : " + item.label);
        }
      });
    }
  });
  $("#options").mySelectMenu({
    width: 400
  });
});

Working Example: https://jsfiddle.net/Twisty/sn1z5vzn/7/
Here is where we're taking the $.ui.selectmenu and extending it to our own use. You can see we're only writing a function for the _renderMenu extension point. Everything else about the selectmenu will be carried through untouched.
This is important since we'll need to define a width option. We need to know the width so that we can create proper columns, essentially.
This will go through each of the items and create li elements to be used with the ul that is created by selectmenu. The resulting items will look like:

  L

Standard Screw Adjustment

  $0.00

jQuery UI does a lot of extra work for us, assigning unique IDs and applying hover classes, etc. Our additions allow us to style and theme different parts of each item.
The category items don't want to play well. So far, I found if I try to add any HTML element into it's li, it cannot render the rest of the menu properly. I may go back and see if _renderItem will help here.
Easy, right!? Comment if you have questions.
References

*

*Selectmenu Widget

*Autocomplete Category Demo

*HTML <optgroup> Tag

*.data()

Update
If you change your Option like so:
<option data-icon-url="https://www.gravatar.com/avatar/b3e04a46e85ad3e165d66f5d927eb609?d=monsterid&r=g&s=16" data-price="$0.00" value="L">Standard Screw Adjustment</option>

You can then update the  to use this as it's background.
CSS Snippet
.ui-menu-item .icon {
  background-repeat: no-repeat;
  background-size: 30px;
  background-position: center center;
  color: #2E6D99;
  font-weight: strong;
  width: 30px;
  padding-left: .5em;
}

JavaScript Snippet
    li.prepend($("", {
      class: "icon",
      style: "background-image: url('" + iconUrl + "')"
    }).html(" "));

The   renders a Non-breaking Space character.

A common character entity used in HTML is the non-breaking space:
A non-breaking space is a space that will not break into a new line.
Two words separated by a non-breaking space will stick together (not break into a new line). This is handy when breaking the words might be disruptive.

*

*HTML Entities
Working Example: https://jsfiddle.net/Twisty/sn1z5vzn/12/

A: That's invalid HTML and I assume most browser will ignore that.
Use an extension point if you want to change the rendering:
http://api.jqueryui.com/selectmenu/#method-_renderItem


text:
Q: scanf Cppcheck warning Cppcheck shows the following warning for scanf:

Message: scanf without field width limits can crash with huge input data. To fix this error message add a field width specifier:
    %s => %20s
    %i => %3i

Sample program that can crash:

#include
int main()
{
    int a;
    scanf("%i", &a);
    return 0;
}

To make it crash:
perl -e 'print "5"x2100000' | ./a.out

I cannot crash this program typing "huge input data". What exactly should I type to get this crash? I also don't understand the meaning of the last line in this warning:
perl -e ...

A: The last line is an example command to run to demonstrate the crash with the sample program. It essentially causes perl to print 2.100.000 times "5" and then pass this to the stdin of the program "a.out" (which is meant to be the compiled sample program).
First of all, scanf() should be used for testing only, not in real world programs due to several issues it won't handle gracefully (e.g. asking for "%i" but user inputs "12345abc" (the "abc" will stay in stdin and might cause following inputs to be filled without a chance for the user to change them).
Regarding this issue: scanf() will know it should read a integer value, however it won't know how long it can be. The pointer could point to a 16 bit integer, 32 bit integer, or a 64 bit integer or something even bigger (which it isn't aware off). Functions with a variable number of arguments (defined with ...) don't know the exact datatype of elements passed, so it has to rely on the format string (reason for the format tags to not be optional like in C# where you just number them, e.g. "{0} {1} {2}"). And without a given length it has to assume some length which might be platform dependant as well (making the function even more unsave to use).
In general, consider it possibly harmful and a starting point for buffer overflow attacks. If you'd like to secure and optimize your program, start by replacing it with alternatives.

A: I tried running the perl expression against the C program and it did crash here on Linux (segmentation fault).

A: Using of 'scanf' (or fscanf and sscanf) function in real-world applications usually is not recommended at all because it's not safe and it's usually a hole for buffer overrun if some incorrect input data will be supplied.
There are much more secure ways to input numbers in many commonly used libraries for C++ (QT, runtime libraries for Microsoft Visual C++ etc.). Probably you can find secure alternatives for "pure" C language too.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Manipular elementos HTML usando Angular 7 ¿Cómo manipular los elementos HTML utilizando angular 7?
Por ejemplo, obtener el tamaño de la ventana del navegador y asignar su tamaño a un div mostrando un mensaje con el alto y ancho del div.
import { Component, HostListener } from '@angular/core';

@Component({
  selector: 'app-ejemplo',
  template: '

'
})
export class EjemploComponent {

  alto:any;
  ancho:any;

  constructor() {
    this.getTamanos();
  }

  //Evento para obtener el tamaño de la ventana del navegador
  @HostListener('window:resize', ['$event']) getTamanos(event?) {
    this.alto = window.innerHeight;
    this.ancho = window.innerWidth;

    //A partir de aquí se le asignarían los mismos tamaños de la venta al elemento div
  }
}

A: Esto te puede ayudar
@Component({
selector: 'app-root',
template: `

width: {{ width }}

height: {{ height }}

`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'windows-event';
// si pones esta valor en 0 el valor del div sera el mismo que el de la ventana.
margin = 20;

width: string;
height: string;

constructor() {
  this.resizeDiv();
}

@HostListener('window:resize')
resizeDiv(): void {
  this.width = window.innerWidth - this.margin + 'px';
  this.height = window.innerHeight - this.margin + 'px';
}
}


text:
Q: Convert time-series data from seconds to hourly means in R Note:I have re-framed the previous question as told in the comments.
I am using three different packages,i.e, dplyr, data.table and xts to aggregate my seconds data to hourly mean representation. But, to my surprise xts behaves differently as compared to other two. Issues with xts are:

*

*Results in one extra observation as compared to other two

*Hourly mean calculated is totally different than the other two

Here is the condensed code for your testing purposes:
library(xts)
library(data.table)
library(dplyr)
t2 <- as.POSIXct(seq(from = 1438367408, to = 1440959383, by = 30), origin = "1970-01-01")
dframe <- data.frame(timestamp=t2, power=rnorm(length(t2)))
#using xts
x <- xts(dframe$power,dframe$timestamp)
h1 <- period.apply(x, endpoints(x, "hours"), mean)
h1 <- data.frame(timestamp=trunc(index(h1),'hours'), power=coredata(h1))
#using data.table
h2 <- setDT(dframe)[, list(power= mean(power)) ,(timestamp= as.POSIXct(cut(timestamp, 'hours')))]
#using dpylr
h3 <- dframe %>% group_by(timestamp= as.POSIXct(cut(timestamp, 'hour'))) %>% summarise(power=mean(power))

Outputs in regard to size:
> dim(h1)
[1] 721   2
> dim(h2)
[1] 720   2
> dim(h3)
[1] 720   2

Outputs in regard to Hourly means:
> head(h1)
            timestamp       power
1 2015-08-01 00:00:00  0.04485894
2 2015-08-01 01:00:00 -0.02299071
> head(h2) # equals to head(h2)
             timestamp       power
1: 2015-08-01 00:00:00  0.10057538
2: 2015-08-01 01:00:00 -0.07456292

Extra observation in case of h1:
> tail(h1)
              timestamp        power
719 2015-08-30 22:00:00  0.069544538
720 2015-08-30 23:00:00  0.011673835
721 2015-08-30 23:00:00 -0.053858563

Clearly for the last hour of day there are two observation. Normally, there should be only one.
My system information:
> sessionInfo()
R version 3.2.2 (2015-08-14)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.10.3 (Yosemite)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] dplyr_0.4.3      data.table_1.9.7 xts_0.9-7        zoo_1.7-12

loaded via a namespace (and not attached):
 [1] lazyeval_0.1.10 magrittr_1.5    R6_2.1.1        assertthat_0.1  parallel_3.2.2  DBI_0.3.1       tools_3.2.2
 [8] Rcpp_0.12.1     grid_3.2.2      chron_2.3-47    lattice_0.20-33

Note:

*

*Original dataset can be found at the link

*I want a solution to this issue, because in my implementation scenario xts is nearly 35 times faster than the remaining two

A: This looks like it might be a bug in endpoints because your local timezone is not a full hour offset from UTC.  I can replicate the issue if I set my local timezone to yours.
R> Sys.setenv(TZ="Asia/Kolkata")
R> x <- xts(dframe$power,dframe$timestamp)
R> h <- period.apply(x, endpoints(x, "hours"), mean)
R> head(h)
                        [,1]
2015-08-01 00:29:31 124.9055
2015-08-01 01:29:31 129.7197
2015-08-01 02:29:31 139.0899
2015-08-01 03:29:32 145.6592
2015-08-01 04:29:32 153.6840
2015-08-01 05:29:32 114.4809

Note that the endpoints are at half-hour increments, rather than at the end of the hour. This is because Asia/Kolkata is UTC+0530 and endpoints does all its calculations on times represented in UTC.
You can avoid this by explicitly setting the timezone for the POSIXct object to UTC.
require(xts)
require(dplyr)
require(data.table)
Sys.setenv(TZ="Asia/Kolkata")

dframe <- read.csv("~/ap601.csv",head=TRUE,sep=",")
# set timezone on POSIXct object
dframe$timestamp <- as.POSIXct(dframe$timestamp, tz="UTC")

#using xts
x <- xts(dframe$power, dframe$timestamp)
h <- period.apply(x, endpoints(x, "hours"), mean)
h1 <- data.frame(timestamp=trunc(index(h),'hours'), power=coredata(h))
# using data.table
h2 <- setDT(dframe)[, list(power= mean(power)) ,(timestamp= cut(timestamp, 'hour'))]
# using dplyr
h3 <- dframe %>% group_by(timestamp= cut(timestamp, 'hour')) %>% summarise(power=mean(power))

all.equal(h1$power, h2$power)  # TRUE
all.equal(h1$power, h3$power)  # TRUE

Here's a work-around to get the same results without setting the timezone for the POSIXct column to UTC. Note that this may not work for timezones with Daylight Saving Time (Asia/Kolkata does not observe any DST).
Basically, the idea is to subtract half an hour from the local time when calculating the endpoints, so that the underlying UTC time aligns on the hour.
dframe <- read.csv("~/ap601.csv",head=TRUE,sep=",")
dframe$timestamp <- as.POSIXct(dframe$timestamp)

# subtract half an hour from the index when calculating endpoints
h <- period.apply(x, endpoints(index(x)-3600*0.5, 'hours'), mean)
h1 <- data.frame(timestamp=trunc(index(h),'hours'), power=coredata(h))
all.equal(h1$power, h2$power)  # TRUE
all.equal(h1$power, h3$power)  # TRUE


text:
Q: Multiple Git Fix Up Commits I would like to make a fixup commit against a previous commit.
However that commit has already had a fixup commit made against it for another reason.
Should I make my new fixup against the last fixup commit, or can I still fixup against the original commit, essentially meaning I have 1 original commit and 2 fixup commits.

A: You can do either it shouldn't be an issue.

A: Situation you mentioned is similar to this one:
pick b7d9adb99 A
fixup 08bcd9b3d fixup for A
fixup 76014576b fixup for A
fixup 58ab94324 fixup for A

or this one:
pick b7d9adb99 A
fixup 08bcd9b3d fixup for b7d9adb99
fixup 76014576b fixup for 08bcd9b3d
fixup 58ab94324 fixup for 76014576b

So effectively it does not matter if you make fixup to 'main' commit or make 'fixup to fixup'. As a result, 'main' commit (in my case b7d9adb99) will include all of the fixup-changes and change its hash (in my case into 29074c0ec).


text:
Q: I need to reload my page for display CKEDITOR I have used CKEDITOR 4 with two homemade plugin on my project since 1 month and everything is working  well.
I tried to do a third plugin by just following the template of my last plugin and the plugin by himself is working well.
The problem is when I go to my Index view for the second time and then go to the New view where ckeditor field is. Only the CKEDITOR field doesn't appear anymore except after reloading the page. If I go out and come back again CKEDITOR will not appear until I reload the page.
There is no error or warning on the console.
If I remove the last plugin I just made it's working correctly.
But if I keep the last plugin but remove my 2nd homemade plugin it's working well too.
Now if I remove my first homemade plugin and keep the 2nd and the last one I've got the same bug.
So I guess it's something with that but I have no idea how to debug it since there is no error or warning visible.
I even don't know which code I can give you so here is the code of both plugin
2nd one:
plugin.js
CKEDITOR.plugins.add( 'linkfile', {
    icons: 'linkfile',
    lang: [ 'zh', 'en'],
    init: function( editor ) {
        editor.addCommand( 'linkfileDialog', new CKEDITOR.dialogCommand( 'linkfileDialog' ) );
        editor.ui.addButton( 'linkfile', {
                label : 'Image/video url',
            command: 'linkfileDialog',
            toolbar: 'insert'
        });

        CKEDITOR.dialog.add( 'linkfileDialog', this.path + 'dialogs/linkfile.js' );
    }
});

`dialogs/linkfile.js
CKEDITOR.dialog.add( 'linkfileDialog', function( editor ) {

    return {
                    title : 'Image/video url',
        minWidth: 400,
        minHeight: 75,
        contents: [
            {
                id: 'tab-basic',
                label: 'Basic Settings',
                elements: [
                    {
                        type: 'text',
                        id: 'linkfileURL',
                              label : 'Paste video(mp4/webm) or image (jpg/png/gif) URL',
                    }
                ]
            }
        ],
      onOk: function() {
      var dialog = this;
            var url=dialog.getValueOf( 'tab-basic', 'linkfileURL').trim();
      var fileExtension = url.split('.').pop()
      var content = '';
      var blackList = ['iplogger', '2no.co','bc.vc', 'yip.su', 'bit.do','soo.gd', '7.ly', 'tiny.cc', 'zzb.bz', 'cur.lv', 'shorte.st', 'adf', 'bit', 'biturl', 'rurl.co']
      for (i=0; blackList.length >= i; i++){
        if (url.includes(blackList[i])) {
          alert( 'Forbidden url');
                return false;
        }
      }
      if (fileExtension == "mp4" || fileExtension == "webm") {
        content = '<video style="max-height:400px;" width="100%" controls> <source src="' + url + '"type="video/mp4"></video>'
      } else if (fileExtension == "jpg" || fileExtension == "png" || fileExtension == "gif" ||
        fileExtension == "jpeg") {
        content = '<img src="' + url +'"/>';
        } else {
          alert( 'Incorrect url');
                return false;
        }
          var element = CKEDITOR.dom.element.createFromHtml(content);
          editor.insertElement(element);
        }
    };
});

and the last one
plugin.js
( function() {
    CKEDITOR.plugins.add( 'rsembbed',
        {
            lang: ['en'],
            init: function( editor )
            {
                editor.ui.addButton( 'Rsembbed',
                    {
                        label : "Twitter/instagram embbed",
                        toolbar : 'insert',
                        command : 'rsembbed',
                        icon : this.path + 'icons/rsembbed.png'
                    });

                editor.addCommand( 'rsembbed', new CKEDITOR.dialogCommand( 'rsembbedDialog' ) );
                CKEDITOR.dialog.add( 'rsembbedDialog', this.path + 'dialogs/rsembbed.js' );
            }
        });
})();

dialogs/rsembbed.js
CKEDITOR.dialog.add( 'rsembbedDialog', function( editor ) {

    return {
                    title : 'Twitter/instagram url',
        minWidth: 400,
        minHeight: 75,
        contents: [
            {
                id: 'tab-basic',
                label: 'Basic Settings',
                elements: [
                    {
                        type: 'text',
                        id: 'rsembbedURL',
                              label : 'Paste twitter or instagram URL',
                    }
                ]
            }
        ],
      onOk: function() {
        var dialog = this;
              var url=dialog.getValueOf( 'tab-basic', 'rsembbedURL').trim();
        var content = '';
        if (url.indexOf("twitter.com") > 0){
          $.ajax({
              url: "https://publish.twitter.com/oembed?url=" + url,
              type: 'GET',
              dataType: 'jsonp',
                success: function(res){
                content = res.html
                console.log(content)
                var element = CKEDITOR.dom.element.createFromHtml(content);
                editor.insertElement(element); }
            });
            }  else {
              alert( 'Incorrect url');
                    return false;
            }
          }
        };
      });

If you have any idea of a path I could explore because I'm struggling with this problem since yesterday ...

A: Did you use turbolink ?
i think your problem is turbolink:load instead of ready function
try to use
$( document ).on('turbolinks:load', () ->
  ....
)

and
$(document).on("turbolinks:before-cache", function() {
  ....
});


text:
Q: firebase database only work when read write is set to true I have created firebase database and connected it to my android app. But it only writes when read and write is set to true in security rules. It gives warning that security rules are public. How to resolve this? I think it should work when rule are set to false as I have connected my app to firebase in console using google-services.json file but it doesn't work.

A: You can add rules according to your need like this only authenticated users can access/write data
    {
    "rules":
        {
         ".read": "auth != null",
         ".write": "auth != null"
        }
    }


text:
Q: Spark in Foreach val a = sc.textFile("/user/cts367689/datagen.txt")

val b = a.map(x => (x.split(",")(0),x.split(",")(2),x.split(4))))

val c = b.filter(x => (x._3.toInt > 500))

c.foreach(x => println(x))

or
c.foreach {x => {println(x)}}

I am not getting the expected output when i use for-each statement.I want output to be print one in a line but not sure what wrong in my code.

A: I think that this have been answered already a couple of times before but here we go again and from the Official Programming Guide :
Printing elements of an RDD
One common idiom is attempting to print out the elements of an RDD using rdd.foreach(println) or rdd.map(println). On a single machine, this will generate the expected output and print all the RDD's elements.
scala> val rdd = sc.parallelize(Seq((1,2,3),(2,3,4)))
// rdd: org.apache.spark.rdd.RDD[(Int, Int, Int)] = ParallelCollectionRDD[0] at parallelize at <console>:27

scala> rdd.foreach(println)
// (1,2,3)
// (2,3,4)

However, in cluster mode, the output to stdout being called by the executors is now writing to the executor's stdout instead, not the one on the driver, so stdout on the driver won't show these!
To print all elements on the driver, one need to collect() the data back  to the driver node thus:
scala> rdd.collect().foreach(println)
// (1,2,3)
// (2,3,4)

And here is the limitation. If your data doesn't fit on the driver, this can cause the driver to run out of memory, though, because collect() fetches the entire RDD to a single machine; Thus causing your driver to blow.
If you only need to print a few elements of the RDD, a safer approach is to use the take():
scala> val rdd = sc.parallelize(Range(1, 1000000000))
// rdd: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[2] at parallelize at <console>:27

scala> rdd.take(100).foreach(println)
// 1
// 2
// 3
// 4
// 5
// 6
// 7
// 8
// 9
// 10
// [...]

PS: A small note concerning the foreach method. foreach runs a function on each element of the dataset. This method is usually done for side effects such as updating an Accumulator or interacting with external storage systems.
I hope that this answers your question.


text:
Q: What is the application name of Microsoft Excel? What is the application name of Microsoft Excel that I would use with -[NSWorkspace fullPathForApplication:] ?

A: The name and path of Excel can change, as can any application's. You might want to consider launching using its bundle ID - which is com.microsoft.Excel.

A: It's @"Microsoft Excel" (at least with office 2008):
This:
NSString *path = [[NSWorkspace sharedWorkspace] fullPathForApplication:@"Microsoft Excel"];
NSLog(@"path: %@", path);

Outputs:
2012-09-10 21:42:57.059 Craplet[2164:707] path: /Applications/Microsoft Office 2008/Microsoft Excel.app

I tried "Excel" and "MS Excel" and confirmed they return null.


text:
Q: Was there a toy called "Harry Potter Concoction"? I have scoured the Internet, but I can't find any evidence of a toy called "Harry Potter Concoction".
I have a vivid memory of a commercial that had a song with a low, deep voice and the lyrics:

Make a concoction...A Harry Potter concoction

If I remember correctly, it was similar to Creepy Crawlers
I am trying to determine if this was some sort of crazy dream or if it really existed.

A: Could you be remembering the Polyjuice Potion Maker? I'm not familiar with the commercial you mentioned, but it is conceivable that someone could sing a song like that about a potion making kit, even if the kit's name was different. I have not been able to find other Harry Potter products that involve "concocting" anything, although there is a Wizard's Potion Set available that is not official Harry Potter merchandise.

A: I am sure it was called Polyjuice Potion making kit. I used to see them on TV ads all the time!


text:
Q: Initializing class instance similar to records in F# With record types in F# you can use a syntax like this to initialize a record based on another one:
let rr3 = { defaultRecord1 with field2 = 42 }

Is there something similarly concise and elegant for non-record types as well?
I'm working with C# classes and calling their Clone() method and doing assignments to their properties using the <- operator seems a bit off. I also found this article about object expressions but it seems it isn't the thing I was looking for.
Edit: So to sum it up I'm trying to instantiate C# classes in my F# code and I'm wondering if there is some concise syntax for creating an object of a class based on another object's values just like with records in F# using the with keyword.

A: You can actually use settable properties in method calls as if they were named arguments. So if your class was implemented with a dedicated Clone method that returns the original type:
type Foo() =
    member val X = 0 with get, set
    member val Y = 0 with get, set
    member this.Clone() = new Foo(X = this.X, Y = this.Y)
    interface System.ICloneable with
        member this.Clone() = box (this.Clone())

then you would be able to do the following:
let foo1 = new Foo(X = 1, Y = 2)
let foo2 = foo1.Clone(X = 3)

But most likely your class only has the ICloneable implementation. In this case the above trick will not work out of the box, because ICloneable.Clone returns obj which doesn't have a settable X property. Fortunately, you can add the required method as an extension:
/// Original class
type Foo() =
    member val X = 0 with get, set
    member val Y = 0 with get, set
    interface System.ICloneable with
        member this.Clone() = box (new Foo(X = this.X, Y = this.Y))

let foo1 = new Foo(X = 1, Y = 2)
let foo2 = foo1.Clone(X = 3) // error FS0039: The field, constructor or member 'Clone' is not defined
let foo3 = (foo1 :> System.ICloneable).Clone(X = 3) // error FS0495: The member or object constructor 'Clone' has no argument or settable return property 'X'. The required signature is System.ICloneable.Clone() : obj.

/// Extension that makes the above trick work
type Foo with
    member this.Clone() = (this :> System.ICloneable).Clone() :?> Foo

let foo1 = new Foo(X = 1, Y = 2)
let foo2 = foo1.Clone(X = 3) // works!


text:
Q: Params hash is empty when POSTing JSON I am using the "default" create method from the scaffold:
  def create
    @user = User.new(firstname: params[:firstname], surname: params[:surname])
    respond_to do |format|
      if @user.save
        format.html { redirect_to @user, notice: 'User was successfully created.' }
        format.json { render :show, status: :created, location: @user }
      else
        format.html { render :new }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

(I know I'm not using strong parameters there, but whatever :)).
When I am sending a POST request using a very specific REST client, the params hash doesn't contain the parameters. When I look at the request.body, it contains the parameters as JSON. Also, content_type is "application/json
To fix this issue I had to had
   before_filter :fix_json_params
   [...]
   def fix_json_params
      if request.content_type == "application/json"
        @reparsed_params = JSON.parse(request.body.string).with_indifferent_access
      end
    end

    private

    def params
      @reparsed_params || super
    end

However, I don't understand why?? Why isn't rails parsing my json body correctly if content_type is correct? Any idea?
This is using rails '4.2.4'.

A: You need to configure your params_warrper.rb:
on the top of your controller put:
wrap_parameters format: [:json]

then it should automatic parse it as a JSON.


text:
Q: How to launch another project from a different solution in Visual Studio C#? I have two VS solutions A and B and I want to launch A1 project from solution A from the project B1 from solution B.
Just so you know solution A has more than one project that can be launched. I tried to added A1 as a reference in project B1 but it didn't work so well and I'm getting some error.
Does anyone know what is the correct way to do this? Thanks in advance!

A: Right click on your Solution A in solution explorer, go to Add and then click existing project. Locate the .csproj file for the project from Solution B. That project will then appear in Solution A. You can then set multiple start up projects to get it to run along side the Solution A project.
As a side note, using this method will cause the project from Solution B to build rather than just executing the last exe from the bin folder.
Hope it helps!

A: I tried different ways mentioned in the forum and found the solutions:
- Add project A1 (.exe) as a reference to project B1.
- Make sure both projects use the same platform target (x86, x64 or any) since I got an error message because they were using different.
- Then call project A1 with constructor from B1.
It might seems confusing but I got it work without using Process because someone told me it would be more complicated to use Process.
Thanks for all your replies!


text:
Q: Hypervisor load on local disks What is the I/O load on the local disk system for the host OS in XenServer? I can't find this info anywhere. As we have a SAN for the VMs themselves, can we get away with cheap controller / SATA disk in RAID-1 for the hypervisor? We won't boot from the SAN as it seems prone to problems.

A: I have never used XenServer as such, but in general, the host OS is not having to deal with disk IO much - some log writing, standard OS stuff, nothing else.
The main load is on the SAN LUNs, where the working VMs are.
I have a few hosts with KVM (under RHEV) with very old 60Gb SATA drives, but a lot of CPU cores and RAM. I haven't checked exactly, but the local drives definitely do not seem to be a bottleneck, unless you're going into swap (and you never want to swap with several VMs operating)

A: You can get away with the smallest oldest disc you can get your hands on. I would suggest a 16 / 32 gb SSD for maintenance reasons. Low power and makes no differnce to be cheap here.


text:
Q: Как использовать неопубликованный пакет? Я написал небольшой gulp-плагин для своего текущего проекта. Я не хочу его опубликовывать, т.к. он имеет смысл только в рамках моего проекта. Проблема в том, что когда я делаю что-либо с помощью npm, мой плагин удаляется из node_modules. Я попытался добавить его в package.json, но теперь при использовании npm я получаю ряд ошибкок:
npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/<название пакета> - Not found
npm ERR! 404
npm ERR! 404  '<название пакета>@^1.0.0' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

Отсюда, собственно вопрос: как мне использовать пакет, не опубликовывая его, и возможно ли это вообще?

A: В package.json можно писать пакеты со ссылкой на любой git-репозиторий, например:
"some-my-package": "git+ssh://git@example.com:smth/some-my-package.git#1.1.18"


text:
Q: UnicodeDecodeError: 'utf-16-le' codec can't decode bytes in position 138-139: illegal encoding I seem to have this problem when I try importing my data from access, sometimes it works sometimes it doesn't. How can I fix this? knowing that this is my chunk of code:

    conn = pyodbc.connect(r"DRIVER={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ=C:\Users\file.accdb; Uid=Admin; Pwd=;")
    cursor = conn.cursor()
    columns = [row.column_name for row in cursor.columns(table= table)]
    sql = 'Select * from table'
    cursor.execute(sql)
    data = pandas.DataFrame([tuple(t) for t in cursor.fetchall()])
    table = pandas.DataFrame(data)
    table.columns = columns
    conn.close()

A: You have encountered a known issue with the Access ODBC driver, described here:
https://github.com/mkleehammer/pyodbc/wiki/Tips-and-Tricks-by-Database-Platform#unicodedecodeerror-when-calling-cursorcolumns
One possible workaround is to use an output converter function as illustrated here:
def decode_sketchy_utf16(raw_bytes):
    s = raw_bytes.decode("utf-16le", "ignore")
    try:
        n = s.index('\u0000')
        s = s[:n]  # respect null terminator
    except ValueError:
        pass
    return s

# …

prev_converter = cnxn.get_output_converter(pyodbc.SQL_WVARCHAR)
cnxn.add_output_converter(pyodbc.SQL_WVARCHAR, decode_sketchy_utf16)
col_info = crsr.columns("Clients").fetchall()
cnxn.add_output_converter(pyodbc.SQL_WVARCHAR, prev_converter)  # restore previous behaviour


text:
Q: How do I declare an array of functions? This is part of a CMD Prompt Calc:
1) it display options with 0 - 9
2) user enters number that matches the function they want
Rather then having 10:case i: //do stuff here
can I have an array containing the functions;
functionArrayName = [(float cosx(float _cx);), (float sinx(float _sx);) ... etc ]

then have a for loop:
for(int i = 0; i < 10; ++i){
if(i = userInput){
   //call the function in functionArrayName[i];
}}

A: Ugly but, hey, it's what you asked for...
float (*arr[])(float) = { cosf, sinf,...};
...
float result = arr[i]();

A: You appear to come from a more "flexible" language, BTW.
Anyway, your code has several errors:
First, what matters most:
functionArrayName = [(float cosx(float _cx);), (float sinx(float _sx);) ... etc ]

Shall actually be:
#include <array>
#include <functional>

// ...

std::array<std::function<float(float)>> functionArrayName;

Note that this std::array will only be able to hold function(-like) objects that return a float and take a single float argument.
Secondly...
if(user = input) {

Shall (in most cases) be:
if(user == input) {

Although (in some cases only), that expression was valid, it usually indicates a misunderstanding of comparison operators.
Hope this helps!

A: The following is similar in spirit to what you asked for, but using modern C++
#include <functional>

extern float cosx(float);
extern float sinx(float);
// ... add more

std::function<float(float)> functionArray[] = {cosx, sinx, /*... add more */};

int main() {
  int userInput = 0;
  float x = 3.14159/2;

  float y = functionArray[userInput](x);
}


text:
Q: I need to make a JFrame or a JDialog that even if you change window it stays focused so that the keylistener will listen I need to have a frame or dialog that stays focused even if I change window.
I am building an AutoClicker and it needs while it's clicking in another window to listen to my keyListener so that the user will be able to start/stop it.
    d.setModalityType(ModalityType.APPLICATION_MODAL);// d is my JDialog
    d.addKeyListener(this);
    d.setAlwaysOnTop(true);
    d.toFront();
    d.requestFocus();

    d.setFocusableWindowState(true);

    d.setFocusable(true);


text:
Q: How make dns queries in dns-python as dig (with additional records section)? I trying use dns python and want get all records with ANY type query:
import dns.name
import dns.message
import dns.query

domain = 'google.com'
name_server = '8.8.8.8'

domain = dns.name.from_text(domain)
if not domain.is_absolute():
    domain = domain.concatenate(dns.name.root)

request = dns.message.make_query(domain, dns.rdatatype.ANY)

response = dns.query.udp(request, name_server)
print response.answer
print response.additional
print response.authority

but it return me
[]
[]
[]

When I try make this request with dig:
$ dig @8.8.8.8  google.com -t ANY

; <<>> DiG 9.9.2-P1 <<>> @8.8.8.8 google.com -t ANY
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 2848
;; flags: qr rd ra; QUERY: 1, ANSWER: 25, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;google.com.            IN  ANY

;; ANSWER SECTION:
google.com.     299 IN  A   173.194.40.14
google.com.     299 IN  A   173.194.40.1
google.com.     299 IN  A   173.194.40.7
google.com.     299 IN  A   173.194.40.4
google.com.     299 IN  A   173.194.40.3
google.com.     299 IN  A   173.194.40.0
google.com.     299 IN  A   173.194.40.8
google.com.     299 IN  A   173.194.40.6
google.com.     299 IN  A   173.194.40.5
google.com.     299 IN  A   173.194.40.2
google.com.     299 IN  A   173.194.40.9
google.com.     299 IN  AAAA    2a00:1450:4002:804::1000
google.com.     21599   IN  TYPE257 \# 23 0009697373756577696C6473796D616E7465632E636F6D
google.com.     21599   IN  TYPE257 \# 19 0005697373756573796D616E7465632E636F6D
google.com.     21599   IN  NS  ns2.google.com.
google.com.     21599   IN  NS  ns3.google.com.
google.com.     599 IN  MX  50 alt4.aspmx.l.google.com.
google.com.     599 IN  MX  10 aspmx.l.google.com.
google.com.     3599    IN  TXT "v=spf1 include:_spf.google.com ip4:216.73.93.70/31 ip4:216.73.93.72/31 ~all"
google.com.     599 IN  MX  20 alt1.aspmx.l.google.com.
google.com.     21599   IN  SOA ns1.google.com. dns-admin.google.com. 2013070800 7200 1800 1209600 300
google.com.     599 IN  MX  30 alt2.aspmx.l.google.com.
google.com.     21599   IN  NS  ns1.google.com.
google.com.     599 IN  MX  40 alt3.aspmx.l.google.com.
google.com.     21599   IN  NS  ns4.google.com.

;; Query time: 52 msec
;; SERVER: 8.8.8.8#53(8.8.8.8)
;; WHEN: Tue Jul 16 18:23:46 2013
;; MSG SIZE  rcvd: 623

When I check requests with wireshark then found that dig and dns python have different requests:
dig:
0000  c8 64 c7 3a e3 40 50 46  5d a5 70 99 08 00 45 00   .d.:.@PF ].p...E.
0010  00 43 9f 60 00 00 40 11  09 8f c0 a8 01 03 08 08   .C.`..@. ........
0020  08 08 8e 9e 00 35 00 2f  71 cf ef 49 01 20 00 01   .....5./ q..I. ..
0030  00 00 00 00 00 01 06 67  6f 6f 67 6c 65 03 63 6f   .......g oogle.co
0040  6d 00 00 ff 00 01 00 00  29 10 00 00 00 00 00 00   m....... ).......
0050  00

dns python:
0000  c8 64 c7 3a e3 40 50 46  5d a5 70 99 08 00 45 00   .d.:.@PF ].p...E.
0010  00 38 00 00 40 00 40 11  68 fa c0 a8 01 03 08 08   .8..@.@. h.......
0020  08 08 b8 62 00 35 00 24  23 6b 3d 31 01 00 00 01   ...b.5.$ #k=1....
0030  00 00 00 00 00 00 06 67  6f 6f 67 6c 65 03 63 6f   .......g oogle.co
0040  6d 00 00 ff 00 01                                  m.....

For DNS query section:
dig have AD bit: Set flag:
002C-002D: 01 20 for dig and 01 00 for dns python
and this Additional records section that except for dns-python:
0046-0050: 00 00  29 10 00 00 00 00 00 00  00.
This actual also not only for google.com also for logitech.com mayby other.
So how can I make requests with dns python as dig with this additional section?

A: I found solution, I made request as dig:
import dns.name
import dns.message
import dns.query
import dns.flags

domain = 'google.com'
name_server = '8.8.8.8'
ADDITIONAL_RDCLASS = 65535

domain = dns.name.from_text(domain)
if not domain.is_absolute():
    domain = domain.concatenate(dns.name.root)

request = dns.message.make_query(domain, dns.rdatatype.ANY)
request.flags |= dns.flags.AD
request.find_rrset(request.additional, dns.name.root, ADDITIONAL_RDCLASS,
                   dns.rdatatype.OPT, create=True, force_unique=True)
response = dns.query.udp(request, name_server)

print response.answer
print response.additional
print response.authority

With ADDITIONAL_RDCLASS = 4096 like dig all work too, but I set it full to be on the safe side.
and it works pretty good.


text:
Q: how to get notification counter on every change in db here i use sql dependancy method for changeing db:
    1. i want get notification counter like fb on every change in db
  public static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
           {
            if (e.Type == SqlNotificationType.Change)
            {

                 SqlDependency sqlDep = sender as SqlDependency;
                 sqlDep.OnChange -= dependency_OnChange;
                //  string message="added";
               GlobalHost.ConnectionManager.GetHubContext<MyHub>();
                 context.Clients.All.notify("added");
                // from here we will send notification message to client

            }

        }

here is my jquery code where i want to get notification counter:
but code is not working and string value is not handled from sqldependancy method.
$(function()
              {

              // Proxy created on the fly
              var job = $.connection.myHub;

              // Declare a function on the job hub so the server can invoke it
              job.client.notify = function (message) {
                //

                if (message && message.toLowerCase() == "added") {
                      updateNotificationCount();
                   }

              };
              // Start the connection

                $.connection.hub.start();
                updateNotificationCount();
          });

              function updateNotificationCount() {
                  var count = 10;
                  count = parseInt($('#noti_Counter').html()) || 0;
                  count++;
                  $('#noti_Counter')
              .css({ opacity: 0 })
              .text(function () {
                  return "" + count + "";
              })
                   // ADD DYNAMIC VALUE (YOU CAN EXTRACT DATA FROM DATABASE OR XML).
              .css({ top: '-10px' })
               //.append('' + count + '')
              .animate({ top: '-2px', opacity: 1 }, 500);
              }


text:
Q: Attempted to read or write protected memory. C++ dll imported to C# i have one dll that i build in C++ and one software that i built in C# - windows forms.
When i am calling to the dll via C# i got an fatal exception:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
Here is the call:
    [DllImport("dlltest.dll")]
    [return: MarshalAs(UnmanagedType.SafeArray)]
    private extern static string[] getFiles(string directory, string fileFilter, bool recrusive);

Here is the code from my DLL source:
extern "C" __declspec(dllexport) LPSAFEARRAY getFiles(string directory, std::string fileFilter, bool recrusive);

LPSAFEARRAY getFiles(string directory, std::string fileFilter, bool recrusive)
{
       std::vector<std::string> filesArray;

if (recrusive)
    getFilesByDirs(directory, fileFilter, false);

directory += "\\";

WIN32_FIND_DATAA FindFileData;
HANDLE hFind = INVALID_HANDLE_VALUE;

std::string filter = directory + (recrusive ? "*" : fileFilter);

hFind = FindFirstFileA(filter.c_str(), &FindFileData);

if (hFind == INVALID_HANDLE_VALUE)
{

}
else
{
    if (!recrusive)
    {
        if(isGoodForUs(directory + std::string(FindFileData.cFileName)))
        {
            filesArray.push_back(directory + std::string(FindFileData.cFileName));
        }
    }

    while (FindNextFileA(hFind, &FindFileData) != 0)
    {
        if (!recrusive)
        {
            if(!isGoodForUs(directory + std::string(FindFileData.cFileName))) continue;
                filesArray.push_back(directory + std::string(FindFileData.cFileName));
        }
        else
        {
            if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)>0 && FindFileData.cFileName[0]!='.')
            {
                if(!isGoodForUs(directory + std::string(FindFileData.cFileName))) continue;
                    filesArray.push_back(directory + std::string(FindFileData.cFileName));
            }
        }
    }
}

CComSafeArray<BSTR> a(filesArray.size());

std::vector<std::string>::const_iterator it;
int i = 0;
for (it = filesArray.begin(); it != filesArray.end(); ++it, ++i)
{
    a.SetAt(i, A2BSTR_EX((*it).c_str()), FALSE);
}
return a.Detach();
}

Anyone know what is the problem?

A: The real question is why are you not using the .Net method that is the equivalent of your GetFiles() call
Directory.GetFiles Method (String path, String searchPattern, SearchOption searchOption)

You avoid degugging C++ code, the extra deployment issues and the execution penalty for switch between managed and unmanaged code.
EDIT ADDED
When you want to revert to using your C++ DLL from C# the most painless method if to create a C++ wrapper class that makes this as simple as possible. Microsoft recommends this over "platform invoke" that your were attempting to use (and ran into problems because of the std::string classes).
First, see this  MSDN article for an overview of C#/C++ Interopability. Second, this articlegive a quick example of C++ class wrapping. Microsoft refers to using a C++ wrapping class at the method that "just works".
Having done lots of cross-platform programming in C, and C++ I have to wish you best of luck, it requires lots of effort to get it right. Since you are using C++ apparently as your cross platform interop layer, you  would be well advised to create across-platform library for your interop code (keeping it separate from your application code). And second, create extern C interfaces to your interop as much as possible. This is really the "universal " calling format, no problems with name mangling, etc. A second question is how much interop do you need? Basic Files and Directories are not too hard. Sockets are another set of issues. Multithreading are another. I've used ACE before, it is C++ all the way, been around for a long time -- but it is a very powerful C++ interop library (among other things).


text:
Q: What is JBPM? Why use it? I am java developer. I am developing a new application. In this application am going to integrate JBPM, spring and hibernate also.
So please, answer my below questions,

*

*what is JBPM?

*Why use it?

*What is workflow engine?

please give any example.
Thanks for your answer.

A: *

*JBPM is a good word for IT managers, a nightmare for programmers.

*Do not use it. Jbpm full with bugs..

*A workflow engine: https://en.wikipedia.org/wiki/Workflow_engine

A: Quoting from wikipedia:

jBPM is an open-source workflow engine written in Java that can execute business processes described in BPMN 2.0 (or its own process definition language jPDL in earlier versions). It is released under the ASL (or LGPL in earlier versions) by the JBoss community.

For complete information you can check this out.
Quoting from wikipedia:

A workflow engine is a software application that defines a process, the rules governing process decisions, and routes information. It is a key component in workflow technology and typically makes use of a database server.

The relationship:
jBpm is a flexible, extensible workflow management system. Business processes , expressed in a simple and powerfull language and packaged in process archives, serve as input for the jBpm runtime server. jBpm bridges the gap between managers and developers by giving them a common language : the jBpm Process definition language (jPdl).


text:
Q: Like Button counts the likes of a PDF but does not actually post the activity? I have implemented a Like Button on a page, attempting to allow users to "Recommend" a PDF.  The button appears on the page and seems to function correctly.  Clicking the button opens the comment box; and a user can enter a comment.  However no activity is actually posted on the test user's page.  The counter even increments correctly and the "recommend" action is disabled after the test user has clicked it.  This status is remembered on reload, and the counter is never reset.

Can this button not be applied to this type of resource (PDF)?

A: Well the PDF can't possible have the meta tags used by Facebook to display a story about that URL - when you put the URL into Facebook's Debug Tool you'll see.
You probably should/could have pointed the Like plugin at a URL which has a download link (or redirect) to the PDF, not to the PDF URL itself


text:
Q: NVIDIA Installer Failed - How to upgrade from CUDA 5.0 to CUDA 5.5? I have CUDA 5.0 and need to upgrade to CUDA 5.5. When I run the CUDA 5.5 Installer (default settings), it fails during installation of the CUDA Toolkit, and displays a dialog box with the following message:
"NVIDIA Installer Failed."
If I close the installer and try again, I get a different error:
"NVIDIA Installer Cannot Continue: Required Files Are Missing."
If I reboot and try again, I get the first message once again.
Is there a driver for 5.0 I need to uninstall for 5.5 to install? Any help is appreciated.
I'm using Windows 7 64-bit.

A: Try this link
https://devtalk.nvidia.com/default/topic/572372/cuda-5-5-toolkit-install-fails-on-windows-7-possibly-solved-/
Alternatively, during installation, click custom installation, notice that some package are unavailable example "Cuda samples" etc, un-check those package that are not available.
Not sure why this answer insisted "must be at least 30 characters".


text:
Q: Prime Ideal Properly Contained in principal Ideal.
a) For all $p \in P, p=ar, r \in R.$ Since, $P$ is prime and $P\neq (a) \Rightarrow r\in P.$ For all $x \in aP, x=ap$ Since $P$ is an ideal $\Rightarrow ap \in P $
b) $\forall i$ $1\leq i\leq n$ $ a_i=ap_i=a(a_1r_{i1}+...+a_nr_{in}) \Rightarrow 0=a_1(-ar_{i1})+...+a_i(1-ar_{ii})+a_n(-r_{in})$
Hence, the $r_{ij}$'s are the entries on the matrix.
c) This is the part that I'm stuck at. I can't seem to find the required element. I know it satisfies $(1-ab)*a_i=0$. But I can't proceed any further.
d) Follows easily from (c).
Any hints or solutions?

A: It seems only (c) has some difficulty for you.
denote $A^*$ be the adjoint matrix for $A$.Since $AP=0$ we get $A^*AP=0$.that is $det(A)IP=0$ where $I$ is the unit matrix.remark $det(A)=1-ab$ for some $b$.Hence you can get the result.


text:
Q: Can Internet Explorer bind events to absolute positioned elements? Can Internet Explorer bind events to absolute positioned elements ?
I can't bind a "click" to an element that is overlapping another.
Have tried loads of different ways, here a few tests that don't work in IE:
//version 1:
$(".classHolder").click(function(){ alert( $(this).html() );  });

//version 2:
$(".classHolder").each(function(){ $(this).click(function(){ alert( $(this).html() );  }); });

//version 3:
$("#id3").click(function(){ alert( $(this).html() ); });

//version 4:
$("#id3").click(function(){ alert( $(this).html() ); });
$("#id3").trigger("click");

// in all trials I tested with and without:
// $("img").unbind();
// $("div").unbind();
// just to make sure no "ghost" events were bind into the elements but no success.

G

L

asd asdf asdfg

A: SOLUTION:
added "background-color:#FFFFFF;" to the element style.
and used the wacky function:

function setOpacity(obj,value){
  obj.style.opacity=value/10;
  obj.style.filter='alpha(opacity='+value*10+')';
}

and finally, when binding the evento to the element:

   $("div.classHolder").each(function(){
      $(this).bind("click",function(e){ alert($(this).html()); });
      setOpacity(this,0);
   });

A: Just had the same problem. Resolved with css.
Added this "hack" in my element style definition :
background-color:#ffffff;
filter: alpha(opacity=1);
opacity: 0.01;

Tested in firefox 4, IE 7 and latest safari

A: I don't know if this is necessarily your problem or not, but have you tried changing your "type" attribute to "text/javascript" instead of "application/javascript"? Again, this may have 0 effect. But then again, IE is quirky.

A: Two issues:
1) As someone else pointed out, IE is ignoring the script without the type set to "text/javascript"
2) When the element is absolute positioned, the click events only fire if the mouse is over "content" in the abs div. In this case, the text content like the G letter. You can set a background-color to allow clicks anywhere in the div. Alternatively, you can set a very large font-size and just put a   in the element with overflow:hidden to allow it to be transparent, but still process clicks on the whole element.
Here is a modified version of your example:

asd asdf asdfg


text:
Q: Button events inside UIWebView I want to have a on top of uiwebview, which will scroll out of view as I scroll webview downward. The problem is I am not able to raise/handle the button touchupinside event from the viewcontroller. My guess is webview is eating the event. How can I make the button raise events?
One solution is to have a subview containing the button and then have this and the webview inside a scrollview. However this has its own problems and more so because my webpage has expandable sections inside it.
I am currently adding the button as subview inside documentview of the uiwebview, so it scrolls out of view.
Any help in this regard will be appreciated. Thanks.

A: It's a WebView, so if you're button is actually on the webpage, just use a simple Name attribute on the anchor tag.
If it's not, and it's a UIButton event you are trying to listen to, chances are you wired something up incorrectly with your IBOutlets and IBActions.  To send a message to a UIWebView to make it scroll, you can send the stringByEvaluatingJavaScriptFromString: message which will call javascript inside your page.  Check out the docs for details.


text:
Q: Reduce size and framerate of output GIFs from AWS Elastic Transcoder I have a Lambda function setup that successfully creates an Elastic Transcoding job to transcode an m4v to a GIF. However, I need to reduce the file size of the ouptut GIF by both reducing the size of the content, and using fewer frames.
I have read through the documentation here:
http://docs.aws.amazon.com/elastictranscoder/latest/developerguide/preset-settings.html
http://docs.aws.amazon.com/elastictranscoder/latest/developerguide/create-job.html
but I can't find any settings that work for GIFs that will downscale the content or allow me to change the framerate.
I tried using Width, Height, and Resolution but they all gave me errors that said: UnexpectedParameter: Unexpected key
How can I change the size and framerate of the output?
Here is the code that runs successfully:
var params = {
  Input: {
    Key: key
  },
  PipelineId: 'xxxx',
  Outputs: [
    {
      Key: outputKey(basename(key),'gif'),
      PresetId: '1351620000001-100200', // GIF (Animated)
      Composition: [
          {
              TimeSpan: {
                  Duration: '00:00:03.000'
              }
          }
      ]
    }
  ]
};

A: To change these settings, you need to create a new Preset

*

*Visit https://console.aws.amazon.com/elastictranscoder/home#presets:

*find the GIF (Animated) preset, select it and click 'Copy'

*Specify Width / Height / Bit Rate / Frame Rate in the Video section of your new custom preset

*update the PresetId value in your output to match your new preset's id


text:
Q: Counting in recursion calls I need to write a method that checks how many possible ways there are to finish a grid (a 2D array).
the movement inside the grid is like this:
start with [0][0] take the number inside there (for instance 14) then go to either
[array.[0][0]%10][array.[0][0]/10] or [array.[0][0]/10][array.[0][0]%10]
for our example:
[1][4] or [4][1]
until you get to the end of the array (bottom right corner).
I can get to the end of the array (all possible ways) - my problem is to count how many times I actually finished the array - I can not use a variable outside of the method, and the method has to be recursive.
this is the code :
private static int howMany(int[][] array, int y, int x, int count) {
    if(y+(array[y][x]%10) < array.length && x+(array[y][x]/10)< array[y].length && array[y][x]!=0) {
        System.out.println("["+y+"]["+x+"] is: "+array[y][x]);
        howMany(array, y+(array[y][x]%10), x+(array[y][x]/10),count);
    }
    if(y+(array[y][x]/10) < array.length && x+(array[y][x]%10)< array[y].length && array[y][x]!=0) {
         System.out.println("["+y+"]["+x+"] is: "+array[y][x]);
         howMany(array, y+(array[y][x]/10), x+(array[y][x]%10),count);
    }
    if(y==array.length-1 && x==array[y].length-1) count++;
    return count;
}

this is obviously wrong and will return what count was in the first place, I tried many other ways but to no avail...
here's the full class (with an array to test):
link to full class
edit: a big Thanks to everyone for their help!

A: The count is already returned from each call to howMany. I think you just need to save it:
count = howMany(array, y + (array[y][x] % 10), x + (array[y][x] / 10), count);

Do this inside both if blocks. I made this change in your linked code and got the expected result (3).

A: Return 1 if you've reached the end of the array (bottom right corner) and 1+howMany(array, newY, newX) otherwise. You don't need to keep the count and pass it every time. The function will work so:
1 + returned value of 2nd call =
1 + 1 + returned value of 3rd call =
1 + 1 + 1 +  returned value of 4th call =... and so on.
Finally as result you'll get number of calls which is what you want.

A: You are already on the right track, since your method signature returns an int. You should define a variable to hold the count, increment it for the primary recursive call, and add to it the result of the recursive method itself. Passing the count into the each recursive call is unnecessary and should be removed.


text:
Q: Change output shape of two merged layers in Keras I am trying to create a model for argument mining, which takes two sentences as input and return a single output, whether the two are neural, disagreeing or agreeing. The model is build with two bidirectional LSTM layers which get merged into a single layer, Model can be seen here. The problem is that the output layers shape is (timestamps, label) where I would like it to be a single output of shape (1, label).
    LstmLayer = LSTM(32, activation='tanh', return_sequences=False)
    left_input = Input(shape=(1000,), dtype='float32', name='left_input')
    right_input = Input(shape=(1000,), dtype='float32', name='right_input')

    left = Embedding(len(self.word_index) + 1,
                     100,
                     weights=[self.embeddingMatrix],
                     input_length=1000,
                     trainable=False)(left_input)
    left = Bidirectional(LstmLayer, merge_mode='concat')(left)

    right = Embedding(len(self.word_index) + 1,
                     100,
                     weights=[self.embeddingMatrix],
                     input_length=1000,
                     trainable=False)(right_input)
    right = Bidirectional(LstmLayer, merge_mode='concat')(right)

    merged = kl.concatenate([left, right], axis=1)
    merged = Dense(32, activation='tanh')(merged)
    main_output = Dense(self.OUTPUT_SIZE, activation='softmax', name='main_output')(merged)
    self.model = Model(inputs=[left_input, right_input], outputs=[main_output])

The summary of the model can be seen below:
    Layer (type)                     Output Shape      Param #         Connected to
    =====================================================================
    left_input (InputLayer)         (None, 1000)         0
    right_input (InputLayer)        (None, 1000)         0
    embedding_1 (Embedding)         (None, 1000, 100)    629600      left_input[0][0]
    embedding_2 (Embedding)         (None, 1000, 100)    629600      right_input[0][0]
    bidirectional_1 (Bidirectional) (None, 64)           34048       embedding_1[0][0]
    bidirectional_2 (Bidirectional) (None, 64)           34048       embedding_2[0][0]
    concatenate_1 (Concatenate)     (None, 128)          0           bidirectional_1[0][0]
                                                                     bidirectional_2[0][0]
    dense_1 (Dense)                 (None, 32)           4128        concatenate_1[0][0]
    main_output (Dense)             (None, 3)            99          dense_1[0][0]
    ======================================================================
    Total params: 1,331,523
    Trainable params: 72,323
    Non-trainable params: 1,259,200

The prediction function encodes the two sentences to the same length, and tokenize them with the pre-trained tokenizer which the model used.
 pred = self.model.predict([self._encode_sentences(sentence1), self._encode_sentences(sentence2)])
    return pred

If i predict on ("I am looking at a dog", "I am looking at a cat"), the output shape is (21,3)

A: What you probably want:

I would like it to be a single output of shape (1, label).

You can obtain it getting the last output in the output sequence i.e result_matrix[-1].
pred = self.model.predict([self._encode_sentences(sentence1), self._encode_sentences(sentence2)])
return pred[-1]

as this is the last state of model prediction with any of the given two input sentences.


text:
Q: Using WebEX API with PHP I am a beginner to using Webex API. I went through the documentation and couple of links(How can I use the WebEx URL/XML API to register a user for an event?) for an understanding of how it works. But while trying to use it, I get some errors and I am not receiving the intended result. If someone could give me a brief introduction on how it works, it would be great.
I want to access the login page in the webex API. By documentation, it goes of the name (p.php?AT=LI) and I tried to access the same using WebEX ID and Password which are the mandatory fields(as given in the documentation), I did not include the back URL. While giving this thing, I am receiving this error AT=LI&ST=FAIL&RS=UnknownATCommand.
Also I have these details. I have WebEX username, password, site ID and Partner ID. By WebEX ID, what does it mean ? Does WebEX ID and Partner ID one and the same?
Any help on this topic is highly appreciable.
Thanks & Regads,
Ramkumar

A: if you want to use Webex Xml API,
Your XML headers must have these elements
<header>
        <securityContext>
            <siteID>xxxx</siteID>
            <webExID>siteadmin</webExID>
            <password>password</password>
        </securityContext>
    </header>
I think you use URL API, its different


text:
Q: change opened link color with JS & CSS Good day, i want to change opened link color. Here is my code:
CSS
a {color: #fff; font-size: 19px; padding-right:25px;
 }
a:link {color: #fff;
 }
a:visited {
 }
 a:hover {  color: #000;

}
 a:active { color: #000;
}

.active {color:#000;}

JS
$(document).ready(function(){
       $("a.nav1").click(function () {
          // switch all tabs off
          $(".active").removeClass("active");
          // switch this tab on
          $(this).addClass("active");
       });
    });

Link example

Home

This work but padding-right:25px; reorganize my slideshow. I need to use it with #navigation
#navigation a {color: #fff; font-size: 19px;     padding-right:25px;
 }
#navigation a:link {color: #fff;
 }
#navigation a:visited {
 }
#navigation a:hover {   color: #000;

}
#navigation a:active {  color: #000;
}

.active {color:#000;}

But when i use #navigation JS script do not change color opened link to black. If i miss out #navigation a and use only #navigation a link, ... default color of links is violet (no color defined in #navigation a:link ).
I tried to change opened link color with
 .currentLink {
       color: #640200;
       background-color: #000000;
    }

It does not work.

A: try changing
#navigation a:active {  color: #000; }
to
#navigation a.active {  color: #000; }


text:
Q: How to skip controller actions in case of authorization is not succeed in ZF2 I am implementing REST API on ZF2. Now I need to check authorization token on Module.php and return with error if authorization failed. But I did not know how to return response from Module.php.
I wrote code to check authorization in DISPATCH Event of onBootstrap. Now how to return error from Module.php without accessing controllers if authorization failed. As only exit function/call make possible to return without accessing controller. But In that case I did not getting any response. Using json_encode(array) is not look like a standard as I am already enabled ViewJsonStrategy and using JsonModel in controllers.

A: You can shortcircuit the event by having your listener return a response, eg...
public function onBootstrap(EventInterface $e)
{
    $eventManager = $e->getApplication()->getEventManager();
    // attach dispatch listener
    $eventManager->attach('dispatch', function($e) {
        // do your auth checks...
        if (!$allowed) {
            // get response from event
            $response = $e->getResponse();
            // set status 403 (forbidden)
            $response->setStatusCode(403);
            // shortcircuit by returning response
            return $response;
        }
    });
}


text:
Q: PyTorch broadcasting: how this worked? I'm new to Deep Learning. I'm studying from Udacity.
I came across one of the codes to build up a neural network, where 2 tensors are being added, specifically the 'bias' tensor with the output of the tensor-multiplication product.
It was kind of...
def activation(x):
return (1/(1+torch.exp(-x)))

inputs = images.view(images.shape[0], -1)
w1 = torch.randn(784, 256)
b1 = torch.randn(256)
h = activation(torch.mm(inputs,w1) + b1)

After flattening the MNIST, it came out as [64,784] (inputs).
I'm not getting how the bias tensor (b1) of dimension [256], could be added to the multiplication product of 'inputs' and 'w1' which comes out to be the dimensions of [256, 64].

A: In simple terms, whenever we use "broadcasting" from a Python library (Numpy or PyTorch), what we are doing is treating our arrays (weight, bias) dimensionally compatible.
In other words, if you are operating with W of shape [256,64], and your bias is only [256]. Then, broadcasting will complete that lacking dimension.

As you can see in the image above, the dimension left is being filled so that our operations can be done successfully. Hope this is helpful

A: 64 is your batch size, meaning that the bias tensor will be added to each of the 64 examples inside of your batch. Basically it's like if you took 64 tensor of size 256 and added the bias to each of them. Pytorch will naturally broadcast the 256 tensor to a 64*256 size that can be added to the 64*256 output of your precedent layer.

A: This is something called PyTorch broadcasting.
It is very similar to NumPy broadcasting if you used the library.
Here is the example adding a scalar to a 2D tensor m.
m = torch.rand(3,3)
print(m)
s=1
print(m+s)

# tensor([[0.2616, 0.4726, 0.1077],
#         [0.0097, 0.1070, 0.7539],
#         [0.9406, 0.1967, 0.1249]])
# tensor([[1.2616, 1.4726, 1.1077],
#         [1.0097, 1.1070, 1.7539],
#         [1.9406, 1.1967, 1.1249]])

Here is the another example adding 1D tensor and 2D tensor.
v = torch.rand(3)
print(v)
print(m+v)

# tensor([0.2346, 0.9966, 0.0266])
# tensor([[0.4962, 1.4691, 0.1343],
#         [0.2442, 1.1035, 0.7805],
#         [1.1752, 1.1932, 0.1514]])

I rewrote your example:
def activation(x):
    return (1/(1+torch.exp(-x)))

images = torch.randn(3,28,28)
inputs = images.view(images.shape[0], -1)
print("INPUTS:", inputs.shape)

W1 = torch.randn(784, 256)
print("W1:", w1.shape)
B1 = torch.randn(256)
print("B1:", b1.shape)
h = activation(torch.mm(inputs,W1) + B1)

Out
INPUTS: torch.Size([3, 784])
W1: torch.Size([784, 256])
B1: torch.Size([256])

To explain:
INPUTS: of size [3, 784] @ W1: of size [784, 256] will create tensor of size [3, 256]
Then the addition:
After mm: [3, 256] + B1: [256] is done because B1 will take the shape of [3, 256] based on broadcasting.


text:
Q: VB.NET Graphics.DrawString Resize font to fit container with word wrap I took the following example from MSDN and converted it to VB. Then adjusted it to try to take the height of the container into consideration to allow for word wrapping.
public Font GetAdjustedFont(Graphics GraphicRef, string GraphicString, Font OriginalFont, int ContainerWidth, int MaxFontSize, int MinFontSize, bool SmallestOnFail)
{
// We utilize MeasureString which we get via a control instance
for (int AdjustedSize = MaxFontSize; AdjustedSize >= MinFontSize; AdjustedSize--)
{
  Font TestFont = new Font(OriginalFont.Name, AdjustedSize, OriginalFont.Style);

  // Test the string with the new size
  SizeF AdjustedSizeNew = GraphicRef.MeasureString(GraphicString, TestFont);

  if (ContainerWidth > Convert.ToInt32(AdjustedSizeNew.Width))
  {
// Good font, return it
     return TestFont;
  }
}

// If you get here there was no fontsize that worked
// return MinimumSize or Original?
if (SmallestOnFail)
{
  return new Font(OriginalFont.Name,MinFontSize,OriginalFont.Style);
}
else
{
  return OriginalFont;
}
}

Here's what I have:
Protected Overrides Sub OnPaint(e As PaintEventArgs)
    MyBase.OnPaint(e)

    Dim drawFont As New System.Drawing.Font(SystemFonts.DefaultFont.Name, 16)
    Dim drawBrush As New System.Drawing.SolidBrush(Me.ForeColor)
    Dim drawFormat As New System.Drawing.StringFormat

    drawFont = GetAdjustedFont(e.Graphics, noticeText, drawFont, RectangleF.op_Implicit(ClientRectangle), 40, 8, True)

    e.Graphics.DrawString(noticeText, drawFont, drawBrush, RectangleF.op_Implicit(ClientRectangle))

    drawFont.Dispose()
    drawBrush.Dispose()

End Sub

Public Function GetAdjustedFont(ByRef GraphicRef As Graphics, ByVal GraphicString As String, ByVal OriginalFont As Font, ByVal ContainerSize As RectangleF, ByVal MaxFontSize As Integer, ByVal MinFontSize As Integer, ByVal SmallestOnFail As Boolean) As Font

    ' We utilize MeasureString which we get via a control instance
    For AdjustedSize As Integer = MaxFontSize To MinFontSize Step -1

        Dim TestFont = New Font(OriginalFont.Name, AdjustedSize, OriginalFont.Style)

        ' Test the string with the new size
        Dim AdjustedSizeNew = GraphicRef.MeasureString(GraphicString, TestFont, ContainerSize.Size)

        If ContainerSize.Width > Convert.ToInt32(AdjustedSizeNew.Width) Then
            If ContainerSize.Height > Convert.ToInt32(AdjustedSizeNew.Height) Then
                ' Good font, return it
                Return TestFont
            End If
        End If
    Next

    ' If you get here there was no fontsize that worked
    ' return MinimumSize or Original?
    If SmallestOnFail Then
        Return New Font(OriginalFont.Name, MinFontSize, OriginalFont.Style)
    Else
        Return OriginalFont
    End If
End Function

The ClientRectangle is 456 wide by 48 high. The text i'm trying to print is "This is a test string to see how well the application resizes it's text to fit the control.". The font is being returned as size 28 and all I can see is "This is a test string to see".
I want it to wrap the text and use the largest font which will allow all of the text to be displayed, but I'm struggling to work out how to achieve it.

A: I managed to get it working. Rather than comparing the width and height of the printed string against the container, I checked if MeasureString was able to fit all characters. I had to reduce the height of the drawing rectangle when measuring the string because half of the bottom line was getting clipped with longer strings.
Protected Overrides Sub OnPaint(e As PaintEventArgs)
    MyBase.OnPaint(e)

    Dim drawFont As New System.Drawing.Font(SystemFonts.DefaultFont.Name, 16)
    Dim drawBrush As New System.Drawing.SolidBrush(Me.ForeColor)
    Dim drawFormat As New System.Drawing.StringFormat

    Dim drawRect As New RectangleF(e.ClipRectangle.Location, e.ClipRectangle.Size)
    drawRect = New RectangleF(New Drawing.PointF(0, 0), Me.ClientRectangle.Size)
    drawRect.Height = drawRect.Height * 0.65 'The bottom line of text was getting partially clipped, so reduced the height of the drawing area to 65%

    drawFont = GetAdjustedFont(e.Graphics, noticeText, drawFont, drawRect, 40, 4, True)

    e.Graphics.DrawString(noticeText, drawFont, drawBrush, RectangleF.op_Implicit(ClientRectangle))

    drawFont.Dispose()
    drawBrush.Dispose()

End Sub

Public Function GetAdjustedFont(ByRef GraphicRef As Graphics, ByVal GraphicString As String, ByVal OriginalFont As Font, ByVal ContainerSize As RectangleF, ByVal MaxFontSize As Integer, ByVal MinFontSize As Integer, ByVal SmallestOnFail As Boolean) As Font

    'Loop through font sizes and MeasureString to find the largest font which can be used
    For AdjustedSize As Integer = MaxFontSize To MinFontSize Step -1

        Dim TestFont = New Font(OriginalFont.Name, AdjustedSize, OriginalFont.Style)
        Dim charsFitted As Integer
        Dim linesFilled As Integer

        ' Test the string with the new size
        Dim AdjustedSizeNew = GraphicRef.MeasureString(GraphicString, TestFont, ContainerSize.Size, New StringFormat, charsFitted, linesFilled)

        If charsFitted = GraphicString.Length Then 'If every characted in the string was printed
            'Good font, return it
            Return TestFont
        End If

    Next

    ' If you get here there was no fontsize that worked
    ' return MinimumSize or Original?
    If SmallestOnFail Then
        Return New Font(OriginalFont.Name, MinFontSize, OriginalFont.Style)
    Else
        Return OriginalFont
    End If
End Function

A: Thank you for this great Solution!
A little extension:
When you only want an oneliner change your "Good Font If-Clause" =>
If charsFitted = GraphicString.Length And linesFilled = 1 Then
     Return TestFont
End If


text:
Q: Highstock --- logarithmic yAxis does not work for negative columns I tried to plot a column chart with positive and negative values. I intended to dynamically change the yAxis type to logarithmic when the data are too skewed. What is desired for a logarithmic yAxis is that it has two directions. For example, one direction has ticks [0.01, 0.1, 1, 10, 100, 1k], the other has ticks [-0.1, -1, -100], depending on what the data are like. This is what I used for the chart load event:
events: {
    load: function(){
        var s = this.series[0],
            d = s.data,
            minSize = 99999,
            size;
        for (var i = 0; i < d.length; i++) {
            if (d[i].y < 0)
                d[i].update({color: '#FF0000'}, false, false);
            size = Math.abs(d[i].y);
            if (size < minSize)
                minSize = size;
        }
        if (s.dataMax/minSize > 20 || Math.abs(s.dataMin)/minSize > 20) {
            this.yAxis[0].update({
                type: 'logarithmic'
            })
        }
    }
}

I found that highstock/highcharts won't generate what I want. All the negative values are skipped and only positive ones are recognized, i.e., only one direction of the yAxis is drawn.
A guess is that highstock/highcharts calls a log(y) function to compute log values, ignoring negatives, but I don't know if there is a workaround.
If I use a log function by myself, compute the values and draw the chart, the ticks can't be correct, because the axis type is linear, which is not what I want.
Any ideas?
Thanks!


text:
Q: How to Improve this Star Schema Design I'm taking a course on Business Intelligence and I have to deal with a Star Schema for the first time in about 3 years so I wanted your feedback on what I've done if possible and see if there is anything I can do to improve my current design.
So the example says that we want to track performance of some clinics to understand their operations with some metrics like patient waiting time, cost, revenues, etc. The company has a well defined relational database that goes like this:

My start schema is as follows:


text:
Q: Ansible didnt pass down variables between files I was trying to use Ansible to put some jinja2 templates to a directory, e.g. path/from/*.j2 to path/to/*.txt.
In my ./defaults/main.yml:
---

test_var:
  - a: 1
    b: 2
  - a: 10
    b: 20

In my ./tasks/main.yml:
---

- name: "Copy file"
  include: copy-files.yml
  with_nested:
    - test_var
  loop_control:
    loop_var: test_loop

In my ./tasks/copy-files.yml:
---

- name: "copy {{ test_loop }}"
  template:
    src: "{{ test_loop.0.a }}"
    dest: "{{ test_loop.0.b }}"

I got the following error:
fatal: [localhost]: FAILED! => {"failed": true, "msg": "'unicode object' has no attribute 'b'"}

Then I used debug and saw that the variables went missing.
task path: ./tasks/main.yml
Wednesday 06 February 2019  01:15:10 +0000 (0:00:00.286)       0:00:04.308 ****
ok: [localhost] => {
    "msg": [
        {
            "a": 1,
            "b": 2
        },
        {
            "a": 10,
            "b": 20
        }
    ]
}

TASK [./ : Copy files] ********
task path: ./tasks/main.yml
Wednesday 06 February 2019  01:15:11 +0000 (0:00:00.064)       0:00:04.373 ****

TASK [./ : debug] *******************************
task path: ./tasks/copy-files.yml
Wednesday 06 February 2019  01:15:11 +0000 (0:00:00.089)       0:00:04.463 ****
ok: [localhost] => {
    "msg": [
        "a",
        "b"
    ]
}

So what could be wrong here?
ansible 2.1.0.0

A:
So what could be wrong here?

There are a few things at play.
Foremost, you are missing the jinja substitution of your with_nested:; I have no earthly idea why you even got "a" and "b", since that is very clearly a list of str you fed to with_nested:. I believe you wanted with_nested: "{{ test_var }}". It's possible ansible "helped" you because of the incredibly, disturbingly ancient version of ansible you're on, but a modern version doesn't auto-coerce that name into a variable, so be aware.
However, even fixing that won't solve your problem, since with_nested: wants a list of list, not a list of dict; as you can see from the fine manual, it is effectively calling {{ with_nested[0] | product(with_nested[1]) }} and product of a dict is a list of tuple of its .keys(), which explains the "a" and "b" you're seeing
If you want src and dest to be the values of the a and b key respectively, then skip the pretense and construct the with_nested: that way:
with_nested:
- '{{ test_var | map(attribute="a") | list }}'
- '{{ test_var | map(attribute="b") | list }}'


text:
Q: DB2 triggers or monitoring abilities for physical deletion I'm pretty new with IBM DB2, so I need some help on this topic please:
In my internship i'm dealing with an IBM DB2 data base with almost 300 tables and one super complex web based API( i am not an expert). The client asked us to prepare a testing manual in order to verify if there is any physical deletion (with logs proof). This data base has been designed and implemented by another third party company and we don't know exactly how they have done it. I have already tested logical deletion with an automated script and it works quite fine. But this second task really trapped me and have no idea how it should be done. My question is, do you know any trigger/monitoring techniques
Any suggestion would be appriciated.
Thanks in adavance.


text:
Q: ItemsControl ItemTemplate Binding In WPF4.0, I have a class that contains other class types as properties (combining multiple data types for display).  Something like:
public partial class Owner
{
     public string OwnerName { get; set; }
     public int    OwnerId   { get; set; }
}

partial class ForDisplay
{
    public Owner OwnerData { get; set; }
    public int Credit { get; set; }
}

In my window, I have an ItemsControl with the following (clipped for clarity):
<ItemsControl ItemsSource={Binding}>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
          <local:MyDisplayControl
                OwnerName={Binding OwnerData.OwnerName}
                Credit={Binding Credit} />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

I then get a collection of display information from the data layer, and set the DataContext of the ItemsControl to this collection.  The "Credit" property gets displayed correctly, but the OwnerName property does not.  Instead, I get a binding error:

Error 40: BindingExpression path
error: 'OwnerName' property not found
on 'object' ''ForDisplay'
(HashCode=449124874)'.
BindingExpression:Path=OwnerName;
DataItem='ForDisplay'
(HashCode=449124874); target element
is 'TextBlock' (Name=txtOwnerName');
target property is 'Text' (type
'String')

I don't understand why this is attempting to look for the OwnerName property in the ForDisplay class, rather than in the Owner class from the ForDisplay OwnerData property.
Edit
It appears that it has something to do with using the custom control.  If I bind the same properties to a TextBlock, they work correctly.
<ItemsControl ItemsSource={Binding}>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
          <StackPanel>
              <local:MyDisplayControl
                        OwnerName={Binding OwnerData.OwnerName}
                        Credit={Binding Credit} />
              <TextBlock Text="{Binding OwnerData.OwnerName}" />
              <TextBlock Text="{Binding Credit}" />
          </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

A: Are you sure the code you posted here IS the code you use in your solution? Because, this code works for me :
XAML
<ItemsControl ItemsSource="{Binding}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding OwnerData.OwnerName}"></TextBlock>
                <TextBlock Text="{Binding Credit}" />
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Window's Loaded Event
ObservableCollection<ForDisplay> items = new ObservableCollection<ForDisplay>();

for (int i = 0; i < 10; i++)
{
    items.Add(new ForDisplay() { OwnerData = new Owner() { OwnerId = i + 1, OwnerName = String.Format("Owner #{0}", i + 1) }, Credit = i + 1 });
}

DataContext = items;


text:
Q: Checkout remote master branch I'm trying to checkout a colleague's forked repo. I added their fork as a remote, but all their changes are on the master branch.
How do I checkout their master branch as a feature branch in my local repo?

A: git fetch theirremote if you haven't done so already
git checkout theirremote/master
git checkout -b theirfeature
This could be done in one git checkout -b I guess somehow, or one git branch and one simple git checkout somehow, but that way is easier to remember without looking up manuals.


text:
Q: React bootstrap Carousel not working properly I'm new using react bootstrap, and I'm trying to use a Carousel, however it's giving me this bug of the last slide disappearing when changing slide:

Here I'm sliding and that happens, also the slide is delayed, here's my code:
import React from "react";
import {Carousel} from "react-bootstrap";
import perro from "../perro.jpg";
const CarouselContainer = props => {
    return (
        <Carousel>
            <Carousel.Item>

                <Carousel.Caption>

First slide label

Nulla vitae elit libero, a pharetra augue mollis interdum.

                </Carousel.Caption>
            </Carousel.Item>
            <Carousel.Item>

                <Carousel.Caption>

Second slide label

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

                </Carousel.Caption>
            </Carousel.Item>
        </Carousel>
    );
}

A: import bootstrap CSS in page, then it will work.
import 'bootstrap/dist/css/bootstrap.min.css';

A: I'm not sure if this answer is going to help you, but i have the same issue with react bootstrap, and the error was in my css when the elements inside the carousel had a flex display. For any reason that property causes that blank slide just before the scroll effect. If that doesn't solve the problem, you can try changing the react-bootstrap carousel to the only bootstrap carousel.
First import the bootstrap.bundle.min.js script in your
index.html:

Note that this bootstrap script is for 5.1 version, so if you are using another version, just search the script in the documentation for that version.
Then, put your bootstrap carousel into your component and keep in mind that the flex display causes the error.
I hope i've helped. Sorry if it wasn't clear, but is my first time answering here :D

A: This happened to me too when I added my own indicators to the carousel. I also had a dynamic array of items that had to be presented in the carousel. It seems it happened to you for some reason too. In my case, react-bootstrap's carousel overran the list of items when it was sliding. I handled it controlling the sliding using the activeIndex and onSelect properties for the Carousel component.
In your case, you can try something like this:
import React from "react";
import {Carousel} from "react-bootstrap";
import perro from "../perro.jpg";

function CarouselContainer() {
  //critical to set initial state to zero
  const [index, setIndex] = useState(0);

  const handleSelect = (selectedIndex, e) => {
    //adjust index to 0 if greater than index of last slide or less than zero
    //slide indexes are zero-based so yourLasSlideIndex would be 1 I guess
    if (selectedIndex >= yourLastSlideIndex+1 || selectedIndex < 0 ){
            this.setIndex(0);
        } else if (selectedIndex !== index) {
            setIndex(selectedIndex);
        }
  };

  return (
    <Carousel activeIndex={index} onSelect={handleSelect}>
      <Carousel.Item>

                <Carousel.Caption>

First slide label

Nulla vitae elit libero, a pharetra augue mollis interdum.

                </Carousel.Caption>
            </Carousel.Item>
            <Carousel.Item>

                <Carousel.Caption>

Second slide label

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

                </Carousel.Caption>
            </Carousel.Item>
    </Carousel>
  );
}

render(<CarouselContainer />);

You might also be able to control it using the onSlid or onSlide callback properties, but not sure.


text:
Q: Theos on mac error I have done this (making hacks with theos before)
xcode 6.1
command line
coolstar theos
ldid
curl
perl
wget
make
However when I type
make package

I get these stuff
uname: illegal option -- o
usage: uname [-amnprsv]

But why "uname: illegal option -- o
    usage: uname [-amnprsv]" When it supposed to be s instead of o.
And how do I fix it?


text:
Q: GPS Data string to Associative array I want to convert below GPS device data string
{"alarm":"input2Inactive","odometer":594,"rssi":0,"sat":0,"status":0,"input":0,"output":0,"adc1":2437,"adc2":331,"adc3":117,"driverUniqueId":"1","distance":0.0,"totalDistance":270.03,"motion":false}

to an associative array like below array code
$array = array("alarm" => "input2Inactive","odometer" => "594","rssi" => "0","sat" => "0","status" => "0","input" => "0","output" => "0","adc1" => "2437","adc2" => "331","adc3" => "117","driverUniqueId" => "1","distance" => "0.0","totalDistance" => "270.03","motion" => "false");


text:
Q: Find the most efficient grouping of a series of intervals I have an application where I have a series of non overlapping fixed width intervals, each of which have a given key. Each interval has the same width, and there may be contiguous intervals. Essentially I want to group the intervals and keys in such a way that I minimize the amount of separate intervals. This could be done by merging contiguous intervals with the same key or looking for matching intervals and combining them into single intervals with multiple keys. My current algorithm tries the above two approaches and sees which results in the smallest number of intervals, but I feel like there must be a smarter way of approaching the problem. Any advice would be much appreciated!
For example:
|-----| |-----| intervals with key k1 (contiguous)
|-----| interval with key k2
|-----| interval with key k3
In this problem the intervals with key k1 could be merged to a single contiguous interval, resulting in 3 instead of four total intervals. Or the first interval for each key k1, k2 and k3 could be combined to one interval with keys k1, k2 and k3, resulting in one interval plus the second remaining interval in k1.
Worst case would be something like 70,000 intervals.

A: An idea for good approximation solution. Since intervals of fixed width input data can be represent as bitmask with intervals on one (X) axis and keys on other (Y) axis. For you data like:
k3  1  0
k2  1  0
k1  1  1
   i1 i2

Problem is similar to partitioning rectilinear polygon problem. There is a very good answer that covers the topic.
This is not exact problem since in this case order of keys is not important, what can be seen in example:
k3  1  1
k2  1  0
k1  1  1
   i1 i2

Partitioning will produce find result with 3 rectangles, and solution should be 2.
Simple solution to this (also approximation) is to make output post-processing and join rectangles on same intervals. Here will help pre-processing that reorders keys so that keys with similar 'covering' are nearer or neighbours.
More complex solution is (for which I am not 100% it works) is to use idea from algorithm for partitioning rectilinear polygons. Idea is to:

*

*take all possible splits (cords),

*create graph with cords as vertices and edges where cords intersect,

*find maximal (cord) independent set.

In original case, each inner (270deg) corner produces two cords in two directions. Since key ordering is not important, I think that Z cords should go through whole 'geometry'. That means cords are:

*

*one key continues intervals (X direction)

*interval ends (Z direction, goes through whole geometry).


text:
Q: Finalize method causing a memory leak? I cannot resolve a problem and need your help. When I click on menu I call customer account and then afterwards I close it. Every time I call customer account the memory increases. It should diminish when I close the account, but it does not happen.
Class Menu
mnItemCL_Cust.setOnAction(new EventHandler<ActionEvent>() {
  @Override
  public void handle(ActionEvent t) {
    try {
      panCenterPrev = (Pane) root.getCenter();
      panCenterAct = Customer.listCustomer();
      root.setCenter(null);
      root.setCenter(panCenterAct);
      Customer.btCanc.setOnAction(new EventHandler<ActionEvent>() {
        @Override public void handle(ActionEvent e) {
          try {
            Customer.Fim();
            panCenterAct.getChildren().clear();
            panCenterAct = null;
            root.setCenter(null);
            root.setCenter(panCenterPrev);
          } catch (Throwable ex) {
            Logger.getLogger(Customer.class.getName()).log(Level.SEVERE, null, ex);
          }
        }
});

Class Customer
public class Customer
{

  public static Pane listCustomer() throws SQLException, ClassNotFoundException
  {
    ...
    final ObservableList<MyCustomer> data = FXCollections.observableArrayList();
    ...
  }

  public static class MyCustomer {
    private final SimpleIntegerProperty idcl;
    private MyCustomer(Integer pIdcl ) {
      this.idcl = new SimpleIntegerProperty(pIdcl);
    }

    public Integer getIdcl() {
         return idcl.get();
    }

    public void setIdcl(Integer pIdcl) {
        idcl.set(pIdcl);
    }
  }

  public static void Fim() throws Throwable {
    ...
    rs = null;

    tbViewCL.getItems().clear();
    tbViewCL = null;
    colIDCL.getColumns().clear();
    colIDCL = null;
  }

  ...

  protected void finalize() throws Throwable {
    try{
      ...
      rs.close();
      ...// Never happens... why??
    } catch(Throwable t) {
        throw t;
    } finally {
        JOptionPane.showMessageDialog(null,"End?");
        super.finalize();
    }
  }

Regards

A: Java usually reclaims the memory you used when it see it fits, so even if you finalize the object, the memory may still be there. However, if rs.Close() never executes, probably is because something before it is throwing and exception, i recommend you to check the code before just to be sure that nothing is doing so, also, if you catch an exception is a good practice to log it so you can know what is happening.


text:
Q: Config for external (eg. bower) plugins How can I use an configuration file (config.json) for easier grunt setup
I want to add/setup all needed plugins in my config.json and I want a seperated file for all Plugins or seperate FOlder for images
config.json
{
    "images": {
        "pluginA": [
            "./faces/*.jpg"
        ],
        "pluginB": [
            "./corpes/*.jpg"
        ]
    },
    "javascript": {
        "pluginA": [
            "./faces/*.js"
        ],
        "pluginB": [
            "./corpes/*.js"
        ]
    }
}

Gruntfile.js
plugins: grunt.file.readJSON('plugins_config.json')
jshint: {
    development: {
        files: {
            **plugins.javascript**
        }
    }
}

desired output
dist/

*

*images

*

*pluginA

*

*faces1.jpg

*faces2.jpg

*pluginB

*

*corpes1.jpg

*corpes2.jpg

*javascript

*

*pluginA.js

*pluginB.js

*styles

*

*pluginA.css

*pluginB.css

A: The way you usually access a grunt config is through the method grunt.config(key), so your json file is accessible through grunt.config('plugins').
Unfortunately the config object is initialized by grunt.initConfig, so you can't use it in the call to initConfig itself, which is what you need to do.
Your solution is to use a separate local variable outside initConfig, instead of a config:
module.exports = function(grunt) {
  var plugins = grunt.file.readJSON('plugins_config.json');
  // ...
  grunt.initConfig({
    jshint: {
        development: {
            files: {
              src: plugins.javascript.pluginA,
            }
        }
    },
  // ...
  });
};