text:
Q: Get Sum(Column) over (partition by other columns) with subset of partition I need to make a sum of the count of all items in "count2" for the partitions, the screenshot below shows better than I could explain, but I need to sum the items in that column and then subtract them form the "Lead2" column
I have the following query:
SELECT td.EVENT_ID AS event_id,
       td.MENU_HINT AS race,
       td.EVENT_NAME AS event,
       td.expr1003 AS [date],
       td.raceno AS [race number],
       td.countwinnerprice5to8 AS [count1],
       td.sumwinnerprice5to8 AS [sum1],
       td.countwinnernotprice5to8 AS [count2],
       td.sumwinnernotprice5to8 AS [sum2],
       lead(td.sumwinnerprice5to8,1) OVER(PARTITION BY countwinnerprice5to8  Order by expr1003 desc, raceno desc, event_id desc ) as lead2,
       sum(td.countwinnernotprice5to8) OVER(PARTITION BY countwinnernotprice5to8  Order by expr1003 desc, raceno desc, event_id DESC rows between 1 following and unbounded following       ) as countlead2
FROM tbldata5 td
WHERE
menu_hint LIKE '%Flem%'
ORDER BY expr1003 desc, raceno desc, event_id desc

which returns this table:
╔═══════════╦═══════════════════════════╦═════════════════╦════════════╦═════════════╦════════╦══════╦════════╦═══════╦═══════╦════════════╗
║  event_id ║ race                      ║ event           ║ date       ║ race number ║ count1 ║ sum1 ║ count2 ║ sum2  ║ lead2 ║ countlead2 ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 145719665 ║ AUS / Flem (AUS) 21st Jul ║ R9 1000m Hcap   ║ 2018-07-21 ║ 9           ║ 0      ║ NULL ║ 1      ║ 7.40  ║ NULL  ║ 1          ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 145719663 ║ AUS / Flem (AUS) 21st Jul ║ R8 2000m Hcap   ║ 2018-07-21 ║ 8           ║ 0      ║ NULL ║ 0      ║ NULL  ║ NULL  ║ 0          ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 145719661 ║ AUS / Flem (AUS) 21st Jul ║ R7 1600m 3yo    ║ 2018-07-21 ║ 7           ║ 0      ║ NULL ║ 1      ║ 6.22  ║ NULL  ║ 2          ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 145719659 ║ AUS / Flem (AUS) 21st Jul ║ R6 1100m 3yo    ║ 2018-07-21 ║ 6           ║ 0      ║ NULL ║ 1      ║ 7.60  ║ NULL  ║ 3          ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 145719657 ║ AUS / Flem (AUS) 21st Jul ║ R5 1800m 2yo    ║ 2018-07-21 ║ 5           ║ 0      ║ NULL ║ 1      ║ 7.69  ║ NULL  ║ 4          ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 145719655 ║ AUS / Flem (AUS) 21st Jul ║ R4 1200m Hcap   ║ 2018-07-21 ║ 4           ║ 0      ║ NULL ║ 1      ║ 5.90  ║ NULL  ║ 5          ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 145719653 ║ AUS / Flem (AUS) 21st Jul ║ R3 2500m Hcap   ║ 2018-07-21 ║ 3           ║ 0      ║ NULL ║ 0      ║ NULL  ║ NULL  ║ 0          ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 145719651 ║ AUS / Flem (AUS) 21st Jul ║ R2 1700m Hcap   ║ 2018-07-21 ║ 2           ║ 1      ║ 6.67 ║ 1      ║ 6.56  ║ 8.00  ║ 6          ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 145719649 ║ AUS / Flem (AUS) 21st Jul ║ R1 1400m 3yo    ║ 2018-07-21 ║ 1           ║ 0      ║ NULL ║ 0      ║ NULL  ║ NULL  ║ 0          ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 145210614 ║ AUS / Flem (AUS) 7th Jul  ║ R9 1200m Listed ║ 2018-07-07 ║ 9           ║ 0      ║ NULL ║ 1      ║ 5.26  ║ NULL  ║ 7          ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 145210612 ║ AUS / Flem (AUS) 7th Jul  ║ R8 1600m Listed ║ 2018-07-07 ║ 8           ║ 1      ║ 8.00 ║ 2      ║ 15.42 ║ 5.64  ║ 2          ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 145210610 ║ AUS / Flem (AUS) 7th Jul  ║ R7 1200m Listed ║ 2018-07-07 ║ 7           ║ 0      ║ NULL ║ 0      ║ NULL  ║ NULL  ║ 0          ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 145210608 ║ AUS / Flem (AUS) 7th Jul  ║ R6 2600m Hcap   ║ 2018-07-07 ║ 6           ║ 0      ║ NULL ║ 2      ║ 12.65 ║ NULL  ║ 4          ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 145210606 ║ AUS / Flem (AUS) 7th Jul  ║ R5 1600m Listed ║ 2018-07-07 ║ 5           ║ 0      ║ NULL ║ 0      ║ NULL  ║ NULL  ║ 0          ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 145210604 ║ AUS / Flem (AUS) 7th Jul  ║ R4 1600m 3yo    ║ 2018-07-07 ║ 4           ║ 0      ║ NULL ║ 1      ║ 5.27  ║ NULL  ║ 8          ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 145210602 ║ AUS / Flem (AUS) 7th Jul  ║ R3 1400m Hcap   ║ 2018-07-07 ║ 3           ║ 1      ║ 5.64 ║ 1      ║ 7.68  ║ 5.51  ║ 9          ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 145210600 ║ AUS / Flem (AUS) 7th Jul  ║ R2 2000m Hcap   ║ 2018-07-07 ║ 2           ║ 0      ║ NULL ║ 0      ║ NULL  ║ NULL  ║ 0          ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 145210598 ║ AUS / Flem (AUS) 7th Jul  ║ R1 1600m 3yo    ║ 2018-07-07 ║ 1           ║ 0      ║ NULL ║ 3      ║ 21.97 ║ NULL  ║ 3          ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 144827118 ║ AUS / Flem (AUS) 23rd Jun ║ R9 1100m Hcap   ║ 2018-06-23 ║ 9           ║ 0      ║ NULL ║ 1      ║ 5.33  ║ NULL  ║ 10         ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 144827116 ║ AUS / Flem (AUS) 23rd Jun ║ R8 1600m Hcap   ║ 2018-06-23 ║ 8           ║ 0      ║ NULL ║ 1      ║ 6.67  ║ NULL  ║ 11         ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 144827114 ║ AUS / Flem (AUS) 23rd Jun ║ R7 1400m Hcap   ║ 2018-06-23 ║ 7           ║ 0      ║ NULL ║ 0      ║ NULL  ║ NULL  ║ 0          ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 144827112 ║ AUS / Flem (AUS) 23rd Jun ║ R6 1600m 3yo    ║ 2018-06-23 ║ 6           ║ 0      ║ NULL ║ 2      ║ 13.03 ║ NULL  ║ 6          ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 144827110 ║ AUS / Flem (AUS) 23rd Jun ║ R5 2520m Hcap   ║ 2018-06-23 ║ 5           ║ 0      ║ NULL ║ 2      ║ 14.56 ║ NULL  ║ 8          ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 144827108 ║ AUS / Flem (AUS) 23rd Jun ║ R4 1400m Hcap   ║ 2018-06-23 ║ 4           ║ 1      ║ 5.51 ║ 3      ║ 20.44 ║ 7.80  ║ 6          ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 144827106 ║ AUS / Flem (AUS) 23rd Jun ║ R3 1100m 3yo    ║ 2018-06-23 ║ 3           ║ 0      ║ NULL ║ 2      ║ 11.94 ║ NULL  ║ 10         ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 144827104 ║ AUS / Flem (AUS) 23rd Jun ║ R2 1400m Hcap   ║ 2018-06-23 ║ 2           ║ 0      ║ NULL ║ 1      ║ 7.29  ║ NULL  ║ 12         ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 144827102 ║ AUS / Flem (AUS) 23rd Jun ║ R1 1400m 2yo    ║ 2018-06-23 ║ 1           ║ 0      ║ NULL ║ 3      ║ 19.39 ║ NULL  ║ 9          ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 144506971 ║ AUS / Flem (AUS) 9th Jun  ║ R9 1000m 3yo    ║ 2018-06-09 ║ 9           ║ 0      ║ NULL ║ 1      ║ 7.97  ║ NULL  ║ 13         ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 144506969 ║ AUS / Flem (AUS) 9th Jun  ║ R8 2000m 3yo    ║ 2018-06-09 ║ 8           ║ 0      ║ NULL ║ 3      ║ 20.10 ║ NULL  ║ 12         ║
╠═══════════╬═══════════════════════════╬═════════════════╬════════════╬═════════════╬════════╬══════╬════════╬═══════╬═══════╬════════════╣
║ 144506967 ║ AUS / Flem (AUS) 9th Jun  ║ R7 1400m Hcap   ║ 2018-06-09 ║ 7           ║ 0      ║ NULL ║ 1      ║ 5.71  ║ NULL  ║ 14         ║
╚═══════════╩═══════════════════════════╩═════════════════╩════════════╩═════════════╩════════╩══════╩════════╩═══════╩═══════╩════════════╝

The table is ordered by date/race number and event_id. this should be the final order of the table.
What I'm needing is to sum the count of every row in count2 within the range between the count1 items.
It might be easier to understand with graphic (click to enlarge).

So basically what I need to do is to summarize what is on the blue boxes and then subtract it to the not null row from lead2 and add into countlead2.
I can even handled it with temporal table or create a new column where to insert, so it can be cleaner and calculated later. but I don't know how to summarize the count of the blue box.
I've tried with combinations of grouping sets, and different combinations of sum over partitions. but I can't seem to be able to do what I need. I think partition by is the way to go.
So far I've tried with the 1 following and unbounded following to try to get the data I want, but it seems to go out of bounds. Is there a way to get the bound to be a variable? or to select the last following as the first of the next? And it seems that the preceding/following is not working with the partition I need.

A: One way is to do it in multiple stages, rather than trying to do it all in a single SELECT statement.
WITH
  base AS
(
  -- your current query goes in here
),
  base_grouped AS
(
  -- First, create a group identifier, but in the -opposite- direction
  -- (This will group the rows where you want to sum [count2])
  SELECT
    *,
    SUM(count1) OVER (ORDER BY [date], [race_number], event_id)   AS group_id
  FROM
    base
),
  base_grouped_summed AS
(
  -- Then do the sum on [count2] within those groups
  SELECT
     *,
     SUM([count2]) OVER (PARTITION BY group_id)   AS sum_count2
  FROM
     base_grouped
)
-- Now deduct it from [lead2] (only does anything when [lead2] is not null)
SELECT
  *,
  lead2 - LAG(sum_count2) OVER (ORDER BY group_id)   AS new_value
FROM
  base_grouped_summed

If you know better ways to identify which rows to SUM(), you may be able to shorten this.  I just went with the most obvious rules based on your sample data.

EDIT:
To demonstrate what Common Table Expressions are, this is what the above code would look like with old-school nested sub-queries...
-- Now deduct it from [lead2] (only does anything when [lead2] is not null)
SELECT
  *,
  lead2 - LAG(sum_count2) OVER (ORDER BY group_id)   AS new_value
