text:
Q: Nulls in rows with three common value, fourth varies with one match My fist table TEMP1 has codes noting period when status starts.
+PRSNID | LVL2  |  LOC   |   initialQTRYR | STAT_IMPRT_VAR

*a      |  AA   |  CHI   |    0118        |     z

*b      |  AA   |  CHI   |    0318        |     z

*b      |  AA   |  LOS   |    0119        |     y

*c      |  AA   |  LOS   |    0119        |     z

*d      |  BB   |  CHI   |    0118        |     y

row count: 100
My second table TEMP2 has a column with codes from all periods EMPLID is present.
+PRSNID | LVL2  |  LOC  |    validQTRYR

*a      |  AA   |  CHI  |      0118

*a      |  AA   |  CHI  |      0218

*a      |  AA   |  CHI  |      0318

*b      |  AA   |  CHI  |      0318

*b      |  AA   |  CHI  |      0418

*b      |  AA   |  LOS  |      0119

*b      |  AA   |  LOS  |      0219

*c      |  AA   |  LOS  |      0119

*c      |  AA   |  LOS  |      0219

*d      |  BB   |  CHI  |      0118

*d      |  BB   |  CHI  |      0218

*d      |  BB   |  CHI  |      0318

row count: 500
I'm left outer joining the two tables TEMP2 to TEMP1 and pulling back values joining on EMPLID, LVL2, LOC, QTRYR (required join condition).  I'm getting nulls when the STAT_IMPRT_VAR is not there in TEMP2 joined with TEMP1.
I need the row count to match TEMP2.
+PRSNID | LVL2  |  LOC   |   drvdQTRYR | STAT_IMPRT_VAR

*a      |  AA   |  CHI   |    0118     |   z

*a      |  AA   |  CHI   |    0218     |  <null>

*a      |  AA   |  CHI   |    0318     |  <null>

*b      |  AA   |  CHI   |    0318     |   z

*b      |  AA   |  CHI   |    0418     |  <null>

*b      |  AA   |  LOS   |    0119     |   y

*b      |  AA   |  LOS   |    0219     |  <null>

*c      |  AA   |  LOS   |    0119     |   z

*c      |  AA   |  LOS   |    0219     |  <null>

*d      |  BB   |  CHI   |    0118     |   y

*d      |  BB   |  CHI   |    0218     |  <null>

*d      |  BB   |  CHI   |    0318     |  <null>

row count: 500
I need the table to actually look like this
+PRSNID |  LVL2 |   LOC  |    drvdQTRYR | STAT_IMPRT_VAR

*a      |  AA   |  CHI   |    0118      |   z

*a      |  AA   |  CHI   |    0218      |   z

*a      |  AA   |  CHI   |    0318      |   z

*b      |  AA   |  CHI   |    0318      |   z

*b      |  AA   |  CHI   |    0418      |   z

*b      |  AA   |  LOS   |    0119      |   y

*b      |  AA   |  LOS   |    0219      |   y

*c      |  AA   |  LOS   |    0119      |   z

*c      |  AA   |  LOS   |    0219      |   z

*d      |  BB   |  CHI   |    0118      |   y

*d      |  BB   |  CHI   |    0218      |   y

*d      |  BB   |  CHI   |    0318      |   y

row count: 500
The validQTRYR less than the status that changes in TEMP1 should keep the sames status from initialQTRYR.  Any help would be appreciated.
I've built several temp table and tried to inner join to get the STAT_IMPRT_VAR.
SELECT e.PRSNID,
e.LVL2
e.LOC
CASE a.initialQTRYR
 WHEN e.validQTRYR  THEN a.initialQTRYR
 ELSE e.validQTRYR
END drvdQTRYR,
e.STRM,
a.STAT_IMPRT_VAR
FROM TEMP2 e
LEFT OUTER JOIN TEMP1 a
ON e.PRSNID= a.PRSNID
AND e.LOC = a.LOC
AND e.LVL2    = a.LVL2
AND e.validQTRYR  = a.initialQTRYR

I need the table to actually look like this
+PRSNID |  LVL2 |   LOC  |    drvdQTRYR | STAT_IMPRT_VAR

*a      |  AA   |  CHI   |    0118      |   z

*a      |  AA   |  CHI   |    0218      |   z

*a      |  AA   |  CHI   |    0318      |   z

*b      |  AA   |  CHI   |    0318      |   z

*b      |  AA   |  CHI   |    0418      |   z

*b      |  AA   |  LOS   |    0119      |   y

*b      |  AA   |  LOS   |    0219      |   y

*c      |  AA   |  LOS   |    0119      |   z

*c      |  AA   |  LOS   |    0219      |   z

*d      |  BB   |  CHI   |    0118      |   y

*d      |  BB   |  CHI   |    0218      |   y

*d      |  BB   |  CHI   |    0318      |   y

Null values is the problem when there's not a match and when the status changes with an update in TEMP1 from z to y.

A: You can try the following query where we have derived one column sum_rn for further grouping.
With your_query as
(SELECT e.PRSNID,
        e.LVL2,
        e.LOC,
        CASE a.initialQTRYR
        WHEN e.validQTRYR  THEN a.initialQTRYR
        ELSE e.validQTRYR
        END drvdQTRYR,
        e.STRM,
        a.STAT_IMPRT_VAR
        FROM TEMP2 e
        LEFT OUTER JOIN TEMP1 a
        ON e.PRSNID= a.PRSNID
        AND e.LOC = a.LOC
        AND e.LVL2    = a.LVL2
        AND e.validQTRYR  = a.initialQTRYR)

select prsn_id,
       lvl2,
       loc,
       drvdqtryr,
       Strm,
       max(STAT_IMPRT_VAR)
       over (partition by prsn_id, sum_rn order by null) as STAT_IMPRT_VAR
       from
      (select t.prsn_id,
              t.lvl2,
              t.loc,
              t.drvdQTRYR,
              t.STRM,
              t.STAT_IMPRT_VAR,
              Sum(case when t.STAT_IMPRT_VAR is not null then 1 end)
              over (partition by t.prsn_id order by to_date(drvdqtryr,'mmyy')) as sum_rn
        From your_query)

Cheers!!

A: You can use FIRST_VALUE() OVER (...) analytic function :
SELECT e.PRSNID,
       e.LVL2,
       e.LOC,
       CASE a.initialQTRYR
           WHEN e.validQTRYR  THEN a.initialQTRYR
           ELSE e.validQTRYR
       END drvdQTRYR,
     --e.STRM,
       FIRST_VALUE(a.STAT_IMPRT_VAR) OVER
                               (PARTITION BY e.PRSNID ,e.LOC ORDER BY e.PRSNID,e.LOC DESC)
       AS STAT_IMPRT_VAR
  FROM TEMP2 e
  LEFT JOIN TEMP1 a
    ON e.PRSNID = a.PRSNID
   AND e.LOC = a.LOC
   AND e.LVL2 = a.LVL2
   AND e.validQTRYR = a.initialQTRYR;

Changing steps for a.STAT_IMPRT_VAR column should be grouped by e.PRSNID and e.LOC columns through PARTITION BY clause(PARTITION BY e.PRSNID ,e.LOC).
Demo


text:
Q: Подсчитать число столбцов матрицы, в которых есть неотрицательные элементы Здравия! Нужно найти число столбцов в матрице, в которых есть неотрицательные элементы(хотя бы одно число>0). Удалось написать программу, которая считает число строчек в которых есть неотрицательные элементы. Очень прошу помочь.
`
for (int i{}; i<real_rows; i++)
{
for (int j{}; j < real_columns; j++)
 {
if (arr[i][j]>=0)
     {
     k++;
     break;
      }
  }
}`

