text:
Q: Ansible Roles and handlers - Cannot get role handlers to work I need to set up Apache/mod_wsgi in Centos 6.5 so my main YAML file is as such:
---
- hosts: dev
  tasks:
    - name: Updates yum installed packages
      yum: name=* state=latest

- hosts: dev
  roles:
    - { role: apache }

This should update all yum-installed packages then execute the apache role.
The apache role is configured to install Apache/mod_wsgi, set Apache to start at boot time and restart it. The following are the contents of roles/apache/tasks/main.yml:
---
- name: Installs httpd and mod_wsgi
  yum: name={{ item }} state=latest
  with_items:
    - httpd
    - mod_wsgi
  notify:
    - enable httpd
    - restart httpd

And the handlers in roles/apache/handlers/main.yml:
---
- name: enable httpd
  service: name=httpd enabled=yes

- name: restart httpd
  service: name=httpd state=restarted

The handlers do not seem to run since the following output is given when I execute the playbook:
PLAY [dev] ********************************************************************

GATHERING FACTS ***************************************************************
ok: [dev.example.com]

TASK: [Updates yum installed packages] ****************************************
ok: [dev.example.com]

PLAY [dev] ********************************************************************

GATHERING FACTS ***************************************************************
ok: [dev.example.com]

TASK: [apache | Installs httpd and mod_wsgi] **********************************
ok: [dev.example.com] => (item=httpd,mod_wsgi)

PLAY RECAP ********************************************************************
dev.example.com            : ok=4    changed=0    unreachable=0    failed=0

And when I vagrant ssh into the virtual machine, sudo service httpd status shows httpd is stopped and sudo chkconfig --list shows it has not been enabled to be started by init.
I'm just starting out with Ansible, so is there something obvious I could be missing?

A: Well, to answer my own question, I realized that there's a subtle point I missed:
http://docs.ansible.com/playbooks_intro.html#handlers-running-operations-on-change
Specifically, the notify signal is produced only if the task introduces a change. So for my use case I think I'll go with enabling and starting Apache in standalone tasks instead of relying on change signal handlers.


text:
Q: How to prove that $\sum_{k=1}^m \cos^2(\frac{2 \pi k}{m}) = \frac{m}{2}$ for $m>2$
How to prove that for $m>2$ $$\sum_{k=1}^m \cos^2\left(\frac{2 \pi k}{m}\right) = \frac{m}{2}.$$

This could be useful for me solving a Differential Geometry problem. And Wolfram Alpha says it's true. But i can only be certain with a proof

A: Note that $\cos^2 z=\frac{1+\cos2z}{2}$. Substituting gives us
$$\sum_{k=1}^m \cos^2\left(\frac{2 \pi k}{m}\right) = \frac{m}{2}+\frac{1}{2}\sum_{k=1}^m \cos\left(\frac{4 \pi k}{m}\right).$$
Also
$\operatorname{Re}e^{iz}$ is $\cos z$. Your problem can be rewritten to
$$\frac{1}{2}\sum_{k=1}^m \operatorname{Re}\left(\exp\left(\frac{2 \pi k}{m}\right)\right) = \frac{1}{2}\operatorname{Re}\sum_{k=1}^m\exp\left(4 \pi i\frac{k}{m}\right)=\operatorname{Re}\frac{1-\exp\left(4\pi i\right)}{1-\exp\left(4\pi i\frac{k}{m}\right)}=0.$$
Now you may use the geometric progression.

A: Let $ S = \sum_{k=1}^m \cos^2(\frac{2 \pi k}{m}) $
Multiply by 2 and subtract m
$2S - m = \sum_{k=1}^m 2\cos^2(\frac{2 \pi k}{m}) -1 $
Since $\cos(2x) = 2\cos^2(x)-1$
$2S - m = \sum_{k=1}^m \cos(\frac{4 \pi k}{m}) $
We have a formula when there is a summation of cosines where the angles are in AP
$Scn = \frac{\sin(\frac{md}{2})}{\sin(\frac{d}{2})} \cos(\frac{2a+(m-1)d}{2})$
We can see that $ d = \frac{4\pi}{m}$
Hence $\sin(\frac{md}{2}) = \sin(4\pi) = 0$
$2S - m = 0 $
$S = \frac{m}{2}$

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use z-index with DIV and PNG image? I have this css:

and this html code:

        -2

        0.1234

        -1

        0.1234

        MEDIA

        0.1234

        +1

        0.1234

        +2

        0.1234

as you can see I use prova2.png that has transparencies.
This is the image:

The result of the code is:

has you can see the green rectangle is ABOVE the image, BUT i really do not understand the reason, because i used the z-index and the div (with the image as background) has z-index:1, so...
Why green div IS above?
I need to set dinamically a color as background, BUT I must the see the vertical lines (of the .png image....the rest of the image is transparent), so the lines ABOVE the green div, and the GREEN in the transparent parts.
Could someone help me?
Thanks!

A: By using z-index you determine not only the stack level of the current, but also of its child elements. See the z-index specification:

Within each stacking context, the following layers are painted in back-to-front order:

*

*the background and borders of the element forming the stacking context.

*the child stacking contexts with negative stack levels (most negative first).

*the in-flow, non-inline-level, non-positioned descendants.

*the non-positioned floats.

*the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.

*the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.

*the child stacking contexts with positive stack levels (least positive first).

EDIT: A very simple way to fix this issue is to create a new
 and place your image there:

.chart {
    position: relative;
    width:300px;
    height:85px;
    padding:0;
    margin:0;
    z-index:1;
}

.chart div{
    /* same as above */
}

.chart .green{
    /* same as above */
}

.chart .chartmap{
    position: absolute; float:none;
    top: 0; left: 0; right: 0; bottom: 0;
    margin: 0; padding: 0; border: 0 none;

    background:url("prova2.png") center bottom no-repeat;
    z-index:1;
}

This time z-index will work since all elements share the same stacking context. Another possible solution is to use a real  and use a negative z-index on your <divs>.

A: Z-index works only for element with specified positioning. So any absolute/relative element's z-index will be higher than non-positioned object's.

A: jsFiddle: http://jsfiddle.net/Mn7rJ/
Add a parent div to your child divs and give it position:absolute;

            -2

            0.1234

            -1

            0.1234

            MEDIA

            0.1234

            +1

            0.1234

            +2

            0.1234

A: From .chart z-index is removed, you dont want to set z-index for parent.
CSS:

And HTML part:

        -2

        0.1234

        -1

        0.1234

        MEDIA

        0.1234

        +1

        0.1234

        +2

        0.1234


text:
Q: Scala: Method overloading over generic types In C# I can overload methods on generic type as shown  in the example below:
// http://ideone.com/QVooD
using System;
using System.Collections.Generic;

public class Test {
  public static void Foo(List<int> ints) {
    Console.WriteLine("I just print");
  }

  public static void Foo(List<double> doubles) {
    Console.WriteLine("I iterate over list and print it.");
    foreach(var x in doubles)
      Console.WriteLine(x);
  }

  public static void Main(string[] args) {
    Foo(new List<int> {1, 2});
    Foo(new List<double> {3.4, 1.2});
  }
}

However if I try to do the same in Scala, it will raise a compile time error that List[Int] and List[Double] erase to the same type due to erasure. I heard Scala's Manifests can be used to work around this, but I don't know how. I didn't find anything helpful in the docs either.
So my question is: How do I use Manifests (or whatever else that works) to overload methods over generic types that erase to same type due to erasure?

A: Kinda hackish, and both methods need the same return type (here: Unit)...
def fooInt(list: List[Int]) = println("int")
def fooDouble(list: List[Double]) = println("double")

def foo[N <: AnyVal](list:List[N])(implicit m:ClassManifest[N]) = m.erasure match {
    case c if c == classOf[Int] => fooInt(list.asInstanceOf[List[Int]])
    case c if c == classOf[Double] => fooDouble(list.asInstanceOf[List[Double]])
    case _ => error("No soup for you!")
}

foo(List(1,2,3,4))
//--> int

foo(List(1.0,2.0,3.0))
//--> double

A: The Manifest won't really help either becuase those will have the same type after erasure.
What will help having different numbers of arguments (or different types after erasure). I find having different numbers of implicit arguments can transparently solve this problem, and by using  scala.Predef.DummyImplicit, you don't even have to import an implicit anywhere.
class Test{
  def foo(ints : List[Int])
  def foo(doubles : List[Double])(implicit i1:DummyImplicit)
  def foo(strings : List[String])(implicit i1:DummyImplicit, i2:DummyImplicit)
}

A: You would not do it like that in Scala. Why try to emulate something that can never work properly given JVM restrictions? Try idiomatic Scala instead:
trait Fooable[T] {
  def foo : Unit
}

object IntListFoo extends Fooable[List[Int]] {
  def foo {
    println("I just print")
  }
}

class DoubleListFoo(val l : List[Double]) extends Fooable[List[Double]] {
  def foo {
    println("I iterate over list and print it.")
    l.foreach { e =>
      println(e)
    }
  }
}

implicit def intlist2fooable(l : List[Int]) = IntListFoo
implicit def doublelist2fooable(l : List[Double]) = new DoubleListFoo(l)

Then, you can execute code like
List(1,2,3,4).foo
List(1.0,2.0,3.0).foo


text:
Q: Is it possible to use the Drupal api to get a list of users? I would like to get a list of all the users who have been assigned a certain role.  I could write my own SQL but I would like to use the api as much as possible.

A: You can use entity_load to get array of users. Here is the sample that will create list of all emails for admin users (used to send notification)
<?php
$users = entity_load('user');
$emails = '';
foreach($users as $user) {
  if (array_key_exists(3, $user->roles)) {
    if (strlen($emails) > 0) {
      $emails .= ' ' . $user->mail;
    } else {
      $emails = $user->mail;
    }
  }
}
?>

A: There are generally no Drupal API functions for this sort of task (pulling up entities that match certain criteria). It tends to focus on single-entity CRUD functions in the API; everything else is up to a developer's own SQL skills.
The Views module allows you to build lists of users filtered by role, permission, etc -- but it could easily be overkill.

A: The SQL that worked for me:

$users = "";
$result = db_query('SELECT users.name AS users_name FROM users users
      INNER JOIN users_roles users_roles ON users.uid = users_roles.uid
      WHERE users_roles.rid = 4');

while ($existing_user = db_fetch_object($result)) {
      if ($users != "") $users .= ", ";
      $users .= $existing_user->users_name; // or do whatever
}
echo $users;

Keep in mind this is for Drupal 6 and I'm not sure about the performance of this for large user bases. Not sure about Drupal 7.

A: One easy option is to use Views to generate the SQL (appears below the view its self when you press the preview button) for you and then use the Drupal SQL abstraction layer to get the results you need if you need to get access to the raw data rather than display a View.
It'd look a bit like this:
$result = db_query('SELECT users.uid AS uid,
   users.mail AS users_mail,
   users.name AS users_name
 FROM users users');
while ($existing_user = db_fetch_object($result)) {
    print_r($existing_user); // or do whatever
  }

Just add more fields to the view to get the complete query.

A: In Drupal 8:
$users = \Drupal\user\Entity\User::loadMultiple();

And if you want to get e.g. only admins:
$admins = [];
foreach ($users as $user) {
  if ($user->hasRole('administrator')) {
    $admins[] = $user;
  }
}

A: I don't know about any API can help to collect users by role. Here you are some link you can get something: http://drupal.org/node/82002.
Although SO is an awesome service I suggest using drupal.org or #drupal channel on irc.freenode.org for Drupal related questions.
Ps.: sometimes SQL is not that evil:)

A: In Drupal 7, use EntityFieldQuery is the proper way.

A: In Drupal 8 the following works (in this example, load all users with the administrator role)
\Drupal::service('entity_type.manager')
  ->getStorage('user')
  ->loadByProperties(['roles' => 'administrator']);

will return a list of user entities.
To get a list of uids instead, an entity field query:
$query = \Drupal::service('entity_type.manager')->getStorage('user')->getQuery();
$query->condition('roles', 'administrator');
$query->execute();


text:
Q: Return number of first-time purchases on a date In Google Data Studio, I'm reporting on data which shows purchases (well, really donations) over a particular time frame. Each purchase shows a transaction ID, the customer ID who made that purchase, and the date of their first purchase.
What I'm trying to do is to get the number of first-time purchases over the course of the report date range. So I want to see how many purchases were made over the date range AND how many of those purchases were customers that were purchasing for the very first time. ie, "Dec 3, 2020: Purchases: 40. First-time purchases: 17."
How can I do that in a Data Studio field when that first-purchase field is always populated with something?
Thanks!

A: With the information you provided, I suppose your Data Source also has a column named Purchase Date (which stores when that particular transaction happened).
Assuming this is true, you can create a new calculated column with the difference, in seconds, between the purchase date and the first purchase date:
Column First Purchase Diff: DATETIME_DIFF(Purchase Date, First Purchase Date, SECOND)
With this column, you can easily detect if that particular transaction is the first purchase (=zero difference between dates), with a new calculated column:
Column Is First Purchase: CASE WHEN First Purchase Diff = 0 THEN 1 ELSE 0 END
Now, just summarize the number in this column to show how many first purchases (or donations) you have in a particular period.


text:
Q: Shade area between two lines using D3 I am trying to shade the area between two lines(vertically). I had tried using clip paths and masking the surrounding with a rectangle but it didn't get me what I wanted. Many solutions I found online only deal with lines on top of another, but in my case the lines will always be side by side.
Here is my code:
  var width = 500;
  var height = 500;

  var data = [

  {
    // line1 data
    x:[268, 293, 251, 287, 265, 269, 253, 251, 253, 260],
    y:[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
  },
  {
    // line2 data
    x:[232, 207, 249, 213, 235, 231, 247, 249, 247, 240],
    y:[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
  }
  ];

    var yscale = d3.scale.linear()
                  .range([height, 0])
                  .domain([0,10]);

    var svg = d3.select("#chart").append('svg').style('width', width).style('height', height)
                .append('g');

    var area = d3.svg.area()
                      .x(function(d,i){return d[0]})
                      .y0(0)
                      .y1(function(d){return yscale(d[1])});
    var areaunder = d3.svg.area()
                      .x(function(d,i){return d[0]})
                      .y0(height)
                      .y1(function(d){return yscale(d[1])});

    console.log( data[0].x );
    var max = d3.max(data[0].x);
    var rectWidth = (max - width/2) * 2;

    console.log(rectWidth);

    var xpos = width/2 - (width/2 - d3.min(data[1].x));
    var ypos = 0;

    console.log(xpos);

    //svg.append('rect')
    //    .attr('x', xpos)
    //    .attr('y', ypos)
    //    .attr('width', rectWidth)
    //    .attr('height', height)
    //    .attr('fill', 'red');

    var line = d3.svg.line()
                  .interpolate("cardinal")
                  .x(function(d,i){return  d[0]})
                  .y(function(d){return yscale(d[1])});

    var areas = svg.selectAll('.area')
        .data( data.map(function(d) {return d3.zip(d.x, d.y);}) )
        .enter().append('g')
        .attr("class", 'area');
        //areas.append('path')
        //.attr('d', function(d){return area(d);});
        //areas.append('path')
        //.attr('d', function(d){return areaunder(d);})

    // svg.append('path')
    //     .datum( data.map(function(d) {return d3.zip(d.x, d.y);}) )
    //     .attr("class", 'area')
    //     .attr("d", area);

    var lines = svg.selectAll(".lines")
                    .data(data.map(function(d) {return d3.zip(d.x, d.y);}))
                    .enter().append("g")
                    .attr('class', "lines")
    lines.append('path')
          .attr('class', 'pathline')
          .attr('stroke', 'black')
          .attr("fill", "none")
          .attr('d', function(d){return line(d)})

and the jsfiddle

A: I was able to solve this by specifying x0, x1, y0, and y1 of the area generator.
The code to fill the area between the lines:
var indexies = d3.range( data[0].x.length );

var area = d3.svg.area()
                  .interpolate("cardinal")
                  .x0( function(d) { return data[1].x[d] } )
                  .x1( function(d) { return data[0].x[d] } )
                  .y0( function(d) { return yscale(data[1].y[d]) } )
                  .y1(  function(d) { return yscale(data[1].y[d]) } );

svg.append('path')
  .datum(indexies)
  .attr('class', 'area')
  .attr('d', area);

The update jsfiddle.
.


text:
Q: Django-ckeditor5 how to set codeblock's programming languages in admin template I am integrating django-ckeditor5 in my Django website but facing some difficulties with adjusting the programming languages that appears on the code-block drop-down from my admin.

I want to customize this section to only include programming languages like Python, SQL and JavaScript. I haven't seen a way to configure this via the setting.py file. Please, I need help.


text:
Q: jquery onclick not firing? EDIT : Original post removed as have narrowed this down quite a bit.  The orignal post was about trying to dynamically add elements on clicking a button.  Having narrowed it down it doesn't seem to be the code but something else.  I can get the exact same code working on jsfiddle so I must be missing something in my setup somewhere that is causing the click event not to fire/be handled. Again not sure where to look to fix this.
I tried adding some inline and in a js file jquery as below and it works (inline and in js file) without issue.
$(document).ready(function(){

    $("div").css("border", "3px solid red");

});

The below code however will not fire at all either inline or in js file.
$(document).ready(function() {
    $("#jpctesting").click(function() {
        alert("this happened");
    });
});

The html element is in the php file as below and upon inspect element it exists with the right id etc
<input type="button" value="Add Currency" id="jpctesting" />

Any thoughts on why this might be?

A: Well your question is bit too unorganized since there are too much of content. But for the question you asked to "dynamically add a field when button clicked" here you could use this function. Imagine you want to dynamically add images to a view. i'm doing it using JQuery.
This is the HTML

 <button type="button" onclick="generate_field_with_click()">Click Me!</button>

This JS file
    var bId = 0;
var imageUrl = "asdasdaimage.jpg"

function generate_field_with_click() {
bId++;
var str = "";

str += "
";
str += "            ";
str += "          <\/div>";

$(".container").append(str);

var id = 'nIcon' + bId;
document.getElementById(id).src = imageUrl;}

There you go, This should work to add any field to the DON,Btw be always mindful to create new IDs.

A: With the narrowed Question you could try this one.
$(document).ready(function() {
  $('#jpctesting').on('click', function() {
 alert("this happened");}); });


text:
Q: What is the correct gravitational potential energy of a single particle in an $N$-body system? I am aware that the total gravitational potential energy of a system of $N$ particles is given by pairwise interactions, i.e., you start with a single particle in the system, and then calculate the work done (negative for an attractive force) to bring in every other additional particle. Like this:
$$U_{total}=-G\sum_{i=1}^{N-1}\sum_{j=i+1}^{N}\frac{m_im_j}{r_{ij}}\tag{1}$$
However, does it make sense to talk about the gravitational potential energy of a single particle? Something like this:
$$U_i=-Gm_i\sum_{j=1,j\neq i}^{N}\frac{m_j}{r_{ij}}\tag{2}$$
However, as can be seen from equation 1, summing over these "individual" gravitational potential energies would result in pairwise interactions being counted twice. Thus, would this:
$$U_i=-Gm_i\frac{1}{2}\sum_{j=1,j\neq i}^{N}\frac{m_j}{r_{ij}}\tag{3}$$
... be a correct equation for the gravitational potential energy of the $i^{th}$ particle in an N-body system? At the very least, using equation 3 to calculate the potential energy of each particle would result in the correct total potential energy for the system when summing the inividual energies of the particles.
Any insight would be much appreciated.

A: The total potential energy of a system of $N$ particles interacting through Newton's gravitational force can always be written either as
$$U_{total}=-G\sum_{i=1}^{N-1}\sum_{j=i+1}^{N}\frac{m_im_j}{r_{ij}}\tag{1}$$
or as
$$U_{total}=-\frac{G}{2}\sum_{i=1}^{N}\sum_{j=1;j \neq i}^{N}\frac{m_im_j}{r_{ij}}\tag{2}.$$
In the form $(2)$, each pair of bodies is counted twice, then the necessity of a factor $1/2$.
Notice that $U_{total}$ is a property of the whole system. However, it is possible to interpret formula $(2)$ as the sum over all the bodies of the potential energy of one body at the time, in the presence of the remaining $N-1$. Therefore, your equation $(3)$.

A: Equation (1) is relevant if you're studying the evolution of the whole system. For example, you can use it to construct the conserved energy or the Lagrangian.
Equation (2) is relevant if you're studying the kinematics of the subject particle over a short time period (so you neglect motion of the rest of the system). For example, its gradient (with respect to $\vec r_i$) tells you the instantaneous force on your particle. This equation might be used when numerically integrating the system's evolution.
I can't think of a context where equation (3) is useful, except as a computation step toward evaluating equation (1).

A: The total potential energy of the whole system is not the sum of the individual potential energies of each particle while holding the other $n-1$ particles fixed. That's because in order to build up the system, you need to bring the particles in one at a time. Or, more generally, the work required to bring in each particle only depends on the other particles that have already been brought in, but not on the ones that will be brought in later.
So a priori, one might expect that the total potential energy of the system might depend on the order in which the particles are brought in. But conveniently, it turns out that the order doesn't matter; adding in the overall  prefactor of $1/2$ takes care of avoiding double-counting particles, regardless of the order that they're brought in.
So your equation (2) is the correct one, but it needs to properly interpreted. It only applies to the last particle that you bring in. (It can apply to every particle if you restrict the sum to only go over the particles that were brought in earlier than the particle in question, but that information is often not available, and fortunately we don't need it.)


text:
Q: generating spectrogram form wav file nodejs and save it i'm new in the world of javascript and i wanted to recreate a project of mine (written in python) with javascript.
so i want to write a script with nodejs that reads a wav file and generate from it a spectrogram.
I used node-wav , canvas and audio-context trying to recreate the method applied in this module
I'm working with local files from my laptop and with javascript client side. I want to do everything locally. This is my code :
const canvas = createCanvas(480, 240)
const spectro = spectrogram(canvas, false)
    const spectrogramsGenerator = async () => {
        // wavfiles return a list of wav files (it works)
        const files = await wavFiles()
        for (file in files) {
            const buffer = fs.readFileSync('path/to/file/' + files[file])
            spectro.connectSource(buffer, audioContext)
            spectro.start()
        }
    }

with that code snippet i get the following error :
   /path/to/workspace/node_modules/spectrogram/spectrogram.js:34
        window.onresize = function() {
        ^

    ReferenceError: window is not defined
        at new Spectrogram (/path/to/workspace/spectrogram/spectrogram.js:34:5)
        at Spectrogram (/path/to/workspace/node_modules/spectrogram/spectrogram.js:16:14)
        at Object.<anonymous> (/path/to/workspace/spectrogram.js:13:17)
        at Module._compile (internal/modules/cjs/loader.js:736:30)
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:747:10)
        at Module.load (internal/modules/cjs/loader.js:628:32)
        at tryModuleLoad (internal/modules/cjs/loader.js:568:12)
        at Function.Module._load (internal/modules/cjs/loader.js:560:3)
        at Function.Module.runMain (internal/modules/cjs/loader.js:801:12)
        at executeUserCode (internal/bootstrap/node.js:526:15)

if this the wrong way doing it (i think it is) .. what packages should i use to achieve my goal or how should i approach this problem. Thanks in advance


text:
Q: Make my Style specific to a single instance My wpf application has this Style:
Xaml:
<Style x:Key="customTableViewDataRowStyle" TargetType="{x:Type xcdg:DataRow}">

C#
this.Resources.Add(typeof(DataRow), this.FindResource("customTableViewDataRowStyle"));

It modifies the look of a Row in an Xceed Datagrid.
This all works great!
But I went and added another Xceed Datagrid to my app and it is using the style too.
Is there a way to not have it do that?  Can I make it only affect specific grids?

A: You could seperate the style into a standalone ResourceDictionary and then reference the ResourceDictionary only in the desired DataGrids.
Example with two DataGrids an only one of them have the style set:
CustomDataGridStyles.xaml:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Style TargetType="{x:Type DataGrid}">
        <Setter Property="Background" Value="Red" />
        <!-- Other Style Settings -->
    </Style>

</ResourceDictionary>

Window:
<Window x:Class="SpecificControlStyle.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>

        <DataGrid Grid.Row="0">
            <DataGrid.Resources>
                <ResourceDictionary>
                    <ResourceDictionary.MergedDictionaries>
                        <ResourceDictionary Source="CustomDataGridStyles.xaml" />
                    </ResourceDictionary.MergedDictionaries>
                </ResourceDictionary>
            </DataGrid.Resources>
        </DataGrid>
        <DataGrid Grid.Row="1" />
    </Grid>
</Window>


text:
Q: Configurar horário específico no AlarmManager pelo TimePicker e DatePicker estou fazendo um teste ainda antes de implementar no aplicativo real. Tenho um aplicação com dois botões (Data e Horário) e um botão (Agendar). Assim que usuário clica no botão Data, abre um DatePicker para ele escolher a data. No horário é a mesma coisa, abre um TimePicker para que ele escolha o horário. A data e hora vão para um EditText para o usuário possa visualizar e assim poder tocar no botão Agendar.
Não estou conseguindo colocar o Horário no AlarmManager. Se eu configurar apenas a data funciona, mas se eu configurar a data e horário, a notificação já exibida logo em seguida.
Códido Main
    public class MainActivity extends AppCompatActivity {

    private EditText dataEscolhida;
    private EditText materia;
    private EditText horarioEscolhido;
    private Button calendarioData;
    private Button horarioAgendado;

    private Button botaoAgendar;

    SimpleDateFormat formatarData = new SimpleDateFormat("dd/MM/yyyy");
    SimpleDateFormat formatarHora = new SimpleDateFormat("HH:mm", Locale.getDefault());
    Calendar calendar = Calendar.getInstance();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        dataEscolhida = (EditText) findViewById(R.id.edt_dataEscolhida);
        materia = (EditText) findViewById(R.id.edt_materia);
        botaoAgendar = (Button) findViewById(R.id.btn_agendarNotificacao);
        calendarioData = (Button) findViewById(R.id.btn_calendárioDatePicker);
        horarioAgendado = (Button) findViewById(R.id.btn_horario);
        horarioEscolhido = (EditText) findViewById(R.id.edt_horario);

        botaoAgendar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String dataAgendada = dataEscolhida.getText().toString();
                Log.d("Data agendada", String.valueOf(dataAgendada));

                String materiaAgendada = materia.getText().toString();
                agendarNotificacao(getNotification(materiaAgendada), calendar.getTime());

                Log.d("Agendamento", "Agendou");

            }
        });

        calendarioData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                atualizarData();
            }
        });

        horarioAgendado.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                atualizaHorario();
            }
        });

    }

    private void exibeDataNoCampo() {
        dataEscolhida.setText(formatarData.format(calendar.getTime()));
        Log.d("Data escolhida: ", String.valueOf(dataEscolhida));
    }

    private void exibeHorarioNoCampo() {

        horarioEscolhido.setText(formatarHora.format(calendar.getTime()));

        Log.d("Hora escolhida: ", String.valueOf(horarioEscolhido));
    }

    private void atualizarData() {

        new DatePickerDialog(this, data, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)).show();
    }