FROM
(
  -- Then do the sum on [count2] within those groups
  SELECT
     *,
     SUM([count2]) OVER (PARTITION BY group_id)   AS sum_count2
  FROM
  (
    -- First, create a group identifier, but in the -opposite- direction
    -- (This will group the rows where you want to sum [count2])
    SELECT
      *,
      SUM(count1) OVER (ORDER BY [date], [race_number], event_id)   AS group_id
    FROM
    (
      -- your current query goes here
    )
      AS base
  )
    AS base_grouped
)
  AS base_grouped_summed

Most people, once they get used to CTEs, find them much easier to read, modify and debug.


text:
Q: Python Module Only Found With .py I am attempting to make a command line python tool to locate IP addresses.  I am using the pygeoip library. When I have the file as filename.py, and I run it using
python filename.py -options

it works fine.  But when I rename it to just filename (no .py) and add
#!/usr/bin/python

To the top of the top of the file, the pygeoip module can no longer be found.  I have chmoded the file properly.
Anyone come across this before?

A: The problem is that /usr/bin/python is not the same python where pygeiop is installed. The shebang
#!/usr/bin/python

tells the shell to execute the script with the program given. If you change it to
#!/usr/bin/env python

the shell will search the PATH for a python and use it. If your "real" python is first on the path, it is run. You could use virtualenv, or even just add your favorite python to the front of PATH to control what is executed.
For deployment, /usr/bin/env is superior because then you don't have to worry about where the user installed python. It could be in /usr/local/bin or who knows where, and the shell will find it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: analytic functions from square to unit disk Let $f$ be an analytic function from $\{z; -1 < \Re(z) < 1, -1 < \Im(z) < 1\}$ to $\{z; |z| < 1\}$. If $f(0)=0$ and $f$ is one-one and onto, should $f(i\ z)=i\ f(z)$ for each $z$? I tried to show that $f(i\ z)-i\ f(z)$ is a constant, but it seems that I could not use  Liouville Theorem.
Thank you very much.

A: Assuming you mean the open square, then yes.
Let $g(z)=f(iz)$ and $h(z)=if(z)$.  Then $g$ and $h$ are analytic bijections from the square to the disk such that $g(0)=h(0)=0$ and $g'(0)=h'(0)=if'(0)$.  This implies that $k=g\circ h^{-1}$ is an analytic bijection of the disk such that $k(0)=0$ and $k'(0)=1$.  By Schwarz's lemma, $k(z)=z$ for all $z$ in the disk, and therefore $g=h$.


text:
Q: CSS and firefox issue The left margin of this DIV aligns too far left when on Firefox. It looks fine on Chrome, Safari, and IE. But I can't get it to align with the images below on Firefox. Any help?  Here is the link to the site: http://www.aerlawgroup.com
I have this div tag:

 IN THE NEWS

and this is the CSS:
.text-box21 {
    font-size: 20px;
    color: #000000;
    margin: 0;
    padding-top: 1.2px;
    padding-bottom: 1.9px;
    line-height: 1.5;
    font-family: "museo-sans", sans-serif;
    font-weight: bold;
    text-transform: uppercase;
    background-image:url('http://www.aerlawgroup.com/uploads/2/1/1/5/21159280/6156337_orig.png');
    background-repeat: repeat-x;
    text-align: left;
}

A: Adding width: 282px; forces the boxes to match the image widths above and below... but then the parent div with the bottom border has a mismatched width of 100% that's set in JS. You would need to update the width there too.


text:
Q: Plot showing information about parameters I have a list containing a function and 5 parameters (all of them can change).
list={x^2,0.5,0.1,5,1,1}.

I would like to create a plot of the function, while displaying the values of the parameters inside the plot as relevant information. The parameters should be displayed including a string about what they mean. For example I would like to see the plot and on the right side of the plot I would like to see something like: "norm = 0.5", "visibility = 0.1" and so on..
Any idea how to do that?

A: Clear["Global`*"]

list = {x^2, 0.5, 0.1, 5, 1, 1};

labels =
  {"func", "norm", "visibility", "param3", "param4", "param5"};

Row[{
  Plot[Callout[x^2, labels[[1]]], {x, 0, 1},
   ImageSize -> Medium],
  Column[StringForm["`` = ``", #[[1]], NumberForm[#[[2]], {5, 2}]] & /@
     Transpose[{Rest@labels, Rest@list}]]}]

A: list= {.5,2};
Plot[a x^b, {x, 0, 1},
 PlotLabel ->
  Column[
 {Text["norm a =" <> ToString[list[[1]]]],
  Text["exponent b =" <> ToString[list[[2]]]]}]]


text:
Q: jquery multiselect dropdown check box which gets data from database? I have a requirement where in I need to display a dropdown check box as follows.
The data has to be pulled from datbase on type ahead.
Is there any jquery plugin to accomplish this?

A: You could use select2 select-replacement. http://ivaynberg.github.io/select2/
you can give an ajax property as an data aquire function which can load data from an remote resource.
http://ivaynberg.github.io/select2/#ajax


text:
Q: Prototype and YUI I saw a reference on a company intranet recently that "You should use YUI instead of prototype". (formerly Prototype was company recommended JS framework).
Is that because YUI builds on/extends Prototype?
Or merely implements a super-set of its functionality?

A: YUI is a completely separate library from to Prototype. YUI has more built in UI elements than Prototype and a very different design philosophy.

A: YUI and prototype are completely separate and have nothing in common except for both being a JS library.
Prototype is what is is, a JavaScript framework that makes working with the DOM very easy. It depends on scriptaculous for effects. Prototype is the first popular JavaScript framework since ajax became popular, IMHO it has been exceeded by jQuery, mootools and many more since then.
YUI is a JavaScript framework too but features a much bigger API and has several built in widgets (datepicker, grid, validation,...) which of course makes it a bigger library too.
What i like most about YUI is the fact that the code organised in very clear namespaces.


text:
Q: Ionic different tab content I am trying to do a hybrid app using ionic with the structure that look like this:
#/app                 (sidemenu.html)
#/app/noTabContent1   (notab-content1.html)
#/app/noTabContent2   (notab-content2.html)
#/app/tab1            (tab1.html)
#/app/tab1/content1   (tab1-content1.html)
#/app/tab1/content2   (tab1-content2.html)
#/app/tab2            (tab2.html)
#/app/tab2/content1   (tab2-content1.html)
#/app/tab2/content2   (tab2-content2.html)

The problem is that, it seems like conflict between the tab page. For example, if I first visit tab1 content page, then I go visit tab2 content page later on, it will still display tab1 content. If I visit tab2 content page first, it will always display tab2 content no matter how I try to access tab1 content page.
Why is it like that? Is my structuring wrong? Or, it is ionic bug? How can I overcome it?
edit: Here's my example code for easier understanding:
index.html:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link href="http://code.ionicframework.com/1.1.0/css/ionic.css" rel="stylesheet">

    <ion-nav-view></ion-nav-view>

app.js
// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a  attribute in index.html)
// the 2nd parameter is an array of 'requires'
angular.module('starter', ['ionic'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})

.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider

    .state('app', {
    url: '/app',
    abstract: true,
    templateUrl: 'templates/menu.html',
    //controller: 'AppCtrl'
  })

    .state('app.tab', {
    url: '/tab',
    views:{
            'menuContent':{
                templateUrl: 'templates/tab1.html'
            }
        }
  })
    .state('app.tab2', {
    url: '/tab2',
    views:{
            'menuContent':{
                templateUrl: 'templates/tab2.html'
            }
        }
  })

  .state('app.content1', {
      url: '/content1',
      views: {
        'menuContent': {
          templateUrl: 'templates/content1.html'
        }
      }
    })
  .state('app.content2', {
      url: '/content2',
      views: {
        'menuContent': {
          templateUrl: 'templates/content2.html'
        }
      }
    })
  .state('app.tab.content1', {
      url: '/content1',
      views: {
        'tab-Content': {
          templateUrl: 'templates/content1.html'
        }
      }
    })
 .state('app.tab.content2', {
      url: '/content2',
      views: {
        'tab-Content2': {
          templateUrl: 'templates/content2.html'
        }
      }
    })

.state('app.tab2.content1', {
      url: '/content1',
      views: {
        'tab2-Content': {
          templateUrl: 'templates/content1.html'
        }
      }
    })
 .state('app.tab2.content2', {
      url: '/content2',
      views: {
        'tab2-Content2': {
          templateUrl: 'templates/content2.html'
        }
      }
    })

  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/app/content1');
});

http://codepen.io/anon/pen/LpVVOr?editors=101

A: Welcome to the world of the mysterious ionic navigation.
I guess nobody has ever mastered this strange beast and, hopefully, at someone, at some point, will be able to fix it ... or, even better, rewrite it.
Loads of questions have been asked on this topic and many more in the forum; issues opened on the subject have been there, pending for ages but there's no definitive answer.
The strange thing is not even the creators have got a proper explanation or are will to answer those questions.
Anyway, going back to your problem. The only way to make it work is to disable the caching system.
Caching

By default, views are cached to improve performance. When a view is
  navigated away from, its element is left in the DOM, and its scope is
  disconnected from the $watch cycle. When navigating to a view that is
  already cached, its scope is then reconnected, and the existing
  element that was left in the DOM becomes the active view. This also
  allows for the scroll position of previous views to be maintained.
Caching can be disabled and enabled in multiple ways. By default,
  Ionic will cache a maximum of 10 views, and not only can this be
  configured, but apps can also explicitly state which views should and
  should not be cached.
Note that because we are caching these views, we aren't destroying
  scopes. Instead, scopes are being disconnected from the watch cycle.
  Because scopes are not being destroyed and recreated, controllers are
  not loading again on a subsequent viewing. If the app/controller needs
  to know when a view has entered or has left, then view events emitted
  from the ionView scope, such as $ionicView.enter, may be useful.

Each view is cached - and this is perfectly fine - but when you start messing around with tabs or menus things get out of hand.
If you really want to fix your problem just disable the cache for each state. There are a few options there but the only I've found easy to manage it to set cache: false when you're configuring your states:
.state('app', {
    cache: false,
    url: '/app',
    abstract: true,
    templateUrl: 'templates/menu.html',
  })

just disable cache for all the states and things will work properly.
This is your working Plunker.


text:
Q: Error: Can't set headers after they are sent using passportjs/Express The error in question

Error: Can't set headers after they are sent.

server.js
// set up ======================================================================
var express = require('express')
    , app = express()
    , cookieParser = require('cookie-parser')
    , bodyParser = require('body-parser')
    , expressSession = require('express-session')
    , server = require('http').createServer(app)
    , passport = require('passport')
    , local = require('passport-local').Strategy
    , md5 = require('md5')
    , util = require('util')
    , flash = require('connect-flash')
    , port = 80
    , url = require('url')
    , db = require('./db');

// optimization ================================================================
var compress = require('compression');
app.use(compress());

// configuration ===============================================================
app.use(express.static('public'));
app.use(cookieParser());
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

