text:
Q: Android TextView avoid being out of view I create a TextView programmatically and at a random position. The problem is: If the text is long enough (e.g. "yellow") the TextView is out of range.
My code
private TextView createField(int textColor, String text){
    int width = Random(10, 500);
    int height = Random(10, 500);
    TextView valueTV = new TextView(this);
    valueTV.setText(text);
    valueTV.setTextColor(textColor);
    valueTV.setTextSize(25);
    valueTV.setTypeface(null, Typeface.BOLD);
    valueTV.setSingleLine(true);
    valueTV.setMaxLines(1);

    LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    llp.setMargins(width, height, 50, 50); // llp.setMargins(left, top, right, bottom);
    valueTV.setLayoutParams(llp);

    return valueTV;
}

How can I achieve that if the text is to long for the screen the TextView is automatically moved to the left?

A: If your going to add views dynamically, first you need to get the width and height of current device screen. Use the following code to get width of the screen:
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int screenWidth = displayMetrics.widthPixels;

Then, calculate every times to add view with remaining space available in total width in single row. My suggestion is please use each separate layout for every row.
I hope this will help you.


text:
Q: Not getting emails from php code The form and the PHP code are working fine, but the only problem I am having with this is that it will not send an email to me nor to the person signing up. Please if you could look at the codes to see what I am doing wrong.
Thanks in advance.
This the HTML.

<form action="formprocess.php" method="post">

  <fieldset class="first">

Welcome to the SBOCC Questions & Comments Page.

Please fill out the form below with your question(s) or comment(s)

  so that you may receive an answer. Shalom (Peace). BLESS THE COMFORTER.

  Your Name:
  (Required)
  <input name="name" />

  Your Email:
  (Required)
  <input name="email" />

  Questions/Comments:
  <textarea name="speak"></textarea>
  </fieldset>

  <fieldset>
  <input class="btn" name="submit" type="submit" value="Send Email" />
  <input class="btn" name="reset" type="reset" value="Clear Form" />
  </fieldset>

  <fieldset class="second">

Would you like to be added to our mailing list?

  <input class="ckbox" type="checkbox" name="mailing" value="yes" checked="yes" /> Yes
  <input class="ckbox" type="checkbox" name="mailing" value="no" /> No
  </fieldset>

And these are the PHP codes:
<?php

$to = "shealtielyisrael@gmail.com";
$from = $_REQUEST['email'];
$name = $_REQUEST['name'];
$headers = "From: $from";
$subject = "Contact The SBOCC";

$fields = array();
$fields{"name"} = "name";
$fields{"email"} = "email";
$fields{"speak"} = "questions/comments";
$fields{"mailing"} = "newsletter";

$body = "We have received the following information:\n\n"; foreach($fields as $a => $b)
{$body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }

$headers2 = "From: noreply@thesbocc.com";
$subject2 = "Thank you for contacting The SBOCC";
$autoreply = "Thank you for contacting us. Your question(s)/comment(s) has been     received. Shalom. Bless the comforter";

if($name == '') {print "You have not entered a name, please go back and try again";}
else {
 if($from == '') {print "You have not entered an email, please go back and try      again";}
else {
$send = mail($to, $subject, $body, $headers);
$send2 = mail($from, $subject2, $autoreply, $headers2);
if($send)
{header( "Location: thankyou.html");}
else
{print "We encountered an error sending your mail, please notify shealtielyisrael@gmail.com";}
}
}

?>

A: Dear if you are working on a local server just like XAMPP or APPSERV or whatsoever you have to install mail server on you local machine
and if you are working on a real host server make sure the the php setting in the server allow you to use mail function cuse many server has stop this function.
so i recommend you to use smtp to send mail take a look here
http://email.about.com/od/emailprogrammingtips/qt/PHP_Email_SMTP_Authentication.htm
and there is a supper powerful library to send email PHPMailer
https://code.google.com/a/apache-extras.org/p/phpmailer/

redpajama_set_name: RedPajamaStackExchange


text:
Q: C fread() magically reading dynamically allocated struct members, how? This is a test program that I have written for a larger project that I am working on. It has to do with writing struct data to disk with fwrite() and then reading that data back with fread(). One member of the struct is dynamically allocated.
First, here is my code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define STRING_LEN  128

struct Person {
    int age;
    char *name;
};

int main(int argc, const char *argv[])
{
    struct Person *person = calloc(1, sizeof(struct Person));
    person->age = 22;
    person->name = calloc(STRING_LEN, sizeof(char));

    char *name = "Name that is really, really, really, really, really, really, long.";
    strncpy(person->name, name, STRING_LEN);

    FILE *out_file = fopen("rw.out", "w");
    fwrite(person, sizeof(struct Person), 1, out_file);
    fclose(out_file);

    FILE *in_file = fopen("rw.out", "r");
    struct Person *person_read = calloc(1, sizeof(struct Person));
    fread(person_read, sizeof(struct Person), 1, in_file);
    fclose(in_file);

    printf("%d %s\n", person_read->age, person_read->name);

    free(person->name);
    free(person);
    free(person_read);

    return 0;
}

And the outpout
22 Name that is really, really, really, really, really, really, long.

My question is, why is this working? Shouldn't fwrite() only write the address that 'name' contains (i.e., the address of the beginning of the string)? That is, I am passing in sizeof(struct Person) to fwrite() and yet it is writing the string the 'name' is pointing to.
Even more confusing to me is the behavior of fread(). Again, if I am passing sizeof(struct Person), how is the actual value of 'name' being read? How is the memory for it being allocated?
My previous understanding of how to use fwrite() + fread() was that I would have to "manually" write the data that 'name' was pointing to, "manually" read that data, and then copy that string after allocating memory for both the structure and the 'name' member. In other words, I would have to traverse any pointers myself, write the data, and then read that data back in the same order.
EDIT: Dan and the others are correct. I have looked at the output file with xxd:
0000000: 1600 0000 0000 0000 30a0 d900 0000 0000  ........0.......

If I print out the address that 'name' contains before writing and after reading it is the same (0xd9a030), which matches the output from xxd.

A: Both person->name and person_read->name wind up pointing to the same memory location.  Since you didn't deallocate person->name before reading the file back in, the pointer value in person_read->name is still valid.
If you had deallocated person->name or read the file from a different program, the pointer value would no longer be valid, and attempting to reference it would invoke undefined behavior - you would either have printed out gibberish or gotten a segfault.

A: You are writing the data in the struct, which is an int followed by a pointer to a string. It's just data like anything else, and you know how long it is because the struct is fixed length - an int plus a pointer. You read the same pointer to the same name string as the original. The name itself is neither written nor read.

A: The *name pointer remains valid throughout the fwrite and fread calls, which is seemingly a fluke to you. If you free(person->name) before printf you would get the result or error your were expecting.


text:
Q: iTunes song queue My app is controlling iTunes via scripting bridge.
Other apps are able to choose a range of songs, and play them in order without having to create a playlist. I have searched the web for examples and red the iTunes.h file a dozen times, but I didn't find a solution.
Can maybe someone of you help me?
Look at the iTunes header file here:
iTunes.h
Thanks!

A: With iTunes 10 it's simply not possible without creating a playlist. The function(which is a known from great other music players) you are talking about is coming in iTunes 11, which will be out in October.
It's called next.
I think just wait a few weeks and then the details will be out how to do it programmatically

A: You can keep track of the songs in your own app and the when you start playing the first song, set a timer to fire at the finishTime of the track you started playing. When the timer fires start playing the next song and repeat the timer. If there are no songs to play end with a stop command to iTunes.
@property (retain, nonatomic) NSMutableArray *songsToPlay;

- (void)playNext:(NSTimer *)aTimer {

    if (songsToPlay.count) {
        iTunesTrack *track = songsToPlay.firstObject;
        [track playOnce:YES];
        [NSTimer scheduledTimerWithTimeInterval:track.finish - 1.0 target:self selector:@selector(playNext:) userInfo:nil repeats:NO];
        [songsToPlay removeObjectAtIndex:0];
    }
    else {
        [iTunes stop];
    }
}

Somewhere you prime songToPlay with iTunesTrack songs and then call [self playNext:nil].


text:
Q: SignalR LongPolling: The request filtering module is configured to deny a request where the query string is too long I have a problem with SignalR LongPolling. After an issue with the group management in long polling that has been solved (I think) thanks to the workaround @dfowler told me, things stop working eventually because the polling stop working.
The app works well, but after a some time of inactivity, this start to happen:

HTTP Error 404.15 - Not Found The request filtering module is
  configured to deny a request where the query string is too long.

I can see that the URL is in fact very long:

https://localhost/MyTestWeb1.PriceIsRight.Web/updates/poll?transport=longPolling&connectionToken=Wi8JkSIcjGdvYVBxzJ3CZclkwYL7d2peZzobOJABzsPzirhKHgTI2K%2BQh%2FNbfGv3L3iGoIhp8HxbZnptzuynccLQq9dbaHIHy0OlshLGHf%2Be%2BxPxV%2F3NoP1XNRVLtSJs&groupsToken=%2F6rKIYLag7J94szTAkdB2z9201%2BQ3eK5y9HjYwSBmTAp77FO6%2FYf5TcnzcYX2mieQ%2FN16z7A9FL8jn%2Bhbz8K5q%2BAjKE5z%2BqixE6oGO9JcsJcOzWYSDMG25Y96Bw6AyoRFEfBjWC0k1xsaTIVArKoWvw8rvqua7R8bPX3UQcvhGxa1ODABLtPch2NW5QGWbRnomPnqJwm9cO9elfQeh5Yt9Toneu8f4JFSXcub0uH78RgGIoc0bIABsAIPJa5lBOrIwAFe8LZKKx7FWRPzssql6GBN9VJ7KZW4sEEpPS4OpIMgcLlZ4UbpfOLbb%2F%2BBRlIvGRIS4PXRQufozELnh7E3JkWNH7tCJy2fcuc8nOKA3w1cyQU9RVlOf7Y6zyY4GNuuIbkEmq8SN9xfrF%2B0oTQ5FY%2Fq%2BdqPdm2heVBY6pH0liKwMjRo%2BTEtiU9zzTjXFsXhCdnGjdNeVzONKIpXN1q1Xhu%2FS7JLVYOZN2ITbD9BUIH3q%2FRPgKkevZSpInUXa1CDueNlR1iWJYP7wJKY%2FfheR%2BORzwu%2BmK1RwgGTZkG8rnT%2F1jIeu23SBBURajqcXPgw6BQJuAL9q8JQx8ZTKA3odt3ja34ROCAvEyXrtG4urIv75HMQRkhrpRUPm6s6P44ZPA31cKrWq1CrdtP2Ge%2BtmbXu5N0LBdE3FHxdw797CFHkzvc9iTMFsbCunFYSU%2B2%2BLVGRGzsLyvubFJ87FYLhN1ir8MPFXyzisJ2pFhPLRmGNWgF78IirGyePgUvI40%2Fiij4PkVlQ43Q2IkkR7cUTerwQKTHVK2upKSVbHG4jIE2c8u2%2FDmOKmV%2Bt2B35fYJxnu0f8xx9%2FDH%2BWSpxYJ9ZmSXnTtF7iqtWS18pxyHoUyS2O3BYQxCwvo7JOI%2F4hBuWeZn09N%2BzC3V%2BhFp7JW8LWWB%2FfLhAWTMfRYpTE%2FfVfwRsGYQBaJwc5x7Q%2BXvwTqlQAni5clfyFyBP2oMZXV9Y84Tt2hLfshcFiV1Il7SaTgM8Q2GdTw3EKbMrIQbldAz06TGKdtYJ%2BFyVQVOB4WJ70Kfilnjh9KI94%2FGU%2BPUSdBUV9VfOKXpUokISalXGyCbT6EgjG4WtS%2BCu4K6gALrYHly5c1CVD7Gu8hM5FwRD%2B0J%2BkYTn2oSRs7cSULYA6w5wB2BSgyPXJ6FvxYACqnD4pD8Bt6SGBYTPkpn6nBfwhG%2FKC9y%2FO4NWm%2Ba9I%2F4gAUVPfr6GNZVJFAL5DRN0Gf9bhSTPQtnWzoXqW1KjXHynFcMO8sH3NR30VDjr1oB2ru760Ur7ruVf4PQZQej0Dva2Q%2FV%2Btwkft352H%2F59%2FuJRViH8BgM%2B%2FNe3VYPFLsrc3q%2Fbd6i%2FA2uIKuHaqKdWtU8SxDXeO4jwfXsoqvuc5m4yXghtzFByDNuuz%2FRCsBP6768HxFUnb1Mx4CjrtKV7ci70DSRr6A4YPyTbEF4YaTPnz7f85pMuPDMGVIR7WIA4fwhte%2BemUz2rpQkhP0xJ7Cx30CwKAgBl5aiJa8htm7UX9ApWQRaC22GyuUoMEyDVrcd6geMGHAFuj2czd3TQKNgnCzyNBfYYdUrcILKkKtcOXmhMeydPmk%2FQUkR30oNl9TB1hIm7q6qVskCwCaPSN5m04Thj2MAIzHGuG18zbHxB6lqBwbXM9FyKmFeAiVNPhY3WTvC5wPEatIMzXBNJ4S6m5rUppcoQLFseBVPRYB%2BfMRqDaU%2FRbWdWxlPHsGkQxVq&messageId=d-B836F05A-B%2C52%7Cb%2CC%7Cc%2C0%7Cf%2C3A%7Cg%2C38%7Ch%2C32%7Ci%2C36%7Cj%2C36%7Ck%2C38%7Cl%2C38%7Cm%2C3E%7Cn%2C34%7Co%2C3E%7Cp%2C0&param=true&tid=10&_=1390238814537

The reconnection also fails, and then it disconnects:
[17:38:08 GMT+0000 (GMT Standard Time)] SignalR: Couldn't reconnect within the configured timeout (30000ms), disconnecting. jquery.signalR-2.0.1.js:77
[17:38:08 GMT+0000 (GMT Standard Time)] SignalR: Stopping connection.

If I refresh the page, all start to work well again. Then when I check a the poll request, the URL looks much shorter:

https://localhost/MyTestWeb1.PriceIsRight.Web/updates/poll?transport=longPolling&connectionToken=z4yGjBDaK8hh9eOfWPxXy4%2BpkC%2BDTCtZjlsi%2BDM0Z3JJofNE0E7BX%2B2QtIn0n0mzCsXyk0Tna3%2FCYRaKoSliA6uFNraONdleoKJgoq1chUZSRf5qHs5RazfXrQFw6ifQ&groupsToken=z8QTCuB6CWlSFs76g62l5odbEtSW3Rv1a46podyAeNBRjlIrCDNcgEDoRhPpiOE1aRoOiy7x%2B3wFicWhHhK4FCTKKk8We%2BzIvnERITIhstdJ3e5yOt8veR2aWcLhyOsPf8i5zoeRLwrizj0QZlplP1GgmbjO9wFJG4ySe2TKddGRFfFE4Qfy%2F03OBD4sL8mOC8kBMAWNE6oTvaJiJJ3QMKvtUBjFeg%2BorNvl26EwaG5zE5laJZkwTha7BHHnysOPvxFXFKE6yVoad9zifiHQDj%2Fp8TYQ3DbSFKsaSynyEYlU4YCg4TzgyrXGvhUPGZ4EYlTwBa7RoPsqOwspeIziDEBk4OW9sb8LtTdOXJXTVZXFoZ34XOdgqcZVHHCJvESczZE5AmsLoCts4Xq58ld6f9PDHdxmtTUkAEj0CcS9Bqg%3D&messageId=d-B836F05A-q%2CA%7Cr%2C3%7Cs%2C0%7Cv%2C45%7Cw%2C9&param=true&tid=0&_=1390239846281

Is there any reason why the URL could grow that way?
Thanks.
PS: There is a formatting issue in this post. I don't know where =1390238814537"> and =1390239846281"> at the beginning of the pasted URLs are coming from.

A: As @halter73 pointed out, the problem are the groups.

This is being caused by the groupsToken which expands as you add the
  client to more groups.


text:
Q: TabBar with Phonegap not working on every page I'm using PhoneGap with the NativeControls/TabBar plugin and it's working for the first page. However, when I press to navigate to a different page the plugin stops being effective.
On the index.html page:
    <script>
        document.addEventListener("deviceready", function() {
            nativeControls = window.plugins.nativeControls;
            nativeControls.createTabBar();
            console.log("TabBar initiated");
            nativeControls.createTabBarItem(
              "about",
              "About",
              "/www/img/20-gear2.png",
              {"onSelect": function() {
                window.location.href="about.html";
              }}
            );
            nativeControls.createTabBarItem(
              "guide",
              "Guide",
              "/www/img/76-baby.png",
              {"onSelect": function() {
                window.location.href="grid.html";
              }}
            );
            nativeControls.createTabBarItem(
              "ideas",
              "Ideas",
              "/www/img/27-planet.png",
              {"onSelect": function() {
                window.location.href="ideas.html";
              }}
            );
            nativeControls.showTabBar();
            nativeControls.showTabBarItems("about", "guide", "ideas");
        }, false)
    </script>

Pressing any of the buttons takes it to the corresponding HTML page with the correct tab selected. However, on this page, none of the tabs continue to work - pressing the tab button simply highlights it but doesn't relocate the view to the page.
I have tried pasting this same script onto the header of the other pages but there is no result there either.

A: A previous solution I have used for this was to load all the content via AJAX rather than loading additional .html pages. I've included some snippets below:
In index.html, I have a DIV designated to receive the HTML for each page
<div id="ajaxCont"> </div>

Also within index.html, I have the following function declared:
function loadPage(url, onleave, onenter, title) {

   // If onleave function specified
   if (onleave) {
      onleave();
   }

   var xmlhttp = new XMLHttpRequest();

   // Callback function when XMLHttpRequest is ready
   xmlhttp.onreadystatechange=function(){
      if(xmlhttp.readyState == 4){
         if (xmlhttp.status == 200 || xmlhttp.status == 0) {
            document.getElementById('ajaxCont').innerHTML = xmlhttp.responseText;

            // If onenter function specified
            if (onenter) {
                onenter();
            }
         }else {
            document.getElementById('ajaxCont').innerHTML = "Error loading page " + url;
         }
      }
   };

   xmlhttp.open("GET", url , true);
   xmlhttp.send();
}

Then, each tabbar item can be created like so:
tabBar.createItem("contact", "Contact", "/www/img/734-chat.png", {
    onSelect: function() {
       loadPage("contact.html", null, null, "Contact");
    }
});


text:
Q: How do I delete files in hdfs directory after reading it using scala? I use fileStream to read files in the hdfs directory from Spark (streaming context). In case my Spark shut down and starts after some time, I would like to read the new files in the directory. I don't want to read old files in the directory which was already read and processed by Spark. I am trying to avoid duplicates here.
val lines = ssc.fileStream[LongWritable, Text, TextInputFormat]("/home/File")

any code snippets to help?

A: You can use the FileSystem API:
import org.apache.hadoop.fs.{FileSystem, Path}

val fs = FileSystem.get(sc.hadoopConfiguration)

val outPutPath = new Path("/abc")

if (fs.exists(outPutPath))
  fs.delete(outPutPath, true)

A: fileStream already handles that for you - from its Scaladoc:

Create an input stream that monitors a Hadoop-compatible filesystem for new files and reads them using the given key-value types and input format.

This means that fileStream would only load new files (created after streaming context was started), any files that already existed in the folder before you started your streaming application would be ignored.


text:
Q: Import Activity Failed to All Subscribers List We are running an automation process that syncs the email address of the All Subscribers List to the contact email address in Sales Cloud. This automation is run daily.
However last night the data extension used for updating the All Subscribers List was empty because the email addresses were all synced previously. So the import activity failed.
Is there a way to prevent this error? If the data extension is empty then don't run import activity?