//Salva a data que o usuário configurou
    DatePickerDialog.OnDateSetListener data = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, month);
            calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            exibeDataNoCampo();
        }
    };

    private void atualizaHorario() {
        new TimePickerDialog(this, horario, calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE), true).show();
    }

//Salva o horário que o usuário configurou
    TimePickerDialog.OnTimeSetListener horario = new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

            calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
            calendar.set(Calendar.MINUTE, minute);
            exibeHorarioNoCampo();

        }
    };

    @TargetApi(Build.VERSION_CODES.N)
    private void agendarNotificacao(Notification notification, Date dataAgendada) {

        Intent intentNotificacao = new Intent(this, Notificacao.class);
        calendar.setTime(dataAgendada);

        //Irá gerar as id aleatorias para cada notificação
        int id = (int) (Math.random() * 1000);

        intentNotificacao.putExtra(Notificacao.NOTIFICATION_ID, id);
        intentNotificacao.putExtra(Notificacao.NOTIFICATION, notification);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, id, intentNotificacao,
                PendingIntent.FLAG_UPDATE_CURRENT);

        // long tempodedisparo =  calendar.getTimeInMillis() + segundosAgendado * 60000 ;

        //disparo de notificacao
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                pendingIntent);

        Log.d("AgendarNOtificacao", "agendarnotificacao");
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private Notification getNotification(String content) {
        Notification.Builder builder = new Notification.Builder(this);
        builder.setContentTitle("Lembrete: Estudar a matéria");
        builder.setContentText(content);
        builder.setSmallIcon(R.mipmap.ic_launcher);

        Log.d("Construindo Notificacao", "Construindo Notificacao");

        return builder.build();

    }

}

Minha classe de Broadcast
public class Notificacao extends BroadcastReceiver {

    public static String NOTIFICATION_ID = "notification-id";
    public static String NOTIFICATION = "notification";

    @Override
    public void onReceive(Context context, Intent intent) {

        NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);

        Notification notification = intent.getParcelableExtra(NOTIFICATION);
        int id = intent.getIntExtra(NOTIFICATION_ID, 0);
        notificationManager.notify(id, notification);

        //som da mensagem
        try {
            Uri som = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Ringtone toque = RingtoneManager.getRingtone(context, som);
            toque.play();

        }catch (Exception e){e.printStackTrace(); }

        Log.d("Notificação Exibida", "Notificacao Exibida");
    }
}

Meu XML
 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="notificacaocomalarmmanager.com.flaviodeoliveira.notificacaocomalarmmanager.MainActivity">

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textCapCharacters"
        android:ems="10"
        android:id="@+id/edt_materia"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="56dp"
        android:hint="Qual materia?"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textCapCharacters"
        android:ems="10"
        android:id="@+id/edt_dataEscolhida"
        android:hint="Data?"
        android:layout_below="@+id/edt_materia"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="10dp" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Agendar Notificação"
        android:id="@+id/btn_agendarNotificacao"
        android:layout_below="@+id/btn_horario"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Calendario"
        android:id="@+id/btn_calendárioDatePicker"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edt_horario"

        android:hint="Horário"
        android:layout_below="@+id/edt_dataEscolhida"
        android:layout_centerHorizontal="true" />

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Horário"
        android:id="@+id/btn_horario"
        android:layout_below="@+id/btn_calendárioDatePicker"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

A:
[...]a notificação já exibida logo em seguida...

Isso porque realmente você está definindo para que seja exibida logo em seguida. A clicar em botaoAgendar, você está passando a hora atual, usando calendar.getTime(), para definição do alarme, quando na verdade deveria ser o horário definido no EditText.
Para corrigir, basta passar como parâmetro o horário correto definido no TimePicker e DatePicker, no qual deseja que apareça a notificação no método agendarNotificacao();


text:
Q: Creating select modelform based off min and max year present in table? I am attempting to create a ModelChoiceField who's options are based off finding the years present in a number of posts within the database.
So for example there are posts stored in my database with a DateTime field. What i am attempting to do is create a form with the options based on the range of years present in the post table.
ie
We have a post with field date_created. The value is

2013-06-27 03:21:15

and we have another with the value

2012-06-27 03:00:20

I want to display a form with select options for each year present in the post table with no duplicates;
<option value="2013">2013</option>
<option value="2014">2014</option>

Will a ModelChoiceField allow me to do this with a single query or do i need to process and build say a list containing the years.

A: Thanks to lalo for pointing me in the right direction. I managed to figure it out using the following;
    years_list = []
choices = []
year_list = Post.objects.all().values_list('date_created').distinct()