app.use(expressSession({
    secret: 'key',
    resave: false,
    saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());

// passport ====================================================================
passport.use(new local(
    function(username, password, done) {
        // asynchronous verification, for effect...
        process.nextTick(function () {
            db.findUserByName(username, function (err, user) {
                if (err) { done(err); }
                if (!user) { done(null, false, {message: 'Unknown user: ' + username})}
                if (md5(password) == user.password) {
                    done(null, user);
                } else {
                    done(null, false, {message: 'Invalid username or password'});
                }
            });
        });
    }
));
passport.serializeUser(function(user, done) {
    done(null, user.uuid);
});

passport.deserializeUser(function (id, done) {
    db.findUserByUUID(id, done);
});

// routes ======================================================================
require('./routes')(app, passport);

// launch ======================================================================
server.listen(port, function(){
    console.log('server started');
});

routes.js
var flash = require('connect-flash');

module.exports = function(app, passport) {

    app.get('/', function(req, res) {
        res.render('index', { num: 0, logged: false });
    });

    app.get('/login', function (req, res) {
        if (typeof req.user !== 'undefined') {
            // User is logged in.
            res.redirect('/');
        } else {
            req.user = false;
            var message = req.flash('error');
            if (message.length < 1) {
                message = false;
            }
            res.render('login', { logged: false, message: message });
        }
    });

    app.post('/login',
        passport.authenticate('local', {
            failureRedirect: '/login',
            failureFlash: true
        }),
        function(req, res) {
            res.redirect('/');
        }
    );

    app.get('/logout', function(req, res){
        req.logout();
        res.redirect('/');
    });

};

db.js
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/db';

exports.findUserByName = function (username, callback) {
    MongoClient.connect(url, function(err, db) {
        var cursor = db.collection('players').find( { "name": username } );
        cursor.each(function(err, doc) {
            if (doc != null) {
                console.log('YES');
                callback(false, doc)
            } else {
                console.log('NO');
                callback(false, null);
            }
            db.close();
        });

    });
};

var findUserByUUID = function(uuid, db, callback) {
    var cursor = db.collection('players').find( { "uuid": uuid } );
    cursor.each(function(err, doc) {
        assert.equal(err, null);
        if (doc != null) {
            callback(false, doc)
        } else {
            callback(false, null);
        }
    });
};
exports.findUserByUUID = function (uuid, callback) {
    MongoClient.connect(url, function(err, db) {
        assert.equal(null, err);
        findUserByUUID(uuid, db, function(err, data) {
            callback(err, data);
            db.close();
        });
    });
};

I understand that i'm calling done() twice, but when? I'm unable to find it.
I suppose that the problem is on the routes, but I don't know where.

A: In your passport.use() handler, each time you call done(), you need to then return so that the code after it is not also executed.
Right now you have a series of if statements that can each call done(), but they aren't if/else statements so more than one condition you are testing for can be met and thus done() can be called more than once.
For example, change this:
if (!user) { done(null, false, {message: 'Unknown user: ' + username})}

to this:
if (!user) {
    done(null, false, {message: 'Unknown user: ' + username});
    return;
}

And, change this:
if (err) { done(err); }

to this:
if (err) {
    done(err);
    return;
}

Or, you could make everything into if/else if/else if/else such that only one branch could ever execute.  The problem occurs when more than one of your if statements has its condition met and then is executed.

Now, your findUserByName() calls its callback in cursor.each() so it can call it multiple times which then causes you to call done() multiple times.


text:
Q: .htaccess url rewrite and removing %20 Hi Im very new at the rewriting thing. I have an Apache host that is hosting my website and I need to make the url rewrite to make it just look better than it currently is.
So I have this link http://www.kalah.co.za/content.php?page=Civil%20Tactical%20Training and i want it to look like http://www.kalah.co.za/Civil-Tactical-Training.html
Now I can do the first bit I guess with this code
RewriteEngine On
RewriteRule ^([^/]*)\.html$ /content.php?page=$1 [L]

But I need to also remove or replace the - things. I don't know what is more SEO friendly and any suggestions and advice / recommendations will be appreciated.
PS: Also is the .htaccess from a windows server and apache server different in terms of re-writes ?

A: You can have these rules in your root .htaccess:
RewriteEngine On
RewriteBase /

# external redirect from actual URL to pretty one (remove query string)
RewriteCond %{THE_REQUEST} \s/+content\.php\?page=([^\s&]+) [NC]
RewriteRule ^ %1? [R=302,L,NE]

# convert all space (%20) to hyphen
RewriteRule "^(\S*) +(\S* .*)$" $1-$2 [N,NE]
RewriteRule "^(\S*) (\S*)$" $1-$2 [L,R=302,NE]

# rewrite rule to call actual PHP handler
RewriteRule ^([^./]+)\.html$ content.php?page=$1 [L,QSA,NC]


text:
Q: What is composition of convex and concave function?
Suppose that $f: \mathbb{R}\to \mathbb{R}$ is convex function and $g: \mathbb{R}\to \mathbb{R}$ is concave function. What can we say about their composition $g\circ f$ and $f\circ g$? Are they convex or concave functions?

Thank you in advace !

A: Hint. Try $f(x)=e^x$ (convex) and $g(x)=-x^2$ (concave).
What about $f(g(x))=e^{-x^2}$?  Is it convex or concave? Check the plot at WA.
P. S. If we assume that $f,g$ are $C^2$ then
$$(f(g(x))'=f'(g(x))\cdot g'(x),\quad
(f(g(x))''=f''(g(x))\cdot (g'(x))^2+f'(g(x))\cdot g''(x)$$
So if $f''\geq 0$, $g''\leq 0$ and $f'\leq 0$ then $(f(g(x))''\geq 0$.


text:
Q: filter the same values in a row add the same values together In the sample of the dataset below, from the icase_id column, I want to remove numbers that appear more than two (>2) and less than (<2) times.
icase_id 2,2,3,3,3,1,4,4
summ
2
3
1
2
3
4
2
1

*after doing that, want to count the total of each set of numbers and save it in one single icase_id, example as this:

icase_id 2, 4
summ      5, 3
so i need someones help how to accomplished this exercise. Thanking in advance

A: Pretty basic stuff with library(dplyr)
df <- cbind.data.frame(icase_id=c(2,2,3,3,3,1,4,4),summ=c(2, 3, 1, 2, 3, 4, 2, 1))

df %>%
  group_by(icase_id) %>%
  filter(n()==2 ) %>%
  summarise(summ=sum(summ))


text:
Q: Pine Script Run Error "internal server pine compilation error" seen for NR4 Code I have written simple Narrow Range 4 Indicator Code in Pine Script of Trading View , The Source Code is error free.
Tried Debugging in many ways but couldn't figure out the error reason
//@version=3
study(title="Narrow Range 4", overlay=false)

currentHigh = security(tickerid, "1D", high[1])
currentLow = security(tickerid, "1D", low[1])
BarLength = currentHigh - currentLow

//Function for UP Count
NR_UP(TimeLineForToday,BarLen,currtHigh) =>
    MoveUpNR4 =0
    NR4PrevMin = lowest(BarLen[1],3)
    if BarLen < NR4PrevMin
        MoveUpNR4 := iff( currtHigh > currtHigh[1],1,0)
   [MOVEUP] = MoveUpNR4*0.90

//Function for Down Count
NR_DOWN(TimeLineForToday_d,BarLen,currtLow) =>
    MoveDownNR4 = 0
    //NR4
    NR4PrevMin = lowest(BarLen[1],3)
    if BarLen < NR4PrevMin
        MoveDownNR4 := iff( currtLow < currtLow[1],1,0)
    [MOVEDOWN] = MoveDownNR4*0.8

 //Call NR4
 [MOVEUP] = NR_UP("1D",BarLength,currentHigh)
 [MOVEDOWN] = NR_DOWN("1D",BarLength,currentLow)

 plot(series=MOVEUP,color = blue,linewidth=2)
 plot(series=MOVEDOWN,color = red ,linewidth=2)

This code should have produced simple 2 line plots on the tradingview.com chart.


text:
Q: SQL Server Returns error on geography column I have seen questions regarding this but not exactly my scenario:
I have created a service. It runs on one server that is also a web server. It looks at a remote server running SQL Server to gather data to run.
When getting data from one of the tables, there is a column with a geography data type. In the web application that is running, no problems getting this table as Microsoft.SqlServer.Types.dll is referenced.
A service running on the Web server creates and error:

DataReader.GetFieldType(22) returned null.

When doing a select statement on this remote machine even the same dll is referenced.

A: Very Strange. The query is a very basic "Select * from ..... where ....."
I kept searching and found a post suggesting setting the reference to the Microsoft.SqlServer.Types.dll from the following folder:
C:\Program Files\Microsoft SQL Server\110\Shared
I made the change. Copied the recompiled service with the new dll to the installed folder on the web server and now it completes without the error.
I didn't create the original code so I am not sure where the original dll reference came from.


text:
Q: Can I create a form and share it with my private group on Sharepoint O365? I would like the form to be shared on our private group page. I would like once the form is filled out to be kept on a list on that page.

A: *

*You can use Target Audiences functionality of SharePoint.
for more details use this link

*Another way is you can provide unique permission to that list and
give access to only your private group.
for more details use this link


text:
Q: Is it possible to connect asp.net core 2.1 web api with existing database in sql server? I see an official video of visual studio show how to do this. But in the end, the instructor can't make it work, he must alter UseSqlServer() with UseInMemoryDatabase() in Startup.cs.
Here is my code, i follow his instruction.
Firstly, create a file with classes that one contain Dbcontext, others map with tables in database. In my case, database just have one table: Students. This is class contain Dbcontext:
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HoangHoaTham.WebAPI.Entities
{
    public class TodoContext : DbContext
    {
        public TodoContext(DbContextOptions<TodoContext> options) : base(options)
        {
        }

        public DbSet<Students> Students;
    }
}

My Startup.cs, i add UseSqlServer here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using HoangHoaTham.WebAPI.Entities;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace HoangHoaTham
{
    public class Startup
    {
        public IConfiguration Configuration { get; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<TodoContext>(options
                => options.UseSqlServer(Configuration.GetConnectionString("HoangHoaTham")));

            services.AddMvc();
        }

        //You don't need to reed the code below

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }
}

Finally, I add ConnectionString into appsetting.json:
{
  "ConnectionString": {
    "HoangHoaTham": "Server=PC-PC\\SQLEXPRESS;Database=HoangHoaThamHighSchool;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

Anh it doesn't work. The error :
enter image description here
Here is his video: https://www.youtube.com/watch?v=aIkpVzqLuhA
Skip to 50:47 to see how he did that.
Thank you so much.

A: The error is telling you that the result of Configuration.GetConnectionString("HoangHoaTham") is null. Therefore, there's some issue with your configuration, and it turns out there is: the connection string section in appsettings.json is supposed to be ConnectionStrings (plural). You've got ConnectionString (singular) instead.

A: The error is for the ConnectionString you used in appsetting.json just try this code in your appsetting.json1 and tweak the connectionstring` as per your requirements this would work.
ASP.NET Core Web API
{
   "ApplicationInsights":{
      "InstrumentationKey":""
   },
   "ConnectionStrings":{
      "DefaultConnection":"Server=srvrName;Database=Test;User Id=User;Password=pass"
   },
   "Logging":{
      "LogLevel":{
         "Default":"Warning"
      }
   },
   "AllowedHosts":"*"
}


text:
Q: How can I print a PDF client side that was received from my server? So I'm very new to generating PDFs from the server side as I have generally always created them from the client side.  I decided to migrate to creating them strictly server side because I believe there is more flexibility doing it this way.  One thing that I have been struggling with lately is that I'm trying to generate a PDF from the server and then retrieve the data on the client side and be able to print it from there.
I'm using the pdfmake library to generate my PDFs on the server. You can see that I'm using a get request to retrieve the generated PDF here:
server.get(`/api/print_paper_letter`, bodyParser.urlencoded({extended: false}), async (req,res) => {
            try {
                const doc = await PrintPaperLetter(req.body.pdf_obj);
                res.type('application/pdf');
                res.send(doc);
            } catch (e) {
                console.error(`api.print_paper_letter: ${e}`);
                res.sendStatus(400);
            }
        });

And I'm generating the PDF from another file here:
PrintLetter.js
const PdfPrinter = require('pdfmake');
import {PaperLetterNormal} from '../../components/PDFTemplates';

const fonts = {
    Helvetica: {
        normal: 'Helvetica',
        bold: 'Helvetica-Bold',
        italics: 'Helvetica-Oblique',
        bolditalics: 'Helvetica-BoldOblique'
      }
}

export const PrintPaperLetter = async (pdf_obj) => {
    return new Promise(async(resolve,reject) => {
        try {
            const printer = new PdfPrinter(fonts);
            const definition = PaperLetterNormal(pdf_obj);
            const pdf = printer.createPdfKitDocument(definition);
            let chunks = [];
            pdf.on('data', chunk => chunks.push(chunk));
            pdf.on('end',() => resolve(Buffer.concat(chunks)));
            pdf.end();
        } catch (e) {
            console.error(`PaperLetters.PrintPaperLetter: ${e}`);
            reject(e);
        }
    })
}

When I make the call to retrieve the PDF data from the client side I end up getting some sort of garbage data, but I'm not sure how I would be able to print this.
Client side code:
const pdf_obj = {
  .
  .
  .
}

$.post('/api/print_paper_letter',{pdf_obj: pdf_obj},(res) => {
                    if(!res){
                        console.error(`there was an issue retrieving this pdf doc`)
                    }else{
                        console.log({res});
                    }
                })

The response on the client side looks like this:
%PDF-1.3
%ÿÿÿÿ
9 0 obj
<<
/Type /ExtGState
/ca 1
/CA 1
>>
endobj
11 0 obj
<<
/Type /ExtGState
/CA 1
>>
endobj
13 0 obj
<<
/Type /ExtGState
/ca 1
>>
endobj
8 0 obj
<<
/Type /Page
/Parent 1 0 R
/MediaBox [0 0 595.28 841.89]
/Contents 6 0 R
/Resources 7 0 R
>>
endobj
7 0 obj
<<
/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]
/ExtGState <<
/Gs1 9 0 R
/Gs2 11 0 R
/Gs3 13 0 R
>>
/XObject <<
/I1 5 0 R
>>
/Font <<
/F1 10 0 R
/F2 12 0 R
>>
>>
endobj
6 0 obj
<<
/Length 2896
/Filter /FlateDecode
>>
stream
xÍ]ÛrÇ
}߯P»ÑúR¥âíÄ?¤*±Þ\~Ë\*J*QUòû9îλ i.d¦¤
û hà}M_ï¿t¡ÔÇ´ý¼ùæ/4ýåËæßÒ¼GjCõIòÔìå?Ðôý¿6:üÔ7ßïþû·íîÏ?|;m¿lö?ÿeûÏÍÝ3Þâ9¾ý°<§^8uÜËôø¿§òôánóó{V|ço¦üËôáÇÍï><K²§q«¦\h¥¦êmô4;ÐB76,ï[½Nï«ÞLßËîfªx QMâ
ìD#pSjMjºöT«gÄ
Ö·Àî9=ÑqT8ÉSømkÇк
ÂÁ5º[ÙEà*§ª¾ÛQf¨¾^[2§æ@·ù¿Eí;-üû1´rco½¯Ù0ê]ÝÛë×%ëRCgëØA-¾[&Þ,5þâ®ÊV¦ÿm~þ·èïøþqGYÉx>o´éúÁ?Öýø?}÷Gëg±~þtu{Q×#FÃÞÛô÷ÎÜ8'.ÍÅûn%
H·GüÖÂ\Íh©UrÄáÂãcÕÈÂ
þÐ_ͬ0¯ÒhtNÝhA²¡Zêà+Û4[ÉI{½oÀS¬w{jÔê>Z·«In©IÆ÷Ð%m%Bà\/K á°#»&xHù¤£;¸QùãͤQláwª§ó¬æy2é[RÎ]ÏûVBètx¦¶
{D¼kOàÂOô°nà´Þâ{â1IGêÅ%9æãahÁzº¯{Æ'!@É5isû?öá2ÌËbB§n³þ²f39F´ÚÕ!D'¸Üñ[Ù\j,P³Äj ÙÝÏxëÇígD§2rÐIñé|¶å'Ë´ î§kÁÉpÑ©ÊóÉìH0p××XoìÉ¡yºÝ\?`UJ¤Ýë¿´ÉX®æD|dν5$I˹ßþ°:GüÒEgÒ;0qfIª0HdRÏLa(bÌä0Ý*%Ñîàòg¹
¨~!U-ÕÞ²®ï
.
.
.

If someone could explain to me what I'm looking at in terms of the response, and if it's possible to convert this in a way to then print it on the client side, that would be amazing.  Please let me know if you need me to add more to my post.  TIA!

A: When you send a pdf response, you are sending a blob/buffer to the front-end, so you'll need to capture that in the front-end to display/download the content.
if you want to immediately prompt for download, add res.attachment(filename) to your express function.
EXPLANATION:
res.attachment() does the same as the native node response.setHeader() command. It sets the content-disposition header property to attachment, additionally setting the fil-name, if supplied with one.
After that, to actually serve the file, you call the res.send() method to end the process and send the response, as you do with any request.
Alternatively, if you want to render the file on the client you will need to use a compatible element like the (relatively new) HTML object, or another compatible element.


text:
Q: Better way to Split files into 80% and 20% for building model and prediction in MapReduce I am trying to divide my HDFS file into 2 parts/files
80% and 20% for classification algorithm(80% for modelling and 20% for prediction)
Please provide suggestion for the same.
To take 80% and 20% to 2 seperate files we need to know the exact number of record in the data set.And it is only known if we go through the data set once.
so we need to write 1 MapReduce Job for just counting the number of records and
2 nd Mapreduce Job for separating 80% and 20% into 2 files using Multiple Inputs.
Am I in the right track or there is any alternative for the same.
But again a small confusion how to check if the reducer get filled with 80% data.

A: I suggest you to use Random for splitting the dataset and MultipleOutputs to write data into separate paths. It can be done with only one map-only job. Here is an example of mapper that you could use:
public class Splitter extends Mapper<LongWritable, Text, NullWritable, NullWritable> {
    MultipleOutputs mos;
    Random rnd = new Random();

    @Override
    protected void setup(Context context) throws IOException, InterruptedException {
        mos = new MultipleOutputs(context);
    }

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        if (rnd.nextDouble() < 0.8) {
            mos.write(key, value, "learning-set");
        } else {
            mos.write(key, value, "test-set");
        }
    }

    @Override
    protected void cleanup(Context context) throws IOException, InterruptedException {
        mos.close();
    }
}


text:
Q: CSS excluding children from style

ol li{
color: blue;
}
ol ol li {
color:black;
}
ol ol {
 list-style: upper-alpha;

Topic 1

 Sub Topic 1

 Sub Topic 2

 Sub Topic 3

Topic 2

Topic 3

Sub Topic 1

Sub Topic 2

Sub Topic 3

Simple question I hope. The first level of an
 is always a heading.  Trying to style
ol li {
font-size:larger;
}

without changing ol ol li or other children.
So much thanks!
Edit:
HTML structure is

Topic

 Sub Topic 1

 Sub Topic 2

Topic 2

The goal is to remove the need for the bold tags.

A: It's a bit unclear what you are asking: "The first level of an ol is always a heading" - Do you really mean a heading like
,
 etc., or do you mean that you want to apply a special styling to the first
 inside  every
 tag ?
In the latter case, you can use a :first-child selector, like
ol > li:first-child {
  font-size:larger;
}

In case you want to apply a special styling to any first child if every
 tag, you can use the general * selector, combined with :first-child
ol > *:first-child {
  font-size:larger;
}

(Although I doubt that anything else than an li as a direct child of an ol would be valid HTML)

Addition after edit of question:
Since your ol will be inside some other element, you can use the following selector to adess only direct ("first-level") children of the ol. (I applied a class to the parent element and used that in the selector)

.parent>ol>li {
  font-weight: bold;
}

Topic

 Sub Topic 1

 Sub Topic 2

Topic 2

A: If it is inside a certain container always (for example .container), you can do so:
.container > ol > li {
font-size:larger;
}

Here it would only apply it to direct child ol and that only to direct child of that.


text:
Q: Quotations and punctuation The common usage I have been exposed to is that punctuation should only be in a quotation if it's contained in the original source. So what if your quotation ends in a period and your quotation is also the end of your sentence. Do you need two periods?
I asked my son to visit his grandma; however, he said, "No, I won't go.".
Is the above correct?

A: You don't ever want two periods in the same sentence, so just keep it to I asked my son to visit his grandma; however, he said, "No, I won't go." What comes after the semicolon, however, he said, is not a complete sentence and does not warrant a period anyhow. Here's how the Chicago Manual of Style puts it:

Don't ever put two periods in a row. Put one period at the end of a declarative sentence, even if it ends with an abbreviation or a URL.

A: This is a question of style, and styles have changed over time.  At one time it was fairly common to use two periods in a situation such as the example above, but people found that ugly.  Then there was a period of time (I'm thinking ca 1960) when the period would never fall before the closing quote, even if the quote was a "complete sentence".
Current style, when a quote comes at the end of the containing sentence, is to place the period before the closing quote if the quoted text is a complete sentence, and place it after the quote otherwise.  However, note that if the following sentence begins, eg, with an acronym or proper name then using this policy could result in ambiguity for the reader, and hence the second period might be justified.  So to some extent the choice is at the writer's discretion.


text:
Q: How to zoom out status bar when using launch image in iOS I'm developing app and using launch image.
So in iPhone6 or iPhone6 Plus status bar is zoomed.
I know we have to use launch screen to avoid that.
I think We have to use autolayout if we use launch screen.
But Is there no way we can zoom out status bar without using launch screen and autolayout?
Thanks.

A: You have to use launchscreen and autolayout.
Launch image is not recommended way.
With autolayout, status bar will not be zoomed


text:
Q: Is a Document Type required for PNG images? My iOS app im building used various images (.PNG files, some are via the Assets Catalog). For now these images are part of the app. In the future more .PNG images will be downloaded as part of an In-App Purchased package (.PKG).
Do each .PNG file need to be registered into the Document Types list in the info.plist?

A: No. PNG is already a standard registered type. And registering Document Types is for registering a type, not a list of files using that type.


text:
Q: How to set encoded base 64 result on Gtk.Label or Gtk.Entry? I want to use base 64 and print the encode result into Gtk.Label, this is my code so far:
from gi.repository import Gtk

import base64

class classInputs(Gtk.Window):
    def __init__(self):

        Gtk.Window.__init__(self, title="Inputs try window")
        self.set_border_width(10)
        self.set_size_request(200,100)

        # Layout
        vertical_box = Gtk.Box(orientation = Gtk.Orientation.VERTICAL, spacing = 8)
        self.add(vertical_box)

        #userName input
        self.username = Gtk.Entry()
        self.username.set_text("")
        vertical_box.pack_start(self.username, True, True, 0)

        #Password input
        self.password = Gtk.Entry()
        self.password.set_text("aaaaaaaaaaa")
        self.password.set_visibility(False)
        vertical_box.pack_start(self.password, True, True, 0)

        #create login botton here
        self.button = Gtk.Button(label="click me to login")
        self.button.connect("clicked", self.function)
        vertical_box.pack_start(self.button, True, True, 0)

        #create label
        self.label= Gtk.Label()
        vertical_box.pack_start(self.label, True, True, 0)

    #function of the button here bech ki tenzel 3al button y7ot lencode fel input 1
    def function (self, widget):
        self.label.set_text(base64.b64encode(b'data to be encoded'))

shinerghost = classInputs()
shinerghost.connect("delete-event",Gtk.main_quit)
shinerghost.show_all()
Gtk.main()

Any ideas on how I can achieve that?

A: Assuming you want to encode the value of the password field you were pretty close, the only thing you forgot was to get the value of the password field and put it into the encode like this:
def function (self, widget):
    # Get the value from the input field
    string = self.password.get_text()

    # Turn the string into bytes
    byte_string = string.encode('utf-8')

    # Encode the string
    encoded_string = base64.b64encode(byte_string )

    # Set the label text
    self.label.set_text(encoded_string)


text:
Q: How do I detect when a CCSprite has reached a certain point? I am writing a game using the Cocos2d library for iOS. So far I have a sprite on the screen that I would like to drag around. Basically I have a CGPoint called End. When I drag across the screen it moves. I want to have the sprite figure out on each frame whether End has moved, and if it has start moving toward it at a given velocity, and stop right on top of it. End is like an anchor. I have accomplished the first two steps by plotting out the vector like this:
-(void) update:(ccTime)deltaTime
{
    CGPoint Pos = _player.position;
    velocity = 15;

    diff.x = End.x - _player.position.x;
    diff.y = End.y - _player.position.y;
    length = ccpLength(diff);

    norm.x = diff.x / length * velocity;
    norm.y = diff.y / length * velocity;

    Pos.x += norm.x;
    Pos.y += norm.y;
}

I move the End point around like this:
- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint touchLocation = [self convertTouchToNodeSpace:touch];

CGPoint oldTouchLocation = [touch previousLocationInView:touch.view];
oldTouchLocation = [[CCDirector sharedDirector sharedDirector] convertToGL:oldTouchLocation];
oldTouchLocation = [self convertToNodespace:oldTouchLocation];

CGPoint diff = ccpSub(touchLocation, oldTouchLocation);

End = ccpAdd(End, diff);
}

What is the best way to detect when the _player has reached it's destination? I've tried this a number of ways, but I really can't get it to be precise enough. I tried adding a timer that times the duration of each move, so I could test if velocity * duration >= length. Is that the way to do it? It didn't work out too well. Any master programmers want to give me some tips?

A: At the end of your update method, check for distance. If distance is under velocity, you're done, set the position to the endpoint and fire off whatever method you'd like. In cocos2d, you can use the method ccpDistance.


text:
Q: Are these Stephen Hawking's statements legitimate? I am reading 'Brief Answers to the Big Questions' by Stephen Hawking and it seems to me that some of his statements are just hypotheses, but they are written in such a way that they 'sound' like they are supposed to be scientific facts.
For example:

*

*There was no time before the Big Bang.

I do not know much about cosmology so I tried to look it up and to me it looked like there isn't any consensus.

*Physical laws are unchangeable and universal.

While this assumption certainly makes life easier and no one has ever seen  anything that would disprove it, I am pretty sure that we just don't know that. We don't know whether laws of nature were and will be the same, just as we don't whether they aren't any different in distant galaxies. It's all just convenient assumptions, right? (Btw. yes I know the Occam's razor, but it just triggers me a little that he never uses phrases such as 'I assume' or 'hypothetically', when making this statement.)

A: Light from distant galaxies emitted eons ago has the same spectral lines as from elements on Earth, excepted redshifted due to their journey through the expanding universe. That seems to me like good evidence that atoms then and there were obeying the same laws of physics as atoms here and now.
I can't offer similar evidence for "no time before Big Bang". That was Hawking's opinion. Some cosmologists think that our Big Bang may have actually been a Little Bang in a larger multiverse. In that case, there would have been time before our Little Bang.

A: I think these are more the philosophical type of facts than scientific facts. They stem from the axioms for our reasoning and definitions of the words, and thus cannot be "verified" because, well, they must be believed to be true.

*

*The Big Bang is considered the beginning of everything. When we make this statement, it is implied that we believe Big Bang's existence as a priori; and "everything" means literally everything, including time. So yeah, the Big Bang is the beginning of time, the first event. And before the first event, by definition of the word "first", there cannot be time before the "first" event, otherwise the Big Bang would not be the first event, right?

*The physical laws, as a concept, do not change because they are defined as things that are unchangable. Careful that they are different from our perception of them, which is the useful thing that we use to make better of our lives. Sure, constants like pi can change, or maybe the sun starts rising from the West, but that cannot be because the laws suddenly change. It can only be because we are dumb, because our perception of the laws is flawed. The laws are still, as they always have been, by definition, the way they are. It's us who need to update our understanding of them.
Personal opinion: it's all just definition and tautology. Fun to read for a while, important to know, but at some point it becomes useless quarrelling.


text:
Q: Parsing JSON Response using Jackson I have written a web-service and hosted in the following URL http://192.168.2.34:8081/MyWebService/facility/university
Response from this web service in JSON format is:
{
  "university": [
    {
      "emailOfPrincipal": "prin1@gmail.com",
      "labLists": [
        {
          "instrumentLists": [
            {
              "instrumentId": "1",
              "instrumentName": "Instrument 1"
            },
            {
              "instrumentId": "2",
              "instrumentName": "instrument 2"
            }
          ],
          "labId": "11",
          "labName": "Lab 11"
        },
        {
          "instrumentLists": [
            {
              "instrumentId": "3",
              "instrumentName": "instrument 3"
            },
            {
              "instrumentId": "4",
              "instrumentName": "instrument 4"
            }
          ],
          "labId": "22",
          "labName": "Lab 22"
        }
      ],
      "univAddress": "Kolkata",
      "univId": "111",
      "univName": "University 111",
      "univPrincipalName": "Principal 1"
    },
    {
      "emailOfPrincipal": "prin2@gmail.com",
      "labLists": [
        {
          "instrumentLists": [
            {
              "instrumentId": "5",
              "instrumentName": "Instrument 5"
            },
            {
              "instrumentId": "6",
              "instrumentName": "Instrument 6"
            }
          ],
          "labId": "33",
          "labName": "Lab 33"
        },
        {
          "instrumentLists": [
            {
              "instrumentId": "7",
              "instrumentName": "Instrument 7"
            },
            {
              "instrumentId": "8",
              "instrumentName": "Instrument 8"
            }
          ],
          "labId": "44",
          "labName": "Lab 44"
        }
      ],
      "univAddress": "Bangalore",
      "univId": "222",
      "univName": "University 222",
      "univPrincipalName": "Principal 2"
    },
    {
      "emailOfPrincipal": "prin3@gmail.com",
      "labLists": [
        {
          "instrumentLists": [
            {
              "instrumentId": "9",
              "instrumentName": "Instrument 9"
            },
            {
              "instrumentId": "10",
              "instrumentName": "Instrument 10"
            }
          ],
          "labId": "55",
          "labName": "Lab 55"
        },
        {
          "instrumentLists": [
            {
              "instrumentId": "11",
              "instrumentName": "Instrument 11"
            },
            {
              "instrumentId": "12",
              "instrumentName": "Instrument 12"
            }
          ],
          "labId": "66",
          "labName": "Lab 66"
        }
      ],
      "univAddress": "Hyderabad",
      "univId": "333",
      "univName": "University 333",
      "univPrincipalName": "Principal 3"
    }
  ]
}

I am trying to convert JSON data into Java object using jackson api. But getting an error.
My Java Objects are:
University.java
public class University {
    private int univId;
    private String univName;
    private String univAddress;
    private String univPrincipalName;
    private String emailOfPrincipal;
    private List<Laboratory> labLists = new ArrayList<>();

    //... Getter and Setter Methods...
}

Laboratory.java
public class Laboratory {

    private int labId;
    private String labName;
    private List<Instruments> instrumentLists = new ArrayList<>();
    //... Getter and Setter Methods...
}

Instruments.java
public class Instruments {

    private int instrumentId;
    private String instrumentName;
    private String bookingStatus;
    private Date bookingFrom;
    private Date bookingTo;
    private Date requestedTime;

    //... Getter and Setter Methods...
}

The Client written is:
public class ParseJSONData {

    public static void main(String[] args) throws ClientProtocolException, IOException {
        String URL = "http://192.168.2.34:8081/MyWebService/facility/university";
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(URL);
        HttpResponse response = httpclient.execute(httpget);
        // System.out.println(response);

        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity);

        ObjectMapper mapper = new ObjectMapper();

        University universities = mapper.readValue(result, University.class);
        System.out.println(universities.getEmailOfPrincipal());
    }

The error I am getting says
Exception in thread "main" org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "university" (Class University), not marked as ignorable
 at [Source: java.io.StringReader@100edc0; line: 1, column: 16] (through reference chain: University["university"])

I know my JSON data is returning List of universities. But how to map those in List I am not aware of. Any sort of help will be greatly appreciated.

A: You can add parent class
public class UniversityList {
    private List<University> university;
    //... Getter and Setter Methods...
}

and us it like this:
ObjectMapper mapper = new ObjectMapper();
UniversityList list = mapper.readValue(json, UniversityList.class));
University university = list.getUniversity().get(0)

Other option is to create custom deserializer for your University class
Here is demo:
public static void main(String[] args) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addDeserializer(University.class, new UniversityDeserializer());
    mapper.registerModule(module);
    University university = mapper.readValue(json, University.class);
}

public static  class UniversityDeserializer extends JsonDeserializer<University> {
    private ObjectMapper unmodifiedMapper = new ObjectMapper();
    @Override
    public University deserialize(JsonParser p, DeserializationContext ctxt)
                                                                throws IOException{
        JsonNode node = p.readValueAsTree();
        JsonNode array = node.get("university");
        if (array != null && array.isArray()){
            JsonNode uniNode =  array.get(0);
            return unmodifiedMapper.treeToValue(uniNode, University.class);
        }
        return null;
    }
}


text:
Q: Argument matching not working properly with NSubstitute I have this code and I can't get httpClient to return the string response no matter what.
HttpClient httpClient = Substitute.For<HttpClient>();

httpClient.PostAsync("/login", Arg.Any<StringContent>())
          .Returns(this.StringResponse("{\"token\": \"token_content\"}"));

Console.WriteLine(await httpClient.PostAsync("/login", new StringContent(string.Empty)) == null); // True

Here is the StringResponse method if someone wants to reproduce this:
private HttpResponseMessage StringResponse(string content)
{
    var response = new HttpResponseMessage(HttpStatusCode.OK);

    if (content != null)
    {
        response.Content = new StringContent(content);
    }

    return response;
}

What am I doing wrong?
It works when I do
httpClient.PostAsync("/login", Arg.Any<StringContent>())
              .ReturnsForAnyArgs(this.StringResponse("{\"token\": \"token_content\"}"));

But I don't need just any arguments, I need one of them to be the string "/login" and the other to be of type StringContent.
I tried to put something more general in the Arg.Is call like HttpContent but that doesn't work too.
I'm using NSubstitute 2.0.0-rcon .NET Core, but I also tried using NSubstitute 1.10.0 on standart console application and got the same result.

A: The problem here is that the public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content) method isn't virtual and NSubstitute cannot correctly link your argument specification and return value to the method. That's a problem of all mocking libraries based on Castle.Core.
What's important is that NSubstitute links the specification to the first virtual method in the execution stack which turns out to be public override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) method somewhere down the stack. You were "lucky" to have the same return type in it. And as you can see it has different arguments that obviously don't match with those you provided. Surprisingly ReturnsForAnyArgs() works because it doesn't check the argument specification you provided.


text:
Q: Unknown encoder 'libvorbis' I am facing problem in converting videos by using ffmpeg. Its installed and all the libraries are also there. but using certain commands its showing for different encoders that they are Unknown.
Unknown libvorbis
Unknown libvpx
Unknown libogg
etc
Can anyone help please.
/bin$ ffmpeg
ffmpeg version 0.10.15 Copyright (c) 2000-2014 the FFmpeg developers
  built on Aug 30 2014 15:49:19 with gcc 4.4.7 20120313 (Red Hat 4.4.7-3)
  configuration: --prefix=/usr --bindir=/usr/bin --datadir=/usr/share/ffmpeg --incdir=/usr/include/ffmpeg --libdir=/usr/lib64 --mandir=/usr/share/man --arch=x86_64 --extra-cflags='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic' --enable-bzlib --disable-crystalhd --enable-gnutls --enable-libass --enable-libcdio --enable-libcelt --enable-libdc1394 --disable-indev=jack --enable-libfreetype --enable-libgsm --enable-libmp3lame --enable-openal --enable-libopenjpeg --enable-libpulse --enable-librtmp --enable-libschroedinger --enable-libspeex --enable-libtheora --enable-libvorbis --enable-libv4l2 --enable-libx264 --enable-libxvid --enable-x11grab --enable-avfilter --enable-postproc --enable-pthreads --disable-static --enable-shared --enable-gpl --disable-debug --disable-stripping --shlibdir=/usr/lib64 --enable-runtime-cpudetect
  libavutil      51. 35.100 / 51. 35.100
  libavcodec     53. 61.100 / 53. 61.100
  libavformat    53. 32.100 / 53. 32.100
  libavdevice    53.  4.100 / 53.  4.100
  libavfilter     2. 61.100 /  2. 61.100
  libswscale      2.  1.100 /  2.  1.100
  libswresample   0.  6.100 /  0.  6.100
  libpostproc    52.  0.100 / 52.  0.100
Hyper fast Audio and Video encoder
usage: ffmpeg [options] [[infile options] -i infile]... {[outfile options] outfile}...

Use -h to get full help or, even better, run 'man ffmpeg'

A: Your ffmpeg build has --enable-libvorbis for Vorbis audio encoding support, but lacks --enable-libvpx so you have no VP8/VP9 encoding support.
0.10.15 is old. Users are recommended to use a build from current git master, or, if that is not possible, a recent release.
You have a few options to resolve this issue:

*

*Compile ffmpeg using whatever configure options that will fit your needs. See FFmpeg Wiki: Compile Guide for CentOS, RHEL, Fedora.

*Or download a static build of ffmpeg. The static build contains support for Vorbis and VP* encoding.
Then point your scripts to your new build.


text:
Q: Simpson's rule and Trapezoid Rule? Let $S(n)$ and $T(n)$ be the approximations of a function using $n$ intervals by using Simpson's rule and the Trapezoid rule respectfully.
My book then states:
$$S(2n) = \frac{4T(2n) - T(n)}{3}$$
Can someone please give me a proof of this? I wasn't able to find one through Google.

A: Consider $x_0\le x\le x_0+2h$, where $h=(b-a)/(2n)$.  This will be one interval in  the trapezoidal rule for $n$ intervals, and so we have
$$T_1(n)=2h\frac{f(x_0)+f(x_0+2h)}{2}$$
for the trapezoidal approximation over this single interval.  The same interval counts as two intervals if we are looking at $2n$ intervals overall, so we then get the trapezoidal approximation
$$T_1(2n)=h\frac{f(x_0)+f(x_0+h)}{2}+h\frac{f(x_0+h)+f(x_0+2h)}{2}$$
and the Simpson's approximation
$$S_1(2n)=h\frac{f(x_0)+4f(x_0+h)+f(x_0+2h)}{3}\ .$$
It is easy to check that
$$S_1(2n)=\frac{4T_1(2n)-T_1(n)}{3}\ ,$$
and adding these for all $n$ intervals gives what you want.


text:
Q: Interact with a STM32 chip's memory in C I would like to interact with a STM32 chip's memory, STM32L476, first to read and store its electronic signature (MCU_ID) and then to write data in its memory. I am using a STM32QFP64 socket linked to a JTAG ST-LINK.
I am quite good in C but really beginning embedded programming so I chose Atollic Studio IDE because it seemed quite complete and was based on Eclipse which I had already used prior.
My problem is that I can't find some sort of documentation listing the functions, variables etc. I could use to interact with the chip. I have searched in nearly all the PDFs given on the ST site, read ST's GitHub, but since I am a beginner I could have missed those information for I did not know what what I am searching for looks like.
The code below is irrevelant and completely imagined, but it could help understanding what I am trying to do, which I picture somehow like this :
#define MEMORY_ADRESS_MCU_ID FFFFF // A memory adress ( I should be able to find it in STM32L476 documentation)
#define MEMORY_ADRESS_TO_WRITE FFFF // Same

unsigned extractMCUID() {

   return READ_IN_MEMORY(MEMORY_ADRESS_MCU_ID); // Returns the ID stored in a particular memory adress

}

void writeData(char* d) {

   WRITE_IN_MEMORY(MEMORY_ADRESS_TO_WRITE, d); // Writes data in specified memory adress

}

Thus, in this case and even more generally :
1) Where should I look for such documentation ?
2) Does those functions and variables change depending on what STM32 chip I am dealing with ?
3) Where could I have found the answers to 1) and 2) if not on StackExchange ?