A: I had the same problem and solved it by adding a UNION to the end of the email-sync query, forcing a constant user into the update data extension:
SELECT
b.SubscriberKey
,b.EmailAddress
,a.Status
FROM _Subscribers a
LEFT JOIN [All Customers DE] b ON a.SubscriberKey = b.SubscriberKey
WHERE a.EmailAddress != b.EmailAddress

UNION

SELECT
c.SubscriberKey
,c.EmailAddress
,c.Status
FROM _Subscribers
WHERE c.SubscriberKey = 'TEST_SUBSCRIBER_01'

The top half of the SQL Query Activity selects all customers where the EmailAddress has changed, while the second half pick up my test subscriber record (TEST_SUBSCRIBER_01) and updates itself, with itself.
This ensures there is always 1 record in the import process.


text:
Q: XmlSerializer not observing default namespace? I have this class:
 [Serializable]
    public class Element
    {
        [XmlAttribute("maxOccurs")]
        public int MaxOccurs{get; set;}
        [XmlAttribute("minOccurs")]
        public int MinOCcurs{get; set;}
        [XmlAttribute("name")]
        public string Name{get; set;}
        [XmlAttribute("nillable")]
        public bool IsNillable{get; set;}
        [XmlAttribute("type")]
        public string Type{get; set;}

    }

I have created an XmlSerializer like so:
XmlSerializer serializer = new XmlSerializer(elementType, "http://www.w3.org/2001/XMLSchema");

When I attemp to deserialize this sample XML
http://www.w3.org/2001/XMLSchema\" />
I get the following exception message:
{"http://www.w3.org/2001/XMLSchema'> was not expected."}
What did I miss ?
TIA,

A: Check out the XmlSerializer constructor -
http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.xmlserializer.aspx
You will want to pass in "your" namespace, not the w3c namespace.


text:
Q: Send numerical data via TCP/IP ethernet So I know many of you will advise against this but I want to send floats via TCP/IP to a TCP Server running on a SoC (Zynq7020, with the server on the Arm A9). I want to get this working as a simple proof of concept before moving onto using UDP which is probably more suited to sending raw data. I am having trouble converting the float into a char array on the client side and back again on the server. Although I am not sure this is the best approach.
I am using  the WinSocket API, and am sending the data as so (although I am not sure this is correct or efficient!):
char * sendbuf;
sendbuf = reinterpret_cast<char *>(f);
iResult = send(ConnectSocket, sendbuf, (int) strlen(sendbuf), 0);

Basically is this correct, and without using UDP, what is the best way to floats via TCP. I guess decoding will essentially be reverse engineering the method used to send the float as char*.
---Below is a complete working example of sending floats via WinSock to a Zynq ARM cpu LwIP--
Host Windows 7 (htonf maybe used, but I am on x86 so there are no endian issues):
int FPGA_Accelerator::sendFloat(float* f) {
    char *sendbuf;
    int iResult;
    char arr[4];

    *(float*)arr= *f;

    printf("Sending "); printf(arr); printf("\n");
    iResult = send(connection, arr, (int) sizeof(arr), 0);
    if (iResult == SOCKET_ERROR) {
    printf("send failed: %d\n", WSAGetLastError());
    closesocket(connection);
    WSACleanup();
    return -1;
    }

    printf("Bytes Sent: %ld\n", iResult);

    return 1;
};

Zynq code. Where in the recv_callback I call the function parse_input(p->payload)
void parse_input(char* input){
    xil_printf("Input : ");
    xil_printf(input);
    xil_printf("\n\r");

u32 d = *(u32*)input;
union v{
    float f;
    u32 u;
};
union v val;
val.u = d;

printf("Value u32 = %i \n\r",val.u);
printf("Value float = %f \n\r",val.f);

}

A: It doesn't matter what you send is float or string. You send data as array of bytes and receive them on the other side and interpret them as you wish. So in your case, you should send a float which is 4 bytes long. You should send 4 bytes as array of bytes and on the other side cast it to a float and use it.
iResult = send(ConnectSocket, (char*)&f, (int) sizeof(float), 0);

in receiver part:
char *receivebuf;
// read data from socket
float *receivedFloat = (float*)receivebuf;

Using UDP is easier, because you don't have to check connection and success of sent data. You just send it without connecting to the server.

A: This is not a question of TCP vs UDP.
First, to send a single float value, you don't reinterpret it as an address, but take the address of the float
iResult = send(ConnectSocket, &f, (int) sizeof(f), 0);

But this works only, if you have the same architecture on both ends of the communication.
To make it independent of architecture issues, you must use some External Data Representation for the transmission from one system to another. Alternatively, you can also use a text based protocol and convert the float value to a string.

A: This is incorrect. As its name suggests, strlen is for strings. You need to pass the actual size of the buffer to send.


text:
Q: Java 8: Merge two list of objects by id I have two list of objects. Person and PurchaseOrder.
Person has a name, age, id, etc.
PurchaseOrder has a personId (FK Person id), timestamp, amount, etc.
Using Java 8, how do I get the average of purchase order amount where person's age < 18?
List<Person> personList = Arrays.asList(person);
List<PurchaseOrder> purchaseOrderList = Arrays.asList(purchaseOrders);

List<Person> underAgePerson = personList.stream()
        .filter(p -> p.getAge < 18)
        .collect(Collectors.toList());

// TODO:
purchaseOrderList.stream()
        .forEach(o1 -> underAgePerson.stream()
                .filter(o2 -> o1.getPersonId() == o2.getId()));

purchaseOrderList.stream().mapToDouble(o2 -> Long.valueOf(o2.getAmount())).average();

A: I would create a set of Person id who are < 18 then compute the average of their purchases :
List<Person> persons = Arrays.asList(
    new Person(1, 18), //(id, age)
    new Person(2, 24),
    new Person(3, 14),
    new Person(4, 10)
);

//Same person can place multiple purchases.
List<PurchaseOrder> purchaseOrders = Arrays.asList(
    new PurchaseOrder(1, 24), //(person id, purchase amount)
    new PurchaseOrder(1, 40),
    new PurchaseOrder(2, 10),
    new PurchaseOrder(2, 24),
    new PurchaseOrder(3, 23),
    new PurchaseOrder(3, 45),
    new PurchaseOrder(4, 68),
    new PurchaseOrder(4, 12),
    new PurchaseOrder(4, 23)
);

Set<Integer> personIds = persons
    .stream()
    .filter(person -> person.getAge() < 18)
    .map(Person::getId)
    .collect(Collectors.toSet());

OptionalDouble average = purchaseOrders
    .stream()
    .filter(purchaseOrder -> personIds.contains(purchaseOrder.getPersonId()))
    .mapToInt(PurchaseOrder::getAmount)
    .average();

A: I would take the set of over 18 first.
Set<String> over18 = personList.stream()
                               .filter(p -> p.getAge < 18)
                               .map(Person::getId)
                               .collect(Collectors.toSet());
