text:
Q: Deleting an FMXobject inside its event handler I have the following components, tncrdragdata (tframedscrollbox) tdragdata (tgroupbox)
The main Idea is to combine them and use them as a list box (I need it this way).
The groupbox contains five tedit, one tcombobox and one tbutton.
The problem is when I try to free the tdragdata inside its event handler.
I use the FreeNotification method to relocate the group boxes in the framedscrollbox. The problem is that the overridden notification method is executed twice for some reason I don't know.
My question is: Why the overridden method is executed twice?
If I remove the condition (self.components[index]<>AComponent)
in the relocate items method I get an AV. When I debugged this I noticed that the method is executed twice.
This is the code for the two components:
unit ncrdragdataunit;

interface

uses
  System.SysUtils, System.Classes, FMX.Layouts, FMX.Controls.Presentation,
  FMX.StdCtrls, system.Generics.collections, dragdataunit, FMX.objects,
  system.types, FMX.graphics, FMX.dialogs, System.Messaging;

type
  Tncrdragdata = class(TFramedScrollBox)
    private
      { private declarations }
      Faddimage: timage;
      Fnextcoor: tpointf;
      Fitemcounter: integer;
      Fncrdata: tlist<tdragdata>;
      Flocate: boolean;
      function calculate_next_coor: tpointf;
      procedure additem(Aname: string);
      procedure relocate_items(AComponent: TComponent);
      procedure createaddimage(path: unicodestring);
      procedure clickaddimage(sender: tobject);
      procedure Notification(AComponent: TComponent; Operation: TOperation); override;
    protected
      { protected declarations }
    public
      { public declarations }
      constructor Create(AOwner: TComponent); override;
      destructor Destroy; override;
      procedure extract_dragdata(var dragdata: tlist<tdragdatafields>);
    published
      { published declarations }
  end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('ncrcontrols', [Tncrdragdata]);
end;

{tncrdragdata}

constructor tncrdragdata.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
    {spesific data}
  Fncrdata: = tlist<tdragdata>.create;
  Flocate: = true;
  Fnextcoor.X: = 0;
  Fnextcoor.Y: = -60;
  Fitemcounter: = 0;
  if not(csDesigning in ComponentState) then
  begin
    createaddimage('C:\Users\nacereddine\Desktop\down-arrow-2.png');
    additem('item' + inttostr(Fitemcounter));
  end;
end;

destructor tncrdragdata.Destroy;
begin
  Flocate: = false;
  Faddimage.Free;
  Fncrdata.Free;
  inherited;
end;

function Tncrdragdata.calculate_next_coor: tpointf;
begin
  if(self.componentcount = 0) then
  begin
    result.x: = 20;
    result.y: = 20;
  end
  else
  begin
    result.x: = 20;
    result.y: = Fnextcoor.y + 80;
  end;
end;

procedure Tncrdragdata.additem(Aname: string);
var
  a: tdragdata;
begin
  Fnextcoor: = calculate_next_coor;
  a: = tdragdata.create(self);
  Fncrdata.Add(a);
  inc(Fitemcounter);
  with a do
  begin
    name: = Aname;
    text: = '';
    position.y: = Fnextcoor.y;
    position.x: = Fnextcoor.x;
    parent: = self; // parent name
    a.FreeNotification(self);           <---- this is the problem
  end;
  Faddimage.Position.X: = Fnextcoor.x + 260;
  Faddimage.Position.y: = Fnextcoor.y + 60;
end;

procedure Tncrdragdata.relocate_items(AComponent: TComponent);
var
  index: Integer;
begin
  if self.componentcount<1 then exit;
  Fnextcoor.X: = 0;
  Fnextcoor.Y: = -60;
  for index: = 1 to self.componentCount-1 do
  begin
    if (self.components[index] is Tdragdata)and(self.components[index]<>AComponent) then
    begin
      Fnextcoor: = calculate_next_coor;
      (self.components[index] as Tdragdata).Position.Y: = Fnextcoor.y;
      (self.components[index] as Tdragdata).Position.x: = Fnextcoor.x;
    end;
  end;
  Faddimage.Position.X: = Fnextcoor.x + 260;
  Faddimage.Position.y: = Fnextcoor.y + 60;
end;

procedure Tncrdragdata.createaddimage(path: unicodestring);
begin
  Faddimage: = timage.Create(self);
  Faddimage.Parent: = self;
  Faddimage.Width: = 40;
  Faddimage.Height: = 40;
  Faddimage.Bitmap.LoadFromFile(path);
  Faddimage.onclick: = clickaddimage;
end;

procedure Tncrdragdata.clickaddimage(sender: tobject);
begin
  additem('item' + inttostr(Fitemcounter));
end;

procedure Tncrdragdata.Notification(AComponent: TComponent; Operation: TOperation);
begin
  inherited;
  if (Operation = opRemove) and (AComponent is Tdragdata)and Flocate then
  begin
    relocate_items(AComponent);
    Fncrdata.remove(Tdragdata(AComponent));
  end;
end;

procedure Tncrdragdata.extract_dragdata(var dragdata: tlist<tdragdatafields>);
var
  I: Integer;
begin
  for I: = 0 to Fncrdata.Count-1 do
  begin
    dragdata.Add(Fncrdata.Items[I].dragdatafields);
  end;
end;

end.

unit dragdataunit;

interface

uses
  System.SysUtils, System.Classes, FMX.Types, FMX.Controls,
  FMX.Controls.Presentation, FMX.StdCtrls, FMX.listbox, FMX.edit, System.Messaging;

type
  tsectiontype = (ST_vertical, ST_curved, ST_straight);

  tdragdatafields = record
  TVD, MD, VS, Inc, Alfa30: single;
  sectiontype: tsectiontype;
  end;

  tdragdatafield = (df_TVD, df_MD, df_VS, df_Inc, df_Alfa30);

  tdragdata = class(tgroupbox)
    private
      (* private declarations *)
      Fdata: array[0..4] of single;
      OTVD, OMD, OVS, OInc, OAlfa30: tedit;
      Fsectiontype: tsectiontype;
      Osectiontype: tcombobox;
      headerlabel: tlabel;
      Odeletebtn: tbutton;
      procedure onchangevalue(sender: tobject);
      procedure ondeletebtnclick(sender: tobject);
      function getdata: tdragdatafields;
    protected
      (* protected declarations *)
    public
      (* public declarations *)
      constructor Create(AOwner: TComponent); override;
      destructor Destroy; override;

    published
      (* published declarations *)
      property dragdatafields: tdragdatafields read getdata;
  end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('ncrcontrols', [Tdragdata]);
end;

{tdragdata}
constructor tdragdata.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
    {spesific data}
  SetBounds(10, 10, 550, 60);
  self.Text: = '';
  OTVD: = tedit.create(self);
  with OTVD do
  begin
    text: = '';
    SetBounds(10, 30, 80, 21);
    onchange: = onchangevalue;
    parent: = self;
  end;
  OMD: = tedit.create(self);
  with OMD do
  begin
    text: = '';
    SetBounds(100, 30, 80, 21);
    onchange: = onchangevalue;
    parent: = self;
  end;
  OVS: = tedit.create(self);
  with OVS do
  begin
    text: = '';
    SetBounds(190, 30, 80, 21);
    onchange: = onchangevalue;
    parent: = self;
  end;
  OInc: = tedit.create(self);
  with OInc do
  begin
    text: = '';
    SetBounds(280, 30, 80, 21);
    onchange: = onchangevalue;
    parent: = self;
  end;
  OAlfa30: = tedit.create(self);
  with OAlfa30 do
  begin
    text: = '';
    SetBounds(370, 30, 80, 21);
    onchange: = onchangevalue;
    parent: = self;
  end;
  Osectiontype: = tcombobox.create(self);
  with Osectiontype do
  begin
    SetBounds(460, 30, 80, 21);
    items.Add('STvertical');
    items.Add('STcurved');
    items.Add('STstraight');
    //Selected.Text: = 'STvertical';
    onchange: = onchangevalue;
    parent: = self;
  end;

  headerlabel: = tlabel.create(self);
  with headerlabel do
  begin
    text: = 'TVD (m)              MD (m)                VS (m)                '
         + 'Inc (°)                  Alfa (°/30m)         Section type';
    SetBounds(10, 9, 560, 21);
    parent: = self;
  end;
  Odeletebtn: = tbutton.create(self);
  with Odeletebtn do
  begin
    text: = '';
    SetBounds(537, 9, 10, 10);
    parent: = self;
    onclick: = ondeletebtnclick;
  end;

end;

destructor tdragdata.Destroy;
begin
  OTVD.free;
  OMD.free;
  OVS.free;
  OInc.free;
  OAlfa30.free;
  Osectiontype.free;
  headerlabel.free;
  Odeletebtn.Free;
  inherited;
end;

procedure tdragdata.onchangevalue(sender: tobject);

  function getvalue(st: tedit): single;
  begin
    try
      result: = strtofloat(st.Text);
    except
      result: = -1;
      st.Text: = '-1';
    end;
  end;

  function gettype(st: tcombobox): tsectiontype;
  begin
    if st.Selected.Text = 'STvertical' then result: = ST_vertical
    else if st.Selected.Text = 'STcurved' then result: = ST_vertical
    else if st.Selected.Text = 'STstraight' then result: = ST_vertical
    else begin result: = ST_vertical;  end;
  end;

begin
  if sender = OTVD then
  begin
    Fdata[ord(df_TVD)]: = getvalue(OTVD);
  end
  else
  begin
    if sender = OMD then
    begin
      Fdata[ord(df_MD)]: = getvalue(OMD);
    end
    else
    begin
      if sender = OVS then
      begin
        Fdata[ord(df_VS)]: = getvalue(OVS);
      end
      else
      begin
        if sender = OInc then
        begin
          Fdata[ord(df_Inc)]: = getvalue(OInc);
        end
        else
        begin
          if sender = OAlfa30 then
          begin
              Fdata[ord(df_Alfa30)]: = getvalue(OAlfa30);
          end
          else
          begin
            if sender = Osectiontype then
            begin
              Fsectiontype: = gettype(Osectiontype);
            end
            else
              Exception.Create('sender unknown');
            end;
          end;
        end;
      end;
    end;
  end;

function tdragdata.getdata: tdragdatafields;
begin
  result.TVD: = Fdata[ord(df_TVD)];
  result.MD: = Fdata[ord(df_MD)];
  result.VS: = Fdata[ord(df_VS)];
  result.Inc: = Fdata[ord(df_Inc)];
  result.Alfa30: = Fdata[ord(df_Alfa30)];
  result.sectiontype: = Fsectiontype;
end;

procedure tdragdata.ondeletebtnclick(sender: tobject);
begin
  self.Release;
end;

end.

A: I found something interesting about FreeNotification() method here.

Use FreeNotification to register AComponent as a component that should
  be notified when the component is about to be destroyed. It is only
  necessary to register components this way when they are in a different
  form or have a different owner. For example, if AComponent is in
  another form and uses the component to implement a property, it must
  call FreeNotification so that its Notification method is called when
  the component is destroyed.
For components with the same owner, the Notification method is called
  automatically when an application explicitly frees the component. This
  notification is not sent out when components are freed implicitly,
  because the Owner is already being freed.

And then when I removed the line
a.FreeNotification(self);

In the method (the first component)
procedure Tncrdragdata.additem(Aname:string);

And the problem was gone.
I think the problem is that I was calling the FreeNotification() method with Tdragdata, not having a different owner. Clearly I was breaking a rule.
Thanks to @victoria and @CraigYoung for their help.


text:
Q: How to not light certain objects in unity2D I have been working on a small unity project which uses limited view. The issue is that the assets I add into the scene seem to be automatically lit and I'm not sure how to change this. I am using a Universal Render Pipeline. The project