A: You may want to have a look here:
http://www.openstm32.org
This part may give you a hint:
char in_ccram_buffer[1024] __attribute__((section("ccmram")));
I have something similar in my AVR code:
 const uint16_t tempTable[42] __attribute__((section(".eeprom"))) = ...

works a charm.

A: STM publishes several types of documents for each MCU and it's difficult for me to guess which document will contain the piece of information that I'm looking for.  So I search within the documents for related key words until I narrow in on the information.  The two most important documents are the Datasheet and the Reference Manual so I always start with them.
In this case I started searching the Datasheet for "MCU_ID" and found nothing so I searched for the more generic "ID" and found it associated with the more specific keyword "unique".  I searched the Datasheet for "unique" but didn't find the register address information.  So then I searched the Reference Manual for "unique ID" and found the base address for the register in section 49.1 on page 1808.
Yes, details like this can change from one STM MCU to the next so you need to ensure you're using the correct Datasheet and Reference Manual.  However, STM provides a Hardware Abstraction Layer (HAL) called STM32Cube, which abstracts away MCU specific details like this and allows you to call more generic functions which are MCU independent.
Edit:  I may have pointed you to the wrong ID register.  Clifford points out in the comments that there is an MCU device ID register at address 0xE0042000.  This MCU device ID register is different from the Unique device ID register and it's described in section 48.6.1 on page 1782 of the Reference Manual.