for years_avail in year_list:
    years_list.append(years_avail[0].strftime('%Y'))

for year in years_list:
    choice =(year, year)
    choices.append(choice)

years = forms.ChoiceField(choices, label='')

Is this a good way to go about doing this or is this inefficient/wrong?

A: ModelChoiceField is for model select, based in foreign key. I think you have to user ChoiceField and generate the options in runtime.
Show me where you use the form, maybe can show you how to do.


text:
Q: Collection View freezes for long when populated using response obtained by hitting API I am trying to get data from server and populate collection view cells with that data, but when collection view gets populated freezes and takes very long time to scroll.
What is exactly going wrong?
-(void)callService:(NSNumber*)categoryid{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer
                                  serializerWithReadingOptions:NSJSONReadingAllowFragments];

    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    NSMutableDictionary *dict = [NSMutableDictionary new];
    [dict setValue:@1 forKey:@"page"];
    [dict setValue:@25 forKey:@"limit"];

  [dict setValue:categoryid forKey:@"category_id"];

    [manager POST:@"https://www.foodfuels.com/Api/getrecipes"
       parameters:dict progress:nil success:^(NSURLSessionTask *task,id responseObject)
     {
         int status = [[responseObject objectForKey:@"status"] intValue];

         if(status == 200)
         {
             responseArray = [responseObject valueForKey:@"data"];

             dispatch_async(dispatch_get_main_queue(), ^{
                 [MBProgressHUD hideHUDForView:self.view animated:true];
                 [_outerCollectionView reloadData];

             });
         }

         else
         {
             [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"logininfo"];
             UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Error" message:@"some eror!"  delegate:self cancelButtonTitle:Nil otherButtonTitles:@"Ok", nil];
             [alert show];
         }
         dispatch_async(dispatch_get_main_queue(), ^{

          //[MBProgressHUD hideHUDForView:self.view animated:YES];

         });

     }
          failure:^(NSURLSessionTask *operation, NSError *error)
     {
         UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Error" message:error.localizedDescription delegate:self cancelButtonTitle:Nil otherButtonTitles:@"Ok", nil];

         [alert show];

         dispatch_async(dispatch_get_main_queue(), ^{

           //  [MBProgressHUD hideHUDForView:self.view animated:YES];

         });

     }];

}

Collection View
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if(collectionView==_headingCollectionView){
        recipeHeading = (RecipeHeadingCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"headingCell" forIndexPath:indexPath];
        _headingCollectionView.delegate = self;
        [recipeHeading.headingBtn setTitle:[recipeTypeArray objectAtIndex:indexPath.row] forState:UIControlStateNormal];
        [recipeHeading.headingBtn addTarget:self action:@selector(doSomething:) forControlEvents:UIControlEventTouchUpInside];

        bool d = [allValues[indexPath.row] boolValue];

        if(d)
        {
            [recipeHeading.headingBtn setTitleColor:[UIColor colorWithRed:36/255.0 green:71/255.0 blue:113/255.0 alpha:1.0] forState:UIControlStateNormal];            [recipeHeading.headingBtn addSubview:bottomBorder];
        }
        else
        {
            [recipeHeading.headingBtn setTitleColor:[UIColor whiteColor]forState:UIControlStateNormal];
        }

        return recipeHeading;
    }
    else if (collectionView==_outerCollectionView){
        RecipeOuterCell *outerCell =(RecipeOuterCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"outerCell" forIndexPath:indexPath];
        return outerCell;
    }
    else{
        RecipeInnerCell *innerCell = (RecipeInnerCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"innerCell" forIndexPath:indexPath];
        [innerCell populateRecipeScreen:responseArray index:indexPath];
        return innerCell;

    }
}

Inner Collection View Cell
-(void)populateRecipeScreen:(NSArray*)recipeResponseArr index:(NSIndexPath*)path{
    NSLog(@"the value of recipe array are as follows %@",recipeResponseArr);
    for(int i=0;i<recipeResponseArr.count;i++){
        self.comment_Count.text =[[[recipeResponseArr valueForKey:@"comment_count"]objectAtIndex:path.row]stringValue];
        self.titleLbl.text =[[recipeResponseArr valueForKey:@"description"]objectAtIndex:path.row];
        self.like_Count.text = [[[recipeResponseArr valueForKey:@"like_count"]objectAtIndex:path.row]stringValue];
        NSData *data= [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: [[[recipeResponseArr valueForKey:@"user"]valueForKey:@"image"]  objectAtIndex:path.row]]];
        ;            self.smallImgView.image=[UIImage imageWithData:data];

        self.share_Count.text = [[[recipeResponseArr valueForKey:@"share_count"]objectAtIndex:path.row]stringValue];
        self.subTitleLbl.text = [[[recipeResponseArr valueForKey:@"user"]valueForKey:@"username"]  objectAtIndex:path.row];
        NSLog(@"url obtained as result %@",[[[recipeResponseArr valueForKey:@"upload_images"]valueForKey:@"name"]  objectAtIndex:path.row]);
        NSArray *urlString = [[[recipeResponseArr valueForKey:@"upload_images"]valueForKey:@"name"]  objectAtIndex:path.row];

        NSData *mainData=[[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:[urlString objectAtIndex:0]]];
        self.mainImg.image=[UIImage imageWithData:mainData];
    }
}