List<PurchaseOrder> over18orders = purchaseOrderList.stream()
                                          .filter(o -> over18.contains(o.getId())
                                          .collect(Collectors.toList());
double sum = over18Orders.stream().mapToDouble(o -> o.getValue()).sum();
double average = sum / over18.size(); // average per person.


text:
Q: loop over array of numbers doesn't square the numbers I'm trying to get my code for class to produce the desired results, but what I've got here doesn't do what I'd like.
This is the code that I'm testing:
const sampleArray = [
  876, 755, 661, 24532, 758, 450,
  302, 2043, 712, 71, 456, 21, 398,
  339, 882, 9, 179, 535, 940, 12
];

let myFunction = function() {
  let squareNumbers = [];

  for (let counter4 = 0; counter4 < sampleArray.length; counter4++) {
    if (Math.pow(sampleArray[counter4], 2)) {
      squareNumbers.push(sampleArray[counter4])
    }
  }

  console.log(squareNumbers);
}

myFunction();

It shows the items in the array, but doesn't square them and I'm at a loss as to why. I've already got a solution a different way, but I feel like there should be something better that I could do

A: Okay, i see what you are after.  How about this:
// unchanged
const sampleArray = [876, 755, 661, 24532, 758, 450, 302, 2043, 712, 71, 456, 21, 398, 339, 882, 9, 179, 535, 940, 12];

// unchanged
let squareNumbers = [];

// unchanged
let myFunction = function() {

  // unchanged
  for (let counter4 = 0; counter4 < sampleArray.length; counter4++) {

    // minor change...
    // Math.pow(sampleArray[counter4], 2) squares the number
    // but it only returns the number.
    // If used within an "if" is returns a form of "true".
    var mysquare = Math.pow(sampleArray[counter4], 2);

    // this is not required..it's just so you can see "the return"
    console.log("the squre of " + sampleArray[counter4] + " is " + mysquare);

    // To "put it in the array" you must push "the return" onto the array.
    squareNumbers.push(mysquare)
  }
}

// unchanged
myFunction();
console.log('my squareNumbers:');
console.log(squareNumbers);

which produces this:
the squre of 876 is 767376
the squre of 876 is 767376
the squre of 755 is 570025
the squre of 661 is 436921
the squre of 24532 is 601819024
the squre of 758 is 574564
the squre of 450 is 202500
the squre of 302 is 91204
the squre of 2043 is 4173849
the squre of 712 is 506944
the squre of 71 is 5041
the squre of 456 is 207936
the squre of 21 is 441
the squre of 398 is 158404
the squre of 339 is 114921
the squre of 882 is 777924
the squre of 9 is 81
the squre of 179 is
the squre of 535 is
the squre of 940 is
the squre of 12 is 144
my squareNumbers:
Array(20) [ 767376, 570025, 436921, 601819024, 574564, 202500, 91204, 4173849, 506944, 5041, … ]


text:
Q: Prevent users from sharing private keys in cryptocurrency related communities Being an active member of the Ethereum Stack Exchange community, I stumble upon many threads started by new users containing sensitive information about their digital wallets - private keys and 12-words mnemonics.
Here's just two examples I found in my recent revision history:

*

*How to generate account address from pivate key?

*Unknown account error while deploying dapp on Ropsten testnet
The community always react quickly to remove the private information from the question description, but it's still available in the revision history. Although most likely those private keys map to empty wallets used for development, you can never know.

*

*Is there a way for the community moderators to completely erase this type of information from the revision history?

*To prevent future mistakes, is there a way for the question editors in Bitcoin, Ethereum etc to show a warning whenever a 64-char word is typed? That it, something like "Heads up! You might've pasted your private key. It's not safe to do that, just use a placeholder". I guess it's harder to validate against 12-word passphrases, but there could be a warning whenever the word "mnemonic" or "passphrase" is typed.

A: Redactions are possible. The UI is a pain so discussing a workflow that works with your moderators is a great idea.
This is no different from any other personally identifying information - as if you'd posted your private key elsewhere or password in my opinion.
The latter is probably unlikely to happen, especially as something unique to a few sites. While there's blocklists of some things, implimenting that specifically that is going to be some painful regex.


text:
Q: SWFUpload (uploadify) upload >2GB+ Issue, flash questions about integers I was trying to upload files via Uploadify, which is using SWFUpload. Then I got some problems when uploading files >4GB+, so started digging. I ended up with result that the problem is in SWFUpload. (I am not about to use this for my large files to upload, just the curious question)
It looks like SWFUpload has its limit at 2147483647 bytes. But I could sucessfully upload a 2.9GB file. I've contacted the developer and he told me, that I should try to compile it with newer Flash player 10, 11 or 11.7 (SWFUpload is compiled under Flash Player 9) (but he does not remember more, because stopped developing this plugin years ago and he is confused how I could upload 2.9GB file). I've downloaded everything compiled it under 32bit windows and newest version of Flash Player, nothing changed. Variables are :Number, so it should take number bigger than 2147483647, but no success.
(Please note: I dont know much about Flash)
So the question is: Where does this limit come from? Is this 32/64bit compiler, or 32/64bit Flash Player? or 32/64bit browser? Are there even x64 browsers?

A: If you're doing files larger than 2GB you should break up the data byte array into multiple uploads and re-assemble the files on the server. Even commercial upload services like dropbox limit uploads to 2GB due to inconsistent ability for all users to go over that size.
You can check the memory limit imposed by the browser: https://superuser.com/questions/354725/how-do-i-change-the-amount-of-memory-flash-can-use-in-chrome
Large uploads can all be accomplished with forms/js now. Particularly JQueryForm will help you out.
Limitation could be from anywhere:
Memory available to the flash plugin as limited by the browser encapsulating it (for security reasons).
Memory available to the client machine.
Memory available on the server.
Server Misconfiguration.
The initial version of as3 used uint instead of number thus maxed out at 4BG for the file reference object because numbers larger than that were unrepresentable.
Timeout: the server simply times out the execution due to settings.


text:
Q: Detectar F5 o recargar y enviarlo siempre a home. JSF Necesito saber si hay alguna manera de identificar cuando un usuario hace una recarga de la página mediante f5 o actualizar en el botón del navegador para programar una acción y que este redirija siempre a la pagina de inicio.
Estoy utilizando un phase listener en donde puedo comparar antes de cargar cada pagina el id de la vista y los comparo si son iguales hago una re dirección a la regla de navegación del home.
El problema de este método esta en que no se diferencian cuando hago un actualizar , a cuando se recarga la pagina mediante Ajax , por ejemplo en el paginador de una tabla.
¿Hay alguna opción en la cual pueda identificar si la recarga viene desde ajax o si viene desde f5 o botón actualizar del navegador ?
este es el código de el listener.
Gracias
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

@SuppressWarnings("serial")
public class PostRedirectGetListener implements PhaseListener {
private String previousPage = null;

public PhaseId getPhaseId() {

    return PhaseId.RENDER_RESPONSE;
}

public void beforePhase(PhaseEvent event) {

    String msg = "";
    UIViewRoot viewRoot = FacesContext.getCurrentInstance().getViewRoot();
    String id = viewRoot.getViewId();
    if (previousPage == null) {
        msg = "First page ever";
    } else if (previousPage.equals(id)) {
        msg = "F5 or reload";
        FacesContext facesContext = FacesContext.getCurrentInstance();
        String outcome = "urlHome";
        facesContext.getApplication().getNavigationHandler()
                .handleNavigation(facesContext, null, outcome);
    } else if (FacesContext.getCurrentInstance().isPostback()) {
        msg = "It's a postback";
    } else
        msg = "It's a navigation";
    previousPage = id;
    System.out.println(msg);
}

public void afterPhase(PhaseEvent event) {

}

}

A: En tu vista puedes agregar lo siguiente:
<f:metadata>
   <f:viewAction action="#{f5Detector.checkF5}" onPostBack="true"/>
</f:metadata>

BackEnd
@SessionScoped
@ManagedBean
public class F5Detector {
  private String previousPage = null;

  public void checkF5() {
    String msg = "";
    UIViewRoot viewRoot = FacesContext.getCurrentInstance().getViewRoot();
    String id = viewRoot.getViewId();
    if (previousPage != null && (previousPage.equals(id))) {
       // It's a reload event
    }
    previousPage = id;
  }
}

Lo puedes hacer también mediante javascript, ya que al pulsar F5 se activa el evento event window.onunload().
Incluso puedes intentar con .
<meta http-equiv="refresh" content="30; ,URL=http://redirecciona a ...">


text:
Q: Using Dask parallelizing in xarray to select data I am trying to calculate the hours after sunrise over a data array that has a length of ca. 300k (chunk size ca. 900). The resulted array is a dask.array with no problem using xr.apply_ufunc and astroplan functions. However, it appears to be extremely slow when I use this dask.array for filtering data using xr.where(). Where can I improve it?
Here is my workstream:
from astropy.time import Time
from astroplan import Observer
import astropy.units as u
import xarray as xr
import numpy as np

def cal_sunrise_h(lat, lon, mjd):
    points = Observer(longitude=lon*u.deg, latitude=lat*u.deg, elevation=89*u.km)
    times = Time(mjd, format='mjd')
    sunrise = points.sun_rise_time(times, which="previous")
    hours_after_sunrise = (times-sunrise).sec/3600
    return hours_after_sunrise

# some fake dataset for reproducing the problem
total_len = 300000
chunk_size = 900
mjd = np.linspace(0, 0.1, total_len) + 5.45559e4
latitude = xr.DataArray(np.linspace(-80, 80, total_len), dims='mjd', coords=[mjd])
longitude = xr.DataArray(np.linspace(-180, 180, total_len), dims='mjd', coords=[mjd])
ds = xr.Dataset({'latitude':latitude, 'longitude':longitude}).chunk({'mjd': chunk_size})

# calculate hours after sunrise
hours_after_sunrise = xr.apply_ufunc(cal_sunrise_h, ds.latitude, ds.longitude, ds.mjd,
                                     output_dtypes=[float], dask='parallelized') #dask.array
# make a filter
sunrise_filter = (hours_after_sunrise>5) #dask.array

# mask out with filter
ds.where(sunrise_filter, drop=True) #super slow!

A: astroplan was designed to vectorize over targets observed at single observatories, rather than computing the sun rise/set times at many observatories. The code example you shared will compute the location of the sun total_len independent times, which is a very expensive operation. I'm afraid dask doesn't help with that problem. It would be more efficient to compute the position of the sun at each time using astropy's get_sun function, then compute the sunrise time for each location. You can do this using an algorithm just like astroplan's Observer._horiz_cross method. If you have any trouble implementing this, further support can be found in the #astroplan channel of the astropy slack team.


text:
Q: Operator-overloading is defined as a function but not used as a function Consider the following C++ code such that I took it from "Sololearn". I'm a beginner and I would be grateful if any one could answer. It is on operator-overloading topic.
  class MyClass {
 public:
  int var;
  MyClass() {}
  MyClass(int a)
  : var(a) { }

  MyClass operator+(MyClass &obj) {
   MyClass res;
   res.var= this->var+obj.var;
   return res;
  }
};

When they use it in main environment they use the following code
int main() {
  MyClass obj1(12), obj2(55);
  MyClass res = obj1+obj2;

  cout << res.var;
}

My questions:
Why does MyClass has two constructors? The most important question for me is that  "operator+" has been defined like a function but when we use it in main its usage is not like a function. Why? Another different  question is that is it true to say that the + used in this line  MyClass res = obj1+obj2;  is from the Operator+?

A:
Why does MyClass has two constructors?

Because that's what the person who wrote it wanted. They wanted to make it so that you can provide an initial value if you wanted, and just let it default to zero otherwise.
Unfortunately, they made a mistake, and their default constructor is broken. It should be like this:
MyClass() : var(0) {}

…otherwise the value of var is indeterminate and a program trying to read it has undefined behaviour.
Now you can create an object like this:
MyClass obj;      // uses first constructor

Or like this:
MyClass obj(12);  // uses second constructor

"operator+" has been defined like a function but when we use it in main its usage is not like a function. Why?

Because you can. Because operators are special. C++ is designed this way. To be able to overload/define them they need to be functions, but to be operators they need their own syntax to use.
Note that you can call it like a function if you want to:
MyClass res = obj1.operator+(obj2);

…but you don't want to.

is it true to say that the + used in this line MyClass res = obj1+obj2; is from the Operator+?

Yes.

It would be better to learn C++ from a proper book.


text:
Q: Google Apps script - IN operator for minutes I try to run a sequential code. First update should happen every 15 minutes, the second one always 3 minutes after the first one.
The code below runs every minute.
However, it never works in Google Apps Script. Any idea how to fix it?
I only came up with writing out the in clause to == and or. It does not look straight.
function update_per_1_min() {

var d = new Date();
var m = d.getMinutes();

  var m = 16

  if(m in [1.0,16.0,31.0,46.0]){

    update_0()

  } else if (m in [4,19,34,49]) {

    update_1()
  }
}

A: in checks whether the expression is a property of the object. Arrays have properties like 0 for the first index, 1 for the second index, etc:

const arr = ['foo', 'bar'];
console.log('foo' in arr);
console.log('0' in arr);

Properties are not the same thing as values, of course. It looks like you're trying to check whether the value is contained in the array, in which case you could use .includes (if you were able to use ES6), or indexOf for GAS:
function update_per_1_min() {
  var d = new Date();
  var m = d.getMinutes();
  if([1,16,31,46].indexOf(m) !== -1){
    update_0()
  } else if ([4,19,34,49].indexOf(m) !== -1) {
    update_1()
  }
}

(note that trailing zeros after the . in numbers is meaningless - feel free to leave those out entirely)


text:
Q: Почему Django не выводит изображение через папку static? settings.py:
MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

STATIC_URL = 'static/'

STATIC_ROOT = os.path.join(BASE_DIR, "static/")

STATICFILES_DIRS = [
    BASE_DIR / "main/static"
]

в html шаблоне:
{% load static %}

Две папки static, одна в приложении main, другая в acc, html шаблон из acc.
На сайте изображение не появляется, что делать?

A: при обращении к файлу
{% load static %}

если ты хочешь, чтобы статический файл был расположен в приложении acc, то необходимо, чтобы

*

*приложение было добавлено в файле settings в INSTALLED_APPS

*Файл должен располагаться по адресу/acc/static/acc/media/logotw.png (acc в пути будет встречаться дважды)


text:
Q: How do I load the values from one array, into another array, without changing the memory address of the array receiving the new values? If I do this:
a = []
b = [1, 2, 3]
a = b

a will then refer to b
I want to copy all of the values in b into a without changing any memory address/references.

A: You could push the values without changing the reference from a or b.
var a = [],
    b = [1, 2, 3];

a.push(...b);

A: If you want to populate a in-place, without ever discarding the initial array, then you can simply loop over b and add all the items in a:

var a = []
var b = [1, 2, 3]

var firstA = a; //get a initial element

b.forEach(function(item) {
  this.push(item)
}, a);// <-- pass `a` as the `this` context

console.log("`a` is unchanged", a === firstA);
console.log("`a` is not `b`", a !== b);
console.log(a);

A: let a = b.map(x => x);

The .map() function will create a new array with values generated from the source elements via the passed-in callback function.
As noted in a comment
let a = b.slice();

is pretty much exactly the same.
Basically this saves you the step of
let a = [];

since one brand-new empty array is as good as another. However, if you really have your heart set on using the empty array explicitly initialized, you could use
b.forEach(x, i) { a[i] = x; });