text:
Q: Wowonder 4.0.1 Login Loop I woke up one morning and found my Wowonder website had stopped letting people login. When you try it goes into a login loop taking you right back to the login again.
I installed a second copy in a new location and works fine. I even tried changing my current one to a new DB and it worked fine.
I was told to go to Varibles under phpmyadmin by a guy who runs Wowonder himself and search for mode. That brought up sql_mode and he told me to remove everything on that line except for: NO_ENGINE_SUBSTITUTION so I did and still loops (attaching screenshot of it).
If anyone has any suggestions let me know. I have 400+ members and don't want to start over.
MySQL Screenshot

A: I guess since no one answered, I'll give the way I fixed it:
SET GLOBAL sql_mode = 'NO_ENGINE_SUBSTITUTION'
Run that command under the varibles tab in phpmyadmin to fix thwe issue.
Hope this helps you!!!


text:
Q: Tags
A: If you put the <script>-tag in before, you need to encode it, so that the browser does not parse the content
So - use htmlspecialchars():
<form action="/savepage" method="POST">
   <button type="submit">Save</button>
    <fieldset>
            <textarea name="content">
<?php echo(htmlspecialchars('
              Some <b>text</b>
              <script src="script_source" type="text/javascript"></script>'); ?>
            </textarea>
    </fieldset>
</form>

A: Because that is being parsed as HTML script tag instead of being treated as text. Use html-entities for parsing it as text.
So, it'll be:
<script src="script_source" type="text/javascript"></script>


text:
Q: How can I create panelAccordion in ORACLE MAF? panelAccordion component was supported in ADF Mobile but not in ORACLE MAF. Is it possible to achieve this feature in MAF?

A: Accordion are not common in mobile apps since they consume too much space for the areas they don't show- you usually use a different approach to showing different data on the same area - in MAF you can use the card component to achieve this.
Use a toolbar to control what card is being shown.


text:
Q: Error 'Iterator cannot contain return statement ' when calling a method that returns using a yield I'm hoping there's a nicer way to write this method & overloads with less code duplication. I want to return a sequence of deltas between items in a list. this method:-
    public static IEnumerable<decimal> CalculateDeltas(this IEnumerable<decimal> sequence)
    {
        decimal prev = default(decimal);
        foreach (var item in sequence)
        {
            var current = item;
            decimal diff = current - prev;
            prev = item;
            yield return diff;
        }
    }

works just fine.
I then thought about an overload which would allow an absolute delta, but would call the original method if absolute wasn't required:-
    public static IEnumerable<decimal> CalculateDeltas(this IEnumerable<decimal> sequence,bool absolute)
    {
        if (absolute)
        {
            decimal prev = default(decimal);
            foreach (var item in sequence)
            {
                var current = item;
                decimal diff = Math.Abs(current - prev);
                prev = item;
                yield return diff;
            }
        }
        else
        {
            return CalculateDeltas(sequence);
        }
    }

but this doesn't compile because of Error

"Cannot return a value from an iterator. Use the yield return
  statement to return a value, or yield break to end the iteration."

I've had a look at this post and it seems like I won't be able to do anything other than repeating the code from the original method:-
    public static IEnumerable<decimal> CalculateDeltas(this IEnumerable<decimal> sequence,bool absolute)
    {
        if (absolute)
        {
            decimal prev = default(decimal);
            foreach (var item in sequence)
            {
                var current = item;
                decimal diff = Math.Abs(current - prev);
                prev = item;
                yield return diff;
            }
        }
        else
        {
            decimal prev = default(decimal);
            foreach (var item in sequence)
            {
                var current = item;
                decimal diff = current - prev;
                prev = item;
                yield return diff;
            }
        }
    }

Can anyone suggest a better way of doing this?

A: The simplest approach is probably to split the method into two, one of which is implemented via an iterator block and one of which isn't:
public static IEnumerable<decimal> CalculateDeltas(this IEnumerable<decimal> sequence,
                                                   bool absolute)
{
    return absolute ? CalculateAbsoluteDeltas(sequence)
                    : CalculateDeltas(sequence);
}

private static IEnumerable<decimal> CalculateAbsoluteDeltas
    (IEnumerable<decimal> sequence)
{
    decimal prev = default(decimal);
    foreach (var item in sequence)
    {
        var current = item;
        decimal diff = Math.Abs(current - prev);
        prev = item;
        yield return diff;
    }
}

This split approach also allows you to eagerly validate sequence, e.g.
if (sequence == null) {
    throw new ArgumentNullException("sequence");
}

... in the non-iterator block method.

A: A single method cannot both yield return and return. You must choose one or the other.
You can either do a foreach to yield return the list:
else
{
    foreach (var item in CalculateDeltas(sequence))
        yield return item;
}

Or separate your code into two methods:
if (absolute)
    return CalculateAbsoluteDeltas(sequence);
else
    return CalculateDeltas(sequence);


text:
Q: rails invalid date issue I have a basic reservation form using rails 5.0.1 that is not working, I am getting an ArgumentError (invalid date) error upon submit. The form takes a start and end date and submits to a reservation table for the booking.
The logs show this:
Started GET "/preview?start_date=Wed+May+03+2017+00%3A00%3A00+GMT-0400+(EDT)&end_date=&post_id=3" for ::1 at 2017-04-19 21:47:37 -0400
Processing by ReservationsController#preview as */*
  Parameters: {"start_date"=>"Wed May 03 2017 00:00:00 GMT-0400 (EDT)", "end_date"=>"", "post_id"=>"3"}
  User Load (0.7ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 4 ORDER BY `users`.`id` ASC LIMIT 1
Completed 500 Internal Server Error in 56ms (ActiveRecord: 0.7ms)

ArgumentError (invalid date):

app/controllers/reservations_controller.rb:14:in `parse'
app/controllers/reservations_controller.rb:14:in `preview'

Controller:
class ReservationsController < ApplicationController
    before_action :authenticate_user!, except: [:notify]

    def preload
        post = Post.find(params[:post_id])
        today = Date.today
        reservations = post.reservations.where("start_date >= ? OR end_date >= ?", today, today)
        render json: reservations
    end

    def preview
        start_date = Date.parse(params[:start_date])
        end_date = Date.parse(params[:end_date])

        output = {
            conflict: is_conflict(start_date, end_date)
        }
        render json: output
    end

    def create
      @reservation = current_user.reservations.create(reservation_params)

      if @reservation
        # send request to paypal
          values = {
              business: 'test@test.com',
              cmd: '_xclick',
              upload: 1,
              notify_url: 'http://xyz.ngrok.io/notify',
              amount: @reservation.total,
              item_name: @reservation.post.tool_name,
              item_number: @reservation.id,
              quantity: '1',
              return: 'http://xyz.ngrok.io/your_rentals'
            }
            redirect_to "https://www.sandbox.paypal.com/cgi-bin/webscr?" + values.to_query
        else
            redirect_to @reservation.post, alert: "Oops, something went wrong..."
        end
    end

    def notify
      params.permit!
      status = params[:payment_status]
      reservation = Reservation.find(params[:item_number])
      if status == "Completed"
          reservation.update_attributes status: true
      else
          reservation.destroy
      end
      render nothing: true
    end

    def your_rentals
      @rentals = current_user.reservations
    end

    def your_reservations
      @posts = current_user.posts
    end

private

   def reservation_params
      params.require(:reservation).permit(:start_date, :end_date, :price, :total, :post_id)
   end

       def is_conflict(start_date, end_date)
          post = Post.find(params[:post_id])
          check = post.reservations.where("? < start_date AND end_date < ?", start_date, end_date)
          check.size > 0? true : false
       end
end

View:
<%= form_for([@post, @post.reservations.new]) do |f| %>

        $<%= @post.price %>
        Per Day

       Begin Date
       <%= f.text_field :start_date, readonly: 'true', placeholder: 'Start Date', class: 'form-control' %>

       Return Date
       <%= f.text_field :end_date, readonly: 'true', placeholder: 'End Date', class: 'form-control', disabled: true %>

  <%= f.hidden_field :post_id, value: @post.id %>
  <%= f.hidden_field :price, value: @post.price %>
  <%= f.hidden_field :total, id: 'reservation_total' %>

           Day(s)

           Total
           $

  <%= f.submit "Book Now", id: "btn_book", class: "btn btn-primary wide", disabled: 'true' %>
<% end %>

Model:
class Reservation < ApplicationRecord
  belongs_to :user
  belongs_to :post
end

A: You are passing a blank date ("end_date"=>"") in your parameters, check on your log:
Parameters: {"start_date"=>"Wed May 03 2017 00:00:00 GMT-0400 (EDT)", "end_date"=>"", "post_id"=>"3"}

So when you do something like end_date = Date.parse(params[:end_date]) you get an error because you are trying to parse an empty string (or, to be more accurate, an invalid_date; check the docs).
You need to check first if params[:end_date] contain the right date format (or at least, is not blank) before using Date.parse.

A: use on your controller
start_date = Date::strptime(reservation_params[:start_date], "%m/%d/%y")
end_date = Date::strptime(reservation_params[:end_date], "%m/%d/%y")


text:
Q: Get a source file and line of any function using Firebug Some guy points out that Firebug does display the source file and line for event handlers. I have a pseudo-class defined somewhere within 11 script files. Could I use Firebug to find out which file did I put it into? *
It's embarrassing when you write a code and you just can't find it while executing it...
* Pseudo-class is just a function that keeps it's namespace after execution. If I put it very simply...

A: To find the code you can simply use the search field at the top right of Firebug when you are at the Script panel.

Ensure you have checked the option Multiple Files within the search options, then type the name of your "pseudo-class". You can hit Enter multiple times to switch through the matches.
When you found the code, the name of the file is displayed within the panel toolbar. Hover it to get the full URL of the file as tooltip.


text:
Q: Error inserting object with one-to-zero-or-one relation Consider a Course can has a Curriculum or not. So the relation between the Course and Curriculum is 1..0 or 1..1.
The classes are:
public class Course
{
    public int Id {get; set;}
    public Curriculum { get; set; }
}

public class Curriculum
{
    [ForeignKey("Course")]
    public int Id { get; set; }

    public Course Course { get; set; }
}

I configured the relation by fluent api like below:
public class CourseConfiguration : EntityTypeConfiguration<Course>
{
    public CourseConfiguration()
    {
        HasOptional(course => course.Curriculum)
            .WithRequired(cur => cur.Course);
    }
}

unfortunately, when i want to save a course in the Db this error is raised:

Cannot insert explicit value for identity column in table 'Curricula' when IDENTITY_INSERT is set to OFF

Additionally, i added attributes [DatabaseGenerated(DatabaseGeneratedOption.Identity)] or [DatabaseGenerated(DatabaseGeneratedOption.None)] to the primary key of Curriculum class, but it has no effect or creates new exception!
Do you have any idea?

A: I took your code and it worked:
> public class MyContext : DbContext
>     {
>         public DbSet<Curriculum> Curriculum { get; set; }
>         public DbSet<Course> Course { get; set; }
>
>         protected override void OnModelCreating(DbModelBuilder modelBuilder)
>         {
>             base.OnModelCreating(modelBuilder);
>             modelBuilder.Configurations.Add(new CourseConfiguration());
>         }
>     }
>     public class Course
>     {
>         [DatabaseGenerated(DatabaseGeneratedOption.None)]
>         public int Id { get; set; }
>         public Curriculum Curriculum { get; set; }
>     }
>
>     public class CourseConfiguration : EntityTypeConfiguration<Course>
>     {
>         public CourseConfiguration()
>         {
>             HasOptional(course => course.Curriculum)
>                 .WithRequired(cur => cur.Course);
>         }
>     }
>     public class Curriculum
>     {
>         [ForeignKey("Course")]
>         public int Id { get; set; }
>
>         public Course Course { get; set; }
>     }

However, in your case, since the the table was first created with identity set to true, EF wouldn't change it for you. If you had had the following attribute on the Id property of Course in your first migration, the problem wouldn't have occured:

[DatabaseGenerated(DatabaseGeneratedOption.None)]

In order to fix your problem, you need to recreate the table Course.
The following link can also help you:
https://stackoverflow.com/a/18917348/2348125


text:
Q: R: how to use the aggregate()-function to sum data from one column if another column has a distinct value? Hei,
I have a problem with the aggregate-function. My data looks like this:
 transect_id    year    day month   LST precipitation
 1  TR001   2010    191 4   30.62083    0.0000
 2  TR001   2010    191 4   30.62083    0.0003
 3  TR001   2010    191 5   30.62083    0.0001
 4  TR001   2010    191 7   30.62083    0.0000
 5  TR001   2010    191 7   30.62083    0.0000
 6  TR001   2011    191 7   30.62083    0.0007

and I want to sum the precipitation for each quartal of each year. Which means: sum precipitation for months 1-3, months 4-6, 7-9 and 10-12 for every year (in my case 2010-2013). And add a column for it.
I figured that I should use the mutate()-function from the plyr-package and then do something like
weather_gam.mutated<-mutate(weather_gam, precipitation.spring=aggregate(precipitation by = list(Category=year)))

but what to do for the months? I simply can't figure it out. I tried stuff like by = list(Category= month==1) but obviously that's not what it takes to succeed here.
So basically I just try to do what SUMIFS(F1:Fx, B1:Bx = "2010", D1:Dx = "1", D1:Dx = "2", D1:Dx = "3" would do in Excel, just I hope that by setting
by = list(Category=year)

It will automatically always sum when the year is the same so I don't need to do it manually for every year.
I really would appreciate any help here, also if you have a completely different idea how to solve it.

A: Here is a solution with dplyr and lubridate; the idea is to use the quarter function of lubridate to find out at which quarter months belong to. Create the Quarter column, group by Quarter and create the Sum or precipitation for each group.
library(lubridate)
library(dplyr)
df$month <- month(df$month)
df %>% mutate(Quarter = quarter(month)) %>% group_by(Quarter) %>% mutate(SumPre = sum(precipitation))

Source: local data frame [6 x 8]
Groups: Quarter

  transect_id year day month      LST precipitation Quarter SumPre
1       TR001 2010 191     4 30.62083         0e+00       2  4e-04
2       TR001 2010 191     4 30.62083         3e-04       2  4e-04
3       TR001 2010 191     5 30.62083         1e-04       2  4e-04
4       TR001 2010 191     7 30.62083         0e+00       3  7e-04
5       TR001 2010 191     7 30.62083         0e+00       3  7e-04
6       TR001 2011 191     7 30.62083         7e-04       3  7e-04

and here another approach with aggregate
library(lubridate)
df$month <- month(df$month)
df$Quarter <- quarter(df$month)
aggregate(precipitation ~ Quarter, data = df, sum)
Quarter precipitation
1       2         4e-04
2       3         7e-04

data
df <- structure(list(transect_id = structure(c(1L, 1L, 1L, 1L, 1L,
1L), .Label = "TR001", class = "factor"), year = c(2010L, 2010L,
2010L, 2010L, 2010L, 2011L), day = c(191L, 191L, 191L, 191L,
191L, 191L), month = c(4L, 4L, 5L, 7L, 7L, 7L), LST = c(30.62083,
30.62083, 30.62083, 30.62083, 30.62083, 30.62083), precipitation = c(0,
3e-04, 1e-04, 0, 0, 7e-04)), .Names = c("transect_id", "year",
"day", "month", "LST", "precipitation"), row.names = c("1", "2",
"3", "4", "5", "6"), class = "data.frame")

A: use dplyr instead of plyr:
library(dplyr)

d.in %>%
    mutate(q=cut(month, c(0,3,6,9,12), labels=c("q1", "q2", "q3", "q4"))) %>%
    group_by(year, q) %>%
    mutate(sum.prec = sum(precipitation))


text:
Q: Local native Node module causes error: Uncaught Error: No native build was found for platform=win32 arch=x64 runtime=electron abi=75 uv=1 libc=glibc I have a native Node addon I wrote that I'm trying to add to an Electron app. I use npm install /path/to/addon to install the addon. Then electron-rebuild and electron-build, which don't complain.
But when I run npm start, in the dev console I get the following error:
Uncaught Error: No native build was found for platform=win32 arch=x64 runtime=electron abi=75 uv=1 libc=glibc
    at Function.load.path (C:\path\to\node_modules\node-gyp-build\index.js:55:9)
    at load (C:\path\to\node_modules\node-gyp-build\index.js:20:30)
    at Object.<anonymous> (C:\path\to\index.js:2:42)
    at Object.<anonymous> (C:\path\to\index.js:27:3)
    at Module._compile (internal/modules/cjs/loader.js:880:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:892:10)
    at Module.load (internal/modules/cjs/loader.js:735:32)
    at Module._load (internal/modules/cjs/loader.js:648:12)
    at Module._load (electron/js2c/asar.js:717:26)
    at Function.Module._load (electron/js2c/asar.js:717:26)

I can't find much online regarding this error. I've tried recompiling everything, tried rebuilding the addon with Electron as target and nothing helps. Why does this error happen, and how can I remedy it?

A: The error was with a silly one.
In index.js, I was doing
let addon= require("node-gyp-build")("./");
Essentially, "./" will not link correctly when installed with npm since ./ is the root directory of the current project not the installed. Using __dirname instead will properly link the addon
let addon= require("node-gyp-build")(__dirname);
Note: I also switched to using prebuildify which means I no longer have to run npm electron-builder


text:
Q: Load Runner VU Gen fails to record HTTP When I attempt to record Web (HTTP/HTML) scripts in HP VUGen the browser "Stops Working" and the action recorded is empty. Recording Web (Click and Script) scripts works fine - but is unsuitable for the application I am testing.
My setup:

*

*HP Virtual User Generator 9.50.0.0 (Build 3210)

*Windows 7 on a corporate network

*Internet Explorer 8

*Chrome 15

When I click the "Start Record" button in VU Gen and confirm fill in the details the browser launches but immediately I get a process error:

Internet Explorer has stopped working
A problem caused the program to stop working correctly. Please close
  the program.
[Close the program] [Debug the program]

Dismissing the error doesn't actually kill the browser and so I can navigate my application and submit requests, etc. However when I stop recording no steps have been recorded and I am left with a blank action:
Action()
{
    return 0;
}

Every now and again the process dialog does not "crash" until I close the browser, but it still fails to record.
I have subsequently tried configuring Chrome as my browser in the hope that this would solve this problem however it suffers from identical symptoms.
A quick peek in my event log shows that for each browser I get the following event log errors:
IE

Faulting application name: iexplore.exe, version: 8.0.7601.17514, time
  stamp: 0x4ce79912 Faulting module name: bbhook.dll_unloaded, version:
  0.0.0.0, time stamp: 0x496e148e Exception code: 0xc0000005 Fault offset: 0x41fa6c0e Faulting process id: 0x15ac Faulting application
  start time: 0x01ccadc25da25278 Faulting application path: C:\Program
  Files (x86)\Internet Explorer\iexplore.exe Faulting module path:
  bbhook.dll Report Id: 9f6bdfa8-19b5-11e1-be8f-b8ac6f2deb5b

Chrome

Faulting application name: chrome.exe, version: 15.0.874.106, time
  stamp: 0x4ea7969e Faulting module name: bbhook.dll_unloaded, version:
  0.0.0.0, time stamp: 0x496e148e Exception code: 0xc0000005 Fault offset: 0x41fa6c0e Faulting process id: 0x1464 Faulting application
  start time: 0x01ccadc15ed87df8 Faulting application path:
  C:\Users\me\AppData\Local\Google\Chrome\Application\chrome.exe
  Faulting module path: bbhook.dll Report Id:
  9cb19ee8-19b4-11e1-be8f-b8ac6f2deb5b

Would anyone know how to resolve this?

A: The answer is actually quite simple:
VU Gen 11.x officially supports IE8.
VU Gen 9.50 does not officially support IE8 and definitely doesn't support Chrome.
Some users have reported a work around but they do not seem to work for me either.
Conflicting information on the internet suggests that patching software to VU Gen 9.52 is also a solution I could not test this because I could not find a download for this patch.
VU Gen 11.x officially supports IE8.

A: Installing v9.52 with all patches and the IE8 patch should make it work, BUT only under Windows XP. Under Win7 there is much discussion and dispute about this.
I know for a fact that I got it working, but I do not know WHY or HOW. Read more here.
I also suggest you move on to v11 that works under Win7 and supports all IE versions.
As for the failure it is partly related to the BHO installed under IE. This BHO does not work right with new IE versions. The whole of VuGen works badly under Win7 because it was not designed to work there.

A: You are using LoadRunner in an unsupported environment from both and OS and Browser perspective.   It is not surprising at all that it is not working.   Drop back to your requirements for your tool.   Reconcile your requirements to your environment and then fix one or the other.   If Windows 7 is mandatory then you need to leverage your maintenance agreement and upgrade to LoadRunner 11.


text:
Q: Empty tables are squeezed I am trying to generate tables with random sizes, such as n * n where n can be between 3 to 7. The tables should be reponsive and should fit wholly on any device screen.
Problem:
When the table is generated all the cells are squeezed up and if I add data into the any cell, other cells squeeze up while that particular cell expands.
What I want:
I want all the cells to be responsive and square in shape too. By square I mean when the table is generated, each cell should be width = height. And the table as whole should nicely fit the viewport.
What I did:
I used a bit of JS to make each cell reponsive but on larger screens each cell turned out to be huge, resulting in a huge table, which overflows the height of the viewport.
HTML

                 Back

CSS
html, body {
    height: 100%;
    background-color: #333;
}
.site-wrapper {
     width: 100%;
     height: 100%;
     min-height: 100%;
     -webkit-box-shadow: inset 0 0 100px rgba(0,0,0,.5);
     box-shadow: inset 0 0 100px rgba(0,0,0,.5);
     border-top: 5px solid #5A332B;
     background-color: #ccbb99 !important;
    overflow-y: auto;
 }
.navbar {
    border-radius: 0;
    border: none;
    background-color: #683F36;
}
.navbar-brand {
    cursor: pointer;
    color: #ffffff !important;
    font-family: chalkitup, "sans-serif";
}
.centerMe {
    position: relative;
    top: 50%;
    transform: translateY(-60%);
}
.site-wrapper {
    width: 100%;
    height: 100%;
    min-height: 100%;
    -webkit-box-shadow: inset 0 0 100px rgba(0,0,0,.5);
    box-shadow: inset 0 0 100px rgba(0,0,0,.5);
    border-top: 5px solid #5A332B;
    background-color: #ccbb99 !important;
}
#board, #board td {
    border: none;
}
#board td:nth-child(2n + 1) {
    border-left: 1px solid black;
    border-right: 1px solid black;
}
#board td:first-child {
    border-left: none;
}
#board td:last-child {
    border-right: none;
}
#board tr {
    border-top: 1px solid black;
    border-bottom: 1px solid black;
}
#board tr:first-child {
    border-top: none;
}
#board tr:last-child {
    border-bottom: none;
}