A: You can create new unlit material (In inspector) for your sprite and assign your game objects, with this way it should work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: "Invalid precision or scale value" error from SQL Server with pypyodbc for Decimal('0.00'), Decimal('0.12') I am developing an application in python. I am inserting some financial data into database. I have approx. 1300 tables all with same schema, one table for each company.
I am using pypyodbc 1.3.3(latest).
I have Decimal as datatype. I am using precision of as Decimal(8,2).
In my table, datatypes are DATE, DECIMAL, TINYINT and INT.
I am inserting the following row in one of the table from my python program.
['05-JAN-2015', Decimal('30.90'), Decimal('31.40'), Decimal('30.40'), Decimal('30.85'), None, Decimal('0.00'), Decimal('0.00'), None, Decimal('0.00'), Decimal('0.00'), None, Decimal('0.00'), Decimal('0.00'), None, None, Decimal('30.88'), Decimal('0.00'), Decimal('0.00'), Decimal('0.00'), Decimal('0.00'), 32024, 321, Decimal('0.00'), Decimal('0.00'), None, Decimal('0.00'), None, Decimal('0.00')]

Datatype of 05-JAN-2015 is DATE, All None have datatype as TINYINT, and value 32024, 321 have datatype as INT.
But still I am getting the SQL exception as
  File "C:\Python27\lib\site-packages\pypyodbc.py", line 1470, in execute
    self._BindParams(param_types)
  File "C:\Python27\lib\site-packages\pypyodbc.py", line 1433, in _BindParams
    check_success(self, ret)
  File "C:\Python27\lib\site-packages\pypyodbc.py", line 986, in check_success
    ctrl_err(SQL_HANDLE_STMT, ODBC_obj.stmt_h, ret, ODBC_obj.ansi)
  File "C:\Python27\lib\site-packages\pypyodbc.py", line 964, in ctrl_err
    raise Error(state,err_text)
Error: (u'HY104', u'[HY104] [Microsoft][SQL Server Native Client 10.0]Invalid precision or scale value')

When I try to insert the same data directly into SQL server from management studio, then It get inserted successfully.
I have cross checked the datatype of the variables and all are perfect.
As I am inserting data into ~1300 tables in a loop somewhat like
for i in range(tables_number):
    insertion_data = calculate_values()
    insert_into_db(insertion_data)

,does that causes the problem?
I have also tried by using the delay of 0.1 second in a loop.
Does Anybody have any idea? Is this bug in driver? Or Is there any other cause that I am missing?
UPDATE:
After debugging the code, I found in the script pypyodbc.py, function SQLBindParameter(<many parameters>) returns -1 which is SQL_ERROR for parameter Decimal('0.00') or Decimal(0.12) or Decimal(-0.12) means decimal of the form 0.*

A: It appears to be a bug in pypyodbc. This code, using pypyodbc 1.3.3, fails just as you describe ...
from decimal import *
import pypyodbc
connStr = "DSN=myDb_SQLEXPRESS;"
cnxn = pypyodbc.connect(connStr, autocommit=True)
crsr = cnxn.cursor()
sql = "INSERT INTO Invoices (InvoiceAmount) VALUES (?)"
invamt = Decimal('0.01')
crsr.execute(sql, [invamt])
crsr.close()
cnxn.close()

... but doing the exact same thing using pyodbc works okay:
from decimal import *
import pyodbc
connStr = "DSN=myDb_SQLEXPRESS;"
cnxn = pyodbc.connect(connStr, autocommit=True)
crsr = cnxn.cursor()
sql = "INSERT INTO Invoices (InvoiceAmount) VALUES (?)"
invamt = Decimal('0.01')
crsr.execute(sql, [invamt])
crsr.close()
cnxn.close()

Furthermore, if I run the pypyodbc version against an identical table in a MySQL database ...
from decimal import *
import pypyodbc
connStr = "DSN=usbMySQL;"
cnxn = pypyodbc.connect(connStr, autocommit=True)
crsr = cnxn.cursor()
sql = "INSERT INTO Invoices (InvoiceAmount) VALUES (?)"
invamt = Decimal('0.01')
crsr.execute(sql, [invamt])
crsr.close()
cnxn.close()

... the value that gets inserted into the database is 0.10, not 0.01.


text:
Q: How to handle Risk in TFS scrum templates In the TFS CMMI template, I can find the Risk work item and it's very useful for us.
But I couldn't find this work item in the Scrum and the Agile template.
Please let me know how to handle the Risk within the TFS Scrum and Agile template.

A: Having a Risk Work Item is mostly considered an unnecessary overhead and is not required to meet CMMI. Since Risks don't change often, and should not abound, I would keep them on a list on the Team wall. If you have so many risks that you and your team cant remember them then that should set alarm bells off!
Wherever you keep them they should be visible and accessible by the engineers.
Option 1: Stickies on the wall (best)
Option 2: In Excel, printed and on the wall
Option 3: Create your own Risk work item


text:
Q: Is the following function C1? Please check my answer Let us consider the function:
$$ f(x,y) \,=\, (xy)^{\gamma} \,(x+y-2) $$
with gamma defined as
$$ \gamma = \begin{cases} 2 \quad \text{if} \quad x<y \\ 5 \quad \text{if} \quad x \geq y.\\ \end{cases} $$
Is this function continuously differentiable in the point (x,y) = (1,1) ?
My answer is yes.
The partial derivative $\frac{\partial f(x,y)}{\partial x} = (xy)^{\gamma}\biggl[ \gamma \frac{x+y-2}{x} +1 \biggr]$ evaluated at (1,1) does not depend on gamma. The same is true for $\frac{\partial f(x,y)}{\partial y}$, and so the function $f(x,y)$ is C1 in (1,1). Is this correct?

A: \begin{eqnarray}
f_x(1,1)&=&\lim_{h\to0}{h(1+h)^{\gamma}}\\
&=&0\\
f_y(1,1)&=&\lim_{h\to0}{h(1+h)^{\gamma}}\\
&=&0\\
\end{eqnarray}
It doesn't matter whether $x<y$ or not because $\lim_{h\to0^\pm}(1+h)^{\gamma}$ is $1^{5}$ or $1^2$ which is $1$.
Therefore the full derivative is:
\begin{eqnarray}
D_xf(1,1)&=&f_x(1,1)+f_y(1,1)D_xy(1,1)\\
&=&0\\
D_yf(1,1)&=&f_y(1,1)+f_x(1,1)D_yx(1,1)\\
&=&0
\end{eqnarray}
Given $D_xy$ and $D_yx$ exist at $(1,1)$.


text:
Q: Java String variable setting - reference or value? The following Java code segment is from an AP Computer Science practice exam.
String s1 = "ab";
String s2 = s1;
s1 = s1 + "c";
System.out.println(s1 + " " + s2);

The output of this code is "abc ab" on BlueJ. However, one of the possible answer choices is "abc abc". The answer can be either depending on whether Java sets String reference like primitive types (by value) or like Objects (by reference).
To further illustrate this, let's look at an example with primitive types:
int s1 = 1;
int s2 = s1; // copies value, not reference
s1 = 42;

System.out.println(s1 + " " + s2); // prints "1 42"

But, say we had BankAccount objects that hold balances.
BankAccount b1 = new BankAccount(500); // 500 is initial balance parameter
BankAccount b2 = b1; // reference to the same object
b1.setBalance(0);
System.out.println(b1.getBalance() + " " + s2.getBalance()); // prints "0 0"

I'm not sure which is the case with Strings. They are technically Objects, but my compiler seems to treat them like primitive types when setting variables to each other.
If Java passes String variables like primitive type, the answer is "abc ab". However, if Java treats String variables like references to any other Object, the answer would be "abc abc"
Which do you think is the correct answer?

A: Indeed, String is a class and it's assigned / passed by reference.
But what's confusing is the statement:
String s = "abc";

Which suggests that String is a primitve ( like 'int x = 10;' );
But that's only a shortcut, the statement 'String s = "abc";' is actually compiled as 'String s = new String( "abc" );'
Just like 'Integer x = 10;' is compiled as 'Integer x = new Integer( 10 );'
This mechanism is called 'boxing'.
And more confusing is: there's a class 'Integer' and a primitive 'int',
but String doesn't have a primitive equivalent (allthough char[] comes close)
Sije de Haan

A: In Java, String objects are assigned and passed around by reference; it this respect they behave exactly like any other object.
However, Strings are immutable: there isn't an operation that modifies the value of an existing string in place, without creating a new object. For example, this means that s1 = s1 + "c" creates a new object and replaces the reference stored in s1 with a reference to this new object.

A: String is a class, so a String variable is a reference.  But it's a language intrinsic, in the sense that Java has special handling and syntax for it, which is why you can do things like your example.
See e.g. http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html.

A: java.lang.String is an object, not a primitive.
What the code did in the first example is:

*

*Define s1 as "ab"

*Set s2 equal to the same underlying object as s1

*Set s1 equal to a new string that is the combination of s1's old value and "c"

But to answer your question about reference or value, it's by reference.

A: java Strings are immutable, so your reassignment actually causes your variable to point to a new instance of String rather than changing the value of the String.
String s1 = "ab";
String s2 = s1;
s1 = s1 + "c";
System.out.println(s1 + " " + s2);

on line 2, s1 == s2 AND s1.equals(s2).  After your concatenation on line 3, s1 now references a different instance with the immutable value of "abc", so neither s1==s2 nor s1.equals(s2).

A: The difference between your BankAccount and a String is that a String is immutable.  There is no such thing as 'setValue()' or 'setContent()'.  The equivalent example with your bank account would be :
BankAccount b1 = new BankAccount(500); // 500 is initial balance parameter
BankAccount b2 = b1; // reference to the same object
b1 = new BankAccount(0);
System.out.println(b1.getBalance() + " " + s2.getBalance()); // prints "0 500"

So if you think of it this way (not actually what the compiler does, but functionally equivalent) the String concatenation scenario is:
String s1 = "ab";
String s2 = s1;
s1 = new String("abc");
System.out.println(s1 + " " + s2); //prints "abc ab"

A: It is not relevant whether String is treated like a primitive or like an object!
In the String example, the concatenation of two strings produces a new String instance, which is then assigned to s1. The variable s2 still references the unchanged(!) old String instance.
Assuming the BankAccount had a method to set the balance, which returns a new BankAccount, your example could look like this:
BankAccount b1 = new BankAccount(500); // 500 is initial balance parameter
BankAccount b2 = b1; // reference to the same object
b1 = b1.createNewAccountWithBalance(0); // create and reference a new object
System.out.println(b1.getBalance() + " " + b2.getBalance()); // prints "0 500"

A: The assertion

if Java treats String variables like references to any other Object, the answer would be "abc abc"

is incorrect. Java does treat String variables like references to any other Object. Strings are Objects but the answer is "abc ab" none the less.
The issue is not what the assignment operator does. The assignment operator assigns a reference to a String object in every case in your example.
The issue is what the concatenation operator ('+') does. It creates a new String object. As other have said, this is necessary because a String object is immutable but it is an issue of operator behaviour and not merely because String is immutable. The concatenation operator could return a new Object even if a String object were mutable.
In contrast, in your second example, b1.setBalance(0) does not create a new object, it modifies the existing object.

A: int s1 = 1;
int s2 = s1; // copies value, not reference
s1 = 42;

System.out.println(s1 + " " + s2); // prints "1 42"

Doesn't print "1 42" but "42 1".Take each discrete line into consideration.First s1 assigns 1, then s2 assigns s1, which is 1 up until now(suppose java didn't see the third line yet.) Then java sees the third line and immediately changes s1 into 42.After that java was told to print what it knows so far, and that is s1 is 42 and s2 is 1(the old s1).
As for the String the same thing happens.
String s1 = "ab";
String s2 = s1;
s1 = s1 + "c";
System.out.println(s1 + " " + s2);// prints "abc ab".