A: It seems like you are loading images from network (namely from recipeResponseArr["user"]["image"] in main thread via initWithContentsOfURL:. This is strongly discouraged and against best practised. From the documentation:

Important
Don't use this synchronous method to request network-based URLs. For
  network-based URLs, this method can block the current thread for tens
  of seconds on a slow network, resulting in a poor user experience, and
  in iOS, may cause your app to be terminated.
Instead, for non-file URLs, consider using the
  dataTaskWithURL:completionHandler: method of the NSURLSession class.
  See URL Session Programming Guide for details.

If you need effective and easy tool to load images I would recommend using SDWebImage or AlamofireImage


text:
Q: Convert dataframe to a rec array (and objects to strings) I have a pandas dataframe with a mix of datatypes (dtypes) that I wish to convert to a numpy structured array (or record array, basically the same thing in this case).  For purely numeric dataframes, this is easy to do with the to_records() method.  I also need the dtypes of pandas columns to be converted to strings rather than objects so that I can use the numpy method tofile() which will output numbers and strings to a binary file, but will not output objects.
In a nutshell, I need to convert pandas columns with dtype=object to numpy structured arrays of string or unicode dtype.
Here's an example, with code that would be sufficient if all columns had a numerical (float or int) dtype.
import pandas as pd
df=pd.DataFrame({'f_num': [1.,2.,3.], 'i_num':[1,2,3],
                 'char': ['a','bb','ccc'], 'mixed':['a','bb',1]})

struct_arr=df.to_records(index=False)

print('struct_arr',struct_arr.dtype,'\n')

# struct_arr (numpy.record, [('f_num', '<f8'), ('i_num', '<i8'),
#                            ('char', 'O'), ('mixed', 'O')])

But because I want to end up with string dtypes, I need to add this additional and somewhat involved code:
lst=[]
for col in struct_arr.dtype.names:  # this was the only iterator I
                                    # could find for the column labels
    dt=struct_arr[col].dtype

    if dt == 'O':   # this is 'O', meaning 'object'

        # it appears an explicit string length is required
        # so I calculate with pandas len & max methods
        dt = 'U' + str( df[col].astype(str).str.len().max() )

    lst.append((col,dt))

struct_arr = struct_arr.astype(lst)

print('struct_arr',struct_arr.dtype)

# struct_arr (numpy.record, [('f_num', '<f8'), ('i_num', '<i8'),
#                            ('char', '<U3'), ('mixed', '<U2')])

See also:  How to change the dtype of certain columns of a numpy recarray?
This seems to work, as the character and mixed dtypes are now <U3 and <U2 rather than 'O' or 'object'.  I'm just checking if there is a simpler or more elegant approach.  But since pandas does not have a native string type as numpy does, maybe there is not?

A: Combining suggestions from @jpp (list comp for conciseness) & @hpaulj (cannibalize to_records for speed), I came up with the following, which is cleaner code and also about 5x faster than my original code (tested by expanding the sample dataframe above to 10,000 rows):
names = df.columns
arrays = [ df[col].get_values() for col in names ]

formats = [ array.dtype if array.dtype != 'O'
            else f'{array.astype(str).dtype}' for array in arrays ]

rec_array = np.rec.fromarrays( arrays, dtype={'names': names, 'formats': formats} )

The above will output unicode rather than strings which is probably better in general but in my case I need to convert to strings because I'm reading the binary file in fortran and strings seem to read in more easily.  Hence, it may be better to replace the "formats" line above with this:
formats = [ array.dtype if array.dtype != 'O'
            else array.astype(str).dtype.str.replace('<U','S') for array in arrays ]

E.g. a dtype of <U4 becomes S4.

A: As far as I am aware, there is no native functionality for this. For example, the maximum length of all values within a series is not stored anywhere.
However, you can implement your logic more efficiently via a list comprehension and f-strings:
data_types = [(col, arr[col].dtype if arr[col].dtype != 'O' else \
               f'U{df[col].astype(str).str.len().max()}') for col in arr.dtype.names]


text:
Q: casting variable as the function's returned class instance I have a function that returns one of classes instances.
What I want to do is to 're-cast' the variable as the returned value's actual type.
typescript playground
// classes
class Cake{
    myName: string;
    base: string = "vanilla"
    frosting: string = "empty"
    constructor(myName: string) {
        this.myName = myName
    }
}

class Chocolate extends Cake{
    frosting: string = "chocolate"
    cut() {
        console.log("cut to 8 pieces!")
    }
}

class Strawberry extends Cake {
    frosting:string="strawberry"
    topping:string="coconut"
}

// functions
function getCake(frosting:string, myName:string):Chocolate|Strawberry {
    const chocolateClass = new Chocolate(myName)
    const strawberryClass = new Strawberry(myName)
    const classes:any = { chocolateClass, strawberryClass }
    let returnedObj: Chocolate|Strawberry;
    Object.keys(classes).forEach((key) => {
        if (classes[key].frosting == frosting) {
            returnedObj = classes[key]
        }
    })
    return returnedObj
}

// logic
const myCake: Strawberry | Chocolate = getCake("chocolate", "John")
console.log(myCake.frosting)  // can access it
console.log(myCake.myName)  // can access it
myCake.cut() // can access it, but has linting error + can't see it through intellisense

I can access specific properties from the strawberry class,
console result
but my issue is that the linting says it doesn't exist even though it does. This also prevents intellisense from seeing cut().
So I came to the conclusion that, in some way, I need to recast myCake variable based on what is returned in getCake() function. How can I do that?
I do not want specific functions for each cake type (getStrawberryCake()), because I could have 50 cakes.

A: If you'd like the compiler to help infer the proper types for you, as opposed to having to "cast" (actually type assert) in multiple places, then it can be done by changing a few things in your code.
The first thing is that the compiler does not understand that Chocolate's frosting property is always the exact string "chocolate", because you've annotated it as string.  To give it a better idea of the relationship between frosting and the type of cake, you can mark the properties as readonly and don't annotate at all.  This prompts the compiler to infer that "chocolate" is a string literal type which can be used later to key off of a mapping from cake frosting names to class types:
class Chocolate extends Cake {
  readonly frosting = "chocolate"
  cut() {
    console.log("cut to 8 pieces!")
  }
}

And the same goes for Strawberry:
class Strawberry extends Cake {
  readonly frosting = "strawberry"
  topping: string = "coconut"
}

Then we'll do a little type juggling to give names to the mapping from frosting to class type:
type PossibleCakes = Chocolate | Strawberry;
type CakeMap = { [K in PossibleCakes["frosting"]]: Extract<PossibleCakes, { frosting: K }> };
// type CakeMap = { chocolate: Chocolate; strawberry: Strawberry; }

The PossibleCakes type is just the union you were using, and you can always add members to this union as desired.  The CakeMap uses a mapped type whose properties use the Extract utility type to pull the proper member out of the PossibleCakes union. This ends up becoming the equivalent of {chocolate: Chocolate; strawberry: Strawberry;}.
Now we can finally write the getCake() function.  It should be a generic function so that by calling it with a particular frosting value, the output will be a particular class, not the PossibleCakes union.
Here it is:
function getCake<K extends keyof CakeMap>(frosting: K, myName: string): CakeMap[K] {
  return { chocolate: new Chocolate(myName), strawberry: new Strawberry(myName) }[frosting];
}

First let's look at the signature... the frosting parameter is of type K, a generic type variable constrained to keyof CakeMap which in this example is "chocolate" | "strawberry".  If you call getCake("chocolate", "xxx") the value of K should be inferred as "chocolate".  Then the return type is CakeMap[K], which is what you get when you look up the K-keyed property of CakeMap.  If K is "chocolate", then CakeMap[K] is Chocolate.
Notice that I've changed the implementation significantly into a straightforward object lookup. That is partially just stylistic choice, but mostly it's because the compiler can actually verify that the output of that will be a CakeMap[K], because the object is a CakeMap and the index is a K.  The iterative version with Object.keys() and forEach() is not as conducive to compiler inference.  If you stick with that version, you'll likely need a type assertion somewhere.
Anyway, let's see if it works:
const myCake = getCake("chocolate", "John")
console.log(myCake.frosting)
console.log(myCake.myName)
myCake.cut()

No errors anymore.  myCake is known by the compiler to be Chocolate and therefore the cut() method is known to be available.  Okay, hope that helps; good luck!
Playground link to code


text:
Q: python error while using urllib module I was making python http banner grabber using urllib but it gives me an error.
I was not able it import urllib2 (module not found error) so tried with with urllib instead.
Here's the code , what's wrong with it?
#!/usr/bin/env python
import urllib
url=urllib.urlopen('www.bing.com')
print (url.info())

Error:
AttributeError: 'module' object has no attribute 'urlopen'

A: You are using Python 3; use urllib.request instead.
import urllib.request

url = urllib.request.urlopen('http://www.bing.com')
print(url.info())

This is documented at the top of the urllib2 page:

Note: The urllib2 module has been split across several modules in Python 3 named urllib.request and urllib.error. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.


text:
Q: Irreducible decomposition of varieties vs primary decomposition of ideals I'm new to working with varieties, and the statement mentioned below is left as an exercise, but I'm having some difficulty trying to prove it.
Let $R=K[x_1,...,x_n]$. If $X=X_1\cup ... \cup X_n$, then $I(X)=I(X_1)\cap ...\cap I(X_n)$, where $X,X_1,...,X_n$ are varieties. Here $I(X):=\{f\in R|f(a_1,...,a_n)=0, \space\forall (a_1,...,a_n)\in X\}$.
Also, if $X_i$ are all irreducible varieties, then would that imply that $I(X_i)$ are primary?

A: Recall and write out everything in detail, there is not much to prove.
$I(X)$ is the set of all $f$ such that $f(a)= 0$ for all $a \in X$.
So in particular for such an $f$ one has $f(a)=0$ for all $a\in X_1$, simply as  $X_1 \subset X$, and $f \in I(X_1)$.
The same is true for every $X_i$ so $f \in I(X_i)$ for all $i$. This it is in the intersection for all $I(X_i)$.
Conversely, if $f$ is in the intersection. Then $f(a)= 0$ for all $a \in X_i$, and this for all $i$, which is the same as saying it is true for all $a \in \cup X_i$. Thus $f \in I(X)$.


text:
Q: List java.lang.ClassCastException: java.util.Vector cannot be cast to java.util.ArrayList This is my simple code. I need a clone of the ArrayList listOnayStatu.  GtbEtobsOYenibelge is a entity. But there is a cast problem java.lang.ClassCastException: java.util.Vector cannot be cast to java.util.ArrayList.
Thank you
List<GtbEtobsOYenibelge> listOnayStatu = new ArrayList<>();
List<GtbEtobsOYenibelge> cloneOnayStatu;
listOnayStatu = servis.listOnayStatus4Belge(user.getBirimId().getId());
cloneOnayStatu =  ((List) ((ArrayList) listOnayStatu).clone());

All code is that.

A: You can just use the copy constructor of ArrayList which accepts a Collection<? extends E>:
List<GtbEtobsOYenibelge> listOnayStatu = servis.listOnayStatus4Belge(user.getBirimId().getId());
List<GtbEtobsOYenibelge> cloneOnayStatu = new ArrayList<>(listOnayStatu);

That way you create a copy of listOnayStatu. Also you should not rely on clone() anymore as it has been confirmed to been a bad decision

A: The method servis.listOnayStatus4Belge returns a Vector. A Vector implements the List interface but is not an ArrayList. Therefore you can't cast it to one.
Looking at the problematic statement:
cloneOnayStatu =  ((List) ((ArrayList) listOnayStatu).clone());

You are copying a Vector and assigning it to cloneOnayStatu. You should be able to do it like this:
cloneOnayStatu = (List<GtbEtobsOYenibelge>) ((Vector<GtbEtobsOYenibelge>)listOnayStatu).clone();

The clone() method call will return another Vector but it's declared return type is Object. Therefore you need to cast it to a List for the assignment to work.
However, clone() is not used much these days. You can have more control over what kind of List you want the result to be by using a constructor, such as the following:
cloneOnayStatu = new ArrayList<>(listOnayStatu);

A: You can try to save it as a new arraylist.
List<GtbEtobsOYenibelge> listOnayStatu = new ArrayList<>();
List<GtbEtobsOYenibelge> cloneOnayStatu;
listOnayStatu = servis.listOnayStatus4Belge(user.getBirimId().getId());
cloneOnayStatu =  new ArrayList(listOnayStatu);

or you can use addAll
cloneOnayStatu.addAll(listOnayStatu);


text:
Q: Lately I have been developing this piece of code with my knowledge of networking in order to test it and see how it works Lately, I have been developing this piece of code with my knowledge of networking in order to test it and see how it works.I was trying to interact with TCP servers.
It goes like this:
from socket import *
bag = socket(AF_INET,SOCK_STREAM)
bag.bind(("",9000))
bag.listen(5)
while True:
    c,a = bag.accept()
    print ("Received connection from", a)
    c.send("Hello %s\n" % a[0])
c.close()

And the console printed this out:
Traceback (most recent call last):
  File "/Users/spathen/PycharmProjects/untitled31/jsyk.py", line 8, in
Received connection from ('127.0.0.1', 50162)
    c.send("Hello %s\n" % a[0])
TypeError: a bytes-like object is required, not 'str'
Process finished with exit code 1
Any ideas on why this isn't working. An I not doing this right? Is there something going on?
Do I have to send datagrams with UDP instead?


text:
Q: How do I interpret the Google Distance Matrix API response value? {
    "destination_addresses": [
        "New York, NY, USA"
    ],
    "origin_addresses": [
        "Washington, DC, USA"
    ],
    "rows": [
        {
            "elements": [
                {
                    "distance": {
                        "text": "225 mi",
                        "value": 361711
                    },
                    "duration": {
                        "text": "3 hours 53 mins",
                        "value": 13965
                    },
                    "status": "OK"
                }
            ]
        }
    ],
    "status": "OK"
}

I got this response from the Google Distance Matrix API. We have text and value responses on the distance and duration, how do I interpret that? What is it's unit?
Thank you!
I thought the value should be the same as that of the text just not without the unit, but it's entirely different.

A: According to the documentation, the the unit for the value of distance is meters. To quote the documentation:

The total distance of this route, expressed in meters (value) and as text. The textual value uses the unit system specified with the unit parameter of the original request, or the origin's region.

While the unit for the value of duration is seconds. To quote the documentation:

The length of time it takes to travel this route, expressed in seconds (the value field) and as text. The textual representation is localized according to the query's language parameter.

The unit for text for both distance and duration is what ever you asked for in the request or localized based on the region of the world that the request is sent from or the language parameter in the query.


text:
Q: How do I get the account name from UserPrincipal? I am using Active Directory login in one of my Winforms applications. I get a UserPrincipal object but I'm not sure how to get the proper accountname from this object? I can see that there is a SamAccountName that is the same as my account name but it states that this is for old versions of Windows. So how do I get the proper account name no mather old or new Windows systems?
This is the code I use to get the object
if (ADUserName.Length > 0)
    context = new PrincipalContext(ContextType.Domain, ADServer, null,  ADUserName, ADUserPassword);
else
    context = new PrincipalContext(ContextType.Domain, ADServer);

UserPrincipal.FindByIdentity(context, account)

A: SamAccountName is the "account name" as it was used in Windows even before Active Directory was introduced.
It's "legacy" in that it has been supplemented by additional info - your "distinguished name" in the LDAP context etc. - but it is the Windows account name ("short name") - and it's still a mandatory field for any new user being created - just use it!
See User naming attributes for more details on which name is used for what in an AD context.


text:
Q: T4 Visual Studio 2010 include linked T4 Here's one. I have a bunch of T4s in one project / solution. This is a framework with support code and T4 templates.
In a different solution, I want to use this framework, but have the support classes / T4s remain in the original solution.
In the new solution I link to the support code and T4s (add existing / link). Now in the new solution I have a T4 which needs to include the linked T4. It has something like this:
<#@ template language="C#" debug="false" hostspecific="true"#>
<#@ include file="..\Models\DALContextGenerator.tt"#>
<#@ output extension=".cs"#><#
Generate("..\Models\Model1.edmx");
>
In this case, DALContextGenerator.tt is in this solution, but is linked to the real DALContextGenerator.tt in a different solution. WHen I run the T4 I get an error ("Failed to resolve include text"). If I reference the physical location it is fine.
Any ideas?
Thanks
Ray

A: As far as I know, the T4 engine uses the template file as a root and is unaware of the Visual Studio Solution and Solution items. If you're using a Visual Studio link to a file somewhere else this information is only stored in the project file. The T4 engine looks up the include-path relative to the T4 file. That's why referencing the Visual Studio Link relatively fails. But referencing the include file either with its absolute path or a relative one pointing to the physical file succeeds.
Here are some ideas how to address your problem, but there is no "smooth" solution I can think of:

*

*Use a hard link between the original include file and a file located next to the template file (command line: mklink /H source target)

*if you are using a source control system (like svn) you can work with external directories without duplicating your originals

*Have a (meta-)T4 template that generates the actual T4 template with the proper paths based on the information you get from Env.DTE Visual Studio Model

A: Old but relevant question, I think the same as this other thread, where I posted a reply, using expansions $(ProjectDir) and $(SolutionDir): https://stackoverflow.com/a/42785952/1948625


text:
Q: How do you get a pointer to a new PHCollectionList (or PHAssetCollection) after creating I'm trying to create a Photo "folder" and return a pointer to it. Is this possible?  Below is the code I have so far. Thanks.
- (PHCollectionList *) CreatePhotoFolder: (NSString *) folderName
{
    [[PHPhotoLibrary sharedPhotoLibrary]
        performChanges:^{
            // Create the folder
            [PHCollectionListChangeRequest creationRequestForCollectionListWithTitle: folderName];
        }
        completionHandler:^(BOOL success, NSError *error) {
            if (!success) { NSLog(@"Error creating Folder: %@", error); }
            else {
                // How do I return the new PHCollectionList* for the new folder?
            }
        }
     ];
}

A: You need to get the local ID by placeholder first.
    __block NSString * localId;
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        PHAssetCollectionChangeRequest *assetCollectionChangeRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:@"XD"];
        localId = [[assetCollectionChangeRequest placeholderForCreatedAssetCollection] localIdentifier];
    } completionHandler:^(BOOL success, NSError *error) {
        if (!success) {
            NSLog(@"Error creating album: %@", error);
        } else {
            NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
            [prefs setObject:localId forKey:@"collection"];
            [prefs synchronize];
        }
    }];