A: A= b.slice(). It will create a shadow copy of element without changing original one. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice


text:
Q: MySQL NDB Cluster and Master Master replication I'm asking this to see whether I'm doing the things are correctly or to get advise what needs to be done.
Thing is I'm trying to run both NDB clustering and Master Master replication to same database.

In here What I'm trying to do is create a db and run both clustering and master master replication in same database.

As eg : I create db called my_db_1 and create user table which has the engine NDBCluster and also
  create a table data_log and change its engine in to INNODB. Put both
  master master configuration and ndb configuration in to my.cnf.
Except this I added replicate_do_table=data_log in my.cnf too.

What I need to know is, is this setup ok to run in production and what issues will be occurred, having this kind of architecture for the system.

A: If I understand you correctly you want some parts of your data in NDB
and a data log in InnoDB. One thing to remember here is that InnoDB
doesn't support Multi-master. So you have to make sure that any updates
of the data_log table is directed to the correct MySQL server.
I think with Group replication it is technically possible to run with
Multi-master for Inno


text:
Q: Time Trigger in Google Apps Script on date and time In Google apps script it is possible to create timetrigger on a specific date and time. Excactly on that moment the trigger fires. Great!
The question is what is the code in apps script of this trigger?
Following code will fire somewhere between 9:00 and 10
 ScriptApp.newTrigger("function")
.timeBased()
.onWeekDay(ScriptApp.WeekDay.MONDAY)
.atHour(9)
.create();

Following code fires somewhere between 9:00 and 10 too.
 ScriptApp.newTrigger("function")
.timeBased()
.onWeekDay(ScriptApp.WeekDay.MONDAY)
.atHour(9)
.nearMinute(12)
.create();

.atMinute does not exist in apps script.
So who knows the code of the manual trigger on specific date and time?

A: Since you want it to be on a specific date and time, you need to use at instead.
Script:
function myFunction() {
  Logger.log(new Date());
}

function trigger() {
  ScriptApp.newTrigger("myFunction")
  .timeBased()
  // month starts at 0 (e.g. Jan - 0, Feb - 1, etc)
  .at(new Date(2022, 1, 19, 0, 15))
  .create();
}

Trigger created:


text:
Q: The potentiality of the electric field Could you please explain using just words why electric the field is potentially? I know the proof using integral:
$$A = \int_{12}q\vec{E}\cdot{d}\vec{r} = qQ\int_{12}\frac{\vec{r}\cdot{d}\vec{r}}{r^3} = qQ\int_{r_1}^{r_2}\frac{dr}{r^2} = qQ\left(\frac{1}{r_1} - \frac{1}{r_2}\right)$$
(so the work depends only on the coordinates of the beginning and the end).
I can hardly understand it and I want to know how to prove it using only words (maybe with simple school math).

A: First you have to ask yourself, for what kind of force you can define a scalar potential. The short answer is a conservative force. Basically, a conservative force is a force for which the work done in moving a particle between any two given points in path independent. From this, it is obvious that for a particle traveling in a closed path, the total work will be zero.
For such a conservative force, you can give some numerical value for the potential at any point. So when you move your particle from point A to point B, the force changes the potential  energy by a given value independent of the path taken.
As a counterexample, take the force of friction. Being a dissipative force (i.e. not a conservative one) you cannot define for it a scalar potential. The potential differences would  not be equal if you take two different paths connecting the same points A and B.
Now lets use a little math to see what conditions must a force $F$ satisfy to be a conservative one:
$$\nabla\times\vec{F}=0$$
$$W=-\oint_c\vec{F}\cdot d\vec{r}$$
$$\vec{F}-\nabla\Phi$$
If your force $F$ satisfies these three conditions, then $F$ is a conservative one. Now, from the gradient theorem it follows that
$$\int_{c[A,B]}\nabla\Phi(\vec{r})\cdot d\vec{r}=\Phi(B)-\Phi(A)$$
In words, the gradient theorem says that line integrals through a irrotational vector field is path independent. So, if you want to use just words you can simply say this: "for any conservative forces, the potential difference depends only on the end points because the work done to move a test particle between said end points is path independent". But focus on the word conservative.

A: Ok, let's consider $\vec{r} \vec{dr}$, it is equal to $|\vec{r}||\vec{dr}|_\vec{r}$ where $|\vec{dr}|_\vec{r}$ is projection of  $\vec{dr}$ on $\vec{r}$. If you draw $\vec{r}$ and a small (remember, you need infinitesimal!) $\vec{dr}$ you will notice that this projection is actual equal to $|\vec{dr}|_\vec{r} = d|\vec{r}|$, so $\vec{r} \vec{dr} = |\vec{r}|d|\vec{r}|$. This is why you change $\vec{r}\vec{dr} = rdr$. No matter what $\vec{dr}$ you choose, while $|\vec{dr}|_\vec{r}$ is the same you get the same value for $\vec{r} \vec{dr}$.
Electric field of a point charge in static case is $\vec{E} = f(r)\vec{r}$, where $f(r)=Q/r^3$, so you see that work $\vec{E} \vec{dr}$ depends only on the change in $|\vec{r}|$ and does not depend on the integration path.

A: Others have provided mathematical explanations, so I'll try an intuitive explanation.
You've probably seen the electric field represented like one of these:

(image source)
At the top of the mountain there is a positive charge, and at the bottom of the valley is a negative charge. A positive test charge in this field experiences a force analogous to a ball rolling downhill.
Notably, at infinity this field converges to a flat plane. This plane is by definition zero potential. Also, any line along the up-down axis will intersect this field at exactly one point. The vertical coordinate of that intersection is the electric potential at that point, measured in volts, analogously to how we measure elevation on the earth's surface in meters. It tells us the work required to move a charge from infinity to that point, per unit charge (thus, volt = joule per coulomb).
Since this is the intuitive explanation I'll skip the math, but if you have an intuitive understanding of what gravity potential means, then by this analogy you can see how the same understanding applies to electric potential as well.

A: If your question is "why is the electric force of a static electric field conservative", it might help you to ask yourself the question "what would happen if the work required to move a charged particle from $r_1$ to $r_2$ would depend on the particluar path the particle travels?".
If this would be true, there would be (at least) two different paths between any two points, say $P_1$ and $P_2$, and assume that more work is required to move the particle along $P_2$ from $r_1$ to $r_2$ than along $P_1$. This also means that you gain more work by moving the particle from $r_2$ to $r_1$ along $P_2$ than you needed to bring it from $r_1$ to $r_2$ along $P_1$. In the end, your particle didn't move after completing once cycle, but you gained work "from nowhere".

A: One simple explanation is that the work you calculate does not depend on the path along which you move the charge. Or, in other words, if you move a charge in a closed path, the work done by the electric field is zero. See,
$A=\oint q\vec E\cdot d\vec r=qQ(1/r - 1/r)=0$


text:
Q: How do I include filtering in IIS Advanced Logging for healthcheck URI via Powershell I looking for a PS script that would exclude the string healthcheck.htm from my Advanced Logging Logs.
I can do this from the GUI, but would appreciate if someone could provide me with the commands for putting this into a script which I can run against all of my servers.
IIS 7.5 Powershell 3.0


text:
Q: Error in Stateful Convolutional LSTM I want to implement a Stateful Convolutional LSTM in this way:
# build CNN/LSTM and train it.
#
model = Sequential()

# build CNN/LSTM and train it.

model.add(TimeDistributed(Conv2D(16, (3, 3), padding='same'), input_shape=(210, 22, 26, 1)))
model.add(Activation('elu'))
model.add(TimeDistributed(MaxPooling2D(pool_size=(2, 2))))
model.add(Dropout(0.2))

model.add(TimeDistributed(Conv2D(32, (3, 3), padding='same')))
model.add(Activation('elu'))
model.add(TimeDistributed(MaxPooling2D(pool_size=(2, 2))))
model.add(Dropout(0.2))

model.add(TimeDistributed(Conv2D(64, (3, 3), padding='same')))
model.add(Activation('elu'))
model.add(TimeDistributed(MaxPooling2D(pool_size=(2, 2))))