Fort String it doesn't necessarily changes s1 but rather s1 now refers to a new String object in the heap memory, but the old "ab" object is still there, with a new reference of s2!


text:
Q: Remove
* indentation I've removed the bullet on my lists using
ul li { list-style: none; }

But I'm still getting an indentation on the lists as if the bullet was there.

I need the list-item in the image to be exactly centered.

A: Browsers ship a default styling attached to <ul/> and <li/> tags
ul,li { list-style-type: none;
        list-style-position:inside;
        margin:0;
        padding:0; }

http://meyerweb.com/eric/tools/css/reset/

A: All the answers provided will fix your issue, but I definately recommend that you look in to using a reset stylesheet so you don't have cross browser issues!
The best one (well most popular one at least), is most likely this:
http://html5doctor.com/html-5-reset-stylesheet/
Hope that helps your issue, but if you don't want to use a reset style sheet simply:
ul, li{
    margin: 0;
    padding: 0;
}

A: You can also add a margin and padding 0:
ul li {
   list-style: none;
   margin:0;
   padding:0;
}

A: If you want to center the text, try
li{
  padding-left: 0px;
  padding-right:0px;
  margin-left:0px;
  margin-right:0px;
  text-align:center;
}


text:
Q: How to get the index of a pivot table as columns I'm trying to pivot a table that I have.  It has 4 main columns, and about 20 other columns of no use.  The columns are Site, Category, Week_Beginning and Total_Hours.
I'm trying to sum the total_hours by site, category and week_beginning.
I'm using the df.pivot_table function, and it does it as I want, but the output needs some fixing.
It works well, but I get the following output:

Index                                              ('sum','Total_Hours')
  ('Site1','Cat1',Timestamp('2019-12-23'))                  725

The code I'm using is:
df2=df.pivot_table(index=['Site','Category','Week_Beginning'],values=['Total_Hours'],aggfunc=[np.sum],fill_value=0)

The code works well from a math perspective, that is to say, that the sum is correct
The output is:
It works well, but I get the following output:

Index                                              ('sum','Total_Hours')
  ('Site1','Cat1',Timestamp('2019-02-23'))                  725

So the output only has one column with a name of ('sum','Total_Hours')
What I was expecting was 4 columns as shown below:
Site       Category           Week_Beginning           Total_Hours
Site1        Cat1               2019-03-23                225
Site1        Cat1               2019-03-30                152

Any help would be appreciated.
I'm using python 3.7.3 via Spyder 3.3.3
Thanks.
-PR.

A: It sounds to me like you should use groupby -
df2=df.groupby(['Site','Category','Week_Beginning']).agg({"Total_Hours":"sum"}).reset_index()


text:
Q: How to get png or jpeg or bmp pictures in wxpython I want to search for png, jpeg and bmp pictures but it doesn't seems to work.
def onClick(self,Event):
        wildcard='PNG files (*.png)|*.png|'|'BMP files (*.bmp)|*.bmp|'|'JPEG files (*.jpg)|*.jpg|'
        openFileDialog = wx.FileDialog(self, "Open", "", "", wildcard,wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
        openFileDialog.ShowModal()

Here is the error and i don't know how to resolve it
wildcard='PNG files (*.png)|*.png|'|'BMP files (*.bmp)|*.bmp|'|'JPEG files (*.jpg)|*.jpg|'
TypeError: unsupported operand type(s) for |: 'str' and 'str'

A: Doing a string | string does not make sense. That means that
'something'|'something'

throws the exception above. All of your | characters should be a part of
the wildcard string.
For just pngs use:
'PNGs (*.png)|*.png'

For gifs and jpegs use:
'Various image formats - png,jpg|*.png;*.jpg'

If you want to let the user choose:
'Various image formats|*.png;*.jpg|Just BMPs (*.bmp)|*.bmp'


text:
Q: How can I set rails routes to redirect some urls to another controller with parameter and default action? I want to mix the two line below with one.
I guess it is possible but I don't know.
any ideas you have?
match '/alias4' => redirect("/original/4") # redirect to original#show => 4
match '/alias4(/:action)' => redirect("/original/4/%{action}") # redirect to some actions (not restful)

A: match '/alias4(/:action)' => redirect("/original/4/%{action}"), :defaults => { :action => "show" }

should work.
Source: http://guides.rubyonrails.org/routing.html#defining-defaults .


text:
Q: Emplear try/except si se produce error de no encontrar cámara Estoy trabajando con mi webcam y opencv. Para ejecutar la cámara se emplea  la siguiente línea:
cap = cv2.VideoCapture(0)

Donde el valor numérico por defecto dentro del paréntesis suele ser 0 pero también podemos poner un 1.
Este valor tiene cómo objetivo definir que cámara vas a usar, la 0 normalmente es la propia del ordenador y la 1 una externa que tengas conectada.
Hasta aquí no hay problema, el problema viene a que me plantee en que en el caso que haya una externa conectada quiero usar la externa pero si no lo hay, que el programa se de cuenta y use la cámara interna (siempre asumiendo que habrá al menos una cámara en el ordenador), entonces me plantee emplear try except.
try:
    cap = cv2.VideoCapture(1)
except:
    cap = cv2.VideoCapture(0)

Pero esto cuando no hay externa no funciona, es decir, nunca entra en el except y por lo tanto me salta un error de que no hay cámara externa. ¿Cómo debo gestionarlo si no es así?
El error es:

cv2.error: OpenCV(4.0.0) /io/opencv/modules/highgui/src/window.cpp:350: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'imshow'

¡Salud y gracias!

A: Tomando como referencia este post de SO en Inglés, lo que sucede es que se crea un objeto VideoCapture, pero inválido.
Una posible solución es:
import cv2

cap = cv2.VideoCapture(1)

if !cap.isOpen():
    print("Invalid device id 1, Selecting default device id 0")
    cap = cv2.videoCapture(0)


text:
Q: You must provide a value expression following the '-Like' operator I want to enable IIS by Enable-WindowsOptionalFeature in windows 8,so I write a python program,its code is:
os.system('powershell -Command "%s"' % r'Enable-WindowsOptionalFeature -Online -FeatureName $(Get-WindowsOptionalFeature -Online | Where { $_.FeatureName -Like "IIS-*"} | Select-Object -ExpandProperty FeatureName)')

when I run the program, it shows that this:
PS C:\Python27> ./python fr.py
At line:1 char:119
+ ... WindowsOptionalFeature -Online | Where { $_.FeatureName -Like IIS-*}  ...
+                                                                  ~
You must provide a value expression following the '-Like' operator.
At line:1 char:120
+ ... sOptionalFeature -Online | Where { $_.FeatureName -Like IIS-*} | Sele ...
+                                                          ~~~~~
Unexpected token 'IIS-*' in expression or statement.
    + CategoryInfo          : ParserError: (:) [],ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ExpectedValueExpression

can you help with this? Thanks.

A: Escape the double quotes via backslash. ... Where { $_.FeatureName -Like \"IIS-*\"}  ...
The main trouble is that os.system() invokes a command-line parsing of full parameter string, which eats up double quotes as part of parsing sequential arguments. Backslash prevents "overparsing" double quotes, passing them to Powershell. An example:
>>> os.system('powershell -command "%s"' % r'get-process | where {$_.name -like \"powershell*\"}')

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    286      24    57948      54196   606     0,51   5336 powershell
    501      32    46540      58164   239     7,58   5456 powershell


text:
Q: Optional IconData on constructor I'm studying Flutter, so I'm just a newbie.
I tried to create a widget with an optional IconData type parameter in the constructor, but I was getting an error.
I got added "?" in front of the local variable. From then on, I just had to enclose the constructor parameters in "{ }". I've found a way to make it work, but I'm not sure it is the best/correct way to do so.
If you have any tip, I'll be happy to hear it!
That's my code:
class Editor extends StatelessWidget {
  final TextEditingController controlador;
  final String label;
  final String hint;
  final IconData? fieldIcon;

  Editor(
      {required this.controlador,
      required this.label,
      required this.hint,
      this.fieldIcon});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(16.0),
      child: TextField(
        controller: controlador,
        style: const TextStyle(
          fontSize: 24.0,
        ),
        decoration: InputDecoration(
          labelText: label,
          hintText: hint,
          icon: fieldIcon != null ? Icon(fieldIcon) : null,
        ),
      ),
    );
  }
}

A: Your code is correct. Nothing inappropriate in my opinion.

However, I feel the following checking for is redundant:
icon: fieldIcon != null ? Icon(fieldIcon) : null,

Given that the icon property of InputDecoration already takes a nullable icon, why not give it just that?
Maybe change the type of fieldIcon from IconData? to Icon? itself. Then, where you consume the icon in the InputDecoration, simply give it the nullable fieldIcon:
icon: fieldIcon,

But wherever you use this Editor widget, remember to give it an Icon for fieldIcon and not an IconData.


text:
Q: UseIdentityServerBearerTokenAuthentication is not working for IdentityServer3 I have used the IdentityServer v3, now I want one website to be both the identity host and the web api host.
The authority option is not used to validate the token. I have verified the token endpoint and the token validation endpoint is working as expected (I can get and validate a token using postman). I used the [Authorize] attribute to decorate my controller method. Full logging is enabled on IdentityServer, nothing is logged when making an api request with a header name 'Authorization' with the value  like 'Bearer mytokenhere'.
This is a vNext website on ASP.NET 5 using the Visual Studio 2015 CTP6.
        app.UseMvc();

        var certFile = AppDomain.CurrentDomain.BaseDirectory + "\\myawesomesite.pfx";

        app.Map("/core", core =>
        {
            var factory = InMemoryFactory.Create(
                            users: Users.Get(),
                            clients: Clients.Get(),
                            scopes: Scopes.Get());

            var idsrvOptions = new IdentityServerOptions
            {
                SiteName = "Lektieplan",
                Factory = factory,
                RequireSsl = false,
                SigningCertificate = new X509Certificate2(certFile, "lektieplan"),
                CorsPolicy = CorsPolicy.AllowAll,
                LoggingOptions = new LoggingOptions { EnableWebApiDiagnostics = true,EnableHttpLogging = true, IncludeSensitiveDataInLogs = true, WebApiDiagnosticsIsVerbose = true }
            };

            core.UseIdentityServer(idsrvOptions);
        });

        app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
        {
            Authority = "http://localhost:57540/core",
            RequiredScopes = new[] { "api1" },
        });

And my project.json
My dependencies:
    "Microsoft.AspNet.Server.IIS": "1.0.0-beta3",
    "Microsoft.AspNet.Mvc": "6.0.0-beta3",
    "Microsoft.AspNet.StaticFiles": "1.0.0-beta3",
    "Microsoft.AspNet.Server.WebListener": "1.0.0-beta3",
    "Thinktecture.IdentityServer3": "1.3.0.0",
    "Microsoft.AspNet.Owin": "1.0.0.0-beta3",
    "Microsoft.AspNet.Security.DataProtection": "1.0.0.0-beta3",
    "Thinktecture.IdentityServer3.AccessTokenValidation": "1.2.2",
    "Autofac": "4.0.0-alpha1",
    "log4net": "2.0.3"

I seems to me that some of the provided samples works because of a cookie based option. I don't want to use the cookies.

A: Is UseIdentityServerBearerTokenAuthentication your only auth type? Do you have any filters defined for MVC?
I would try to split the apps into separate katana pipelines, so they don't conflict at all.
Pseudo:
app.Map("/core", a => a.UseIdsrv());
app.Map("/somethingweb", a => a.UseMvc());
app.Map("/api", a => {
   a.UseBearerTokenAuth();
   a.UseWebApi(); //or Mvc from now on, with v5
});