@media (min-width: 768px) {
    #board {
        margin: 0 auto;
        width: 70%;
    }
}

NOTE: I am using twitter-bootstrap 3.

A: You want the table cells to be square and there are only three cells in each row. The width of each row is assigned to the height. It will obviously create huge boxes. If square boxes are not necessary, then you can set the height of the boxes manually so they do not look too big.


text:
Q: Send Inputs information to another html page with javaScript good Evening friends, i'm trying to make a simple javaScript code that send the inputs information to another html page, and its not working for me.
i've 2 pages
page1.html that contains the inputs :

<link href="smi.css" rel="stylesheet"  type="text/css">

<form action="page2.html" method="post">

Tape your firstname: <input type="text" name="nom">

Tape your lastname: <input type="text" name="prenom">

<button type="submit">gènèrer</button>

</form>

and the page2.html :

<link href="smi.css" rel="stylesheet"  type="text/css">

this is my script :
var x = getUrlVars()["nom"];
var y = getUrlVars()["prenom"];
var w = getUrlVars()["Tel"];

var z = "bonjour " +x+" "+y+"votre Tel est : " +w;
document.getElementById("zone").innerText() = z;

function getUrlVars(){

var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(m,key,value){
vars[key] = value;
});
return vars;
}

i hope if u can help me plz.

A: What @teemu said about using server side code, but you can also do something like this while learning basic HTML:
Add a page1.js with something like this:
function submit(){
   let fName = //get first name;
   let lName = //get last name
   location.href(`page2.html/fName=${fName}&lName=${lName}`);
}

Then call this function from the onsubmit button:
<button onClick="submit();">gènèrer</button>