and then get the PHAssetCollection by this local ID
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString* colletionId = [prefs stringForKey:@"collection"];
if(colletionId == nil) {
    colletionId = @"";
}

PHFetchResult *result = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[colletionId]  options:nil];
self.assetCollection = [result firstObject];


text:
Q: How performance can change using greedy LINQ operators? Is it performant wise to use greedy LINQ operators such as ToList,ToLookUp,Distinct etc?
What would be a best practice(s) for LINQ query execution?
You often use for your objects List<> or making all your objects lists to IEnumerable<>. I know the latest gives more flexibility.
When working with memory (LINQ to Objects) it's ok to always use deffered loading, cause you can access it whenever you need without fear that tha data changed, added or inserted as the reference will execute the query as soon as you need access. But this changes with database LINQ queries such LINQ to EF.
Would like a StackOverflow users opinion.
Thank you!

A:
What would be a best practice(s) for LINQ query execution?

A List may be accessed by index, a Lookup may be accessed by Key.  These types are obviously serializable across a WCF boundary.  A deferred IEnumerable doesn't do these things well.
For EF or LinqToSql, one must run their queries before the DataContext or whatever holds the SqlConnection gets disposed.

In my code, I use deferred IEnumerables only for method scoped variables when convenient.  I use List for properties (sometimes the property constructs the List, but usually it's just backed by an instance) and method return types.  Since I'm doing comparatively expensive things (like accessing the database or using WCF), the performance of eagerly executing in-memory Linq queries has never been an issue.
The final authority on any performance question is: how does it measure?


text:
Q: How to customize WebViewPage executation output? I am going to inject some elements in every view of our Asp.Net MVC application. so to do that (I found this: Custom WebViewPage inject code when razor template is rendering answer) I have subclassed the WebViewPage and I have overridden the ExecutePageHierarchy like below:
   public override void ExecutePageHierarchy()
    {
        base.ExecutePageHierarchy();
        string output = Output.ToString();
        if (MyHelper.InitializationRequired)
            output = MyHelper.GetPageHeader() + output + MyHelper.GetPageFooter();
        //--------------
        Response.Clear();
        Response.Write(output);
        Response.End();
    }

by this code we can wrap all of the output markup with some header and some footer elements such as scripts or additional tags which i want to do that.
BUT in this way we lost the Layout completely! because of clearing the response.
my main question is that, how to inject some HTML markups exactly before or exactly after WebViewPage's output by preserving the content of response which maybe there are some other views or the layout?

A: Finally i found a trick to do it by this way:
 public override void ExecutePageHierarchy()
    {
        var tmp = OutputStack.Pop();
        var myWriter = new StringWriter();
        OutputStack.Push(myWriter);
        base.ExecutePageHierarchy();

        tmp.Write(
            string.Format("
 Header of [{0}]
 {1}
 Footer of [{0}]
",
            VirtualPath,
            myWriter.ToString()));
    }

it works well generally and it wraps the output of view by header and footer. but in my scenario i should able to access to some flags which will assigned on executing view. so i must check them after view execution:
 public override void ExecutePageHierarchy()
    {
        var tmp = OutputStack.Pop();
        var myWriter = new StringWriter();
        OutputStack.Push(myWriter);
        base.ExecutePageHierarchy();
        if (MyHelper.InitializationRequired)
           tmp.Write(
            string.Format("
 Header of [{0}]
 {1}
 Footer of [{0}]
",
            VirtualPath,
            myWriter.ToString()));
        else
           tmp.Write(myWriter.ToString());
    }

this approach works well for me. so i posted it, maybe help some one;)

A: You should use the layout system of MVC ... It's full featured to have a master layout schema :=)


text:
Q: SQL Agent Job - Connection may not be configured correctly or you may not have the right permissions on this connection? I'm getting this error when running an SSIS package through SQL Agent
Failed to acquire connection "ORACLE ADO.NET". Connection may not be configured correctly or you may not have the right permissions on this connection.
When I log on as the SQL Agent User and run the ssis package directly it is fine. When I then execute it through the SQL agent job, it fails.
I've read around extensively on this topic, and it seems a lot of the advise concerns how you are logged in, configuring of proxy accounts, etc, etc, etc, none of which has been helpful.
I am logging onto an Oracle database with an ADO.NET conncetion. The connection string is as follows (datasource, userid and password have been changed):
Data Source=DATASOURCE;User ID=userid;Password=password;Persist Security Info=True;Unicode=True;
I'm loading this from a registry setting using package configuration. To check that I am getting the correct string, I am writing it into a temporary log table. I am definately getting the string I need from the correct registry setting.
I've tested the oracle login credentials though PL/SQL developer, and it lets me login just fine.
As far as I can tell, as I'm using an explicit user name and password for the Oracle connection it just shouldn't matter who the SSIs pacakge is run as. The only point of failure that Ican see would be the reading of the information from the registry, but that seems fine.
I'm really quite baffled, I must confess, and would appreciate any help some of the splendid experts here can offer.
Many thanks,
James

A: Ok, tracked this one down after quite a lot of pain.
It was working fine on one environment, but not another, so I fired up Process Monitor (http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) and ran a package through the SQL Agent job, comparing which system entities were hit on each enviroment.
On the failing environment, at the point of the bulk transfer operation, the package attempted to get the Oracle 11 client DLL, and then hung.
I knew that this was installed, and, moreoever, the DLL path was a system environment setting. After further investigation it was revealed that the server had not been rebooted since the Oracle Client install and the SQL Server Agent process had not bee recycled.
Yes, can you believe it, the old helpdesk fix "Can you reboot your computer?" worked.
Sigh!

A: We had issues at a client with running packages connecting to Oracle before stored on our sql server instance. The work around we found was to change the package property, protection level, to "Dont save Sensitive Data" and for security purposes, we encrypted the username and password in the package configuration that was decrypted by a udf in sql server. Of course, before you try the whole encryption part, I would recommend putting the username and password in the package configuration without encrypting the values to see if changing the protection level setting is the solution to your specific problem. I hope this helps.

A: I was getting this error when tnsnames.ora file did not have a valid entry for the environment


text:
Q: How to change category location block in magento 1.8? Is it possible to exchange positions of the list of categories and the price filter in the left sidebar:

A: Goto
app/design/frontend/yourPackage/Yourtheme/template/catalog/navigation/left.php
Here you find subcategory foreach loop
foreach ($_categories as $_category):
change this foreach loop position as your requirement and your job is done.

A: Please check given below URLs to solve your problem.

*

*https://stackoverflow.com/questions/19423859/how-to-change-category-filter-position-in-magento-layer-navigation

*How to move category filters in layered navigation after the attribute filters


text:
Q: Segment photos of bio-samples to extract circular area of interest with Python image processing I'm having issues with finishing the segmentation in some photos of bio-samples, I'm trying to analyze growth of bacteria with image processing, as in theory it should work. Here is one of the original images I have:

I'm trying to segment the area inside the circle and see how the values of the pixels change as time passes. I've been trying a lot of techniques, as I'm relative new to analyzing these kind of samples.Initially I was using opencv, but I wasn't getting the results I wanted so now I'm using scikit-image for all the techniques for image processing and segmentation.
Here's the code I have until now:
from skimage import morphology, exposure, io, filters
from scipy import ndimage as ndi
from skimage.color import rgb2gray, label2rgb
from skimage.filters import sobel, rank
import matplotlib.pyplot as plt
y1=400
y2=1600
x1=700
x2=1900
test_img = io.imread(folders_path+hour_tested[0]+'5.jpg')
roi_test = test_img[y1:y2, x1:x2,:]
gray_img = rgb2gray(roi_test)
denoised_img = rank.median(gray_img, morphology.disk(5))
val = filters.threshold_otsu(denoised_img)
mask = denoised_img > val
elevation_map=sobel(denoised_img)
segmentation = morphology.watershed(elevation_map, mask=mask)
labeled_bio, num_seg = ndi.label(segmentation)
image_label_overlay = label2rgb(labeled_bio, image=gray_img)
plt.imshow(image_label_overlay)
plt.show()