Guessing you would need to add cookieauth to that mvc pipeline as well, depending on what you want to achieve.


text:
Q: Prevent Google Charts from escaping apostrophes in a title of a chart I'm using google Bar Charts https://developers.google.com/chart/interactive/docs/gallery/barchart. The titles for are stored in a database and some them contain apostrophes. Those apostrophes in the title are rendered as &39, for example "he's" ---> "he&39s"
I want apostrophes to be rendered normally.
I've found several solutions but none of them worked so far for such a simple task.
Any working solution?
update:
This is rendered properly, as I'm goooood
  var chart = new google.visualization.ColumnChart(document.getElementById("my_div"));
  chart.draw(data, {
    title: "I'm goooood",
    legend: {position: "none"},
  });

But this - not, it's ---> I'm goooood
  var chart = new google.visualization.ColumnChart(document.getElementById("my_div"));
  chart.draw(data, {
    title: "<%= get_value_from_db() %>",
    legend: {position: "none"},
  });"

On other pages, without charts but text only, the "<%= get_value_from_db() %>" gets rendered correctly -- I'm goooood.

A: I've had the same issue but only with ' and " which get rendered as  "&39," or  "&34," .
As none of the above fixes worked for me, a quick and pretty dirty solution I've relied upon is using string.replace with the prime ( ′ ), and double prime ( ″ ) symbols - looped through a reasonable number of times.
<%= varName.replace("\'",'′').replace("\"",'″ ') %>

Also I think this error may have something to do with how Google Charts and EJS interact together as both the OP and I are using it and have this issue. (pure speculation)

A: Use \ to escape '. Look at the example

As you are getting tittle from db, you have to add \ before ' in title string using string manipulation.

A: you can use a dom element to convert the ascii characters to readable text
function convertToText(ascii) {
  var tempDiv = document.createElement('DIV');
  tempDiv.innerHTML = ascii;
  return tempDiv.textContent || tempDiv.innerText || '';
}

in your options...
chart.draw(data, {
  title: convertToText("<%= get_value_from_db() %>"),
  legend: {position: "none"},
});

see following working snippet...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ['x', 'y'],
    ['A', 9],
    ['B', 30],
    ['C', 50],
    ['D', 70],
    ['E', 90]
  ]);

  var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
  chart.draw(data, {
    title: convertToText('I'm goooood'),
    legend: {position: 'none'},
  });

  function convertToText(ascii) {
    var tempDiv = document.createElement('DIV');
    tempDiv.innerHTML = ascii;
    return tempDiv.textContent || tempDiv.innerText || '';
  }
});

A: Just use decodeURI on the text.
My title comes from what the user has chosen from categories.
So, when I show the chart title, I do like this:
title: decodeURI(strCategory) + ' from ' + decodeURI(strInitialDate) + ' to ' + decodeURI(strEndDate)
My categories include, 'Alimentação', 'Feira/Sacolão' and others...
It works even on smartphones.
Added: Works with alerts also...
alert('Sem dados para o período de: ' + decodeURI(strInitialDate) + ' a ' + decodeURI(strEndDate))