A: k = 0;
for (int j = 0; j < real_columns; j++)
{
  for (int i = 0; i < real_rows; i++)
  {
    if (arr[i][j] >= 0)
    {
      k++;
      break;
    }
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: First div always on left, the remaining on right - positioning with css I'm try to archieve the following:

with this code:

        asdasd

        asdasd

And the following CSS:
.box {
    width: 45%;
    background-color: green;
    border: 1px solid red;
    float: left;
}

.auto-height {
    height: 50%;
}

The boxes will be looped and the first one is always bigger then the others. So I basically want the first one to be always on left, and the remaining ones to go on right.
I tried http://jsfiddle.net/59bwh/ but I can't get the height: 50% working.
Tho, the boxes on the right might be more then 2 (up to 5).
PP: sorry for the title (I searched that on google, couldn't find anything, someone like me might search the same, so I wrote this as title). I will edit it if you got any suggestions.

A: You have to use absolute positioning.
.wrap {
    position: relative;
}
.box {
    width: 45%;
    background-color: green;
    border: 1px solid red;
/*    float: left; */
}
.fixd {
    position: absolute;
    left: 50%;
    top: 0;
    bottom: 50%;
}
.fixd + .fixd {
    top: 50%;
    bottom: 0;
}

Working Fiddle.
Important is definition of property position: relative; for parent element. First element defines height of the parent. Second and third element are positioned absolutely inside then parent. You can define height of elements by top and bottom properties.
If number of right side elements is not fixed you have to compute size by JavaScript.
The simplest JavaScript should be something like this:
$('.fixd').css('height', $('.fixd').parent().innerHeight() / $('.fixd').size());

In real app you have to do some correction (paddings, margins, borders). Then script for your fiddle should be something like this
var height = $('.fixd').parent().innerHeight(),
    count = $('.fixd').size(),
    boxSize = 0;

// Correction of borders and margin-top size
height = height - count * 2 - (count-1) * 10;
boxSize = Math.floor(height/count);

// set computed size
$('.fixd').css('height', boxSize)
   .first().css('margin-top', 0);

// fix last element (it is because of rounding floating numbers)
$('.fixd').last().css('height', height-(count-1)*boxSize);

Complete fiddle is here

A: I know this doesn't answer your question per say, but this could be very useful for you.
http://css-tricks.com/rotating-feature-boxes/
If you don't want to use a plugin, try this...

and the css:
#container{
width:100%;
margin:auto;
display:block;
height:100%;
}

.left{
width:50%;
height:100%;
padding:10px;
float:left;
}

.right{
width:50%;
height:100%;
padding:10px;
float:left;
}

.box-auto-height{
width:100%;
height:50%;
}

div img{
max-width:100%;
height:auto;
}
}

A: You asked about using a table in the comments...
http://jsfiddle.net/59bwh/12/

    Cell 1
    Cell 2

    Cell 3

A: Fixed your fiddle:
http://jsfiddle.net/59bwh/9/
.box {
    width: 50%;
    background-color: green;
    border: 1px solid red;
    box-sizing: border-box;
}

.fixd1 {
    position:absolute;
    top:0;
    right:0;
    bottom:50%;
}
.fixd2 {
    position:absolute;
    top:50%;
    right:0;
    bottom:0;
}

        asdasd

        asdasd

A: 50% height is derived from the parent, not sibling.

   your boxes goes here

then the CSS would be
.wrapper { height: 300px }
.box { height: 100% }
.auto-height { height: 50% }


text:
Q: External Style Sheet not working I'm working on a project for school (we have to code for a calculator), and we're using external CSS for the first time. I've been trying for an hour, but I guess my external CSS isn't linking properly? The calculator just shows up without any styling at all.
<!DOCTYPE html>

    <title>My Crazy Calc</title>
    <link rel="stylesheet" type="text/css" href="/style.css">

My Crazy Calculator

<form name="calc">

    <input class="textfield" type="text" name="input" >

    <input type="reset" value="clear" onclick="calc.input.value+='reset'">
    <input type="button" value="M" onclick="calc.store.value=calc.input.value;calc.input.value=''">
    <input type="button" value="MR" onclick="calc.input.value+=calc.store.value">
    <input type="button" value="/" onclick="calc.input.value+='/'">

    <input type="button" value="7" onclick="calc.input.value+='7'">

    <input type="button" value="8" onclick="calc.input.value+='8'">

    <input type="button" value="9" onclick="calc.input.value+='9'">

    <input type="button" value="*" onclick="calc.input.value+='*'">

    <input type="button" value="4" onclick="calc.input.value+='4'">

    <input type="button" value="5" onclick="calc.input.value+='5'">

    <input type="button" value="6" onclick="calc.input.value+='6'">

    <input type="button" value="-" onclick="calc.input.value+='-'">

    <input type="button" value="1" onclick="calc.input.value+='1'">
    <input type="button" value="2" onclick="calc.input.value+='2'">
    <input type="button" value="3" onclick="calc.input.value+='3'">
    <input type="button" value="+" onclick="calc.input.value+='+'">

    <input  type="button" value="0" onclick="calc.input.value+='0'">
    <input type="button" value="=" onclick="calc.input.value=eval(calc.input.value)">

    <input type="button" value="." onclick="calc.input.value+='.'">
    <input type="button" value="sin" onclick="calc.input.value=Math.sin(calc.input.value*Math.PI/180)">
    <input type="button" value="cos" onclick="calc.input.value=Math.cos(calc.input.value*Math.PI/180)">
    <input type="button" value="tan" onclick="calc.input.value=Math.tan(calc.input.value*Math.PI/180)">

    <input type="button" value="|x|" onclick="calc.input.value=Math.abs(calc.input.value)">
    <input type="button" value="log(x)" onclick="calc.input.value=Math.log(calc.input.value)">
    <input type="button" value="sqrt(x)" onclick="calc.input.value=Math.sqrt(calc.input.value)">
    <input type="button" value="e^x" onclick="calc.input.value=Math.exp(calc.input.value)">
    <input type="hidden" name="store">

</form>

The style sheet:
  body {
       background-color: black;
        }

    h1 {
       color:white;
       text-align:center;
       font-family:calibri;
     }

   table{
       margin-left:auto;
       margin-right:auto;
       border:3px solid blue;
       border-radius:25px;
     }

A: *

*if the style sheet file is in same folder, add a forward slash:
<link rel="stylesheet" type="text/css" href="/calcstyle.css">

*the file name is usually case sensitive, so ensure you are using the exact same name. Also check for spaces in your code or file name.

A: I think it has something to do with what kind of platform you're using.
When I was using "wampserver" and PHP, I did it your way and of course it worked.
But now I'm using Visual Studio Code. I tried the same way, but it didn't work at all. The following is my link within the :
       <link rel="stylesheet" href="/css/shop.css">

Here my shop.css file is in the "css" folder, which in turn is in the "public" folder. No matter what I did, it just didn't work.
Then I learned that I had to set the path in my app.js file in the following way:
       app.use(express.static(path.join(__dirname, 'public')));

I'm not sure what kind of platform you're using, but I'm afraid that your problem is similar to mine.
This is just a reminder.
Hope it can be of any help.

A: I incorrectly pointed out that the unclosed link element might be the issue.
<!DOCTYPE html>

        <title>My Crazy Calc</title>
        <link rel="stylesheet" type="text/css" href="calcstyle.css"/>


text:
Q: AVD MANAGER NO SE ACTIVA Tengo diferentes apk para probar con el emulador de Android Studio.
no importa que proyecto abra,no se activa el emulador.

intente abrir desde device manager y generar el avd y desde ahi si puedo abrirlo pero no me dejar arrastrar el apk, me aprece el siguiente icono.
¿Saben como puedo activarlo o correr su funcionamiento correcto? Utilizo la ultima versión de android.
`


text:
Q: javascript in jsf/icefaces I have file with jspx extension i write javascript like
function isNumber(inputId){

            var value = document.getElementById('mainForm:'+ inputId).value;
            var  s = value.length;

            while(s >= 0){
                var c = value.charAt(s);
                if(c > "9"){
                    alert("Value must be digit");
                    document.getElementById('mainForm:'+ inputId).value = "";
                    document.getElementById('mainForm:'+ inputId).focus();
                    return false;
                }
                s --;
            }
            return true;
        }

that work perfect but when i check if condition like  if(c > "9" || c < "0") it will gives error like
com.sun.facelets.FaceletException: Error Parsing /WEB-INF/includes/templates/cc-classic-template.jspx: Error Traced[line: 386] The content of elements must consist of well-formed character data or markup.

After long observation i found that <(less than) sign will create problem.
Is JSF not support < sign ?

A: As explained by Matt Handy, you could not use the < or > sign in your JSPX, as this is a XML format. You have three solutions regarding your problem:

*

*Escape by using < or >.

*Use <![CDATA[ ... ]]> to hold your JavaScript code in your page.

*Set your JavaScript code in a separate .js file, and load it in your JSPX page.

A: Enclose your Javascript in CDATA Sections:
<script language="javascript" type="text/javascript">
/* <![CDATA[ */

    function isNumber(inputId){

            var value = document.getElementById('mainForm:'+ inputId).value;
            var  s = value.length;

            while(s >= 0){
                var c = value.charAt(s);
                if(c > "9"){
                    alert("Value must be digit");
                    document.getElementById('mainForm:'+ inputId).value = "";
                    document.getElementById('mainForm:'+ inputId).focus();
                    return false;
                }
                s --;
            }
            return true;
        }

        //Code containing "<" also comes in this section

/* ]]> */
</script>

A: Besides the escaping and CDATA answers:
If you want to check if a value is a number, there is a javascript built-in function for that: isNaN
Here is an example:
if (isNaN(document.getElementById('mainForm:'+ inputId).value))
  {
    alert("Please enter digits");
    document.getElementById(obj).focus();
    document.getElementById(obj).select();
    return false;
  }


text:
Q: Using improbable premise(s) to reach a conclusion Is there a name for a fallacy that involves using an improbable premise or premises to reach a desired conclusion? For example saying (exaggerated to better convey what is meant): "You should always have a truckload of provisions at home even in the spring because you never know, it might snow heavily at any time during the year and trap you in your home." I know I can always say the speaker is being paranoid or just ridiculous, but I am looking for a more polite and formal word, preferably the name of the logical fallacy involved.

A: Specious is an adjective which could describe a seemingly well-reasoned, even plausible, but still fallacious argument.
It means having an attractive appearance which can deceive.
I found it while looking up non sequitur, which is Latin for "it does not follow".

A: What about "begging the question", which means the question is assuming its own conclusion?  Like saying to buy provisions so someone won't be worried about being trapped by snow unprepared at any time of the year - and as for why one should be worried about being hit by a snowstorm at any time of year, because it is natural to worry if someone isn't prepared (by buying provisions).
It's a kind of circular logic, and there's probably better examples out there, but it boils down to "the answer is X, because Y.  why assume Y?  Because then the answer is X".
Maybe there's a better fit, but this is what I thought of first.


text:
Q: CSS or Table 'Dock Layout' Solution for Non Scrolling Header? I have a variable height header that doesn't scroll with the content below it. The content will act like a regular web page, with overflow=auto, constrained to the size of the viewport.
I have yet to find a table-free CSS solution, and using tables overflow doesn't work correctly - the bottom table row is not constrained to the viewport height - header height.
This seems a rather simple and common problem. Has anyone come up with a working solution? I am able to ignore IE < 8, if that helps.

A: Since you're not supporting IE6, you can set the header to position: fixed to prevent it from scrolling with the document.
Note that the scrollbar will still extend to the top of the header, so you should add padding to the top of your content so that when it's scrolled to the top, it doesn't end up behind the header.


text:
Q: TypeORM not returning all records I am developing a web page with node.js + Sveltekit + TypeORM + Oracle.
When I ran a query with TypeORM's find method that resulted in 847 rows, only 10 were retrieved.
When I run the SQL displayed in the log in Oracle SQL Developer, I get 847 records.
I did not specify the take or skip options for the find method.
When I get the count with findAndCount, it comes out as 847, so it seems that pagination is being done arbitrarily.
How can I get all rows?


text:
Q: How to refresh a materialized view as soon as the day gets over in postgres I'm working on a project which requires me to write a query to create a materialized view in postgres. My requirement is that the materialized view must refresh itself periodically everyday only at 12am. Though I found some information that may be relevant on other places in the web, I wasn't so sure to modify and implement, as it may result to be too costly for me plus i'm not too experienced in sql.

A: As the documentation states:
https://www.postgresql.org/docs/current/sql-creatematerializedview.html

CREATE MATERIALIZED VIEW defines a materialized view of a query. The query is executed and used to populate the view at the time the command is issued (unless WITH NO DATA is used) and may be refreshed later using REFRESH MATERIALIZED VIEW.

So in order to refresh a Materialized View you will need:
https://www.postgresql.org/docs/current/sql-refreshmaterializedview.html
REFRESH MATERIALIZED VIEW
In order to to this periodically you will need some kind of cron implementation.
A Postgresql "inhouse" solution could be: https://github.com/citusdata/pg_cron


text:
Q: How to get the best write throughput during a MySQL import with Amazon RDS? tl;dr - How can we get the maximum EBS throughput for a db.r3.2xlarge instance? We're only seeing about half of what it can supposedly do.
Apologies for the long length of this question. We've had quite a lot of back and forth on this, and I want to give as much information as possible.
We have a MySQL database that contains 3 large tables, ~300GB in total. We're looking to move these tables from a server in our office to an AWS RDS instance.
The data itself is not production data. It's used internally only and is more data warehouse kind of stuff, so we don't need to worry about keeping things in sync, etc. As such, we're taking the mysqldump and mysql ... < dump.sql approach.
We're not having issues with the actual import per se, our issue is that it's going slower than we'd expect. We've eliminated obvious factors, i.e. we're importing from an EC2 instance that contains the SQL dumps, bin log is disabled, auto-commit is off, etc, so we'd like to understand why this is.
We initially started with a db.r3.xlarge instance with 500GB of storage and 5000 provisioned IOPS. During the import, we saw write IOPS hovering around the ~2800/s mark, and EBS write throughput hovering ~58MB/s. Network was barely at ~1.3MB/s and CPU was ~13%.
As I come from a developer background, my infrastructure knowledge is OK but limited, so I wanted to understand what was the bottle neck. Based on the numbers I was seeing, I assumed it was disk IO, and after doing some research I believed this page backed up that theory.
The db.r3.xlarge comes with 500Mb/s dedicated EBS throughput, which works out to be 62.5MB/s, matching roughly the number we were seeing. So to get the throughput to increase, we assumed upgrading to the db.r3.2xlarge with its 1000Mb/s dedicated EBS throughput would give us write throughput of ~125MB/s.
This is where the confusion starts. We provisioned a db.r3.2xlarge instance with 800GB of storage and 8000 provisioned IOPS, but only saw an EBS write throughput of ~63MB/s, sometimes hitting ~70MB/s. Write IOPS were now ~3400/s and CPU was ~5%.
Based on this, my only assumption is that disk IO is now not the bottle neck, and something else is throttling the imports. Is this assumption correct, or is there something else going on re: EBS throughput we're not understanding?
We also triggered two separate table imports on two separate MySQL connections, and although the CPU and EBS write throughput, etc, went up, it only went up by a factor of ~5%.
As stated before, the import is happening fine, it just takes a while. We just want to understand why we're seeing the numbers we are seeing.
Thanks for your time.
Edit 1: After doing some more reading, I'm further inclined to believe that our import is being throttled by something. Our queue length never goes above 10 and hovers ~8. From what I've read, this means we're not generating enough IO to fully utilise what we have.


text:
Q: setImmediate() function not being called after process.nextTick() function For this snippet:
const foo = [1, 2];
const bar = ['a', 'b'];

foo.forEach( num => {
  console.log(`setting setImmmediate ${num}`);
  setImmediate(() => {
    console.log(`running setImmediate ${num}`);
    bar.forEach(char => {
      console.log(`setting nextTick ${char}`);
      process.nextTick(() => {
        console.log(`running nextTick ${char}`);
      })
    })
  });
} )

The output is
$ node scratch.js
setting setImmmediate 1
setting setImmmediate 2
running setImmediate 1
setting nextTick a
setting nextTick b
running setImmediate 2
setting nextTick a
setting nextTick b
running nextTick a
running nextTick b
running nextTick a
running nextTick b

From the docs

the nextTickQueue will be processed after the current operation completes, regardless of the current phase of the event loop.

As I understand, process.nextTick() will add to the current event's nextTickQueue, and executed immediately after the current event, no matter what phase the event loop is in.
Shouldn't the output therefor be the following?
setting setImmmediate 1
setting setImmmediate 2
running setImmediate 1
setting nextTick a
setting nextTick b
running nextTick a
running nextTick b
running setImmediate 2
setting nextTick a
setting nextTick b
running nextTick a
running nextTick b

A:
the nextTickQueue will be processed after the current operation completes, regardless of the current phase of the event loop.

I misunderstood the event loop documentation in thinking that "current operation" means the currently processing event, where in actually it means the currently processing phase.
From Danial Khan's What you should know to really understand the Node.js Event Loop/:


text:
Q: Pyspark- Save each dataframe to a single file I am trying to save filtered dataframe back to the same source file.
I wrote below code to transform the content of each file in a directory to separate Dataframe, filter it and save it back to the same file
rdd = sparkSession.sparkContext.wholeTextFiles("/content/sample_data/test_data")
# collect the RDD to a list
list_elements = rdd.collect()
for element in list_elements:
  path, data = element
  df = spark.read.json(spark.sparkContext.parallelize([data]))
  df = df.filter('d != 721')
  df.write.save(path, format="json", mode="overwrite")

I was expecting that it will overwrite the file with the updated data, but it is creating a folder with the file name and creating below structure and part files:

How can I save each updated dataframe back to the same source file(.txt)?
Thanks in Advance.

A: To save it to 1 file use .coalesce(1) or .repartition(1) option before .save(), that will result in the same folder-like structure, but there will be 1 json file inside.
To save it with a "normal" name after saving it you'd need to cut the 1 json file inside, paste and rename it with desired name. You can see code how it could look like for csv files here


text:
Q: Minimisers and critical points of variational integrals In the following we consider $\Omega\subset\mathbb{R}^n\ (n\geq2)$ to be open, bounded and with Lipschitz boundary. Consider the following regular variational integral:
\begin{equation*}
I[u]=\int_{\Omega}f(x, u, Du)\ \mathrm{d}x,
\end{equation*}for all $u$ in the admissible class $W^{1, n}\cap L^{\infty}(\Omega;\mathbb{R}^N)$. Here $N$ is at least $1$, the integral is at least Caratheodory, coercive and $|f(x, z, \zeta)|\leq K|\zeta|^n$ for some $K>0$ and all $(x, z, \zeta)\in\Omega\times\mathbb{R}^N\times\mathbb{R}^{Nn}$.
There are clearly a wide number of problems framed in the above way. I was wondering if there is an example of a variational problem framed in the above way that has a non-constant continuous minimiser, $v$ and a non-constant critical point (not necessarily, but preferably continuous) $u$, that is distinct from $v$. The admissible class can be made smaller if it suits the example. I am looking for explicit examples and not existence theorems.


text:
Q: Inbox showing wrong notification
Possible Duplicate:
Global Inbox Super Collider Thingy showing wrong answer count in notification

I've posted one question on SO today. After a while I saw this:

It says two answers on the question. But I got only one answer on the question. This is the link to the post. Is this a bug?


text:
Q: How to convert parent collection object to child collection object without looping in C#? I have following object structure where B is derived from A and I am getting input as List<A> with lots of records. I want to convert thatList<A> to List<B> with easy steps (without looping). What is the best way to achieve the same.
Note: I don't want to use AutoMapper.
    public class A
    {
        public A() { }
        public virtual string Name
        {
            get;
            set;
        }
    }

    public class B : A
    {
        public B()
            : base()
        {
        }
        private string _name;
        public override string Name
        {
            get
            {
                return _name;
            }
            set
            {
                _name = string.Concat("Hello ", base.Name);
            }
        }

        public string Id
        {
            get { return "101"; }
        }
    }

A: You can do this by declaring constructor for class B from class A
in this way:
public B(A a):base()
{
    this._name = a.Name;
}

And than do this:
var listA = new List<A> { new A { Name = "John" }, new A { Name = "Peter" }, new A { Name = "Julia" } };
List<B> listB = listA.Select(x=> new B(x)).ToList();

A: Based on the comments this is the output, though I still don't really understand the point.
        List<A> thisIsA = new List<A>();

        thisIsA.Add(new B());

        List<B> thisIsB = new List<B>();
        thisIsB.AddRange(thisIsA.Cast<B>());


text:
Q: Proving least squares is a minima Minimizing $ f(\beta) = (Y-X\beta)'(Y-X\beta) $ we take the derivative set it to zero and get $ \beta = (X'X)^{-1}X'Y $ now everywhere I've read they say this is the minima because $ (X'X) $ is positive definite, if its full rank. Now why does that tell us this is a minima? Don't we need to retrieve the hessian matrix or something?

A: The Hessian matrix is $2 X' X$.  But this is taking things slightly backwards.  The idea of the Hessian matrix is to approximate your function in the neighbourhood of the point in question by a quadratic form.  Here you already have a quadratic form to begin with.
One of the characterizations of positive definite is: an $n \times n$ real symmetric matrix $A$ is positive definite if and only if  $v^T A v > 0$ for all  $v \in \mathbb R^n$ except $0$.


text:
Q: Creating Multiple Processes and Communicating with Pipes in C++ I am attempting to create two child processes with a shared parent, the parent must print the output of each of the child processes, It sends a list of numbers to the Child A, child A sorts these numbers, and sends the sorted list to both the parent and child B, child B then finds the median of the list of numbers, and sends it to the parent where it prints both results.
The problem I'm running into is that it executes fine for Child A and prints child A's results, but does not print anything for child b.
#include <string>
#include <vector>
#include <cstdlib>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <bits/stdc++.h>

using namespace std;

int main(int argc, char **argv)
{
    vector<int> numbers;
    vector<int> sortedVector;
    if (argc == 6)
    {
            //Create vector
            numbers.push_back(atoi(argv[1]));
            numbers.push_back(atoi(argv[2]));
            numbers.push_back(atoi(argv[3]));
            numbers.push_back(atoi(argv[4]));
            numbers.push_back(atoi(argv[5]));
    }
    else
    {
        cout << "Error\n";
    }
    int fd[2];
    int fd1[2];

    if (pipe(fd) == -1 || pipe(fd1) == -1)
    {
        std::cout << "Pipe failed.\n";
    }
    int child_a, child_b;
    child_a = fork();

    //Child A process
    if (child_a == 0)
    {
        //Child A code
        sortedVector = numbers;
        sort(sortedVector.begin(), sortedVector.end());
        int array1[5] = { sortedVector.at(0), sortedVector.at(1), sortedVector.at(2), sortedVector.at(3), sortedVector.at(4) };

        //Send to parent
        close(fd[0]);
        write(fd[1], array1, 5*sizeof(int));
        close(fd[1]);

        //Send to B
        close(fd1[0]);
        write(fd1[1], array1, 5*sizeof(int));
        close(fd1[1]);
    }
    else
    {
        child_b = fork();

        if (child_b == 0)
        {

            //Child B code
            cout << "Array from A ";
            //Read from A
            int arrayFromA[5] = { 0, 0, 0, 0, 0 };
            close(fd1[1]);
            read(fd1[0], arrayFromA, 5*sizeof(int));
            close(fd1[0]);

            //Find median
            double median;
            int arraySize = sizeof(arrayFromA) / sizeof(arrayFromA[0]);

            median = (double)(arrayFromA[(arraySize - 1) / 2] + arrayFromA[arraySize / 2]) / 2.0;

            //Send to Parent
            close(fd1[0]);
            write(fd1[1], &median, sizeof(double));
            close(fd1[1]);
        }
        else
        {
            //Parent code
            //Read from Child A
            vector<int> vectorFromChild;
            close(fd[1]);
            int array2[5] = { 0, 0, 0, 0, 0 };
            read(fd[0], array2, 5*sizeof(int));
            close(fd[0]);

            std::cout << "The sorted list: ";
            for (int i = 0; i < 5; i++)
            {
                if (i != 4)
                {
                    std::cout <<  array2[i] << ", ";
                }
                else
                {
                    std::cout << array2[i] << ".";
                }

            }
            std::cout << std::endl;

            //Read from Child B
            double medianOutput;
            close(fd1[1]);
            read(fd1[0], &medianOutput, sizeof(double));
            close(fd1[0]);

            std::cout << "The median of the list is: " << medianOutput << std::endl;
            wait(NULL);
        }
    }
}

It won't even print: "The median of list is: "

A: In Child B code, you close(fd[1]) at line 68, then write to it at line 80: write(fd1[1], &median, sizeof(double));.
UNIX gave us return values for a reason.


text:
Q: Expectation of a function of sorted uniform random variables Let $a,b,c>0$ with $a>b$ and let $X_1,\dots,X_n$ be a collection of independent uniform samples from the unit interval.  Assume that we re-order the samples so that $X_1\leq X_2 \leq \cdots \leq X_n$, and then let $Z_i := X_{i+1}-X_i$ denote the differences between neighbors.  My question is, is there any way to compute the expectation of the sum $$\sum_i\max\{ aZ_i~,~bZ_i+c \}$$?  This seems difficult but not intractably so.

A: Let's throw in $X_0=0$ and $X_{n+1}=1$. Then there are $n+1$ variables $(Z_i)$ lying on the simplex $\{z\in\mathbb R^{n+1}_+\colon z_1+\ldots+z_{n+1}=1\}$. The distribution is uniform. Each $Z_i$ has the same marginal distribution with density $f_Z(z)=(n+1)(1-z)^n$. So your expectation is just $(n+1)\int_0^1 (n+1)\max(az,bz+c)(1-z)^n\,dz$, which is easy to evaluate explicitly.
If you don't like having $Z_1$ and $Z_{n+1}$, the sum is over $n-1$ identically distributed random variables (not independent, but expectation doesn't care), so the pre-factor $n+1$ is replaced with $n-1$.


text:
Q: compare values in arrays and if any values match, increment values in first array I've got this code to check two arrays for any matching values, and if any values do match I ++ everything in array1
I'm wondering if there is a better way to do this, since I feel like this is a lot of looping, and I'll eventually have 5 arrays i need to compare against each other
Any help would be greatly appreciated!
const array1 = [2, 9];

const array2 = [2, 5, 9];

function checkMatch(a, b) {
  for (let i = 0; i < a.length; i++) {
    for (let e = 0; e < b.length; e++) {
      if (a[i] === b[e]) a[i]++;
    }
  }
  return a;
}

console.log(checkMatch(array1, array2))

A: If you know that all arrays are sorted, then you can use the following approach -
CODE -

const array1 = [2, 9];

const array2 = [2, 5, 9];

function checkMatch(a, b) {
  let i = 0,
    j = 0;
  while (i < a.length && j < b.length) {
    if (a[i] === b[j]) {
      a[i]++;
      j++;
    } else if (a[i] < b[j]) {
      i++;
    } else j++;
  }
  return a;
}

console.log(checkMatch(array1, array2))

Explanation -
The above approach will have a time complexity of O(N+M) while your could would have had a time complexity of O(N*M).
In the above function, you are taking advantage of the fact that arrays are sorted. So when a[i] < b[j], you know that you have to increment index i to get a value that can potentially be equal to or greater than b[j]. The same (but in the reverse way) is the case when a[i] > b[j]. So, this approach reduces the overall time-complexity of your code and would increases the overall efficiency.
Hope this helps!

A: You can use includes method to check if all elements of a list (a) exits in all other arrays you need to compare. Then you can update the value in list (a)

function checkMatch(a, b){
    for (let i = 0; i < a.length; i++) {
        if(b.includes(a[i])){
            a[i]++;
        }
    }
  return a;
};

const array1 = [2, 9];
const array2 = [2, 5, 9];

console.log(checkMatch(array1, array2))

A: You can simply make use of map here:

var array1 = [2, 9];
var array2 = [2, 5, 9];

var result = array1.map(n=>(array2.includes(n) ? n++ : n, n));

console.log(result);

A: You could take a Set and map the first array with the value plus the check for this value of the set.

function checkMatch(a, b) {
    var values = new Set(b);
    return a.map(v => v + values.has(v));
}

console.log(checkMatch([2, 9], [2, 5, 9]));


text:
Q: Php get last part of url and remove / Im using an angular script for my site.
I need dynamic titles so I decided to use php to fetch the last part of the url to display for the page title.
This is the code im using. This code is out putting my full url.
<?php

function curPageURL() {
$url = $_SERVER['REQUEST_URI'];
$url_array = explode('/',$link);
$lastPart = array_pop($url);

return $lastPart;
}

echo curPageURL();
?>

The problem is its fetching the whole url.
For example here is my url http://www.istreamradio.ie/category/Music
I need to display just the last part of the url in this case is Music.
Thanks In advance.

A: You can use end() function after exploding the URL . Please try end instead of array_pop.


text:
Q: ASP.NET 4.5 MVC 4 not working on Windows Server 2008 IIS 7 Clearly I'm missing something, I'm unable to deploy a simple ASP.NET MVC 4, .NET 4.5 app on a Windows Small Business Server 2008 on IIS 7.
.NET framework 4.5 is installed.
Should I be supposed to see that version (4.5) on the Application Pool basic settings of the application? At this time, I only have 2.0 and 4.0, since 4.5 is like the 3.5 which only add on top of the 4.0 framework, I guess this is normal.
When I browse the home page, I got the following error:
403 - Forbidden: Access is denied.
You do not have permission to view this directory or page using the credentials that you supplied.
When I request the only controller named Page /page/index I get the 404 not found page. Like the ASP.NET process never get the http request.
I can request a simple HTML page.
The Application Pool is set to .NET 4.0 and Integrated as the Managed pipeline mode.
NETWORK SERVICE has read/write access to the directory.
The app work flawlessly from VS2012 of course.
I'm clueless on what's not right here, and search engine queries are not helping much.
Does anyone would have a hint, that would be extremely appreciated.
Thanks
Edit
The dlls are already on the bin folder like System.Web.Mvc, System.Web.Razor etc.
I created a empty test.aspx page to make sure asp.net worker process was getting the request, and yes the page was OK. So it appears that the MVC routing is not working, though I have ASP.NET MVC 3 web app working fine on that server.
After the .NET 4.5 installation I did a aspnet_regiis -iru in case, that added an aspnet_client folder on the app, but still this does not fix the issue.
Anonymous Authentication is Enable on IIS Authentication section, and Authorization show allow for all users.
ASP.NET MVC 4 is installed, I just did a repair to make sure.
Eventhough the ASP.NET MVC 4 is installed, the 404 error from requesting the /page/index action is returned by the standard IIS and not the standard aspnet error. So indeed it appears like the MVC 4 framework is not properly installed, by I just double check and do a repair. Where can I continue to investigate?
@Mystere Man, I've changed the Anonymous Authentication to use the Application Pool identity, stop, start the app and still the same error. It really look like if ASP.NET MVC 4 is not taking the request.
Here is a part of the web.config:
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="*" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
  </entityFramework>

Edit 2012/09/27
I've re-pair Microsoft Framework .NET 4.5 and repair the ASP.NET MVC 4, re-deploy the simple ASP.NET MVC 4 app, and I still get the same behaviour. I'm not sure what to do next, so I started a bounty in the hope that someone could help me find the problem.
Edit 2014/01/31
When I asked that question, I flagged the runAllManagedModulesForAllRequests as the accepted answer because it did solve the problem. But I was certainly not going to use this in production. I ask why I had to do this and did not have any answers.
Than Martin Hollingsworth answer was really what I was looking for, a good way to fix this problem without all the performance issues related to the runAllManagedModulesForAllRequests.
We almost gave up and bought a new Windows 2012 server (from which the ASP.NET MVC app work as is). After trying Martin's solution, the Windows 2008 server worked.

A: I had a similar problem. I tried many of the solutions described here (the Web.Config system.webServer configuration entry, etc) to no avail. At the very end, I discovered what the issue was with my particular installation. I was publishing my website to the local file system and then copying those files onto the server. It turned out that the file Global.asax was not being part of the published files. Once I copied that file, the error went away.

A: Try using this:
<system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    ...
</system.webServer>

EDIT:
The solution above will work for .NET 3.5 or below.
If you are using .NET 4.0 or above, you might want to try installing IIS7 QFE
Also, this article is worth reading to understand the difference between those two.

A: If you are not able to apply the QFE from  kb 980368, instead of using the runAllManagedModulesForAllRequests solution as suggested in the accepted answer, you should use the modules configuration with preCondition="" shown below to avoid the negative impact on static content as described in the blog posts How asp.NET MVC Routing Works and its Impact on the Performance of Static Requests and Don't use runAllManagedModulesForAllRequests="true" when getting your MVC routing to work and some of the comments on the answers.
Scott Hanselman's blog post about runAllManagedModulesForAllRequests should add some weight to this argument. Rick Strahl's post Caveats with the runAllManagedModulesForAllRequests in IIS 7/8 is the best explanation of the interaction between the settings I have found. The IIS documentation on the module preCondition attribute is also worth a read.
Remember this configuration change is not necessary if you have applied the QFE as this behaviour becomes the default.
<system.webServer>
  <modules>
    <remove name="UrlRoutingModule-4.0" />
    <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
  </modules>
</system.webServer>

A: As per https://stackoverflow.com/a/12521807/695829
I had the same issue and this hotfix fixed it: : http://support.microsoft.com/kb/980368

A: As mentioned by SonicTheLichen, if you are publishing from Visual studio, the gloabal.asax file is not copied by default. By copying the global.asax to your webserver should resolve the issue. Thanks SonicTheLichen for proving the solution.
Regards,
Saurabh

A: I don't know if this will fix your issue, but it fixed one I had deploying and MVC app to IIS.
I had to add a wildcard application map to the aspnet_isapi.dll for the home/virtual directory of the application.  You can do this by right clicking on the web site/virtual directory and selecting the home directory/virtual directory tab, clicking the configuration button and then click the Insert button under the wildcard application maps section.
C:\WINDOWS\microsoft.net\Framework64\v4.0.30319\aspnet_isapi.dll
Good luck!

A: I had a similar problem. I had to deploy a .net MVC site to a new server with Windows 2008 and IIS 7.5 installed. When I checked the programs and features, I saw that only the .Net Framework 4.5.1 was installed. I manually enabled the .Net 3.5.1 Windows feature.  After I installed MVC 4.0 the routing did not work.
My solution:
1) Deinstall the .Net 4.5.1 framework and MVC 4.0
2) Install the .Net Framework 4.0
3) Install .Net framework 4.5.1
4) Install MVC 4.0

A: I know this is old, but windows updates just now wasted a couple of hours for me:
IF you handle your exceptions in Global.asax this can also be simple as keeping windows updates the same as your dev env... For me, i did not obviously, this resulted in a "could not load...." exception, which my global.asax tried to handle and in turn had the same problem but hiding the underlying problem.....

A: I had to enable scripts in the Handler Mapping section of the website properties in IIS.

Open IIS, click on the website in question. Open up Handler Mappings and click "Edit Feature Permissions". Check the boxes for Script and Execute, then click OK. Good to go!


text:
Q: Can't protoc with relative paths from a script Been wrestling with this for a while. I have a protoc command that runs fine in terminal, but fails in a script. The issue seems to be with the recursive protos.
The folder structure is:
ledger-models % ls
Cargo.lock      README.md       gen.rs          ledger-models-protos    target
Cargo.toml      compile.sh      ledger-models-java  ledger-models-rust

in ledger-models-protos there are several folders with protos:
ledger-models-protos % ls
models              requests            services

In the root directory I can sucessfully run the protoc command interactively:
ledger-models % protoc --java_out=ledger-models-java/generated-src --proto_path=ledger-models-protos **/*.proto

However when I run the same line in the script it fails:
echo "generating java protos"
rm -rf ledger-models-java/generated-src
mkdir  ledger-models-java/generated-src
protoc --java_out=ledger-models-java/generated-src --proto_path=ledger-models-protos **/*.proto

ledger-models % ./compile.sh
working directory
/Users/davidjdoherty/Dev/ledger-models
generating java protos
Could not make proto path relative: **/*.proto: No such file or directory

I am stumped as to why I'm getting the error **Could not make proto path relative: /*.proto: No such file or directory.
This is an open source project so the code is: https://github.com/FinTekkers/ledger-models/blob/main/compile.sh


text:
Q: TypeORM: bulk insert with unnest I'm trying to do a bulk insert with TypeORM query builder using postgres unnest function.
Code sample:
manager
  .createQueryBuilder()
  .insert()
  .into(Foo)
  .values(qb =>
    qb.select('*').from('UNNEST($1::int[], $2::text[], $3::text[])', [data1, data2, data3])),
  )

This doesn't work and generates this query:
INSERT INTO "foo"("a", "b", "c") VALUES (DEFAULT, DEFAULT, DEFAULT);

Any idea how to make it work without having to use a raw query?


text:
Q: Swap buttons to select I have something like this

document.getElementsByClassName("options")[0]
  .addEventListener("click", function(e) {
    if (e.target.classList.contains("line-type")) {
      // Remove active class from previous element
      document
        .querySelector(".line-type.is-active")
        .classList.remove("is-active");

      e.target.classList.add("is-active");
      currentLine = e.target.dataset.lineType;
      console.log("Current line: " + currentLine);
    }
  });
.line-type { font-weight:bold }
.is-active { color:red }

      Water pipe

      Electricity line

      Internet line

      RYSUJ TU

  <button id="clear-water-pipe">Clear active line</button>

Now it changes my line color on click of the button but i would like to swap it totally to select, on select change i need to change colors and currentLine. Any tip how to do it? I never moved button into html select. Thanks

A: Here is a start

const linesData = {
  water: {
    linePoints: [],
    lineLines: [],
    color: "blue"
  },
  electricity: {
    linePoints: [],
    lineLines: [],
    color: "yellow"
  },
  internet: {
    linePoints: [],
    lineLines: [],
    color: "gray"
  }
};

let currentType;
let sel = document.createElement("select");
sel.id = "lineType"
sel.appendChild(new Option("Please select", ""));
sel.addEventListener("change", function() {
  currentType = this.value ? linesData[this.value] : {}
  console.log(this.value, currentType)
})
Object.keys(linesData).forEach(key => {
  const title = key[0].toUpperCase() + key.slice(1) +" line";
  sel.appendChild(new Option(title, key));
});
document.getElementById("app").appendChild(sel)

  <canvas id="canvas" width="500" height="350"></canvas>


text:
Q: readOuterXml(), Input is not proper UTF-8, indicate encoding I'm using XMLReader to parse a large XML file from a third party, file size is 1GB+. The XML file specifies the encoding as UTF8 (<?xml version="1.0" encoding="utf-8" ?>), although it isn't.
XMLReader throws an error because of the unknown encoding type, but not until it's already processed most of the file.
Exception message:

Input is not proper UTF-8, indicate encoding

I have determined that the real encoding of the file is ISO-8859-1, and it will work fine if I manually specify this when calling $reader->open().
The problem is that my script needs to parse unknown files from the database, so it needs to rely on the encoding type specified within the file. I need to find a way to parse any file regardless of its encoding, are there any suggestions for doing this?

A: I figured out that vim is pretty good at converting from one encoding to another.
My trick is to parse the file normally, and when the encoding error is encountered just re-encode the file with vim and start parsing again.
Here's the rough idea:
$xmlFile = '/path/to/file.xml';

// Parse the file in a loop
while(...)
{

    try
    {
        // Normal parsing logic...

        $reader->readOuterXml();

        //...
    }
    catch(Exception $ex)
    {
        $encoding = getXMLEncoding($xmlFile) ?: 'utf-8';

        exec(sprintf(VIM_PATH . ' -c "set fileencoding=%s" -c "wq" "%s"', $encoding, $xmlFile));

        // File has been re-encoded
        // The real encoding should now match the declared encoding

        // -> Go back to the beginning and parse the file again
    }

}

Using this method might garble 1 or 2 chars, but it's way better than completely failed parsing. Ideally the 3rd party would mark their files correctly.
My system is Windows, so the vim arguments might be different on Linux (don't know).

A: Use simplexml_load_file to parse XML. In order to avoid encoding problems, use utf8_encode on data.


text:
Q: Email delivery service - Sender address verification process Our product needs a Email Delivery Service Provider to help us deliver emails. We want our customers to be able to use their own emailadresses when sending emails and that makes this a bit harder.
It seems that most companys verify sender adresses by sending an email with a link to that sender address. This is not a ideal solution for us (We don't want to tell our customer to wait for an Amazon email and click a link).
Is there any other verification processes out there, our maybe someone that don't have a verification process?

A: You can verify an entire domain with Postmark (where I work). This process won't send an email, but you'll need access to your customer's DNS settings. More info here: https://postmarkapp.com/support/article/1046-how-do-i-verify-a-domain


text:
Q: Template specialization with non-empty template parameter list I have difficulties to understand the following code
template <typename T>
struct function_traits
    : public function_traits<decltype(&T::operator())>
{};
// For generic types, directly use the result of the signature of its 'operator()'

template <typename ClassType, typename ReturnType, typename... Args>
struct function_traits<ReturnType(ClassType::*)(Args...) const>
// we specialize for pointers to member function
{
  // ...
}

int main()
{
    auto lambda = [](int i) { return long(i*10); };

    typedef function_traits<decltype(lambda)> traits;

    // ...

    return 0;
}

which occurs in the answer https://stackoverflow.com/a/7943765/7006673.
Here,
template <typename ClassType, typename ReturnType, typename... Args>
struct function_traits<ReturnType(ClassType::*)(Args...) const>

seems to indicate a specialization of the template class
template <typename T>
struct function_traits

however, the template parameter list of the specialization template <typename ClassType, typename ReturnType, typename... Args> is not empty (i.e., is not equal to template <>).
Can someone please help me to understand, what kind of specialization this is and how the template parameters ClassType, ReturnType, and Args are deduced?
Many thanks in advance.

A: This is a partial specialization.   It can't be an "anything" like something that just takes typename T, but it still has some variability in it, so it's not a full specialization.
Also, the things that you're looking to match up are the number of types in the original struct/class's template line and the <...> after the name in the specializations.  It's kind of weird because it's asymmetrical.
In your partial specialization:
struct function_traits<ReturnType(ClassType::*)(Args...) const>

All three of the templated types combined still only create a single type - a pointer to member function.  That is the same number of types as the "parent" templated type, even though that single type is broken down into 3 additional templated types in the specialization.
// this is what I'm calling the "master template", this isn't an official term
template<class A, class B, ......., class N>
class Foo{};

template</*...This can have as many (or 0) entries as you need for this specialization...*/>
class Foo</*...This must have the same number as master template above, but can be broken down into as many smaller pieces as you want...*/> {};

A:
What kind of specialization this is?

This is a partial specialization. type_traits is explicitly instantiated with:
T = ReturnType(ClassType::*)(Args...) const

But this T is dependent on ReturnType, ClassType, and Args. That is why you don't have template <> in the declaration (that would be a full specialization), but a template declaration with new parameters describing a particular kind of T.

How the template parameters ClassType, ReturnType, and Args are deduced?

They are deduced when the template is instantiated with an expression that suits this specialization. Here, ReturnType(ClassType::*)(Args...) const can only be substituted with a pointer to a method.
This is an example of SFINAE.


text:
Q: render data inserted to collection in react component My entire application is built on different react classes and displayed like this:
MainLayout = React.createClass({
  render() {
    return (

        {this.props.content}

    );
  }
});

All my front-end is built in react classes like the one below:
InsertData = React.createClass({
    insertToCollection(event) {
        event.preventDefault();
        console.log(this.state.message + " state med message");
        var content = Posts.find().fetch();
            Posts.insert({
                Place: $("post1").val(),
                Type: $("post2").val(),
                dateAdded: new Date(),
            });
    },

    handleChange(event) {
        this.setState({
            message: event.target.value
        })

        console.log(this.state + " mer state her");
        function insert(event) {
            event.preventDefault();
            console.log("added stuff");
        }
    },
    render() {
        return (

                <form onSubmit={this.insertToCollection}>
                    <input type='text' placeholder="Select a restaurant" className="input-field"
                    onChange={this.handleChange} id="post1"/>
                    <input type='text' placeholder="What type of food they have" className="input-field"
                    onChange={this.handleChange} id="post2"/>
                    <button className="waves-effect waves-light btn btn-block" onChange={this.insert}> Submit </button>
                </form>
                <DisplayData />

        );
    }
});

Insert data to my collection works fine. I would like to render the inserted data onto the page from the <DisplayData /> component:
DisplayData = React.createClass({
    render(){
        var posts = Posts.find().fetch();
        var postList = posts.map(function(posts){
            return posts;
        })
        return
 Your collection

    }
});

I'm rather stuck here, and not really sure how to iterate through the collection and render it in a list-structure for example. Here is my collection so far:
Posts = new Mongo.Collection('posts');

Posts.allow({
    insert: function(){
        return true;
    },
    update : function(){
        return true;
    },
    remove : function(){
        return true;
    }
});

A: Here is a demo of how you can approach this: http://codepen.io/PiotrBerebecki/pen/bwmAvJ
I'm not sure about the format of your posts collection, but assuming that it is just a regular array, for example var posts = ['One', 'Two'];, you can render the individual post as follows:
var DisplayData = React.createClass({
    render(){
        var posts = ['One', 'Two'];

        var renderPosts = posts.map(function(post, index) {
            return (

{post}

            );
        });

        return (

 Your collection

              {renderPosts}

        );
    }
});

Here is the full code from my codepen.
var InsertData = React.createClass({
    insertToCollection(event) {
        event.preventDefault();
        console.log(this.state.message + " state med message");
        var content = Posts.find().fetch();
            Posts.insert({
                Place: $("post1").val(),
                Type: $("post2").val(),
                dateAdded: new Date(),
            });
    },

    handleChange(event) {
        this.setState({
            message: event.target.value
        })

        console.log(this.state + " mer state her");
        function insert(event) {
            event.preventDefault();
            console.log("added stuff");
        }
    },
    render() {
        return (

                <form onSubmit={this.insertToCollection}>
                    <input type='text' placeholder="Select a restaurant" className="input-field"
                    onChange={this.handleChange} id="post1"/>
                    <input type='text' placeholder="What type of food they have" className="input-field"
                    onChange={this.handleChange} id="post2"/>
                    <button className="waves-effect waves-light btn btn-block" onChange={this.insert}> Submit </button>
                </form>
                <DisplayData />

        );
    }
});

var DisplayData = React.createClass({
    render(){
        var posts = ['One', 'Two'];

        var renderPosts = posts.map(function(post, index) {
            return (

{post}

            );
        });

        return (

 Your collection

              {renderPosts}

        );
    }
});

ReactDOM.render(
  <InsertData />,
  document.getElementById('app')
);

A: You need to pass posts to your view component DisplayData as props, so in this case after you inserted a post, you should update your state in the InsertData component. Actually it would be better if you do the insertion login inside a service rather than the component itself, but for simplicity right now you can check the following code:
 InsertData = React.createClass({

  getInitialState: function() {
      return {posts: []}; // initialize the state of your component
    },

    insertToCollection(event) {
        event.preventDefault();
        console.log(this.state.message + " state med message");
        var content = Posts.find().fetch();
            Posts.insert({
                Place: $("post1").val(), // better to retrieve these values from state. You can use `handleChange` method to keep track of user inputs
                Type: $("post2").val(),
                dateAdded: new Date(),
            }, function(err, data){
            var posts = this.state.posts || [];
            posts.push(data);
            this.setState({posts: posts}); //after setting the state the render method will be called again, where the updated posts will be rendered properly
            });
    },

    handleChange(event) {
        this.setState({
            message: event.target.value
        })

        console.log(this.state + " mer state her");
        function insert(event) {
            event.preventDefault();
            console.log("added stuff");
        }
    },
    render() {
        return (

                <form onSubmit={this.insertToCollection}>
                    <input type='text' placeholder="Select a restaurant" className="input-field"
                    onChange={this.handleChange} id="post1"/>
                    <input type='text' placeholder="What type of food they have" className="input-field"
                    onChange={this.handleChange} id="post2"/>
                    <button className="waves-effect waves-light btn btn-block" onChange={this.insert}> Submit </button>
                </form>
                <DisplayData posts={this.state.posts}/>

        );
    }
});

var DisplayData = React.createClass({
    render(){
        var posts = this.props.posts || [];

        var renderPosts = posts.map(function(post, index) {
            return (

{post}

            );
        });

        return (

 Your collection

              {renderPosts}

        );
    }
});


text:
Q: my computer is crashing and I think it is overheating My computer is crashing lately with the colors on the display changing and the display not being updated (aside from the fact that I can see hints of mouse movement).
Originally I thought it might be software drivers but now I think it is overheating. I would like to measure the temperatures of both my CPU as well as my GForce display card. I need the display card since I have dual monitors (on a desktop computer).
I found the sensors program which gives:
ilan@ilan-main:~$ sensors
coretemp-isa-0000
Adapter: ISA adapter
Core 0:       +37.0°C  (high = +76.0°C, crit = +100.0°C)
Core 1:       +31.0°C  (high = +76.0°C, crit = +100.0°C)

f71889fg-isa-0a00
Adapter: ISA adapter
+3.3V:        +3.28 V
in1:          +1.07 V  (max =  +2.04 V)
in2:          +1.10 V
in3:          +0.94 V
in4:          +0.69 V
in5:          +0.54 V
in6:          +0.40 V
3VSB:         +3.30 V
Vbat:         +3.18 V
fan1:        1587 RPM
fan2:        1618 RPM
fan3:        1554 RPM
temp1:        +27.0°C  (high = +255.0°C, hyst = +251.0°C)
                       (crit = +255.0°C, hyst = +251.0°C)  sensor = transistor
temp2:        +39.0°C  (high = +255.0°C, hyst = +251.0°C)
                       (crit = +96.0°C, hyst = +92.0°C)  sensor = thermistor
temp3:        +41.0°C  (high = +255.0°C, hyst = +253.0°C)
                       (crit = +255.0°C, hyst = +253.0°C)  sensor = transistor

nouveau-pci-0100
Adapter: PCI adapter
temp1:        +68.0°C  (high = +95.0°C, hyst =  +3.0°C)
                       (crit = +122.0°C, hyst =  +2.0°C)
                       (emerg = +135.0°C, hyst =  +5.0°C)

I see nouveau-pci-0100, whatever that is, is fairly hot. If it is the CPU or the display card, I simply don't know.
ilan@ilan-main:~$ nvidia-settings

** (nvidia-settings:2924): WARNING **: PRIME: Failed to execute child process "/usr/bin/prime-supported" (No such file or directory)
** Message: PRIME: is it supported? no

comes up with a Nvidia dialog with various information, but no obvious temperature. I don't know what prime supported means.
ilan@ilan-main:~$ nvclock -T
Error: You don't have enough permissions to run NVClock! Retry as root or install the Nvidia drivers.
*** stack smashing detected ***: nvclock terminated
Aborted (core dumped)

nvclock was supposed to give me the temperature but it crashes. I looked into installing the Nvidia drivers which it seems to indicate are not installed (even if I get the nvidia dialog from nvidia-settings.
In any case I tried to install the Xorg nvidia drivers and the system wanted to remove Wine. Wine I don't use very often, but once in a while I need it. Thus I didn't agree to install the Xorg nvidia drivers.

A: In order to execute nvclock -T, first log in as root and then execute the command:
~$ sudo su
~# nvclock -T


text:
Q: Messenger Services in Windows 8.1 I was trying to create a CMD Messenger.
I googled for it, and got a few lines of code.
But the problem is that I a unable to find the Messenger services in Windows 8.1 which I need to start in order to get the Messenger.bat file running.
Can anyone suggest, if the Messenger Service is present in Windows 8.1 or not?
And if it is, then how to start it?
Basically, I need to user NET SEND command in CMD. And, I guess, this doesn't works without the Messenger Services.

A: I need to use NET SEND command in CMD
net send was removed in Windows Vista and later, as was the Messenger Service.
It is replaced by msg, but only professional and business editions of Windows have the ability to send network messages using msg. It is not supported in Windows Home.

Further Reading

*

*An A-Z Index of the Windows CMD command line

*msg - Send a pop-up message to a user.

*Windows Msg command help and faq


text:
Q: undefined reference only with .cpp I'm a C++ beginner, so sorry if this question is stupid.
I have three file: main.cpp, mapper.hpp and its src file mapper.cpp.
mapper.hpp declare a struct which extends ff_node, which has the pure virtual method void* svc(void* task);:
//mapper.hpp
#define HAS CXX11 VARIADIC TEMPLATES 1

#include <iostream>
#include <ff/pipeline.hpp>

using namespace std;

#ifndef MAPPER_HPP_
#define MAPPER_HPP_

template<typename S1>
struct Mapper : ff::ff_node {
public:
    void* svc(void* task);
};

#endif /* MAPPER_HPP_ */

This is mapper.cpp:
//mapper.cpp
#include "mapper.hpp"

template<typename S1>
void* Mapper<S1>::svc(void* task) {
    //do something here
}

And finally main.cpp:
#include <iostream>
#include <vector>
#include <ff/pipeline.hpp>
#include <ff/farm.hpp>

#include "mapper.hpp"
#include "splitter.hpp"

using namespace ff;

int main(int argc, char *argv[]) {
//...
    std::vector<std::unique_ptr<ff_node> > Workers;
    for(int i=0;i<nworkers;++i)
        Workers.push_back(make_unique<Mapper<int>>());
//..
}

Compiling with the following command:
g++ -std=c++11 -DNO_DEFAULT_MAPPING  -I /home/luca/fastflow -O3 -finline-functions -DNDEBUG mapper.cpp Main.cpp -o Main -pthread
Returns me the following error:
/tmp/ccUY3VtR.o:(.rodata._ZTV6MapperIiE[_ZTV6MapperIiE]+0x118): undefined reference to `Mapper<int>::svc(void*)'
collect2: error: ld returned 1 exit status

What is strange is that if I declare svc(void*) insider mapper.hpp then no error is returned and everything is compiled correctly!


text:
Q: Apple Terminal script to copy files based on a .csv list of filenames? Been trying for hours to get this to work - but I'm a complete novice (e.g. started using terminal today) and struggling to get this working.
I have a csv file that lists filenames row by row. I want to find them and copy them to a new directory. The files are listed in one directory, but each file is in its own subdirectory.
This is what I have tried, but it is not copying anything. But I can see it cycling through the searches:
    cat /Users/Will/Downloads/three-new.csv | while IFS=, read col1
do
    find /Volumes/LaCie\ 8tb/BPOTY/2021\ Photos -path $col1 -exec cp {} /Volumes/LaCie\ 8tb/BPOTY/2021\ book \;
done

I have also tried this, but it just copies all files from the directory (stripping the subdirectories) and doesn't find the actual filenames.
cat /Users/Will/Downloads/three-new.csv | while IFS=, read col1
do
    find /Volumes/LaCie\ 8tb/BPOTY/2021\ Photos $col1 -exec cp {} /Volumes/LaCie\ 8tb/BPOTY/2021\ book \;
done

The file can be seen here:
https://www.dropbox.com/s/6uqwzky43r25ors/three.csv?dl=0
Have run a command as requested and the CSV outputs:
00000000: 636f 6c31 0d0a 494d 475f 3437 3538 2d64  col1..IMG_4758-d
00000010: 6e2e 6a70 670d 0a43 4f45 5f32 3330 352d  n.jpg..COE_2305-
00000020: 4564 6974 2e74 6966 2e7a 6970 0d0a 5f44  Edit.tif.zip.._D
00000030: 5343 3435 3933 2d68 6972 6573 2d72 6573  SC4593-hires-res
00000040: 6f6c 7574 696f 6e2d 5065 7465 722d 6365  olution-Peter-ce
00000050: 6368 2d54 6865 2d6c 6f6f 6b2e 6a70 67    ch-The-look.jpg

A: Since your are doing this under macOS and the file has CRLF endings, first lets remove the carriage  returns from the three.csv file, in Terminal:
tr -d '\r' < three.csv > new.csv

As the three.csv file only has one column and there are actually no commas, nor are the entries quoted, this is really not a CSV file and can be treated in a more straight forward manner. To that end, use the following shell script syntax to accomplish your goal.
#!/bin/bash

while IFS= read -r line; do
    cd '/path/to/parent_dir' || exit
    find . -type f -iname "$line" -exec cp -av {} '/path/to/destnation_dir' \;
done < '/path/to/new.csv'

Notes:

*

*The cd '/path/to/parent_dir' || exit isn't absolutely necessary, it's just my preferred method in many use cases. The . after find can be replaced with '/path/to/parent_directory'.

*Pathnames with spaces need to either be escaped with a backslash character or the pathname be quoted, single, or double if containing variables, however, not both. As a general rule I almost alway quote non-variable strings with single-quotes. (I did use double-quotes last night on non-variable strings but that was a typo.)

*If executing directly in Terminal then the #!/bin/bash shebang isn't necessary and was included if using it as a standalone shell script.

*The last line of the three.csv file, and thus the new.csv file does not have a line feed character. Edit the file by placing the cursor at the end of line three and press enter, then save the file. Otherwise the last line is not processed.

*As mentioned in the comments of the OP by Gordon Davisson, quote your variables and use ShellCheck to check your bash shell script code.


text:
Q: Java loop not working because of wrong scanner usage I'm making a text editor in java.
I'm using a switch to create a menu.
One of the options of the menu is to insert lines to the existing array where i need to make a loop to add strings to an array and make it stop when i add a empty string.
Note: i cannot use array lists.
i can only use this array.
int tamMax=100;
String [] linhas = new String[tamMax];

This is the code i have so far
        System.out.println("(I)nserir linhas no fim (termine com uma linha vazia");
        System.out.println("(L)istar linhas");
        System.out.println("(A)pagar última linha");
        System.out.println("(E)ditar");
        System.out.println("(F)erramentas");
        System.out.println("(S)air");
        menuPrincipal = input.next().charAt(0);
        switch(menuPrincipal) {
            case 'i':
            case 'I':
                int i=0;
                while (true) {
                    linhas[i] = input.nextLine();
                    System.out.println(linhas[i]);
                    if (linhas[i].isEmpty()) {
                        break;
                    }
                    i++;
                }
                System.out.print(Arrays.toString(linhas));

The loop itself is working fine, the problem is when i put the loop inside the switch case, once i do that and i press "i" the loop stops working, it doesn't let me type anything and only outputs the following result:[, null, null, null, null, null, null, null ...

A: linhas[i] will always be null. You want to check the string that was inserted in the previous iteration (i - 1).
You can do the check within the for-loop body.
for (int i = 0; ; i++) {
    linhas[i] = input.nextLine();
    System.out.println(linhas[i]);

    if (linhas[i].isEmpty()) {
        break;
    }
}

If you don't want the empty string to be inserted, move the check before assignment.
String element = input.nextLine();
System.out.println(element);
if (element.isEmpty()) {
    break;
}
linhas[i] = element;
i++;

Since you do not know the number of times the loop will run, a while loop may be preferred.
while (true) {
    linhas[i] = input.nextLine();
    System.out.println(linhas[i]);
    if (linhas[i].isEmpty()) {
        break;
    }
    i++;
}


text:
Q: Creating a "Next Run Time" date from a cronjob-like syntax In an app I'm creating a user is given the possibility to schedule a repeating task. Simply the values for generating the interval schema are:
Minute: [0-59, 90 (each minute)]
Hour: [0-23, 90 (each hour)]
Day of month: [1-31, 90 (each day of month), 91 (last day of month)]
Month: [1-12, 90 (each month)]

So, for example I've got this format: 10 - 2 - 90 - 90 which translates to 2015-07-16 2:10. The method determining the next run time date is able to present me this date. But, I'm looking for the efficient way to check if the next run time date has already passed (easy part) but then generate the first next run time date again. In this case it would be 2015-07-17 2:10.
I've found out that our brain is easily up to the task but I'm unsure which logical steps to follow to determine this in the most efficient way (without writing out all posibilities that is).
Any suggestions?

A: This is nearly Cron syntax, so why creating something own which does exactly the same job?
It should be pretty easy to switch to a valid cron syntax and use a simple library for parsing, etc.
An example would be https://github.com/mtdowling/cron-expression where you could get the next run date for free:
$cron->getNextRunDate()->format('Y-m-d H:i:s');

You would also have the possibility to use values like 0/15 to run every 15 minutes, etc.
Another benefit is, that cron syntax is common knowledge which prevents misinterpretation of the format.

A: I've assumed the interval of this is daily.  If not you can adjust the strtotime line.
You'll want to turn the date into a timestamp, and then add one day onto it.  PHP makes that pretty easy.
Assuming you've already got the date parsed into international format of 2015-07-17 2:10, you can do the following:
$date = '2015-07-17 2:10'; // Parsed date
$timestamp = strtotime($date);
if($timestamp > time()){
    // Date hasn't hit yet
} else {
    $next_run = strtotime("+1 day", $timestamp);
}

A: Check out https://github.com/fightbulc/moment.php, it offers the possibility to add/substract seconds, minutes, hours, month and years.
For example (taken from the github demo site):
$m = new \Moment\Moment('2012-05-15T12:30:00', 'CET');
echo $m->addHours(2)->format(); // 2012-05-15T14:30:00+0200

$m = new \Moment\Moment('2012-05-15T12:30:00', 'CET');
echo $m->subtractDays(7)->subtractMinutes(15)->format(); //  2012-05-08T12:15:00+0200

A: Why worry about if it has run, or when its next run time is?
Could you just run a script every minute, checking for all matching jobs, then executing them?
Shouldn't be a big problem writing a SQL query that matches all possibilities for a certain point in time :)

A: You could simply use the native DateTime classe.
$timeString = '2015-07-16 2:10';
$date = DateTime::createFromFormat('Y-m-d H:i', $timeString);
$date->modify('+1 day');

$now = new DateTime();

if ($date > $now) {
    // The date is in the future
} else {
    // The date is today, or is in the past
}

But if you need a real cron syntax, the answer by @echox is much better.

A: To be honest I wasn't quite satisfied with the accepted and rewarded answer because I wanted to figure it out myself, not ending up with an external library and rewrite my code.
Given my cron like syntax as described in the question I've created a function to determine the next run time. I'd like to share it with the intention to help out others in the future if you're facing a similar problem. Maybe it points you into the direction you need.
Some demo cases
$cases = [
    // Every minute
    ['i' => 90, 'H' => 90, 'd' => 90, 'm' => 90],
    // Every 5th minute
    ['i' => 5, 'H' => 90, 'd' => 90, 'm' => 90],
    // Every day at 02:15
    ['i' => 15, 'H' => 2, 'd' => 90, 'm' => 90],
    // Every last day of the month at 15:20
    ['i' => 20, 'H' => 15, 'd' => 91, 'm' => 90],
    // June 4th at 12:37
    ['i' => 37, 'H' => 12, 'd' => 4, 'm' => 6],
    // Every minute between 04:00 and 05:00 at every day in October
    ['i' => 90, 'H' => 4, 'd' => 90, 'm' => 10],
];

Function:
function getNextRunTime($config) {
    $minute = $config['i'];
    $hour   = $config['H'];
    $day    = $config['d'];
    $month  = $config['m'];

    // Get minute
    switch($minute) {
        case 90 :
            $nextMinute = date('i', strtotime('now + 1 minute'));
            break;
        default :
            $nextMinute = $minute;
    }

    // Get hour
    switch($hour) {
        case 90 :
            if($minute == 90 || $nextMinute > date('i')) {
                $nextHour = date('H');
            } else {
                $nextHour = date('H', strtotime('now + 1 hour'));
            }
            break;
        default :
            $nextHour = $hour;
    }

    // Get day
    switch($day) {
        case 90 :
            if($hour == 90 && $nextHour > date('H')) {
                $nextDay = date('d');
            } elseif($hour <> 90 && $nextHour <= date('H')) {
                $nextDay = date('d', strtotime('now + 1 day'));
            } else {
                if($nextHour > date('H')) {
                    $nextDay = date('d');
                } else {
                    if ($nextMinute > date('i')) {
                        $nextDay = date('d');
                    } else {
                        $nextDay = date('d', strtotime('now + 1 day'));
                    }
                }
            }
            break;
        case 91 :
            if(date('t') == date('d')) {
                if($nextHour > date('H')) {
                    $nextDay = date('d');
                } elseif($nextHour == date('H') && $nextMinute > date('i')) {
                    $nextDay = date('d');
                } else {
                    $nextDay = date('t', strtotime('now + 1 month'));
                }
            } else {
                $nextDay = date('t');
            }
            break;
        default :
            $nextDay = $day;
    }

    // Get month
    switch($month) {
        case 90 :
            if($day == 90 || $nextDay > date('d')) {
                $nextMonth = date('m');
            } elseif($nextDay == date('d')) {
                if($hour == 90 || $nextHour > date('H')) {
                    $nextMonth = date('m');
                } elseif($nextHour == date('H')) {
                    if($minute == 90 || $nextMinute > date('i')) {
                        $nextMonth = date('m');
                    } else {
                        $nextMonth = date('m', strtotime('now + 1 month'));
                    }
                } else {
                    $nextMonth = date('m', strtotime('now + 1 month'));
                }
            } else {
                $nextMonth = date('m', strtotime('now + 1 month'));
            }
            break;
        default :
            $nextMonth = $month;
    }

    // Get year
    if($month == 90 || $nextMonth > date('m')) {
        $nextYear = date('Y');
    } elseif($nextMonth == date('m')) {
        if($day == 90 || $nextDay > date('d')) {
            $nextYear = date('Y');
        } elseif($nextDay == date('m')) {
            if($hour == 90 || $nextHour > date('H')) {
                $nextYear = date('Y');
            } elseif($nextHour == date('H')) {
                if($minute == 90 || $nextMinute > date('i')) {
                    $nextYear = date('Y');
                } else {
                    $nextYear = date('Y') + 1;
                }
            } else {
                $nextYear = date('Y') + 1;
            }
        } else {
            $nextYear = date('Y') + 1;
        }
    } else {
        $nextYear = date('Y') + 1;
    }

    // Create the timestamp for the 'Next Run Time'
    $nextRunTime = mktime($nextHour, $nextMinute, 0, $nextMonth, $nextDay, $nextYear);

    // Check if the job has to run every minute, maybe a reset to d-m-Y h:00 is possible
    if($nextRunTime > time() && $minute == 90) {
        $tempNextRunTime = mktime($nextHour, 0, 0, $nextMonth, $nextDay, $nextYear);

        if($tempNextRunTime > time()) {
            $nextMinute  = 0;
            $nextRunTime = $tempNextRunTime;
        }
    }

    // Check if the job has to run every hour, maybe a reset to d-m-Y 00:i is possible
    if($nextRunTime > time() && $hour == 90) {
        $tempNextRunTime = mktime(0, $nextMinute, 0, $nextMonth, $nextDay, $nextYear);

        if($tempNextRunTime > time()) {
            $nextHour    = 0;
            $nextRunTime = $tempNextRunTime;
        }
    }

    // Check if the job has to run every day, maybe a reset to 1-m-Y H:i is possible
    if($nextRunTime > time() && $day == 90) {
        $tempNextRunTime = mktime($nextHour, $nextMinute, 0, $nextMonth, 1, $nextYear);

        if($tempNextRunTime > time()) {
            $nextRunTime = $tempNextRunTime;
        }
    }

    // Return the Next Run Time timestamp
    return $nextRunTime;
}

Output (execution time 23-09-2015, 11:12):
string '23-09-2015, 11:13' (length=17)
string '23-09-2015, 12:05' (length=17)
string '24-09-2015, 02:15' (length=17)
string '30-09-2015, 15:20' (length=17)
string '04-06-2016, 12:37' (length=17)
string '01-10-2015, 04:00' (length=17)

A: It is working fine. I am using PHP Cron Parser. It has everything that we needed.
Or else, you could use Cron Expression easier and more efficient. Some reference answers are already here and here in Stack Overflow.
For Cron Expression, you could use:
$cron = Cron\CronExpression::factory('@daily');
$cron->isDue();
echo $cron->getNextRunDate()->format('Y-m-d H:i:s');//this give next run date.
//echo $cron->getPreviousRunDate()->format('Y-m-d H:i:s');//this give previous run date.

And this is exactly the same what you have and Cron Expression also have,

All what you need to do is, just use PHP Cron Expression. Hope this helps.


text:
Q: How to find what relations exists between 2 nodes neo4j? Lets say i have these nodes with these relations (A,B) are nodes and Rs are Relation Names:
A-R1->B
A-R2->B
A-R3->B

Now i do not actually know if one or any R has relation between these 2 nodes. how can i specify if any relation exists between these 2 nodes regardless of knowing what relation is it?
Also if there are any relation exists between these two nodes is it possible to know what relation is it?

A:
how can i specify if any relation exists between these 2 nodes
  regardless of knowing what relation is it?

I believe that a simple MATCH will be sufficient. The below query returns all relationships between a node named "A" and a node named "B", if exists.
MATCH ({name : "A"})-[r]->({name : "B"})
RETURN r

Also if there are any relation exists between these two nodes is it
  possible to know what relation is it?

The type() function returns a string representation of the relationship type. Then the below query will return the string representing the type of each relationship between A and B.
MATCH ({name : "A"})-[r]->({name : "B"})
RETURN type(r) as type


text:
Q: Occasional error in word finding genetic algorithm I (almost) successfully created a genetic algorithm to find a given string, but for some reason, I semi-frequently get an error when running the program, which otherwise works perfectly.
 Cannot read property 'dna' of undefined at Population.populate

I can't seem to figure out what causes this issue only a handful of times.

<!DOCTYPE html>

 <title>Word Search</title>
 <link href='https://fonts.googleapis.com/css?family=Ubuntu' rel='stylesheet'>

 Target: <input type='text' value='Hello World!'  id='target'>

 Population Size: <input type='number' id='size' min='0' max='100' step='1' value='10'>

 Mutation Rate: <input type='number' id='rate' min='0' max='100' step='1' value='10'>%

 <input type='submit' id='submit' onclick='evolution()'>

Generation | 0

A: This error happens when all members have a fitness of zero, then the loop in the natSelection function is looping until j < this.members[i].fitness*10 which is zero, so no loop and nothing is added to genePool.
Now when that happens, obviously this.genePool[Math.floor(Math.random()*this.genePool.length)] will be undefined and when you try to access the property dna, you get the error.
To solve this, you must add some validation so when all members have fitness of zero, you do something about it. Alternatively, at the end of the natSelection function, check genePool.length and if it is still zero, then add at least one item.

A: First, let's make sure we fully understand the error.
You are trying to read property dna of undefined in your populate method.
Said another way:
// Your populate method
this.populate = function() {
    this.generation++;
    this.members = [];
    for(var i = 0; i < this.size; i++) {
        var a = this.genePool[Math.floor(Math.random()*this.genePool.length)].dna;
        var b = this.genePool[Math.floor(Math.random()*this.genePool.length)].dna;
        this.members.push(new Genome(this.target, this.mutationRate, a, b));
    }
}

JavasScript is seeing
this.genePool[Math.floor(Math.random()*this.genePool.length)]

as undefined
and then, you're asking to JavaScript to read the dna property of undefined.
undefined.dna
Now, let's figure out how we can debug the error.
Personally, I would log the following:
// Your populate method
this.populate = function() {
    this.generation++;
    this.members = [];

    console.log('SIZE', this.size);

    for(var i = 0; i < this.size; i++) {

        console.log('I', i);
        console.log('this.genePool', this.genePool);
        console.log('this.genePool.length', this.genePool.length);

        var a = this.genePool[Math.floor(Math.random()*this.genePool.length)].dna;
        var b = this.genePool[Math.floor(Math.random()*this.genePool.length)].dna;
        this.members.push(new Genome(this.target, this.mutationRate, a, b));
    }
}

Next, let's analyze the logs.
Maybe we have using i < this.size when we should be using i < this.size - 1, or something similar elsewhere (aka off-by-one error).
Maybe this.genePool is undefined sometimes.
If you still have trouble, update your question with some log output.


text:
Q: DocuSign not finding anchor tab strings with Field codes in a word document We are trying to use field codes in our word documents to be our anchor tab strings. If I do a Ctrl-A on the document, I see the field codes, but it does not find them with Docusign. If I take those values, such as Seller_Nm, and place it on the document, away from the field codes, it finds it fine. Is there something else I need to do when using field codes?
Edit: here is the envelope definition and the summary
 05/15/2017 11:32:05 - INFO - Created Envelope with definition: {
  "eventNotification": {
    "url": "http://requestb.in/",
    "loggingEnabled": "true",
    "requireAcknowledgment": "true",
    "envelopeEvents": [
      {
        "envelopeEventStatusCode": "Delivered"
      },
      {
        "envelopeEventStatusCode": "Completed"
      },
      {
        "envelopeEventStatusCode": "Declined"
      },
      {
        "envelopeEventStatusCode": "Voided"
      },
      {
        "envelopeEventStatusCode": "Sent"
      }
    ],
    "useSoapInterface": "false",
    "includeCertificateWithSoap": "false",
    "signMessageWithX509Cert": "true",
    "includeDocuments": "false",
    "includeEnvelopeVoidReason": "false",
    "includeTimeZone": "true",
    "includeSenderAccountAsCustomField": "true",
    "includeDocumentFields": "true",
    "includeCertificateOfCompletion": "false"
  },
  "compositeTemplates": [
    {
      "serverTemplates": [
        {
          "sequence": "1",
          "templateId": "8ce7fea6-2ad1-4a45-a8c6-a29af4b2977d"
        }
      ],
      "inlineTemplates": [
        {
          "sequence": "1",
          "recipients": {
            "signers": [
              {
                "name": "Kathy Lori",
                "email": "kathyxxx@gmail.com",
                "recipientId": "1",
                "accessCode": "12345",
                "customFields": [],
                "routingOrder": "1",
                "note": "",
                "roleName": "Customer_SellerName",
                "emailNotification": {
                  "emailSubject": "Please sign the document(s)",
                  "emailBody": "Hello,\r\n\r\nYour consultant has sent you a new document to view and sign.  Please click on the View Documents link below, review the content, and sign the document.  If you have any questions, please contact your consultant.\r\n\r\nThank you!",
                  "supportedLanguage": "en"
                }
              }
            ],
            "certifiedDeliveries": []
          },
          "customFields": {
            "textCustomFields": [
              {
                "name": "EnvelopeInfo",
                "value": "my data"
              }
            ]
          }
        }
      ],
      "document": {
        "documentId": "1",
        "name": "C:\\Temp\\Docusign\\TestTabPlacement.docx",
        "fileExtension": ".docx",
        "documentFields": [
          {
            "name": "DMSID",
            "value": "1"
          }
        ],
        "documentBase64": "[Document:Base64Array]"
      }
    }
  ],
  "status": "sent",
  "emailSubject": "Here is the subject"
}

And here is the summary:
 05/15/2017 11:32:12 - INFO - Envelope summary: {
  "envelopeId": "1e8408d2-c5e4-4c95-95bf-2055cdd9f8ad",
  "uri": "/envelopes/1e8408d2-c5e4-4c95-95bf-2055cdd9f8ad",
  "statusDateTime": "2017-05-15T15:32:12.6503852Z",
  "status": "sent"
}

A: DocuSign automatically converts word documents into PDFs when the document is uploaded. Looks like the field codes in the Word Document are no longer present in the PDF document. So DocuSign is unable to place Tags using the AnchorString.
Troubleshooting Tip : Try saving your word document as PDF and see if your Anchor String is still present in the document.

A: Your template may have "whole words" set for the anchor strings. Try separating the anchor strings from adjacent characters other than whitespace.


text:
Q: Using Meteor publish-with-relations package where each join cannot use the _id field I am working to solve a problem not dissimilar to the discussion present at the following blog post. This is wishing to publish two related data sets in Meteor, with a 'reactive join' on the server side.
https://www.discovermeteor.com/blog/reactive-joins-in-meteor/
Unfortunately for me, however, the related collection I wish to join to, will not be joined using the "_id" field, but using another field. Normally in mongo and meteor I would create a 'filter' block where I could specify this query. However, as far as I can tell in the PWR package, there is an implicit assumption to join on '_id'.
If you review the example given on the 'publish-with-relations' github page (see below) you can see that both posts and comments are being joined to the Meteor.users '_id' field. But what if we needed to join to the Meteor.users 'address' field ?
https://github.com/svasva/meteor-publish-with-relations
In the short term I have specified my query 'upside down' (as luckily I m able to use the _id field when doing a reverse join), but I suspect this will result in an inefficient query as the datasets grow, so would rather be able to do a join in the direction planned.
The two collections we are joining can be thought of as like a conversation topic/header record, and a conversation message collection (i.e. one entry in the collection for each message in the conversation).
The conversation topic in my solution is using the _id field to join, the conversation messages have a "conversationKey" field to join with.
The following call works, but this is querying from the messages to the conversation, instead of vice versa, which would be more natural.
Meteor.publishWithRelations({
  handle: this,
  collection: conversationMessages,
  filter: { "conversationKey" : requestedKey },
  options : {sort: {msgTime: -1}},
  mappings: [{
    //reverse: true,
    key: 'conversationKey',
    collection: conversationTopics,
    filter: { startTime: { $gt : (new Date().getTime() - aLongTimeAgo ) }  },
    options: {
      sort: { createdAt: -1 }
    },
  }]
});

A: Can you do a join without an _id?
No, not with PWR. Joining with a foreign key which is the id in another table/collection is nearly always how relational data is queried. PWR is making that assumption to reduce the complexity of an already tricky implementation.
How can this publish be improved?
You don't actually need a reactive join here because one query does not depend on the result of another. It would if each conversation topic held an array of conversation message ids. Because both collections can be queried independently, you can return an array of cursors instead:
Meteor.publish('conversations', function(requestedKey) {
  check(requestedKey, String);
  var aLongTimeAgo = 864000000;
  var filter = {startTime: {$gt: new Date().getTime() - aLongTimeAgo}};

  return [
    conversationMessages.find({conversationKey: requestedKey}),
    conversationTopics.find(requestedKey, {filter: filter})
  ];
});

Notes

*

*Sorting in your publish function isn't useful unless you are using a limit.

*Be sure to use a forked version of PWR like this one which includes Tom's memory leak fix.

*Instead of conversationKey I would call it conversationTopicId to be more clear.

A: I think this could be now much easier solved with the reactive-publish package (I am one of authors). You can make any query now inside an autorun and then use the results of that to publish the query you want to push to the client. I would write you an example code, but I do not really understand what exactly do you need. For example, you mention you would like to limit topics, but you do not explain why would they be limited if you are providing requestedKey which is an ID of a document anyway? So only one result is available?