model.add(TimeDistributed(Flatten()))

model.add(Conv1D(16, 3, padding='same'))
model.add(Activation('elu'))
model.add(MaxPooling1D(pool_size=8))

model.add(Bidirectional(LSTM(64, batch_input_shape=(32, 26, 16), return_sequences=True, stateful=True)))
model.add(Activation('elu'))
model.add(Bidirectional(LSTM(128, return_sequences=False, stateful=True)))
model.add(Activation('elu'))
model.add(Dense(1, activation='sigmoid'))
adammgm = keras.optimizers.Adam(lr=0.0005, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0001)
model.compile(loss='mean_squared_error', optimizer=adammgm, metrics=['accuracy'])
print(model.summary())

# saves the model weights after each epoch
# if the validation loss decreased
#
checkpointer = ModelCheckpoint(filepath= odir_a + "/temp_lstm_model_weights-{epoch:02d}.h5")

model.fit_generator(generate_reduced_dimension_arrays_from_file(ilist_a, edfroot_a, featroot_a, labroot_a, feat_ext_a, lab_ext_a, num_channels_a, feat_fdur_a, win_len_a,    models_order, lstm_batch_size_a, NEDC_DEF_BATCH_FILE), steps_per_epoch=NEDC_DEF_STEPS_PER_EPOCH, epochs=lstm_epoch_size_a, callbacks=[checkpointer])

But I got this error when I wanted to implement this structure:
ValueError: If a RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors:
- If using a Sequential model, specify the batch size by passing a batch_input_shape argument to your first layer.
- If using the functional API, specify the time dimension by passing a batch_shape argument to your Input layer.
I real all the posts but I still do not know how to fix this issue.

A: The problem was solved. The solution is using the batch_input_shape instead of input_shape in the first layer of CNN:
# build CNN/LSTM and train it.
#
model = Sequential()

# build CNN/LSTM and train it.

model.add(TimeDistributed(Conv2D(16, (3, 3), padding='same'), batch_input_shape=(32, 210, 22, 26, 1)))
model.add(Activation('elu'))
model.add(TimeDistributed(MaxPooling2D(pool_size=(2, 2))))
model.add(Dropout(0.2))

model.add(TimeDistributed(Conv2D(32, (3, 3), padding='same')))
model.add(Activation('elu'))
model.add(TimeDistributed(MaxPooling2D(pool_size=(2, 2))))
model.add(Dropout(0.2))

model.add(TimeDistributed(Conv2D(64, (3, 3), padding='same')))
model.add(Activation('elu'))
model.add(TimeDistributed(MaxPooling2D(pool_size=(2, 2))))

model.add(TimeDistributed(Flatten()))

model.add(Conv1D(16, 3, padding='same'))
model.add(Activation('elu'))
model.add(MaxPooling1D(pool_size=8))

model.add(Bidirectional(LSTM(64, return_sequences=True, stateful=True)))
model.add(Activation('elu'))
model.add(Bidirectional(LSTM(128, return_sequences=False, stateful=True)))
model.add(Activation('elu'))
model.add(Dense(1, activation='sigmoid'))
adammgm = keras.optimizers.Adam(lr=0.0005, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0001)
model.compile(loss='mean_squared_error', optimizer=adammgm, metrics=['accuracy'])
print(model.summary())


text:
Q: Using Task.IsFaulted to denote IO failures without propagating exceptions Before/without Task<>s, I'm using a wrapper object like the below to encapsulate the result of an I/O operation that could fail, without propagating exceptions up the call stack:
public class FetchResult<T>
{
    public readonly bool Success;
    public readonly T Item;

    public FetchResult(bool success, T item)
    {
        this.Success = success;
        this.Item = item;
    }
}

I'd use it like this:
var userResult = Get("robert.paulson@fightclub.com");
if(!userResult.Success)
    // abort, or something

...

public FetchResult<User> Get(string email)
{
    try
    {
        // go to database here, and get the User
        return new FetchResult(true, new User());
    }
    catch
    {
        // log exception
        return new FetchResult(false, null);
    }
}

This works great for me as a model, as it allows me to effectively manage exceptions without using try/catch as program control flow and gives me easy and fine-grained graceful service degredation.
However, with the advent of Task<>, I could very easily end up with:
    public Task<FetchResult<User>> GetAsync(string email)

which seems to be getting out of hand.
Seeing as I'm migrating to async everywhere anyway, I'm contemplating just doing:
    public Task<User> GetAsync(string email)

which id have expected to allow me to do something like:
var userTask = GetAsync("robert.paulson@fightclub.com");
await userTask;
if(userTask.IsFaulted) // (*) - see below
    // abort, or something

However if my GetAsync method returns:
return Task<User>.FromException(new Exception());

what is actually returned after the await (where the (*) comment is) seems to be a Completed Task, whos result is a Task<User> which is faulted.
Why am I getting a nested task in this case, and is there some syntactic sugar I'm missing to make this whole affair tidier?

A: There are two methods in Task library FromException() and FromException<TResult>() both are available via Task and Task<TResult>.
public static Task FromException(Exception exception)
{
   return FromException<VoidTaskResult>(exception);
}

public static Task<TResult> FromException<TResult>(Exception exception)
{
 ...
 ...
}

If you call Task<TResult>.FromException() or Task.FromException() there's no different in these two calls.
Your method signature is: public Task<User> GetAsync(string email)
Now if you try to use Task<User>.FromException(new Exception()) this will return Task<VoidTaskResult> and which is ofcourse is not of type Task<User>. Which means you might be getting compiler error.
This compile time error would be gone if you use Task<User>.FromException<User>(new Exception()); or Task.FromException<User>(new Exception());
You're getting Task<Task<VoidTaskResult>> as specified in comments means there's something more in your method code which is not mentioned in your sample code.
For more internal details about Task methods in .Net source code see here
Update:
After looking at your code found couple of issues.
i) Return type as Task is avoiding the compilation error that I mentioned earlier in my answer.
ii) You're returning a Task with in a Async method without awaiting means the complete task object will be wrapped in Another Task type.
See below example that I tweaked to to show the problem. See even the return type is changed from Task of type Object to Program there's still no error. This is Because of Object which is base of any custom type in C#. So doing below is allowed:
static async Task<object> GetAsync()
{
    try
    {
        throw new Exception();
    }
    catch (Exception e)
    {
        return Task.FromException<Program>(e);
    }
}

Now change the return type of method to Task<Program> you'll get an error or more of warning.
Now the correct version to fix the problem would be to await the Task so that only Program type remain as result which will be automatically returned as Task<Program>.
Correct version:
 static async Task<Program> GetAsync()
        {
            try
            {
                throw new Exception();
            }
            catch (Exception e)
            {
                return await Task.FromException<Program>(e);
            }
        }

Now you won't see any Nested tasks anymore. This is internals of how await works. If you really want know why it happens like this then try to analyze the IL generated of all the above 3 versions of the program using IL spy and you'll get the idea. Cheers!!!

A: Task.IsFaulted means that the Task completed due to an unhandled exception. So I don't think you could set it in a different way than to let the exception go uncaught.
public async Task<User> GetAsync(string email)
{
    // go to database here, and get the User
    return new User();
}

Or catch, log, and rethrow:
public async Task<User> GetAsync(string email)
{
    try
    {
        // go to database here, and get the User
        return new User();
    }
    catch
    {
        // log exception
        throw;
    }
}

I believe you are saying that your GetAsync is returning a nested task because you have something like this:
public async Task GetAsync(string email)
{
    // .... somewhere in the code
    return Task.FromException(new Exception());
}

But when you declare a method using the async keyword, C# magic takes care of wrapping its contents inside a Task. So in this case you actually end up having a task which returns another task - Task<Task<T>>. It would return Task<T> if you removed the async keyword but then obviously you end up with a standard synchronous method.

A: Kind of unusual, but you can explore the fact that the Task.WhenAny method does not throw exception (see Is there a way to Wait for a TPL Task without in throwing an exception?) like this
var userTask = GetAsync("robert.paulson@fightclub.com");
await Task.WaitAny(userTask);
if(userTask.IsFaulted) // (*) - see below
    // abort, or something


text:
Q: Why is my comparison of char array length not working at this instance? UPDATE: It seems that this code is actually fine, but perhaps a problem with my third party compiler Dev C++...
I am currently trying to figure out why this code won't compile and is repeatedly giving me a error saying "source file not compiled".
It seems to work if I try the statements separately(remove two of the if or else statements), but once all three are together it fails to compile.
#include <stdio.h>
#include <string.h>

int main ()
{
   char str1[15] = "a";
   char str2[15] = "b";
   int ret;

   ret = strcmp(str1, str2);

   if(ret < 0)
   {
      printf("str1 is less than str2");
   }
   else if(ret > 0)
   {
      printf("str2 is less than str1");
   }
   else
   {
      printf("str1 is equal to str2");
   }

   return(0);
}

Perhaps there is something wrong with my declaration of the char array?
I am using a third party compiler called Dev c++ if that helps.

A: The code is fine. If rebuilding a project didn't work, try installing new Dev C++.
Source: http://sourceforge.net/projects/orwelldevcpp/


text:
Q: UITableViewController leaving space at top of page only after leaving and returning to the UITableViewController My TableViewController is leaving a gap at the top of the page after I leave the page and come back using a UITabBarController. At the initial load it is fine, the gap only appears when I leave the page then return. I have tried removing my refreshcontrol code but that was not the issue.

A: try setting disable to automatic scroll property
self.automaticallyAdjustsScrollViewInsets = NO;


text:
Q: DB2 - Limit fetched rows in table by selecting row count from other table I am trying to get row count in Table_A, save it in a variable and fetch the same row count in Table_B.
CREATE VARIABLE myvar INTEGER;
SET myvar = (SELECT count (*) FROM Table_A)

SELECT * from Table_B
fetch first {mywar} rows ONLY

DROP VARIABLE myvar;

How can I achieve this in DB2? Is it better in this case to use Limit? Can this be achieved without using variables?

A: You could do e.g.
SELECT * FROM
( SELECT *, ROW_NUMBER() OVER() AS RN from Table_B)
WHERE RN <= (SELECT COUNT(*) FROM Table_A)