text:
Q: ReactJs How to link a page to open with a certain condition? I'm working on a website and I have created a profile page
in this profile page there are buttons ( Settings , Favourites , Posts)
I made it like a multi-step form , when you click one of those buttons it shows one of 3 pages ( each button has an onClick method that sets the page number and an if functions returns every page according to that number )
the first page that shows when you click on profile is the Settings and I have a button for favourites in the navbar and I want to link it to the profile page in a way that shows the favourites page and not the settings when I click on it.
I apologize if my question isn't clear / understandable I'm still new to web development.
Here's the code for the page display :
const [page,setPage]=useState(0);
const FormText=["Reglages","Mes Annonces","Favoris"]
const PageDisplay =()=> {
    if (page === 0){
        return <Reglages/>;
    }
    else if (page === 1){
        return <Mesannces/>;
    }
    else if (page === 2){
        return <Favoris />;
    }

this is the code for the buttons :
<Button onClick={()=>{setPage ((currentPage)=>currentPage=0);}} disabled={page===0}>Reglages</Button>
    <Button onClick={()=>{setPage ((currentPage)=>currentPage=1);}} disabled={page===1}>Mes Annonces()</Button>
    <Button onClick={()=>{setPage ((currentPage)=>currentPage=2);}} disabled={page===2}>Favoris</Button>

A: const [page, setPage] = useState(0)

//Where your will render, inside your div

<div>
{page === 0 ? < Reglages/> : page === 1 ? < Mesannces/> : page === 2 && < Favoris />
</div>

Buttons
<Button onClick={()=>setPage(0)} disabled={page===0}>Reglages</Button>
<Button onClick={()=>setPage(1)} disabled={page===1}>Mesannces</Button>
<Button onClick={()=>setPage(2)} disabled={page===2}>Favoris</Button>

I hope this helps


text:
Q: Have one button bind another button? I'm trying to bind the start button when the reset button is pressed.  When the start button is pressed it unbinds it's click event. But I want it so that when the reset button is clicked it binds the start button's click event so it can be pressed again. The below isn't working.  Any ideas?
//Start
$("#start").bind("click", function(){
  $("#start").unbind('click')
  addCompMove();
  playerMove();
});
$("#reset").bind("click", function(){
  $("#start").bind('click');
  comp.length = 0;
  player.length = 0;
  hoverCount = 0;
  score = 0;
  console.log(comp)
});

A: on() and off() are the preferred methods to bind and unbind event listeners in jQuery since version 1.7.
Instead of using anonymous functions, you should declare them. It's more modular, easier to understand, and lets you do what you're trying to do.
$("#start").on("click", startClicked);

function startClicked(e){
    $(this).off("click");
    $("#reset").on("click", resetClicked);
    // other start stuff
}

function resetClicked(e){
    $(this).off("click");
    $("#start").on("click", startClicked);
    // other reset stuff
}

The problem with some of the other answers is you will easily end up with multiple instances of an event listener stacked on top of each other, all firing from a single click. If you click "reset" many times, you will end up with many bindings of the "start" event listener which you do not want. Depending on the functionality you want, make sure you either only allow one button to have a listener attached at a time, or unbind all previous listeners and rebind only the ones you want.

A: I suggest creating a function that executes your start actions.
That makes it easier to rebind the actions to the click event without redeclaring them every time.
function startActions() {
  $(this).unbind('click');
  addCompMove();
  playerMove();
}

$("#start").bind("click", startActions);

$("#reset").bind("click", function() {
  $("#start").bind("click", startActions);
  comp.length = 0;
  player.length = 0;
  hoverCount = 0;
  score = 0;
  console.log(comp);
});

Edit
Also, in your "reset" handler, I suggest unbinding the click event before rebinding it. This will prevent multiple click events from being bound if the "reset" button is clicked multiple consecutive times.
$("#start").unbind('click').bind("click", startActions);

Demonstration below:

var $output=jQuery('div#output');

function startActions() {
  $(this).unbind('click');
  $output.html($output.html()+"
"+"Started");
}

$("#start").bind("click", startActions);

$("#reset").bind("click", function() {
  $("#start").unbind('click').bind("click", startActions);
  $output.empty();
});

<button type="button" id="start">START</button>
<button type="button" id="reset">RESET</button>

Edit
Another idea is to disable buttons rather than unbinding events:

var $output = jQuery('div#output'),
    $start = jQuery('#start'),
    $reset = jQuery('#reset');

$start.on("click", function() {
  $output.html($output.html() + "
" + "Started");
  $(this).prop('disabled', true);
  $reset.prop('disabled', false);
});

$reset.on("click", function() {
  $output.empty();
  $(this).prop('disabled', true);
  $start.prop('disabled', false);
});

<button type="button" id="start">START</button>
<button type="button" id="reset" disabled>RESET</button>

A: You want to pull out the function you are trying to bind the click to so you can add and remove it as needed.
var doMove = function(){
  $("#start").unbind('click');
  addCompMove();
  playerMove();
}

$("#start").bind("click", doMove); // bind at start
$("#reset").bind("click", function(){
  $("#start").bind('click', doMove); // bind again
  comp.length = 0;
  player.length = 0;
  hoverCount = 0;
  score = 0;
  console.log(comp);
});

A: maybe this is more efficient?
    var started = false;
    $("#start").bind("click", function(){
      if(!started){
      addCompMove();
      playerMove();
      started = true;
      }
    });
    $("#reset").bind("click", function(){
      if(started){
      comp.length = 0;
      player.length = 0;
      hoverCount = 0;
      score = 0;
      console.log(comp);
      started = false;
     }
});

A: Use $('#xyz).one('click',function() {}} instead of bind unbind.  Using one will unbind automatically after firing once so you only have to worry about applying .one to the next control.


text:
Q: Fetch value from multiple drop down with same name row wise I have a table like below-

the code of this table in my view is as following-

   Course Name
   Class
   Subject Name
   Month
   View

   <?php if(!empty($data)) { $i=1; foreach($data as $key => $value) { ?>

        <?php echo $value->course_name; ?>
        <?php echo $value->class_name; ?>
        <?php echo $value->subjectName; ?>
        <select class="form-control" id="month" data-parsley-required="true" data-parsley-error-message="Please Select Class">
             <option value="" hidden="hidden">Select Month</option>
             <option value="1">January</option>
             <option value="2">Febuary</option>
             <option value="3">March</option>
             <option value="4">April</option>
             <option value="5">May</option>
             <option value="6">June</option>
             <option value="7">July</option>
             <option value="8">August</option>
             <option value="9">September</option>
             <option value="10">October</option>
             <option value="11">November</option>
             <option value="12">December</option>
            </select>

           <button id="<?php echo $i;?>" class="form-control" data-eid="<?php echo $this->session->userdata('e_id');?>"                                                data-subjectid="<?php echo $value->subjectId;?>" data-courseid="<?php echo $value->course_id;?>" data-classid="<?php echo $value->class_id;?>">
     View</button>

  <?php $i++; } } ?>

//javascript

Whenever I select month and click the view button the page is redirected correctly, but when I select month in the second row and click the view button again it gives alert select month.
I don't know how to differentiate all the dropdowns based on a name.

A: The issue is because you're repeating the same id attributes in the elements you create in the loop. These need to be unique within the DOM.
To fix the issue you need to change the id to class. Then you can use jQuery's DOM traversal methods to find the month select which is in the same row as the button which was clicked. To do that use closest() to get the parent tr, then find():
<select class="form-control month" data-parsley-required="true" ... >

$('button').on('click', function() {
  var eid = $(this).data('eid');
  var subId = $(this).data('subjectid');
  var courseId = $(this).data('courseid');
  var classId = $(this).data('classid');

  var month = $(this).closest('tr').find('.month').val();
  if (month == '')
    alert("Select Month");
  else
    alert("okay");
});

A: You can do that by looping select with name attribute. something like below.

$(document).ready(function(){

$("#show").on('click',function(){
    $("select[name='car']").each(function(){
          var car=$(this).val();
          console.log(car);
    })
})

})

    Jill
    <select name='car'>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>
    50

    Eve
    <select name='car'>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>
    94

<input type='button' id='show' value='showname'/>


text:
Q: Python & Arrays : Search and Add Missing Element in Array I have a messy array; every element has subelements and every subelement has sub-subelements. My array is;
myComplex=[[['03.04.2019', 'Jack', '7']], [['26.03.2019', 'Micheal', '5'], ['26.03.2019', 'Smith', '8']], [['01.04.2019', 'Jack', '11'], ['01.04.2019', 'Michelle', '2'], ['01.04.2019', 'George', '9']]]

Let me explain this array;
The Subelements that begins with '03.04.2019'; ['03.04.2019', 'Jack', '7']
The Subelements that begins with '26.03.2019'; ['26.03.2019', 'Micheal', '8'], ['26.03.2019', 'Smith', '5']
The Subelements that begins with '01.04.2019'; ['01.04.2019', 'Jack', '11'], ['01.04.2019', 'Michelle', '2'], ['01.04.2019', 'George', '9']
In myComplex above, as you see, every subelements' first sub-subelement is a date. I want to add the missing dates between 01.04.2019 and 05.04.2019 (which are 02.04.2019, 04.04.2019, 05.04.2019 for this list) with sub-subelements like this format;
[['02.04.2019', 'George', '0']]
[['04.04.2019', 'George', '0']]
[['05.04.2019', 'George', '0']]

So I want the output like this when I enter print(myComplex)
[[['26.03.2019', 'Micheal', '5'], ['26.03.2019', 'Smith', '8']], [['01.04.2019', 'Jack', '11'], ['01.04.2019', 'Michelle', '2'], ['01.04.2019', 'George', '9']], [['03.04.2019', 'Jack', '7']], [['02.04.2019', 'George', '0']], [['04.04.2019', 'George', '0']], [['05.04.2019', 'George', '0']]]

How can I do that? Can you give me a solution for this?

A: Rather than using lists, I would suggest entering the data into a pandas DataFrame with a timestamp index and name and value columns and then resample to the desired time period and then complete using ffill.

A: If your output "must" look like that, then I'd imagine you'll just have to rebuild it manually.  If you're open to working alternatives though, you might find it easier to manage as a dictionary:
{date: [[name,number],[name,number]], date2: [[name,number]]}

And though it won't matter much to the dictionary, if it has to stay a list array, consider yyyy.mm.dd for easier sorting.

A: Similarly to what Iain D said you could have a dictionary
my_little_bit_complex_dict = {
    '03.04.2019' : [
                    {'name': 'Jack', 'number': 7}
                    ],
    '26.03.2019' : [
                    {'name': 'Michael', 'number': 7},
                    {'name': 'Smith', 'number': 8}
                    ]
}

But to be honest you might want to consider using a database if the amount of data is big
CREATE TABLE mytable (
    somedate DATE,
    name VARCHAR(255),
    numberthingy INTEGER
)


text:
Q: Why doesn't this execute the function given for RxScala's doOnSubscribe function?   val x: Observable[Int] = Observable.just(1).doOnSubscribe(() => println(s"subscribed"))
  val y = x.subscribe(t => println(s"got item: $t"))
  println("all done")

I would have thought this code would print
subscribed
got item: 1
all done

But it doesn't print the initial "subscribed".

A: The signature of doOnSubscribe is:
def doOnSubscribe(onSubscribe: => Unit): Observable[T]

That is, it takes a by-name argument. So you have to use it as follows:
Observable.just(1).doOnSubscribe(println(s"subscribed"))

by-name means that the println will not be executed when passed to doOnSubscribe, but only once doOnSubscribe uses it.
What you were passing to doOnSubscribe is a 0-arity function, i.e. an expression of type () => Unit, and by discarding the value of an expression, Scala can turn any expression into Unit, so that's why it compiled.
This is IMHO confusing, and I'd prefer a () => Unit argument instead of => Unit, then it would work as you expected.
Btw: you are not the first to be puzzled by this ;-)


text:
Q: Can Fisher information be zero? I have been looking at this problem and attempted calculating the Fisher information. I got zero, so I become unsure and wanted to my answer checked.
$X_1,X_2, ..., X_n$ are i.i.d. with density $\frac{1}{2} exp(-|x- \theta|)$, where $\theta \in \mathbb{R}$ is unknown. The goal is to compute $I_n(\theta)$ for $X_1,X_2, ..., X_n$.
Since $X_1,X_2, ..., X_n$ are i.i.d., $I_n(\theta) = n I(\theta)$ where $I(\theta)$ is the Fisher information for $X_1$.
Use the definition that $I(\theta) = -E_{\theta} \frac{\partial ^2}{\partial \theta ^2} log p_{\theta}(X)$, get $\frac{\partial}{\partial \theta} log p_{\theta}(X) = \frac{x - \theta}{|x - \theta|}$, and $\frac{\partial ^2}{\partial \theta ^2} log p_{\theta}(X) = \frac{(x - \theta)^2 - |x - \theta|^2}{|x - \theta|^3} = 0$, so $I_n(\theta) = n * 0 = 0$.
I have never seen a zero Fisher information so I am afraid I got it wrong. Any help would be appreciated!
Update: I'm now checking whether the smoothness condition is satisfied, which is used when deriving the formula for Fisher information.

A: You need to take distributional derivatives:$$ \frac{\partial^2}{\partial \theta^2}|x-\theta| =-\frac{\partial}{\partial \theta}\operatorname{sgn}(x-\theta) = 2\delta(x-\theta)$$ where $\delta$ is the Dirac delta. Then $I(\theta) = E(2\delta(X-\theta)) = 2p_\theta(\theta) = 1.$
EDIT
Ahh, yes, regularity conditions try to stop us from differentiating non-differentiable functions and the like. For your peace of mind (and also if you don't know about / like the distribution approach), you can instead you use the less-differentiated formula $$ I(\theta)
 = E\left[\left(\frac{\partial \log p_\theta(X)}{\partial \theta}\right)^2\right] = E(\operatorname{sgn}(X-\theta)^2) = E(1),$$ and get the same answer. Surely there's nothing bad going on with the cusp at the origin... the derivative doesn't even diverge there so it can easily be regulated and then removed at the end of the calculation with no effect.


text:
Q: jQuery with PHP in Wordpress I am trying to add a jQuery animation into my Wordpress posts.
The animation works fine, but what is hard is how to do it for each individual post. Meaning, each post is assigned a separate ID (e.g. post-xxxx) and the only way of knowing the post ID (that I know of) is through Wordpress' the_ID() function.
I have my jQuery running in script tags in the index PHP file. How would I go about doing this? My only good idea was to add an onclick HTML listener to the DIV tag for the post and then use the this reference in the jQuery code but it never executed (not sure if my code was wrong).
Here is the code for that thing I tried:
<script>
    function('test') {
        $(this).animate({
            height: '+=350'
        }, {
            duration: 500
        });

        $('.review-thumb').animate({
            opacity: 0
        }, {
            duration: 500
        });
    },
</script>

With this being my HTML tag:
<div onclick="test" class="post number-<?php echo $number; ?> colour-<?php echo $colour; ?>" id="post-<?php the_ID(); ?>">

The website theme can be found at http://vusavusa.com/blog/?theme=vusavusa2. Please excuse the messiness of content right now.

A: You can do something like this assuming that all the Posts starts with post- identifier. The selector below will grab all inputs that has an id that starts with post-.
$('input[id^="post-"]').animate({ height: '+=350' }, { duration: 500 });

The concept can be adapted to whatever you're trying to do such as:
/** Assign an animation to each element */
$('input[id^="post-"]').click(function() {
    $(this).animate({ height: '+=350' }, { duration: 500 });
    return false;
});

Another option is to use slideToggle to animate to expand your Post into a full view. your full view will be preloaded but is hidden by default and will have a class of post-full.
CSS:
.post-full { display: none; }

JS:
$(function() {
    $('[id^="post-"]').click(function() {
        $(this).find('.post-full').slideToggle(500, function(){});
        return false;
    });
});

A: Why don't you add a class (e.g. "postClass") and use
$('.postClass')


text:
Q: Pandas merge in same table with multiple columns producing unexpected output I have a dataframe df with columns: [value, arg1, arg2, diff_value]. I want to find all rows where (diff_value, arg1, arg2) is in df (as the first 3 columns). My code to do this is:
contains_df = df.merge(df,
                left_on=['value', 'arg1', 'arg2'],
                right_on=['diff_value', 'arg1', 'arg2'])\
                .drop(columns=['value_y', 'diff_value_y'])\
                .rename(columns={'value_x':'value', 'diff_value_x':'diff_value'})

I would then assume that df[df.value == 'a'] where 'a' is the value of diff_value in row 1 of contains_df would produce at least one row. However, I get no rows, implying that my merge did not do what I expected it to. How do I fix this?
For example, with:
df = pd.DataFrame({'value':['a', 'b', 'c', 'd'], 'arg1': [1, 1, 0, 0],
                   'arg2':[0, 0, 1, 1], 'diff_value':['z', 'a', 'b', 'y']})

I would expect the result to be row 2: [value:'b', arg1:1, arg2:1, diff_value:'a'] as ('a', 1, 0) is in row 1 as (value, arg1, arg2). However, instead the output is row 1.

A: The problem is that the first values in the left_on and right_on merge need to be swapped.
contains_df = df.merge(df,
            left_on=['diff_valuevalue', 'arg1', 'arg2'],
            right_on=['value', 'arg1', 'arg2'])\
            .drop(columns=['value_y', 'diff_value_y'])\
            .rename(columns={'value_x':'value', 'diff_value_x':'diff_value'})

This produces the desired result.


text:
Q: Word for "extremified"? I tried to describe something I read on the phenomenon that views in groups invariably shift toward the more extreme of the individuals and their group average, so to speak. Therefore there views were [extremified].

A: In the comments, Hugh suggested the word polarize, and Hot Licks suggested the word radicalize. I agree with you that both suggestions apply to the situation that you describe in the question. These words are often used together.
They have somewhat different meanings. Polarization implies the development of opposing extremes (for example, someone might lament the "polarization of politics" in the context of the two-party system of the USA) and the reduction or elimination of intermediate positions between these extremes. *Radicalization" refers to a shift away from mainstream or moderate viewpoints.


text:
Q: Laravel-OCI8 ORA-02275: such a referential constraint already exists in the table I've been trying to use migrations for a cross-dbms database. Using entrust and confide packages, I added migrations after them to add a user_statuses table and a reference in users table to user-statuses' ids; but as I define the foreign key I get this:

[Illuminate\Database\QueryException]
Error Code    : 2275
Error Message : ORA-02275: such a referential constraint already exists in the table
Position      : 53
Statement     : alter table users add constraint users_state_foreign foreign key ( state ) references user_statuses ( id ) (SQL: alter table users add constraint users_state_foreign foreign key ( state ) references user_statuses ( id ))

[yajra\Pdo\Oci8\Exceptions\SqlException]
Error Code    : 2275
Error Message : ORA-02275: such a referential constraint already exists in the table
Position      : 53
Statement     : alter table users add constraint users_state_foreign foreign key ( state ) peferences user_statuses ( id )

Below are the user_statuses and the alteration migration.
user_status creation:
Schema::create('user_statuses', function($table){
    // Columns
    $table->increments('id')->unsigned();
    $table->string('name');

    // Indexes

    // Constraints
});

users alteration:
Schema::table('users',function($table){
    // Columns
    $table->integer('state')->unsigned();
    $table->softDeletes();

    // Indexed

    // Constraints
    $table->foreign('state')->references('id')->on('user_statuses');
});

A: This is already fix at version https://github.com/yajra/laravel-oci8/tree/v1.5.11
Please try or submit an issue to our repo.

A: I put the foreign() statement in another, new Schema::table() statement in the same file, just bellow the one that creates columns as bellow:
Schema::table('users', function($table){
    // Columns
    $table->integer('kojak')->unsigned();
    $table->softDeletes();

    // Indexed

    // Constraints

});
Schema::table('users', function($table){
    $table->foreign('kojak')->references('id')->on('user_statuses');
});

This solved my problem, but the question remains why the conventional code doesn't work.


text:
Q: Error in rasterFromXYZ(xyz = centroids[, c("lon", "lat", "id")], crs = WGS84) : y cell sizes are not regular I'm trying to convert a csv file set of values into a raster but keep receiving the above error.
#Set raster options to improve speed of calculation
rasterOptions(tmptime = 4,
              progress = "text", #displays raster operation progress bar
              timer = TRUE, #outputs raster calculation duration
              maxmemory = 10e+9, #max no. of bytes to read into memory
              chunksize = 5e+9, #max no. of bytes to read/write in a single chunk while processing disk-based raster objects
              tmpdir = tmp_path) #location for writing temporary file

#Define CRS
WGS84 <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"

#select csv file containing RR predicted poverty
pov_csv_path <- "" #paste CSV Flile

#set csv path's parent directory as working directory
setwd(dirname(dirname(pov_csv_path)))

#load csv to dataframe
df_pov<- read.csv(pov_csv_path)

#Subset the predicted poverty dataframe to get the grid ID & lat and lon
centroids <- df_pov %>%
  select(id,lon,lat)

#Make a raster from centroids
#Function generates raster from regular grids like dataset used - assumes minimum distance between x & y coordinates is raster resolution
centroid_rast <- rasterFromXYZ(xyz = centroids[,c("lon","lat","id")], crs=WGS84)

Link to CSV file used: https://drive.google.com/file/d/1uUyNdhWQXLwGYHrfU3jKMRi5XkYrj6K2/view?usp=sharing
Error Message:
Error in rasterFromXYZ(xyz = centroids[, c("lon", "lat", "id")], crs = WGS84) :
  y cell sizes are not regular


text:
Q: How to display specific element from array in GET response I am testing custom API through Postman. I send GET call, and, in response, I receive an array with many elements.
I am just wondering: is it possible to restrict response (in Pre-request script for example) to display only one element in Postman, based, for example, on ID comparison?
This is example response:
"Data": {
        "P2PPayees": [
            {
                "Payee": {
                    "PayeeId": "1",
                    "FullName": "Wivhifgik",
                },
            },
            {
                "Payee": {
                    "PayeeId": "2",
                    "FullName": "Mupjidif",
                },
            },
        ]}

A: It depends on the server which sends the object. Read the documentation and have a look, if you can use query parameters to restrict the response. If the server doesn't support to restrict the response, you have to do it by your own programmatically.


text:
Q: Limit the number of opportunities made in a certain account How can I limit the number of opportunities that can be made for an account? As much as possible, I don't want to use triggers.
Thank you in advance.

A: Typically it is difficult to validate between two records without the use of Apex. But in this instance there is an option.
Account has the ability to do a roll-up summary field what counts the number of child opportunity records.
You could do exactly what you are asking by

*

*Add a roll-up summary field that counts how many opportunities are a child of an account. We'll call it opportunity_count__c

*Add a validation rule to Account that checks for opportunity_count__c to be greater than or equal to your threshold value


text:
Q: Variational formulation of a specific Poisson equation Let

*

*$d\in\mathbb N$

*$\Lambda\subseteq\mathbb R^d$ be bounded and open with Lipschitz boundary $\partial\Lambda$

*$\nu$ denote the outer unit normal vector of $\partial\Lambda$

*$E:=\left\{u\in L^2(\Lambda,\mathbb R^d):\nabla\cdot u\in L^2(\Lambda^)\right\}$

*$G:=\left\{\nabla p:p\in H^1(\Lambda)\right\}$

It's known that there are a unique bounded linear Operator $\gamma_0$ from $H^1(\Lambda,\mathbb R^d)$ to $L^2(\partial\Lambda,\mathbb R^d)$ with $$\gamma_0\left.u\right|_\Lambda=\left.u\right|_{\partial\Lambda}\;\;\;\text{for all }u\in C^1(\overline\Lambda)\tag 1$$ and a unique bounded linear operator $\gamma_\nu$ from $E$ to $H^{1/2}(\partial\Lambda)$ with $$\langle\gamma_0w,\gamma_\nu u\rangle_{H^{1/2}(\partial\Lambda)}=\langle v,\nabla\cdot u\rangle_{L^2(\Lambda)}+\langle\nabla v,u\rangle_{L^2(\Lambda,\:\mathbb R^d)}\;\;\;\text{for all }u\in E\text{ and }v\in H^1(\Lambda)\tag 2$$ and $$\gamma_\nu\left.u\right|_{\Lambda}=\left.u\right|_{\partial\Lambda}\cdot\nu\;\;\;\text{for all }v\in C^1(\overline\Lambda,\mathbb R^d)\tag 3\;.$$ Moreover, it's known that $$L^2(\Lambda,\mathbb R^d)=G\oplus H\tag 4$$ with $$H:=\left\{w\in H^2(\Lambda,\mathbb R^d):\nabla\cdot w=0\text{ and }\gamma_\nu w=0\right\}\;.$$

Now, let $u\in L^2(\Lambda,\mathbb R^d)$. Using $(4)$, we obtain $$u=\nabla p+w\tag 5$$ for some unique $(\nabla p,w)\in G\times H$. Given $u$, I want to numerically compute $w$. In order to do that, I guess that I need to first compute $p$ and then obtain $w$ by $(5)$.
Since I plan to compute $p$ by a Galerkin method, I need to find a variational formulation for that problem. How can we do that?

Sure, we should be in the well-known case of a Poisson equation: Since $\nabla\cdot w=0$, we obtain $w\in E$ and $$\nabla\cdot u=\nabla\cdot\nabla p\;,\tag 6$$ i.e. $$\langle\nabla\phi,u\rangle_{L^2(\Lambda,\:\mathbb R^d)}=\langle\nabla\phi,\nabla p\rangle_{L^2(\Lambda,\:\mathbb R^d)}\;\;\;\text{for all }\phi\in C_c^\infty(\Lambda)\;.\tag 7$$ However, this shouldn't be sufficient to come up with a variational formulation of the problem. What I mean is: I guess that we need to specify a boundary condition for $p$ using $\gamma_0$ and $\gamma_\nu$.

How should we do that and what are the correct test function and solution spaces?


text:
Q: Why does the suffix -ful sometimes mean "evoking," and is there a pattern among the words for which this is true? The suffix -ful usually means characterized by or in full measure as in hateful and spoonful. But an animal's pitiful cry is not full of, or characterized by, pity, and the fearful symmetry  of Blake's tyger is not full of fear. These meanings run counter to what one might naively think. How did this come about? I understand that the suffixes -ful and -ous are part of the battle between words that come through French and those that don't. Sometimes the meanings of prefixes and suffixes change dramatically at the hands of the French.  Para- usually means beside, but in words through the French, like parachute, paraph and parasol, it means against. Does this have any bearing on my question? I see the meanings of piteous and pitiful are frightfully close.

A: The Online Etymology Dictionary notes

Most English -ful adjectives at one time or another had both passive ("full of x") and active ("causing x; full of occasion for x") senses.

Consider the following: an act of gang violence can be disgraceful (effecting disgrace) or a gang can be disgraceful (marked by disgrace); a joyful person feels joy, while a joyful occasion brings joy; a regretful decision may be one that causes regret but a regretful person demonstrates regret.
But in other cases, one or the other meaning never developed, or has died out. For example, the oldest meaning of pitiful in the OED is

(from ca. 1350) 1. Full of or characterized by pity; compassionate, merciful, tender. Cf. pitiable adj. 1.

But it is Now rare., and later senses of pitiful as something deserving of pity and thence contemptible have become the dominant meanings.

A: It appears to be from the original Old English meaning of "ful": characterized by:
-ful:

*

*word-forming element attached to nouns (and in modern English to verb stems) and meaning "full of, having, characterized by," also "amount or volume contained" (handful, bellyful); from Old English -full, -ful, which is full (adj.) become a suffix by being coalesced with a preceding noun, but originally a separate word. Cognate with German -voll, Old Norse -fullr, Danish -fuld. Most English -ful adjectives at one time or another had both passive ("full of x") and active ("causing x; full of occasion for x") senses.

(Etymonline)


text:
Q: ios: workflow app, is there a way to open several new tabs? I use the workflow ios app and I have created a workflow that opens a certain url once. This works fine and it opens this one url in a new tab. However, if I set this to repeat x amount of times it opens all urls in the same tab. (It could also be that the app "refuses" to repeat the command, hard to tell the difference. The central point is that I can only get one new tab, not more.)
The URL I use is https://pinboard.in/random/?type=unread which is a link that redirects to the URL of a random unread item in the bookmarking service pinboard.
The actions I use now are:
URL [$my_url]
Open URLs

With repeat it is:
URL $my_url]
Open URLs
Repeat 5

Is there some way to open one or more URLs in separate tabs with one workflow app workflow?

A: Open URLs action supports multiple URL input. Try putting the one URL in a List action, with however many list entries you need, and passing that into Open URLs. Should work


text:
Q: Not able to trace C++ leaks with instruments I'm using C++ in my objective-c app and doing the following allocations in the scene:
@interface Game1PlayerLayer : CCLayer {

    b2World *_world;
    GLESDebugDraw *_debugDraw;
    MyContactListener *_contactListener;
}

+(CCScene *) scene;

@end

In implementation I allocate:
_world = new b2World(gravity);
_debugDraw = new GLESDebugDraw(PTM_RATIO);
_contactListener = new MyContactListener();

Of course I have to deallocate them with
delete _world;
delete _debugDraw;
delete _contactListener;

But if I am not deleting them, Xcode Leaks instrument doesn't show those leaks. I certainly checked that deallocation of Game1PlayerLayer took place. Leaks instrument set to 1 second snapshot. If Xcode is capable to show C++ leaks, what should I do to track them?

A: How about avoiding the whole issue and using std::shared_ptr instead?
@interface Game1PlayerLayer : CCLayer {

    std::shared_ptr<b2World> _world;
    std::shared_ptr<GLESDebugDraw> _debugDraw;
    std::shared_ptr<MyContactListener> _contactListener;
}

_world.reset(new b2World(gravity));
_debugDraw.reset(new GLESDebugDraw(PTM_RATIO));
_contactListener.reset(new MyContactListener());

#if 0
delete _world;
delete _debugDraw;
delete _contactListener;
#endif


text:
Q: How to report nose tests as skipped in teamcity? We have nose tests that run on a teamcity build agent. Some tests are slow and are therefore not run on each pull request. The problem is that they are not being reported as skipped. They simply don't show up in the teamcity report.
Slow tests are marked with
@attr('nightly')

The ordinary tests are run like this:
nosetests path/to/tests --nocapture --nologcapture -v -a '!nightly'

I can list the nightly tests without running them like this:
nosetests path/to/tests --nocapture --nologcapture -v -a 'nightly' --collect-only

But that reports them as being run successfully.
How can I make the tests get reported to teamcity as being skipped?
--- Update ---
I have been poking around and found that the section I would like to change is in http://nose.readthedocs.io/en/latest/plugins/collect.html?highlight=addSuccess. I would like to change it to addSkipped but it is deprecated so it looks like I should use addError with the error class from http://nose.readthedocs.io/en/latest/plugins/skip.html.
How would I go about adding these changes? It seems nosetests are not actively maintained anymore...

A: This issue can not be resolved by configuration.
You will have to hack the nose attrib plugin as it the code responsible of filtering out tests. TeamCity has no access to filtered out tests, as they are totally ignored by noestest.


text:
Q: Handling "ill-conditioned" system of ODE's with NDSolve I am currently dealing with a system of coupled ODE's which I would like to solve numerically. I have already implemented the system in Mathematica using NDSolve. The system has fixed boundary values (let us say at $-1$ and $1$ the values of the functions are fixed to 0) and one parameter, $k$, which I would like to vary. The system originally includes a Dirac delta, at a certain point $u'$, so my particular implementation tries to find functions at the left and at the right of $u'$ and pastes them appropriately (including the required jump in the derivative).
For small values of $k$ the system is solved properly, however for bigger values, I am getting warnings and messages about the system being "ill-conditioned" or that the "boundary conditions may not be enough to completely specify a solution". I have tried various methods for the solver including StiffnessSwitching as well as tweaking the the working precision, the Accuracy, MaxStepSize and so on.
I actually solve the system in the interval (-.9,.9) in practice and I have noticed that the system can be solved for bigger $k$ if a start making the interval smaller and smaller, however this is not an option for my setting. I believe the instabilities are coming from the boundaries, I should mention they are originally conditions at infinity and I am using a $u=\tanh(x)$ to map $\mathbb{R}$ into $(-1,1)$. Are there any tricks or recommendations on how to handle this phenomena, or alternatives to NDSolve?
EDIT:
A toy model of the problem already appears here I believe
$$\delta(u-u') = \left(2u\frac{\partial}{\partial u}-(1-u^2)\frac{\partial^2}{\partial u^2}+\frac{|\vec{k}|^2}{(1-u^2)}\right)G(u)$$
this is basically a Laplacian and I would like to obtain $G(u)$ for arbitrary $k$ (at least 50, in practice).
myInf = 1;
eq1[G_Symbol, u_, k_,uP_] := (2 u*G'[u] - (1 - u^2) G''[u]) + (k^2) G[u]/(1 - u^2) == DiracDelta[u - uP];
sol[uP_, k_, tol_, vv_] := NDSolve[Evaluate[{eq1[gg, u, k, uP], gg[-myInf + tol] == 0, gg'[-myInf + tol] == vv}], gg, {u, -myInf + tol, myInf - tol}];
greenSol[uP_, k_, tol_, vv_?NumericQ] := gg[u] /. Evaluate[sol[uP, k, tol, vv]][[1]] /. u -> myInf - tol;

Example of good result:
initD = vv /. FindRoot[Evaluate[greenSol[2/5, 2, 0.01`30, vv]], {vv, 0.1},  WorkingPrecision -> MachinePrecision];
Plot[Evaluate[gg[u] /. sol[2/5, 2, 0.01`30, initD]], {u, -myInf + .01,  myInf - .01}, PlotRange -> {{-myInf, myInf}, Automatic}, PlotRangePadding -> Scaled[.1]]

A: Because the homogeneous ODE is singular at its endpoints, begin by determining the asymptotic solution at one of them, here u == 1.
eq = 2 u*G'[u] - (1 - u^2) G''[u] + k^2 G[u]/(1 - u^2);
AsymptoticDSolveValue[eq == 0, G, {u, 1, 1}]
(* (1 - ((k/4 + k^2/4) (-1 + u))/(1 + k/2 + 1/2 (1 + k/2) k - k^2/4))
       (-1 + u)^(k/2) C[1]
 + (1 - ((-(k/4) + k^2/4) (-1 + u))/(1 - k/2 - 1/2 (1 - k/2) k - k^2/4))
       (-1 + u)^(-k/2) C[2] *)

The solution proportional to C[1] satisfies G[1] == 0.  However, its first k/2 - 1 derivatives also vanish at the boundary, which causes NDSolve problems for large k.  It is convenient, therefore, to define a new function, g[u] == G[u]/(1 - u)^(k/2), which is better behaved there, and solve it numerically (here with uP == 1/2 and k == 50.
eqp = Simplify[(1 - u)^(-k/2) eq /. G -> Function[u, g[u] (1 - u)^(k/2)]];
stp = NDSolveValue[{eqp == 0, g[1 - 10^-5] == 1, g'[1 - 10^-5] == 0} /. k -> 50,
    g, {u, 1/2, 1 - 10^-5}, WorkingPrecision -> 30];

Now, do the same at u == -1.
AsymptoticDSolveValue[eq == 0, G, {u, -1, 1}]
(* (1 + u)^(k/2) (1 - ((-(k/4) - k^2/4) (1 + u))/
       (1 + k/2 + 1/2 (1 + k/2) k - k^2/4)) C[1]
 + (1 + u)^(-k/2) (1 - ((k/4 - k^2/4) (1 + u))/
       (1 - k/2 - 1/2 (1 - k/2) k - k^2/4)) C[2] *)

which indicates that here the auxiliary function should be g[u] == G[u]/(1 + u)^(k/2).
eqm = Simplify[(1 + u)^(-k/2) eq /. G -> Function[u, g[u] (1 + u)^(k/2)]];
stm = NDSolveValue[{eqm == 0, g[-1 + 10^-5] == 1, g'[-1 + 10^-5] == 0} /. k -> 50,
    g, {u, -1 + 10^-5, 1/2}, WorkingPrecision -> 30]

To create the corresponding Green's Function at uP == 1/2, match stp[u] (1 - u)^(k/2) and stm[u] (1 + u)^(k/2) and their first derivatives there.
0 == (dp stp[u] (1 - u)^(k/2) - dm stm[u] (1 + u)^(k/2)) /. {u -> 1/2, k -> 50};
-1/(1 - u^2) == D[dp stp[u] (1 - u)^(k/2) - dm stm[u] (1 + u)^(k/2), u]
    /. {u -> 1/2, k -> 50};
sd = Solve[{%, %%}, {dm, dp}] // Flatten;

The Green's Function at uP == 1/2 then  is
gf[u_] = Piecewise[{{dm (1 + u)^(k/2) stm[u], u < 1/2},
    {dp (1 - u)^(k/2) stp[u], u >= 1/2}}] /. sd /. k -> 50;

Plot[gf[u], {u, -1 + 10^-5, 1 - 10^-5}, PlotRange -> All, AxesLabel -> {u, G}]

The peak value,
gf[1/2]
(* 0.00999999999999999817834769562 *)

compares favorably with the analytical value of 1/100.  To see how extreme the variation of gf is, consider
gf[1 - 10^-5]
(* 2.52543880312194881294211586*10^-123 *)

It is no wonder that NDSolve has great difficulty with the original equation.  Incidentally, the symbolic Green's Function can be derived without difficulty (although not with GreenFunction, unfortunately).  When plotted, it matches well the solution determined numerically here.
Addendum: What to do if AsymptoticNDSolve unavailable.
In response to a comment below, the auxiliary function also can be obtained using Series as follows.  For u == 1 replace G[u] by the trial auxiliary function, f[u] (1 - u)^n, and expand eq about u == 1.
Series[(eq /. G -> Function[u, f[u] (1 - u)^n]) (1 - u)^-n, {u, 1, -1}]
(* SeriesData[u, 1, {Rational[-1, 2] k^2 f[1] + 2 n^2 f[1]}, -1, 0, 1] *)

This term needs to vanish, which provides the desired value for n.
SeriesCoefficient[%, -1];
Solve[% == 0, n] // Flatten
(* {n -> -(k/2), n -> k/2} *)

Select the positive solution and proceed as above.


text:
Q: How to fix blue screen when setting a position for Unity? I was wondering if someone could help me understand what is going on. I am currently developing a space shooter game, but once I executed a code to change the position all I see on the game tab is a blue screen. I know it is that one line of code because I then commented it out and then it worked just fine when I ran the game.
The line of code is.
transform.position = new vector3 (0, 0, 0);

A: I think you attached this script to your camera (And probably other game objects like the sky, rocket and etc are in the (0, 0, 0) position). So, when you play the game, the camera moves to (0, 0, 0) and nothing shows. Make sure that you set the camera in a position with z < 0.
transform.position = new Vector3(0, 0, -10);

I hope it helps you!


text:
Q: SQL Server - import bacpac file of Azure SQL database to SQL Server 2014 on Virtual Machine We are moving our Azure SQL Database to SQL Server 2014 on an Azure Virtual Machine.  I created a bacpac file of the Azure SQL Database.
Upon trying to import the bacpac into the SQL Server on the VM, I'm met with the following error:

Could not import package. Warning SQL0: A project which specifies
  Microsoft Azure SQL Database v12 as the target platform may experience
  compatibility issues with SQL Server 2014. Warning SQL72012: The
  object [NegativeMedia_Prod_Data] exists in the target, but it will not
  be dropped even though you selected the 'Generate drop statements for
  objects that are in the target database but that are not in the
  source' check box. Warning SQL72012: The object
  [NegativeMedia_Prod_Log] exists in the target, but it will not be
  dropped even though you selected the 'Generate drop statements for
  objects that are in the target database but that are not in the
  source' check box. Error SQL72014: .Net SqlClient Data Provider: Msg
  7738, Level 16, State 2, Line 1 Cannot enable compression for object
  'Captures'. Only SQL Server Enterprise Edition supports compression.

The way I see it, I have two options:

*

*Upgrade SQL Server on the VM - a little scary to me based on the fact that we have existing data there.  Is the upgrade process somewhat straightforward?  Based on this:  https://learn.microsoft.com/en-us/sql/database-engine/install-windows/upgrade-sql-server it sure looks like anything BUT straightforward.

*Figure out a workaround to get this database imported into SQL Server 2014.  As far as the compression part goes, I can turn that off in the Azure SQL database and recreate the bacpac file.  The rest of the error message then is what I would need to "work around" but I don't fully understand its meaning.
Whichever of the two above options can be achieved in the least amount of time is what I need, in order to keep the boss happy.  Please let me know if anyone has any suggestions on either.

A: Upgrade from SQL Server 2014 to SQL Server 2016 was a quick and painless process.  It's certainly come a long way.  I have upgraded and have now successfully imported the bacpac file.


text:
Q: An estimate for 'almost primes'? In the famous Chen's Theorem which states that every sufficiently large even positive integer $n$ can be written as $n = p + q$, where $p$ is a prime and $q$ is a product of at most two primes. This is the precise 'almost prime' definition we use, where it's either a prime or a product of two primes. Now from the prime number theorem we have a crude estimate for the size of the $n$th prime, namely $p_n \sim n
\log(n)$. Are there any similar estimates for the set of almost primes? To be more precise, let $\mathcal{P}$ denote the set of primes, and let $\mathcal{P}^2$ denote the set {$pq : p,q$ primes}. Set $Q = \mathcal{P} \cup \mathcal{P}^2$ and enumerate the elements of $Q$as $a_1, a_2, \cdots$ The question is do we have an approximation for $a_n$?

A: The number of almost-primes up to $x$ is asymptotic to $x\log\log x/\log x$. It doesn't matter whether you include the primes or not, as there are only $x/\log x$ of them. I think this gives $n\log n/\log\log n$ as a crude estimate for the $n$th almost prime.


text:
Q: How ToDictionary in c# works? I am wondering how this statement works while converting a list to a dictionary.
The expression is much like
OtherList = MyList.ToDictionary(x => x.MyId, y => y.MyName);

can anybody explain that why there are two variables x and y ? And how they work together ? Cant I use the same variable twice ?


text:
Q: Listbox doesn't always show items based on other listbox Based on a value of one listbox (selecttreatment), another listbox (indicators) options are being populated. The javascript code i use:
function sendData() { // onchange
    $("#indicators").empty();
    console.log($("#selecttreatment").val());
    $.getJSON("functions/getcharts.php", {funcid:"giveme_chosen_treatment", chosen_treatment: $("#selecttreatment").val()}, updateData);
}

function updateData(data) {
    console.log(data);

    var option = '';
    for (var i=0;i<data.length;i++){
       //option += '<option value="'+ data[i].zi_indicator_name_id + '">' + data[i].zi_indicator_name_label + '</option>';
       option += '<option value="'+ data[i].indicator_name + '">' + data[i].indicator_name + '</option>';
    }
    $('#indicators').append(option);

}

At first I believed it only went wrong when mysql gives back one row, but that isn't the problem. I can't fugure out whats going wrong.
So my problem is that sometimes the 2nd listbox is being populated with values, but most of the times it isn't.


text:
Q: Why am I getting negative means from a hierarchical clustering model fitted to binomial data using RStan Apologies in advance - I'm new to Bayesian statistical methods and may not get all the terminology correct.
I am trying to run some Bayesian analysis on survey data using the rstan package in R but I'm unsure of how to interpret my output. My aim is to generate a probability distribution for each level of data depending on the response, where the response has predictors variables and there are levels in the data.
The response data I'm inputting are binomial but the resulting probability distribution of the posterior has negative values.
My data are structured as follows:

*

*3524 responses (N)

*23 geographical areas sampled treated as levels (L) where each response is associated with an area (ll)

*each area is scored 1-10 depending on it's level of deprivation and this is treated as a predictor variable (x[,1])

*the age group of each responder is treated as a predictor variable (x[,2])

*there are two predictor variables (D)

*yes or no response to a question in the survey (y)

So for each responder I have a response (1 = yes, 0 = no), a geographical area (1-23), a level of deprivation (1-10) and an age group (1-8 where 1 is the youngest age group and 8 is the oldest).
I'm trying to fit a hierarchical logistical model as follows:
data {
  int<lower=1> D;
  int<lower=0> N;
  int<lower=1> L;
  array[N] int<lower=0, upper=1> y;
  array[N] int<lower=1, upper=L> ll;
  array[N] row_vector[D] x;
}
parameters {
  array[D] real mu;
  array[D] real<lower=0> sigma;
  array[L] vector[D] beta;
}
model {
  for (d in 1:D) {
    mu[d] ~ normal(0, 100);
    for (l in 1:L) {
      beta[l, d] ~ normal(mu[d], sigma[d]);
    }
  }
  for (n in 1:N) {
    y[n] ~ bernoulli(inv_logit(x[n] * beta[ll[n]]));
  }
}

I then run the model using the following code:
fit = stan(model_code=bern.stan, data=list(y=y, N=N, x=x, D=D, L=L, ll=ll), iter=5000)

I can print the fit as follows:
print(fit, probs=c(0.1, 0.9))

The print shows that the mean for each beta is negative (e.g., beta[2,1] where 2 is the level and 1 is the predictor variable age is -0.17). When I extract these data to plot the distribution it is negative.
My question is how can the mean and credible intervals be negative when I'm dealing with binomial data and positive predictor variables?

A: Probabilities cannot be negative, but as said in the comment, this is a logistic regression model, and if you transformed them using inv_logit, as your model does, they would not go outside the bounds.


text:
Q: Update data from web service handling response delay and other errors EventService component retrieves a list of items every 10000 ms
@Injectable()
export class EventsService {
    getEventsStream(): Observable<Event[]> {
        let url = 'event/view';
        return Observable.interval(10000).flatMap(() => {
                return this.http.get(url);
            })
            .map((response: Response) => {
                return (<any>response.json()).map(item => {
                    return item;//new Event(item);
                });
            });
    }
}

However in this way I do not handle the case where the web service is delaying the response or is not available.

*

*How can I handle this by issuing the new request 10000 ms after response has arrived?

*How can I handle unavailability/errors from the web service by issuing a new request 30000 ms after this error?

Thanks in advance!

A: You could use the retry operator for this:
return Observable.interval(10000).flatMap(() => {
         return this.http.get(url);
       })
       .retryWhen(error => error.delay(30000)) // <----
       .map((response: Response) => {
          return (<any>response.json()).map(item => {
             return item;//new Event(item);
          });
       });

See these articles for more details:

*

*http://restlet.com/blog/2016/04/18/interacting-efficiently-with-a-restful-service-with-angular2-and-rxjs-part-3/

*https://jaxenter.com/reactive-programming-http-and-angular-2-124560.html

A: In this way it works:
let obs;
return Observable
    .create((o) => {
        obs = o;
        obs.next();
    })
    .flatMap(() => {
        //console.log("executing request");
        return this.http.get(url);
    })
    .retryWhen(error => error.delay(30000))
    .map((response: Response) => {
        //console.log("response received");
        setTimeout(() => {
            //console.log("pushing next");
            obs.next();
        }, 10000);
        return (<any>response.json()).map(item => {
            return item;//new Event(item);
        });
    });

does this seems a correct solution?


text:
Q: Processing Files using ParallelForeach. Is this the best approach Just some advice
I have 100.000+ xml file to process and move to another system.
The concept is pretty simple I have a loop like:
    public void ProcessFiles()
    {
        IEnumerable<FileInfo> orderedFiles = GetFilesOrdered();

        foreach (FileInfo file in orderedFiles)
        {
            ProcessFile(file);
        }
    }

I have been reading about Task Parallel library but not that confident.
Not that very glued up on threading.
It seems that TPL wraps lots for me.
To put it simply is it just a case of using parallel.Foreach?
any sample or suggestions

A: Yes, it might be as simple as replacing foreach with Parallel.ForEach.
You have to remember that multiple threads would now be executing ProcessFile concurrently.
So, if you are writing to any shared state in that method, you will have to use synchronization constructs to protect it.
If you're new to multi-threading, there's a great introductory ebook you should read here: Albahari

A: Hope it is helpful to you. Simple snippet to demo how to move the file in parallel.
        List<FileInfo> files = new List<FileInfo>();
        files.Add(new FileInfo("F:\\1.xml"));
        files.Add(new FileInfo("F:\\2.xml"));
        files.Add(new FileInfo("F:\\3.xml"));

        Parallel.ForEach(files, f =>
        {
            f.MoveTo("d:\\test\\" + f.Name);
        });


text:
Q: How do I maintain the state of my request data between GET and POST requests in one flask route? I have some user response data that is posted from the front end to my /post end route and then one piece of that data (user id) is posted to another flask route /stats. That is working properly, when I print to the console I am getting the correct user_id I want to get. The problem is that in this /stats end route I am performing a query of the database to gather some important stats and then I am grabbing those on the front end through a get request. The problem is that when I perform the get request, the state of my request_data is lost and throws the error:
line 67, in stats
    user = request_data['user']
TypeError: 'NoneType' object is not subscriptable

the app works perfectly until I perform the get request. here is my code for the flask route /stats:
@app.route('/stats', methods=['GET', 'POST'])
def stats():
  request_data = request.get_json()
  user = request_data['user']
  def get_total_percent_correct(user_id):
    correct = d.db_query('SELECT COUNT(*) FROM cards.responses WHERE guess = answer AND user_id = %s' % user_id)
    total = d.db_query('SELECT COUNT(*) FROM cards.responses WHERE user_id = %s' % user_id)
    return float(correct[0][0])/float(total[0][0])

  response_body = {
        "stat": get_total_percent_correct(user_id=0),
        "user" : user
    }
  print(get_total_percent_correct(user_id=0))
  print(request_data['user'])
  return response_body

I would just make 2 if statements for get and post but the problem is I need the user object for my query data. right now the user_id is hardcoded in as 0 but I want to replace that with user object. I appreciate any help. thanks!


text:
Q: ServiceController seems to be unable to stop a service I'm trying to stop a Windows service on a local machine (the service is Topshelf.Host, if that matters) with this code:
serviceController.Stop();
serviceController.WaitForStatus(ServiceControllerStatus.Stopped, timeout);

timeout is set to 1 hour, but service never actually gets stopped. Strange thing with it is that from within Services MMC snap-in I see it in "Stopping" state first, but after a while it reverts back to "Started". However, when I try to stop it manually, an error occurs:
Windows could not stop the Topshelf.Host service on Local Computer.
Error 1061: The service cannot accept control messages at this time.

Am I missing something here?

A: I had exact same problem with Topshelf hosted service. Cause was long service start time, more than 20 seconds. This left service in state where it was unable to process further requests.
I was able to reproduce problem only when service was started from command line (net start my_service).
Proper initialization for Topshelf service with long star time is following:
 namespace Example.My.Service
 {
    using System;
    using System.Threading.Tasks;

    using Topshelf;

    internal class Program
    {
        public static void Main()
        {
            HostFactory.Run(
                x =>
                {
                    x.Service<MyService>(
                        s =>
                        {
                            MyService testServerService = null;
                            s.ConstructUsing(name => testServerService = new MyService());
                            s.WhenStarted(service => service.Start());
                            s.WhenStopped(service => service.Stop());
                            s.AfterStartingService(
                                context =>
                                {
                                    if (testServerService == null)
                                    {
                                        throw new InvalidOperationException("Service not created yet.");
                                    }
                                    testServerService.AfterStart(context);
                                });
                        });
                    x.SetServiceName("my_service");
                });
        }
    }

    public sealed class MyService
    {
        private Task starting;

        public void Start()
        {
            this.starting = Task.Run(() => InitializeService());
        }

        private void InitializeService()
        {
            // TODO: Provide service initialization code.
        }

        [CLSCompliant(false)]
        public void AfterStart(HostControl hostStartedContext)
        {
            if (hostStartedContext == null)
            {
                throw new ArgumentNullException(nameof(hostStartedContext));
            }
            if (this.starting == null)
            {
                throw new InvalidOperationException("Service start was not initiated.");
            }
            while (!this.starting.Wait(TimeSpan.FromSeconds(7)))
            {
                hostStartedContext.RequestAdditionalTime(TimeSpan.FromSeconds(10));
            }
        }

        public void Stop()
        {
            // TODO: Provide service shutdown code.
        }
    }
}

A: I know I am quite late to answer this but I faced a similar issue , i.e., the error: "The service cannot accept control messages at this time." and would like to add this as a reference for others.
You can try killing this service using powershell (run powershell as administrator):
#Get the PID of the required service with the help of the service name, say, service name.
$ServicePID = (get-wmiobject win32_service | where { $_.name -eq 'service name'}).processID

#Now with this PID, you can kill the service
taskkill /f /pid $ServicePID

A: I've seen this issue as well, specifically when a service is start pending and I send it a stop programmatically which succeeds but does nothing. Also sometimes I see stop commands to a running service fail with this same exception but then still actually stop the service. I don't think the API can be trusted to do what it says. This error message explanation is quite helpful...
http://technet.microsoft.com/en-us/library/cc962384.aspx

A: I run into a similar issue and found out it was due to one of the services getting stuck in a state of start-pending, stop pending, or stopped.
Rebooting the server or trying to restart services did not work.
To solve this, I run the Task Manager in the server and in the "Details" tab I located the services that were stuck and killed the process by ending the task. After ending the task I was able to restart services without problem.
In brief:
1. Go to Task Manager
2. Click on "Detail" tab
3. Locate your service
4. Right click on it and stop/kill the process.
That is it.

A: Either your service is busy processing some big operation or is in transition to change the state. hence is not able to accept anymore input...just think of it as taking more than it can chew...
if you are sure that you haven't fed anything big to it, just go to task manager and kill the process for this service or restart your machine.

A: I faced the similar issue. This error sometimes occur because the service can no longer accept control messages, this may be due to disk space issues in the server where that particular service's log file is present.
If this occurs, you can consider the below option as well.

*

*Go to the location where the service exe & its log file is located.

*Free up some space

*Kill the service's process via Task manager

*Start the service.

A: I know it was opened while ago, but i am bit missing the option with Windows command prompt, so only for sake of completeness

*

*Open Task Manager and find respective process and its PID i.e PID = 111

*

*Eventually you can narrow down the executive file i.e. Image name = notepad.exe

*in command prompt use command TASKKILL

*

*example: TASKKILL /F /PID 111 ; TASKKILL /F /IM notepad.exe

A: I had this exact issue internally when starting and stopping a service using PowerShell (Via Octopus Deploy). The root cause for the service not responding to messages appeared to be related to devs accessing files/folders within the root service install directory via an SMB connection (looking at a config file with notepad/explorer).
If the service gets stuck in that situation then the only option is to kill it and sever the connections using computer management. After that, service was able to be redeployed fine.
May not be the exact root cause, but something we now check for.

A: I just fought this problem while moving code from an old multi partition box to a newer single partition box. On service stop I was writing to D: and since it didn't exist anymore I got a 1061 error.  Any long operation during the OnStop will cause this though unless you spin the call off to another thread with a callback delegate.