On the last line I get to segment by different colors the areas of the sample and get the part I want to analyze in one label, is now that I don't know how to continue or at least how to just see that label and then create a mask.
I'm also sharing the labeled image for anyone to see and maybe help me in the next steps, I feel like or I'm really close to segment my area of interest or really far and confused.
Well here's the labeled image of the sample:

A: Here's an approach using simple image processing techniques

*

*Obtain binary image. Load image, convert to grayscale, then Otsu's threshold to get a binary image

*Perform morphological operations. We create an elliptical shaped kernel then perform morph close to fill in the contours

*Isolate area of interest. We find contours and filter using contour approximation + contour area. Once we isolate the contour, find a minimum enclosing circle to obtain a perfect circle then draw this onto a blank mask. The idea to obtain a perfect circle is from how to modify a mask to make a perfect circle

*Isolate ROI. We find the bounding rectangle ROI on the mask then crop using Numpy slicing

*Bitwise-and to obtain result. Finally we bitwise-and the two extracted ROIs

Here's a visualization of each step:
Input image

Binary image

Morph close

Isolated area of interest highlighted in green and filled contour drawn onto a blank mask

Isolated ROIs

Bitwise-and for result (two versions, one with black background and one with white background, depending on what you want)

Code
import cv2
import numpy as np

# Load image, create blank mask, grayscale, Otsu's threshold
image = cv2.imread('1.jpg')
original = image.copy()
mask = np.zeros(image.shape, dtype=np.uint8)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

# Morph close
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
close = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=5)

# Find contours and filter using contour area + contour approximation
# Determine perfect circle contour then draw onto blank mask
cnts = cv2.findContours(close, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.04 * peri, True)
    area = cv2.contourArea(c)
    if len(approx) > 4 and area > 10000 and area < 500000:
        ((x, y), r) = cv2.minEnclosingCircle(c)
        cv2.circle(mask, (int(x), int(y)), int(r), (255, 255, 255), -1)
        cv2.circle(image, (int(x), int(y)), int(r), (36, 255, 12), 3)

# Extract ROI
mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
x,y,w,h = cv2.boundingRect(mask)
mask_ROI = mask[y:y+h, x:x+w]
image_ROI = original[y:y+h, x:x+w]

# Bitwise-and for result
result = cv2.bitwise_and(image_ROI, image_ROI, mask=mask_ROI)
result[mask_ROI==0] = (255,255,255) # Color background white

cv2.imwrite('close.png', close)
cv2.imwrite('thresh.png', thresh)
cv2.imwrite('image.png', image)
cv2.imwrite('mask.png', mask)
cv2.imwrite('result.png', result)
cv2.waitKey()

Note: Another approach to determine the circular region of interest is to use Hough Circle Transform already implemented as cv2.HoughCircles() but there are many parameters so it may not be the most practical method.

A: After fixing the code this is the correct answer for the biofilm segmentation:
import cv2
import numpy as np
import os
def resize_image(image, percentage):
   scale_percent=percentage
   width = int(image.shape[1] * scale_percent/100)
   height= int(image.shape[0] * scale_percent/100)
   dimensions = (width, height)
   resized = cv2.resize(image, dimensions, interpolation = cv2.INTER_AREA)
   return resized
#this path is changed for each image in the DB
path=folders_path+hour_tested[0]+'1.jpg'
image = cv2.imread(path)
s_image = resize_image(image,50)
original = s_image.copy()
mask = np.zeros(s_image.shape, dtype=np.uint8)
gray = cv2.cvtColor(s_image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
# Morph close
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7,7))
close = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=3)
# Find contours and filter using contour area + contour approximation
# Determine perfect circle contour then draw onto blank mask
im,cnts,hierarchy = cv2.findContours(close, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for c in cnts:
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.04*peri, True)
    area = cv2.contourArea(c)
    if len(approx) > 4 and (area > 8000 and area < 250000) and (peri<2000 and peri>1000):
        ((x, y), r) = cv2.minEnclosingCircle(c)
        x,y,r = int(x),int(y),int(r)
        blank_circle=cv2.circle(mask, (x, y), r, (255, 255, 255), -1)
        filled_circle=cv2.circle(s_image, (x, y), r, (36, 255, 12), 3)
        # Extract ROI
        mask_ROI = blank_circle[y-r:y+r, x-r:x+r]
        mask_ROI = cv2.cvtColor(mask_ROI, cv2.COLOR_BGR2GRAY)
        image_ROI = filled_circle[y-r:y+r, x-r:x+r]
        result = cv2.bitwise_and(image_ROI, image_ROI, mask=mask_ROI)
        cv2.imwrite('result.png',result)


text:
Q: How to make @JsonView annotated Rest apis serializes all fields I have a rest api like "/users/{userId}"
This api returns User data but filters out password by @JsonView(ResourceView.Public.class) annotation.
But I want to get password when the unit test runs.
Is there a way to igore @JsonView annotation when test is running.
Or any other options for me?
public class ResourceView {
    public interface Public {}
    public interface Friends extends Public {}
    public interface Family extends Friends {}
}

public class User {
    @JsonView(ResourceView.Public.class)
    private String name;

    @JsonView(ResourceView.Family.class)
    private String password;
}

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @JsonView(ResourceView.Public.class)
    @GetMapping(value = "/users/{userId}")
    public User getUser(@PathVariable("userId") String userId) {
    return userService.getUser(userId);
    }
}

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles(profiles = "test")
public class UserServiceTest {

    @Autowired
    protected TestRestTemplate restTemplate;

    @Value("${local.server.port}")
    private int port;

    protected String apiEndpoint;

    @Before
    protected void setUp() {
    initRequestContext();
    apiEndpoint = "http://localhost:" + port;
    }

    protected ResponseEntity<User> requestGetUser(String userId) {
    ResponseEntity<User> res = restTemplate.exchange(
        apiEndpoint + "/users/" + userId,
        HttpMethod.GET,
        new HttpEntity<>("parameters", createDefaultHttpHeaders()),
        new ParameterizedTypeReference<User>() {});

    return res;
    }

    @Test
    public void testGetUser() throws Exception {
    ResponseEntity<User> apiRes = requestGetUsers(request);
    assertThat(apiRes.getStatusCode(), is(HttpStatus.OK));
    User user = apiRes.getBody();
    assertThat(user.getName(), is(notNullValue()));
    assertThat(user.getPassword(), is(notNullValue()));
    }
}

@Configuration
public class MyConfig {
    @Bean
    public ObjectMapper objectMapper() {
    ObjectMapper objectMapper = new ObjectMapper().configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
    return objectMapper;
    }
}


text:
Q: What "tools" are available when determining the convergence of a functional series? I am struggling with determining whether a functional series converges, in general.
$$\sum_{j=1}^\infty f_j$$
When determining whether a functional series(FS) is pointwise, we essentially fix $x \in D(f)$ and send j to $\infty$,(There is more to it than that I know, but for brevity) and see what the limit function is, if we can find a $x \in D(f)$ such that the series is divergent then we have neither pointwise/uniform convergence.
Since we fix $x$ to determine pointwise, can we use the ratio test, root test, etc in this case?
I posted a question on this;
Pointwise convergence of a functional series.
and I think it is correct, now I have this to tackle
$$\sum_{j=1}^\infty (\frac{x}{j})^j;x \in \mathbb{R}$$
I am going to try determine whether this series is pointwise convergent.
First when $x=0$, the series converges to $0$.
If we fix $x \neq 0$, then by the root test;
$$\lim_{j \to \infty} \frac{|x|}{j} = 0 < 1$$
and so we have pointwise convergence.
We have to look for a different method for uniform convergence, since we know that the rate at which the FS converges will be different for different $x$. This is reflected in the definition. ($\exists N>0 s.t \forall x \in D$...)
One method that my prof suggested was to use the Cauchy criterion for series.
BUT
I can not use it as this function is not bounded. How would I proceed?

A: If your series does satisfy a uniform version of the Cauchy criterion on the whole real line then for any $\epsilon$ there would be an integer $N$ so that
$$\left|  \sum_{j=m}^n \left( \frac{x}j \right)^j \right| < \epsilon$$
for all $n\geq m\geq N$ and all $x\in\mathbb{R}$.  As a very special case of this with $\epsilon=1$ and
not trying quite so hard, we would know that there is an integer $N$ so that
$$\left|   \left( \frac{x}N \right)^N\right| < 1$$ for
all $x\in\mathbb{R}$.
The uniform Cauchy criterion is equivalent to uniform convergence so you can see that you do not have uniform convergence on $\mathbb{R}$ or indeed on any unbounded set.  Now, to complete the problem, show that you have uniform convergence on any bounded set.
Sometimes when the prof suggests a criterion to use, write it out explicitly and stare at it for quite a while.  Also that "criterion" might be used to prove that something happens or to prove that something does not happen.  You have to consider both directions.  When one fails to work, suspect the opposite.  Go back and forth until a moment of insight arises.


text:
Q: failed to open image in ROS Kinetic hello, i have run this  "roslaunch turtlebot3_navigation turtlebot3_navigation.launch" in ROS Kinetic but its turn out "failed to open image file"  image description here
I'm expecting to display the map

A: This is happening because the correct path to the map.pgm file is not being passed to ROS. I can see the problem with the path happening in the map.yaml file.
Navigate to turtlebot3 -> turtlebot3_navigation -> maps -> map.yaml and change the first line from image: ./map.pgm to image: map.pgm.
This should allow for the map image to be loaded correctly.


text:
Q: How can i take encrypted data in a byte array and put that into an HTTP request in a binary format using C# I want to take encrypted data in a byte array and put that into an HTTP request in a binary format. So far I have this code in C#
byte[] encryptedBytes = var encryptor.Encrypt(dataToEncrypt);

HttpRequestMessage newHttpMessage =  new HttpRequestMessage();

newHttpMessage.Content = encryptedBytes;