text:
Q: Как записать путь файла с помощью двух переменных? Я хочу реализовать скрипт таким образом, чтобы можно было ввести путь к файлу-источнику, путь к файлу-назначению, файл-источник и файл-назначения без вмешательства в код. Значения скрипт принимает, но когда дело доходит до открытия файла, скрипт выдаёт ошибку.
Вот код:
path = [0] * 2
sourcefile = 0
destinationfile = 0

path[0] = input("Write your path to source")
path[1] = input("Write your path to destination")
sourcefile = input("Write your file-source name")
destinationfile = input("Write your file-destination name")

with open(r"%s"+"%s" % (path[0], sourcefile), 'r') as file_in:

Проблема начинается на моменте with open.
Как можно сделать по-другому?

A: Для склейки путей в python есть специальной модуль os в нем есть функция os.path.join для постройки путей лучше всего пользоваться именно ей, вам нужно что-то такое
import os

def main():
    path = [0] * 2
    sourcefile = 0
    destinationfile = 0

    path[0] = input("Write your path to source")
    path[1] = input("Write your path to destination")
    sourcefile = input("Write your file-source name")
    destinationfile = input("Write your file-destination name")

    file_path = os.path.join(path[0], sourcefile)

    # check if file exists before try to open it
    if not os.path.exists(file_path):
        print("No such file")
        return

    with open(file_path, 'r') as file_in:
        pass

if __name__ == '__main__':
    main()

A: Вот это
r"%s"+"%s" % (path[0], sourcefile)

не будет работать. Так как оператор % имеет больший приоритет, чем +, то интерпретатор будет сначала пытаться впихнуть два значения path[0] и sourcefile в строчку "%s" , где есть подстановочное место только для одного значения.
Нужно либо явно указать приоритет с помощью скобок:
(r"%s"+"%s") % (path[0], sourcefile)

либо (что гораздо лучше) просто написать так:
r"%s%s" % (path[0], sourcefile)

Впрочем, в соседнем ответе предложили ещё более лучший вариант с использованием модуля os

A: Кроме os.path.join() можно также воспользоваться относительно новым модулем pathlib (встроен в Python 3.x, для Python 2.x существует в качестве дополнительного модуля - pip install pathlib2) :
try:
    from pathlib import Path       # Python 3.x
except ImportError:
    from pathlib2 import Path      # Python 2.x  (pip install pathlib2)

file_path = Path(path[0]) / sourcefile
with open(file_path) as file_in:
    # ...


text:
Q: Migrating from MySQL to MariaDB I am migrating my database to MySQL to MariaDB. I have binary storage engine in MySQL and MariaDB does not support it.
How can I convert this to make sure my tables will works? Thank You

A: If this is a binary engine that works with MySQL and you have the source for it, then you should be able to easily port it to MariaDB:

*

*The storage engine interface is 99 % identical. We have mainly move
some functionality from the storage engine (like statistic counting)
to the handler interface which should be trivial to fix.

*A few server functions may have changed names, but nothing that
should not be almost trivial to figure out.

In practice one should be able to port a storage engine for MySQL to MariaDB within 30 minutes or so.
If you don't have the source code, you need to ask the vendor for the storage engine to support MySQL. They should be able to do that without much trouble (as long it's a true plugg-in storage engine and not something that makes big changes to the MySQL/MariaDB upper level code).


text:
Q: DBVisualizer query snytax to add a range of values I need to be able to do something like this in DBVisualizer:
WHERE
  Column = {12, 23, 55, 33, 22}
Instead, I am doing this
WHERE
 Column = 12 OR
 Column = 23 OR
 Column = 55 OR
 Column = 33 OR
 Column = 22
Is there some sort of syntax reserved for this purpose? The latter is very tedious, and I am not a database person. So any help is very much appreciated!

A: WHERE Column in (12,23,55,33,22)

note that this language is not a function of dbvisualizer, but of the database you are connecting to.  The above code works for every RDBMS I've ever worked with.
http://www.w3schools.com/sql/sql_in.asp
I think this wants the SQL tag!


text:
Q: Total value with JavaScript and PHP I'm using this form script to automatically calculate totals. Now I need to get that total and add it to a database via PHP and MySQL.
I don't know how to 'name' the totalPrice div, so that I can pass its value to the database.
Edit:
I'm still not getting results in the database. I'm now using $_POST[totalValue] for the field set and totalPrice for the field name.
HTML:

<input type="hidden" name="totalValue" id="totalValue" />

JavaScript:
$("#vendorform").submit(function(){
    var totalValue = document.getElementById('totalValue');
    totalValue.value = vendorPrice; //the actual total value
});

function calculateTotal()
{
    //Here we get the total price by calling our function
    //Each function returns a number so by calling them we add the values they return together
    var vendorPrice = getTentPrice() + getElecPrice() + getPropanePrice();

    //display the result
    var divobj = document.getElementById('totalPrice');
    divobj.style.display='block';
    divobj.innerHTML = "Total Price Vendor $"+vendorPrice;
}

A: Using jQuery:
$("#cakeform").submit(function(){
    var price = $("#totalPrice").text().replace(/[\s\S]+\$/,"")
    $("#cakeForm").append('<input type="hidden" name="estimated_price" value="' + price + '" />')
})

But as @nick-rulez pointed out, is usually not a good idea to save calculated values in a database.

A: You can set the value to:
<input type="hidden" name="totalValue" id="totalValue" />

Which you have to put inside your <form>...</form>.
When you submit the form you're going to receive input's value.
You can set the value to the hidden field with this sniped:
JS
var totalValue = document.getElementById('totalValue');
totalValue.value = myValue; //myValue is the total

A: The vendorPrice variable is not available outside the scope of the function calculateTotal. You could make vendorPrice a global variable, but that's a bit of an ugly hack.
Alternatively, you could do something like this:
function calculateTotal()
{
    var vendorPrice = getTentPrice() + getElecPrice() + getPropanePrice();
    var divobj = document.getElementById('totalPrice');
    divobj.style.display='block';
    divobj.innerHTML = "Total Price Vendor $"+vendorPrice;

    return vendorPrice; // <-- ADDED
}

And this:
$("#vendorform").submit(function(){
    var totalValue = document.getElementById('totalValue');
    totalValue.value = calculateTotal(); // <-- CHANGED
});

This way, you assign the value that is now returned by calculateTotal()  to totalValue.value.
By the way: since it looks like you're already using jQuery, you can rewrite your code like this:
// [...]

var divobj = $('#totalPrice');
divobj.css('display', 'block');
divobj.text("Total Price Vendor $"+vendorPrice);

// [...]

var totalValue = $('#totalValue');
totalValue.val(calculateTotal());

This makes it a bit more readable (although that's debatable) and a bit more cross-browser reliant. jQuery has great docs (e.g. the documentation on .val()). If you're going to use jQuery more often I can highly recommend bookmarking the docs and skimming through them.

A: JavaScript:
function calculateTotal()
{
    var Price = getTshirtPrice() + getTshirtType() + getTshirtColour() +
    getTextColour();

    var divobj = document.getElementById('textbox');
    divobj.value = "Total Price For the T-shirt: £"+Price;

    return Price;
}

HTML:

<input type="text" id="textbox">

Do that. It works perfectly fine.


text:
Q: Probability task uniform distribution currently I'm stuck with some probability task (I will provide my solution below):
We have interval of 10 minutes (in other words [0; 10]). Two people ("A" and "B") come after each other in random time of interval. By assuming that "A" came before "B" and the distribution is uniform, find the probability that B came in the last 5 minutes of interval (meaning [5; 10])
My solution (I guess it's incorrect, as I end up with probability greater than 1):
Let's consider two cases.
In the first case, "A" came in the last 5 minutes (with probability 1/2, as it has 5 minutes out of 10), then "B" must came in the last 5 minutes too (with probability 1). So, it's 1/2 * 1
In the second case, "A" came in the first 5 minutes (let's assume, "A" came at the time 'x'). The probability of this situation is 1/2 as well. Then "B" can came in every time of interval [x; 10]. To came in the last 5 minutes, "B" has probability 5/(10 - x). As I understand, we need to take integral with x from interval [0; 5].
So, the whole formula is 1/2 *1 + 1/2 * (integral of (5/(10 - x)), where x from [0; 5])
End up with the answer something like >1. Any ideas of where I've made the mistake, please?

A:
Then "B" can came in every time of interval [x; 10]. To came in the last 5 minutes, "B" has probability 5/(10 - x).

The arrival time for $B$ is not conditionally uniformly distributed when given that for $A$ .

  The times for $A$ and $B$ cannot be independent and strictly ordered.
  When taking $A,B$ as independent and identically distributed (uniformly over $[0;10]$), you must treat this "assumption" of order as a condition, thus seek to find $\mathsf P(5\leq B\leq 10\mid A<B)$ .
The integration is set up as:
$$\begin{align}\mathsf P(5\leqslant B\leqslant 10\mid A\lt B) ~&=~ \dfrac{~\mathsf P(A<B, 5\leqslant B\leqslant 10)~}{\mathsf P(A\lt B)}\\[2ex]&=~\dfrac{\quad\int\limits_5^{10}\int\limits_0^b f(a)\,f(b)\,\mathrm d a\,\mathrm d b\quad}{\int\limits_0^{10}\int\limits_0^b f(a)\,f(b)\,\mathrm d a\,\mathrm d b}\end{align}$$
$~$

PS: You can save some effort, since by symmetry $\mathsf P(A<B)=1/2$.


text:
Q: Best way to remove header and footer for a particular page in YII I came across a situation where I don't need to show the header (it has the navigator bar and logo)andfooter` for a particular page in yii. There are a number of tweaks to do this. For example, having a check for a particular action where the layout will not load header and footer..
Does yii provide any thing solid for this issue?
Do we have anything like $this->layout->unsetHeader();? or $this->layout->unsetFooter();?
I don't want to have a check in the layout file to sort this out.
Help would be appreciated.

A: You can set $this->layout to false;
$this->layout = false
$this->render('view', $data);

This can also be achieved using renderpartial
$this->renderPartial('view', $data);

The approach above will display a page segment and not other items of the page layout (for example inclusion of javascript and css, and HTML headers).
If you want your layout files to have logic in it, you can pass variables from the controller.
$this->layout = 'mytheme';
$this->show_css = true;
$this->render('view', $data);

and in your layout

   <?php if ($this->show_css) { ?>

Menu Option 1

Menu Option 2

   <?php } <?

      <?php echo $this->content; ?>

If you don't want to use a variable in the controller. use a global variable instead.
   Yii::app()->params['show_menu'] = true;

A: I haven't find function like you looking for.
I think the best and siplest way is however use a proper layout, and call it in controller in this way
public function actionYourView()
   {

    $this->layout='yourLayout';
    $this->render('yourView');
}

In this way you don't need check inside the layout for header and footer the logic is all in the controller. And assign the proper layout is easy.


text:
Q: Pass a parameter into a template file when an index is clicked I have a table populated from some JSON in a JS file.
data.js looks like this:
var data = [
  {
    title: "Avengers Endgame Trailer",
    year: 2019,
    type: "MOV",
    file: "video1.mp4"
  },
  {
    title: "Avengers Infinity War Poster",
    year: 2018,
    type: "PNG",
    file: "image1.png"
  }
];

The data is read in a JS function in my functions.js file (which writes the actual table rows).
function populateTable() {
  for (var i = 0; i < data.length; i++) {
    if (data[i].type == "MOV") {
      var row = '
' + data[i].title + "	";
      row += "" + data[i].year + "
";
      $("#contents").append(row);
    } else {
      var row = '
' + data[i].title + "	";
      row += "" + data[i].year + "
";
      $("#contents").append(row);
    }
  }
}

What I'm trying to figure out is how to allow the link offs for each item to use a different template file. I wrote some dummy code in the HREF above but that's obviously not correct.
For templates, I have two: video.html and image.html. I'd like to pass the filename of the index tapped as a parameter into the template files so it can display the correct file, but I'm unsure what to do?
As an example the video.html template file looks like this:

            <video autoplay muted loop id="main">
              <source src="{filenameGoesHere?}" type="video/mp4">
              Your browser does not support HTML5 video.
            </video>

A: There are multiple things that you're repeating here making it non-optimised. If you can use functions, please use them! If not, the better way is:
function populateTable() {
  for (var i = 0; i < data.length; i++) {
    // Look how I have made the file addition here.
    var row = '
' + data[i].title + "	";
    row += "" + data[i].year + "
";
    // Do the MOV vs. PNG thing/
    row += "
";
    if (data[i].type == "MOV") {
      row += `

            <video autoplay muted loop id="main">
              <source src="${data[i].file}" type="video/mp4" />
              Your browser does not support HTML5 video.
            </video>

`;
    } else {
      row += `

`;
    }
    row += "
";
    $("#contents").append(row);
  }
}

In the above code:

*

*Look how I have made the file addition here on Line 4.

*Do the MOV vs. PNG thing on Line 7.

For the templating thing using How to read GET data from a URL using JavaScript?, what you can do is:

            <video autoplay muted loop id="main">
              <source src="" id="src" type="video/mp4" />
              Your browser does not support HTML5 video.
            </video>


text:
Q: how to get autocorrelation 0, when? I am a newbie in time series and I understood negative autocorrelation through this example http://www.pmean.com/09/NegativeAutocorrelation.html

If you are looking at the amount of time a doctor spends with
  successive patients, if the first patient finished faster than
  expected, you are more likely to adopt a leisurely approach with the
  second patient. If the first patient takes longer than expected, you
  are more likely to rush with the second patient, trying to get back on
  schedule.

Then, if I am correct... high positive auto-correlation (let's say 0.9)... would be: if the first patient took 5', the next/previous one takes 4' 59''.
Then, what would be an example of low auto-correlation (let's say 0.01)? I can't understand the logic behind it...


text:
Q: Is there a Microsoft Graph MS Word API? Question
Are there actually any Graph API endpoints for the Office 365 version of Word at the moment?
(And, if not, are they planned?)
Where I've looked
I've found the documentation for Excel API in Graph, Outlook API in Graph, OneNote API in Graph, but I cannot find any mention of a Word API.
There's no mention of Word in the Productivity section of Graph Overview Official docs.
And there's no sign of it in the Graph Explorer Samples:

And there don't seem to be any sub-projects related to Word in the Microsoft Graph GitHub repo.
Side notes
This question asks a similar thing about the Office 365 API.  I'm not sure if the Graph API is a rebranding of the Office 365 API, which now seems to be end of life according to the official docs?
Ultimately what we're looking for is a replacement for the Office PIAs that we can use from an Azure hosted web app to build Word documents.  We've been using Open XML, but we need dynamic page numbering which OpenXML doesn't support.

A: As of today there is no Word API available under the Microsoft Graph other than managing the file and it's permissions when it's seating in SharePoint/OneDrive for Business.
There is a UserVoice entry supporting the idea.
There used to be APIs provided by Office Online Server/Office Web Apps but I don't think it fits your scenario.
So as you're pointing today the only ways to modify a word document via an API that are available seem to be the interop assemblies, the Office Add-Ins SDK or third party APIs.


text:
Q: How do I check to see if a form field contains a specific word or phrase? I am creating a PHP form, and came across another issue. Unlike the others, this one I cannot figure out (And Google is not helping).
I have an HTML form with PHP validation, and one of the fields is a URL field. I want the input within that field to be formatted a specific way. I will put examples of what is valid/not valid, as well as the code below.
ALLOWED INPUT - Basically anything that includes "thisismydomain.com"

https://www.thisismydomain.com
www.thisismydomain.com
thisismydomain.com
https://thisismydomain.com
Any of the above + directories are allowed, such as adding /anythingathere to any of the above

INVALID INPUT

https://www.notmydomain.com
www.notmydomain.com
notdomain.com
https://notmydomain.com

The form field: (Yes, that does say "vurl". I found that if it says "url", the browser requires a "http://" or "https://" to submit)

            URL

Please provide the URL of the page with the error

            <input type="vurl" name="vurl" id="subject" class="form-feild" size="40">

The Submission Rule: (It don't work at the moment, this is what I need help with. Only the first line does not work, the second line has been tested with other submission rules and it works.)
if (strpos($_POST['vurl'], 'thisismydomain.com"') !== false) {
    redirectWithError("Please enter a valid URL");
}


text:
Q: SSL-сертификат принцип работы Объясните пожалуйста про удостоверяющие SSL-сертификаты. Сколько не читал так и не смог понять механизма их работы.
Как я понимаю SSL-Сертификаты ввели, как противодействие перехвата публичных ключей в асимметричном шифровании, подмену этих ключей и как итог расшифровка, просушка и изменение зашифрованого трафика между Клиентом и Сервером.
Поэтому прежде, чем обменяться публичными ключами, Сервер на GET-запрос Клиента сначала посылает ему удостоверяющий Сертификат.
И тут все, я ничего не понимаю.
-Что из себя представляет этот сертификат?
-как тут задействуется Удостоверяющий центр и его цифровая подпись ?
-Почему нельзя перехватить сертификат и подсунуть свой ? итд...

A: Если не вдаваться в сложную математику, и совсем на пальцах:

*

*В вашей операционной системе (и/или в браузере) уже есть много сертификатов корневых УЦ, которые установлены изначально.

*Когда браузер соединяется с сайтом по https, сайт первым делом отдаёт свой сертификат подписанный одним из корневых УЦ (возможно не напрямую, а через цепочку подписей).

*Браузер (про помощи сложной математики) проверяет что подпись (подписи) настоящие и что сертификат подходит к домену который он запрашивал.

*Далее (про помощи другой сложной математики) браузер и сервер договариваются о сессионном ключ шифрования

*и вся дальнейшая переписка между ними шифруется этим ключом.

Что из себя представляет этот сертификат?

Файл в котором описан срок действия сертификата, для каких доменов он подходит и публичный ключ от асимметричного шифрования. Это файл подписан УЦ  и именно эту подпись проверяет браузер на шаге 3.

как тут задействуется Удостоверяющий центр и его цифровая подпись?

Владелец сервера заранее подписывает свой файл в УЦ.
УЦ проверяет что домен(-ы) в сертификате действительно принадлежат владельцу сервиса.
Сертификаты корневых УЦ уже есть у вашего браузера.

Почему нельзя перехватить сертификат и подсунуть свой?

Можно. Но перехватывающий в общем случае не сможет подсунуть свой сертификат для нужного домена с действительной подписью.
Именно из-за этой угрозы все очень скептически смотрят на российские корневые сертификаты, т.к. опасаются что государственный УЦ «забудет» проверить что ООО «Рога и копыта» владеют доменом google.com.

A: Сертификат служит для проверки что запрошенный сайт является подлинным, а не кто-то им притворяется. Проверив его подпись по центру сертификации браузер решает доверять ли ему.
В сертификате есть открытый ключ который служит шифрования общего ключа (pre master key) при 4х стороннем обмене ключами шифрования.


text:
Q: Disable button onload angularJS While clicking a button am calling a service method which will return an integer value.
Now my need is, on page load i should disable this button if this integer value is 0.
i don't want to use ng-disabled, because then it will keep on calling that service method.
any better way?

A: I don't know if I get the question right but here is what i did in plunker
<!DOCTYPE html>
<html ng-app="sample">

<head>
  <script data-require="angular.js@*" data-semver="1.4.0-beta.5" src="https://code.angularjs.org/1.4.0-beta.5/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>
<script>
  var module = angular.module("sample", []);
  module.controller('ctrl', function($scope) {
    //assuming that this variable came from your service
    var i = 0;

    $scope.disable = true;
    $scope.init = function() {
      $scope.disable = i === 0 ? true : false;
    }

  });
</script>

<body ng-controller="ctrl" ng-init="init()">
  <button ng-disabled="disable">hello world</button>
</body>
</html>

http://plnkr.co/edit/p9qZGcO1znOiDidecFYd
but basically you really need to use ng-disabled and call the ng-init function so that when your page load, it will check if the value of integer is 0 then flag the button to be disabled or not.