I have been provided with an example in Javascript, I need to achieve the same but using C#
                $.post({
                        url: "xyz",
                        contentType: "application/json",
                        headers: {

                            "Ing-Plain-Content-Length": jsonData.length
                        },
                        data: new Uint8Array(encrypted),
                        processData: false,
                        xhr: function () {
                            return xhrOverride;
                        },
                        dataType: "binary",


text:
Q: Can we use "draw screen to other apps" to get that app text I want to get the text of the user what he is seeing right now where API will just whole data of that app. but I need only the data user currently seeing.

A: No, you cannot.
Only accessibility services and other services specifically granted the ability to read the screen content (e.g., Google Assistant-type services) are able to do this.
If any app that could draw over other apps could, that would be a huge security hole.


text:
Q: Dynamic sql and loops I've got some batch job processes that are all built on the same pattern - load new data into a temp table, figure out what operations need to be done based on the data in the temp table, and then run some dynamic sql to shuffle the data in the temp tables into the final tables.
These operations can ultimately be operating on, say, 100 million rows.
The original code, made a dynamic INSERT statement and then ran sp_executeSql in a WHILE loop in batches of 100,000
I thought thousands of invocations of sp_executeSql might be more expensive than executing 1 statement with the WHILE loop built in, so I tried this instead.  To my great surprise, it took 8 times longer to execute than running EXEC sp_executeSql many thousands of times.
Anyone have an idea why doing a WHILE in a dynamic sql statement would perform so badly?
SET @sql = '
DECLARE @minRowID int = 0, @maxRowID int = @batchSize, @totalInsertedCounts bigint = 0;
WHILE (1=1)
BEGIN
     INSERT INTO ' + @destinationTable + ' ('+ @columnList +')
     SELECT ' + @columnsForSelect + '
     FROM ' + @fromTable + ' AS D (NOLOCK)
     INNER JOIN ' + @workTable + ' AS W (NOLOCK) ON D.[RowID] = W.[RowID_Source]
     WHERE W.RowID > @minRowID AND W.RowID <= @maxRowID
     OPTION (MAXDOP 1)
     SET @counts = @@ROWCOUNT
     CHECKPOINT;
    IF @counts = 0 BREAK

    SET @totalInsertedCounts += @counts
    IF (@totalInsertedCounts % 500000 = 0)
    BEGIN
    DECLARE @percent float = ROUND(@totalInsertedCounts * 100 / CAST(@totalCounts as float), 3);
    DECLARE @percentStr varchar(20) = CAST (@percent as varchar);
    RAISERROR(''Insert completed percent: %s'', 10,1, @percentStr) WITH NOWAIT;
    END

    SET @minRowID += @batchSize
    SET @maxRowID += @batchSize

END
SET @counts = @totalInsertedCounts;
'

EDIT:
Based on the comment, I got the plans for the while-in and single statement (with many sp_executeSql execution).
https://www.brentozar.com/pastetheplan/?id=rkDUlLKb5 - while loop runs 1 dynamic statement
https://www.brentozar.com/pastetheplan/?id=S1sjxIFW5 - while loop in dynamic statement

A: It might be due to the query optimizer generating a new execution plan for each iteration of the loop as opposed to what happens when you execute the sp_executesql many times. Check one of the Remarks from the doc:

sp_executesql can be used instead of stored procedures to execute a
Transact-SQL statement many times when the change in parameter values
to the statement is the only variation. Because the Transact-SQL
statement itself remains constant and only the parameter values
change, the SQL Server query optimizer is likely to reuse the
execution plan it generates for the first execution.

The WHILE might cause a different behavior resulting in bad performance. You should also check the execution plan from each method as it would improve your guesses when trying to tune a query.
See the following query from Understanding SQL Server query plan cache to check if an execution plan is being reused or not:
SELECT cplan.usecounts, cplan.objtype, qtext.text, qplan.query_plan
FROM sys.dm_exec_cached_plans AS cplan
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS qtext
CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qplan
ORDER BY cplan.usecounts DESC


text:
Q: When I run sudo -i or sudo su I get an error Error when running sudo su:
su: failed to execute /bi: No such file or directory

Error when running sudo -i:
sudo: /bi: command not found

How do I fix this error?

A: I learned from steeldriver's deleted answer that I corrupted the root user's login shell entry in the password database and I know how to fix that:
sudo vipw

Then replace root:x:0:0:root:/root:/bi with:
root:x:0:0:root:/root:/bin/bash


text:
Q: QtCreator Error exited with code 3 When I try to compile my project in QtCretor, I get the following message:
14:30:27: Running steps for project study ...
14:30:27: Starting: "C: \ Qt \ Qt5.1.0 \ 5.1.0 \ mingw48_32 \ bin \ qmake.exe" C: \ Users \ lmc \ Documents \ QT \ Study \ Estudo.pro-r spec-win32-g + + "CONFIG + = debug" "CONFIG + = declarative_debug" "CONFIG + = qml_debug"
ASSERT: "fileName.isEmpty () | | isAbsolutePath (fileName)" in file Q: \ qt5_workdir \ w \ s \ qtbase / qmake / library / ioutils.cpp, line 61
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
14:30:27: The process "C: \ Qt \ Qt5.1.0 \ 5.1.0 \ mingw48_32 \ bin \ qmake.exe" exited with code 3.
Error while building / deploying Project Study (kit: Desktop Qt 5.1.0 MinGW 32bit)
When executing step 'qmake'
14:30:27: Elapsed time: 0:01.
Anyone know how can I solve this problem?

A: Perhaps a little bit late but here is the corresponding bug report:
"qmake is crashing with "Qwt 6.1 rc3" and Qt 5 "
https://bugreports.qt-project.org/browse/QTBUG-29642


text:
Q: creating a custom UIView with a NIB Normally, I create custom UIViews by overriding drawRect. Is it possible to create a custom UIView that has a nib associated with it? (not asking about creating a custom UIView from a nib). Or is this usually done with a second view controller that gets contained in the first?
I'd still like to be able to call initWithFrame to instantiate it.
thx
EDIT #1
I'd like to have custom actions associated with buttons on it etc.... Is this functionality only capable in a VC or could a custom view work?

A: Yes, you can do it, but beware nib files are stored on disk instead of in RAM so it is ~10,000 times slower than not using a nib. If you are creating a lot of views, don't do it this way.
Basically your init method loads the nib file, grabs the view in the nib (which should be defined as the same class), and the instead of returning self like most init methods, it returns the view in the nib.
If you lookup the language documentation you will see it's common for an init method to return a different object than "self".
If you are not using ARC, you must release self and retain the view you are returning.
Here is how I would implement it (nib file must match the class name):
- (instancetype)initWithFrame:(CGRect)frame
{
  if (!(self = [super initWithFrame:frame]))
    return nil;

  NSArray *loadedObjects = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:nil options:@{}];
  id newView = nil;
  for (id loadedObject in loadedObjects) {
    if ([loadedObject isMemberOfClass:[self class]]) {
      newView = loadedObject;
      break;
    }
  }

  // if ARC is disabled, you must do this:
  // [self release];
  // [newView retain];

  self = newView;

  self.frame = frame;

  return self
}

A: It's hard to achieve exactly what you are after. Using nib is one way to load views, the other is to create them programatically.
So, trying to answer you questions:

*

*Yes, it is possible to associate a nib with a custom view through the Identity Inspector in IB. However, this is also "creating a custom UIView from a nib". Is that not what you are looking for?

*You do not have to use view controller containment to load views from nibs.

*Being able to call initWithFrame: is not part of using nibs at all since nibs need to use an NSCoder and are inflated from disk. -initWithCoder: should be used instead.

*Yes, you absolutely can have custom views in a nib respond to events from their subviews (UIButtons etc.). You would hook up the IBActions to the custom view subclass as normal. This is not exclusively part of a view controller, although according to MVC this might be breaking a "rule".

Loading a custom view from a nib is strait forward.
Create a strong property for your custom view (In your view controller is a good place)
@property (strong, nonatomic) BBCustomView *customView;

Then to instantiate it:
self.customView = [[[NSBundle mainBundle] loadNibNamed:@"View" owner:nil options:nil] lastObject];

At that point initWithCoder will be called on the custom view. Then you can add that custom view into an existing view hierarchy as normal.
Don't forget to set the proper class for the custom view in the nib file.
Hopefully that clears things up a bit!


text:
Q: Printing a Christmas Tree, using user input and for loops I need to create a program that lets the user put in what they want the height of the Christmas tree to be. Then it needs to print the Christmas with a trunk attached to it.
I got the Christmas tree part down, but I'm having issues with how I should approach centering the trunk underneath the tree with respect to the tree's actual output.
If someone could point me in the right direction, it would be greatly appreciated.
Thank you in advance.
Here is my code so far:

package Homework8;

import java.util.Scanner;

public class Merry_Christmas2 {
 public static void main(String[]args){

  System.out.println("Welcome to Christmas Tree!\n");

  Scanner input = new Scanner(System.in);
  System.out.println("How tall do you want your tree to be?");
  int height = input.nextInt();

  for(int i = 0; i < height;i++){
   for(int j = 0; j< height - i; j++){
    System.out.print(" ");
   }
   for(int k =0; k <= i; k++){
    System.out.print("* ");
   }
   System.out.println();
  }
   for(int i = 0; i <= height;i++){
    for(int j = 0; j >= height;j++){
     System.out.print(" ");
    }
    for(int k = 1; k < 2; k++){
     System.out.print("*");
    }
    System.out.println();
   }
  input.close();
  }
}

A: You have an error in your for j loop:
for(int j = 0; j >= height;j++){

Change >= to < and check if it works.


text:
Q: How to fix while loop stopping + unhandled exception error While loops runs through the if statement once and stops.
I am new to c#, so excuse me if I am overlooking something seemingly obvious. I am currently writing a program that visualizes the Collatz conjecture through console entries. The program begins by prompting the user to enter a natural number. The program is supposed to run that number through the formulae of the conjecture until it eventually reaches a value of 1. However, when I type in the number in console, the program runs it through one formula and crashes. It seems that is has a problem with the Double.Parse line. I already tried using the convert method and tried defining "num" as a decimal instead of a double.
    {
        Console.WriteLine("Enter a natural number:");

        Double num = Convert.ToDouble(Console.ReadLine());

        while (num != 1)
        {
            {
                if (num % 2 == 0)
                {
                    Console.WriteLine(num / 2);
                    num = Double.Parse(Console.ReadLine());
                }
                else
                {
                    Console.WriteLine(num * 3 + 1);
                    num = Double.Parse(Console.ReadLine());
                }
            }

            Console.ReadLine();
        }
    }
}
}

A: To be honest, I'm not positive what you're trying to achieve from the description (i.e., I have not idea what a Collatz conjecture visualization formula is), but I think I figured out what your issue is.
I think you're a little confused about Console.ReadLine(). This method pauses and waits for user input. As a result, during your first loop through the while statement, your program will pause and wait for user input. I think what you're trying to do is take the result of the formula in either the "if" or "else" section and capture that as the new value of "num."
Here is my best guess at what you're trying to achieve:
static void Main(string[] args)
    {
        Console.WriteLine("Enter a natural number:");

        Double num = Convert.ToDouble(Console.ReadLine());

        while (num != 1)
        {
            if (num % 2 == 0)
            {
                num /= 2;
                Console.WriteLine(num);
            }
            else
            {
                num = num * 3 + 1;
                Console.WriteLine(num);
            }
        }

        Console.WriteLine(num);

        Console.ReadLine();
    }

Also, it looks like you might have an extra set of brackets within your while statement. It doesn't seem like that would compile as-is, so perhaps it is just the way in which you copied it into your question.