text:
Q: Attachment uploads but how do I email it? I have the php code working up to the point where I need the image to get attached to a variable and i gets emailed with the rest of my form. I get 2 errors. One error is telling me that $messageImage in undefined on line 75? and the other is: Call to a member function addAttachment() on a non-object on line 75.
can someone explain the proper way of declaring the variable and making sure it is an object so that addAttachment works. Thank You
 //copy the temp. uploaded file to uploads folder
$upload_folder = 'uploads/';

$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;

$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
if(is_uploaded_file($tmp_path)) {
  if(!copy($tmp_path,$path_of_uploaded_file))
  {
    $errors = '\n error while copying the uploaded file';
  }
}

$to = "example@gmail.com"; // this is your Email address
$from = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL); // this is the sender's Email address
$first_name = filter_var($_POST['first_name'], FILTER_SANITIZE_STRING);
$story = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
$subject = "subject";
$subject2 = "Thank You for submitting";

$messageImage->addAttachment($path_of_uploaded_file);

$message = $first_name . " wrote the following:" . "\n\n" . $story;
$message2 = "Here is a copy of your story " . $first_name . "\n\n" . $story;

$headers = "From:" . $from;
$headers2 = "From:" . $to;

mail($to,$subject,$message,$messageImage,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender

A: In your code, $messageImage is not being set.  Since it is not set, it is NULL, causing the next error, you are trying to refer to the method of an object, but it is null.
To send a message with attachments, you need to set email headers, and the image is base64 encoded in the message.  I would look at this other StackOverflow answer:
https://stackoverflow.com/a/17371739/2832264
To make a simple object:
$obj = new stdClass();

Otherwise, you would create a class, make sure it is included in your script, and create a new instance of that:
$obj = new Person();

I would read the official PHP documentation on classes.

A: '$messageImage' is an object in your code and it is not define.
You can check this with simple if check like below,
       if ($messageImage) {
            // do something
       }

Following code can work for you,
       //copy the temp. uploaded file to uploads folder
       $upload_folder = 'uploads/';

       $to = "example@gmail.com"; // this is your Email address
       $from = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL); // this is the sender's Email address
       $first_name = filter_var($_POST['first_name'], FILTER_SANITIZE_STRING);
       $story = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
       $subject = "subject";
       $subject2 = "Thank You for submitting";

       $message = $first_name . " wrote the following:" . "\n\n" . $story;
       $message2 = "Here is a copy of your story " . $first_name . "\n\n" . $story;

       $headers = "From: $from";
       // boundary
       $semi_rand = md5(time());
       $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

       // headers for attachment
       $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";

       // multipart boundary
        $message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
        $message .= "--{$mime_boundary}\n";

       $content = '';
       $tmp_path = $_FILES["uploaded_file"]["tmp_name"];
       if($tmp_path) {
                    $filename = $_FILES["uploaded_file"]["name"];
                    $path_of_uploaded_file = $upload_folder . $filename;
                    if(!copy($tmp_path, $path_of_uploaded_file))
                    {
                                  $errors = '\n error while copying the uploaded file';
                    }
                    $file_size = filesize($path_of_uploaded_file);
                    $handle = fopen($path_of_uploaded_file, "rb");
                    $content = fread($handle, $file_size);
                    fclose($handle);
                    $content = chunk_split(base64_encode($content));
             }

       // if attachment
       if ($content) {
        $message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"{$filename}\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"{$filename}\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $content . "\n\n";
$message .= "--{$mime_boundary}\n";
       }
       $headers2 = "From:" . $to;

       mail($to, $subject, $message, $headers);
       mail($from, $subject2, $message2, $headers2); // sends a copy of the message to the sender


text:
Q: Optimize duplicated but negated subquery I have what I call a 'Hamlet' query in the form:
select * from stuff a
left join otherStuff b on (a.x=b.x) -- lots of joins ommited
where
 (b.ToBe = 1 and a.Being in (select Being from stuffThatIs where stuffThatIs.Name = b.Name)
 or
 (b.ToBe <> 1 and a.Being not in (select Being from stuffThatIs where stuffThatIs.Name = b.Name)

The most-nested queries being identical, so I thought the database would reuse the result instead of doing 2 queries.
But in the execution plan the query shows twice with the same cost of 19%.
Can this be optimized manually? Or a hint added?
I'd prefer a portable solution instead of a maximum perf one.
There are indexes on all named columns, sometimes even unique. The example is simplified, the whole where clause is in a join condition itself etc. So please optimize just the pattern, not the whole query.

A: Maybe this query would be better?
We would check stuffThatIs for every row, and then validate if

*

*ToBe=1 and there is a.Being in stuffThatIs OR

*ToBe<>1 and there isn't a.Being in stuffThatIs
SELECT *
FROM someStuff a
LEFT JOIN otherStuff b ON (a.x = b.x)
OUTER APPLY (
  SELECT 1 [is_inside]
  WHERE EXISTS(SELECT *
               FROM stuffThatIs x
               WHERE x.Name = b.Name
                 AND x.Being = b.Being) -- instead of "...a.Being in (select Being..."
) x
WHERE ((a.ToBe = 1 AND x.is_inside IS NOT NULL)
    OR (a.ToBe <> 1 AND x.is_inside IS NULL))

A: I think this might work... unless you expect multiple duplicates from stuffthatis (in which case, try joining to a subquery of SELECT DISTINCT).
select A.*, B.*
from stuff a
left join otherStuff b on (a.x=b.x) -- lots of joins ommited
LEFT JOIN stuffthatis c on b.name = c.name

where
 (b.ToBe = 1 and a.Being = C.being)
 or
 (b.ToBe <> 1 and C.name is null)

redpajama_set_name: RedPajamaStackExchange


text:
Q: excel formula of sum with error and cells not in range I want a sum formula that will ignore errors.
For example something like: =sum(c3+f3+h3+j3+n3) however, some of these cells may contain an error.
Between these cells there is data which I do not want to sum.
Please help

A: You can use the AGGREGATE function to SUM and ignore errors:
=AGGREGATE(9,6,c3,f3,h3,j3,n3)

A: You can use IFERROR to do an alternative for an error, in your example the alternative is 0.
So you could write it as =IFERROR(C3, 0) + IFERROR(F3, 0) + So on....

A: Is the formula you're looking for something like this?
= SUMIF (A1: A14; "<> # N / A")

= SUM (IF(ISERROR(A1: D2), "", A1: D2))

SUM on its own does not ignore nested subtotals, hidden rows and can't cope with error values.  SUBTOTAL using function 9 (SUM) ignores nested subtotals but returns an error when the range it is calculating on includes an error value.  SUBTOTAL using function 109 does the same but does ignore hidden rows (row 9 is hidden). The AGGREGATE function, again using SUM function 9, and using option 3 (see below) ignores everything the SUBTOTAL 109 ignores but also ignores errors.The last 6 functions: VAR.P, MEDIAN, MODE.SNGL, LARGE, SMALL, PERCENTILE.INC , QUARTILE.INC, PERCENTILE.EXC and QUARTILE.EXC require a k value as a fourth argument. In the example below in row 16, the LARGE function is used with a k value of 2.  This returns the second largest value in the range.  Row 17 uses the SMALL function with a k value of 3 – the third smallest value.

A: Try this formula:
=SUMIF(A1:A6,">0")+SUMIF(A1:A6,"<=0")


text:
Q: cannot find symbol method d(java.lang.String,java.lang.String) When I compile the code below error occurs:

canot find symbol
 location: interface org.apache.commons.logging.Log    Log.d(TAG,"JSON parsing error - fix it:" + e.getMessage());`

This is my code:
//convertJSONtoArray

private void convertJSONtoArray(String rawJSON){
    try {
        JSONObject completeJSONObj = new JSONObject(rawJSON);
        String json = completeJSONObj.toString();
        Log.d(TAG,json);
        JSONObject results = completeJSONObj.getJSONObject("results");
    } catch (JSONException e) {
        Log.d(TAG,"JSON parsing error - fix it:" + e.getMessage());
    }
}

A: There are two possible reasons:
1. You are using Android
In that case replace the import for Apache Commons Logging Log with:
import android.util.Log;

2. You are developing in normal Java environment
Your import statement at the top of your class includes Apache Commons Logging Log, but the code was definitely not written for Commons Logging.
For Commons Loggig is should look like this:
private static final Log LOG = LogFactory.getLog(NAME_OF_YOUR_CLASS.class);

private void convertJSONtoArray(String rawJSON){
    try {
        JSONObject completeJSONObj = new JSONObject(rawJSON);
        String json = completeJSONObj.toString();
        if (LOG.isDebugEnabled()) {
            LOG.debug(TAG,json);
        }
        JSONObject results = completeJSONObj.getJSONObject("results");
    } catch (JSONException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug(TAG,"JSON parsing error - fix it:" + e.getMessage());
        }
    }
}


text:
Q: EMR spark not honoring number of executor conf I'm using --num-executor with EMR spark-submit but the conf is not getting honored. The job runs with multiple executors even if I set it --num-executor 1. I tried it with different EC2 instance type and the number of executors it runs by default seems to vary by instance types.

A: I guess dynamic allocation is active. You must inactive this parameter on spark configurations or send in spark-submit line like this:
spark-submit --conf spark.dynamicAllocation.enabled=false --class ...


text:
Q: Return records from select based on column value. Oracle So i do have select witch looks like this:
SELECT * FROM database1 WHERE ID = 3933185
Records witch select returns to me are:
ID          VALUE   ATTR_VALUE
3,933,185   1           1
3,933,185   1           1
3,933,185   1           1
3,933,185   1           2
3,933,185   1           2

As you can see per attr_value column there could be different values, 1 or 2, nothing more.
So what should i add to make a check, when attr_value exists with value 1, then it will return records where attr_value = 1, in other case it will return where attr_value = 2.
Hope my question is clear.

A: I think you want:
select t.*
from t
where t.value = (select min(t2.value) from t t2 where t2.id = t.id);

You can also use analytic functions:
select t.*
from (select t.*, min(t.value) over (partition by id) as min_value
      from t
     ) t
where value = min_value;

A: You could use exists logic here:
SELECT d1.*
FROM database1 d1
WHERE NOT EXISTS (SELECT 1 FROM database1 d2
                  WHERE d1.ID = d2.ID AND d2.ATTR_VALUE > d1.ATTR_VALUE);

A: If I followed you correctly, you can use analytical functions:
select id, value, attr_value
from (select t.*, rank() over(order by attr_value) rn from mytable t) t
where rn = 1


text:
Q: How to automatically flag strings for makemessage translation file in django I'm creating a signal that sends messages to multiple users, and each message should be translated to the receiver's language.
this is a simplified example of that the alert handler does:
def alert_handler(**kwargs):
    t_message = kwargs.pop("message", None)
    context = kwargs.pop("context", None)

    for recipient in recipients:
        activate(recipient.language)
        message = _(t_message, context)
        new_alert = Alert(recipient=recipient, message=message)

This works as intended but the makemessages command doesn't recognize the sting passed in the kwargs as a translatable string.
Is it possible to flag a string to be picked up by the makemessages command?


text:
Q: Prove that for $f\in L^1(\mathbb R)$, $\int_{\mathbb R}|f|=0\implies f=0$ a.e. Let $f\in L^1(\mathbb R)$ s.t. $$\int_{\mathbb R}|f|=0\implies f=0\ a.e.$$
My attempt
Suppose $f$ continuous and that there is $y$ s.t. $|f(y)|\neq 0$. In particular, there is $\delta >0$ s.t. $f(x)\neq 0$ for all $x\in [y-\delta ,y+\delta ]$. By continuity, there is $m>0$ s.t. $|f(x)|\geq m$ for all $x\in [y-\delta ,y+\delta ]$. Therefore, $0<2m\delta\leq \int_{[y-\delta ,y+\delta ]}|f(x)|\leq \int_{\mathbb R}|f|,$
which is a contradiction. Therefore $f=0$ everywhere.
Since $f\in L^1$. There is a sequence of continuous function s.t. $$\|f_n-f\|_{L^1}\to 0.$$
In particular, $$\int_{\mathbb R}|f_n|\to \int_{\mathbb R}|f|=0.$$
How can I prove that $f_n=0$ for all $n$ ?

A: There is no reason to have $f_n=0$ for all $n$... Your proof would be fine if $$\left\{f\in L^1(\mathbb R)\mid \int_{\mathbb R}|f|=0\right\},$$
would be a dense subspace of $L^1(\mathbb R)$. Since it's not the case, your proof can't work.
For a proof, let $E=\{x\mid |f(x)|>0\}$. Suppose that $m(E)>0$. Let $$E_n=\left\{x\mid |f(x)|\geq\frac{1}{n}\right\}.$$
Then, $$\frac{1}{n}\boldsymbol 1_{E_n}<|f|\boldsymbol 1_{E_n}  \leq |f|,$$
and thus, $$\frac{1}{n}m(E_n)\leq \int_{\mathbb R}|f|=0.$$
Therefore, $m(E_n)=0$ for all $n$. Since $\lim_{n\to \infty }m(E_n)=m(E)$, you get a contradiction.


text:
Q: Concurrent access to static methods I have a static method with the following signature:
public static List<ResultObjects> processRequest(RequestObject req){
  // process the request object and return the results.
}

What happens when there are multiple calls made to the above method concurrently? Will the requests be handled concurrently or one after the other?

A: I see a lot of answers but none really pointing out the reason.
So this can be thought like this,
Whenever a thread is created, it is created with its own stack (I guess the size of the stack at the time of creation is ~2MB). So any execution that happens actually happens within the context of this thread stack.
Any variable that is created lives in the heap but it's reference lives in the stack with the exceptions being static variables which do not live in the thread stack.
Any function call you make is actually pushed onto the thread stack, be it static or non-static. Since the complete method was pushed onto the stack, any variable creation that takes place lives within the stack (again exceptions being static variables) and only accessible to one thread.
So all the methods are thread safe until they change the state of some static variable.

A: Answering exactly your question:

*

*Method will be executed concurrently (multiple times in the same time if you have several threads).

*Requests will be handled concurrently.

You need to add the synchronized modifier if you are working with objects that require concurrent access.

A: You can check it yourself:
public class ConcurrentStatic {

    public static void main(String[] args) {
        for (String name: new String[] {"Foo", "Bar", "Baz"}) {
            new Thread(getRunnable(name)).start();
        }
    }

    public static Runnable getRunnable(final String name) {
        return new Runnable() {
            public void run() {
                longTask(name);
            }
        };
    }

    public static void longTask(String label) {
        System.out.println(label + ": start");
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(label + ": end");
    }

}

A: All your calls to the method will be executed concurrently... but:
You may have concurrency issue (and being in non thread-safe situation) as soon as the code of your static method modify static variables. And in this case, you can declare your method as synchronized
If your method only use local variables you won't have concurrency issues.

A: If you need to avoid concurrent execution, you need to explicitly synchronize. The fact that the method is static has nothing to do with it. If you declare the method itself to be synchronized, then the synchronization will be on the class object. Otherwise you will need to synchronize on some static object (since this doesn't exist for static methods).

A: all method invocations from separate threads in java are concurrent by default.


text:
Q: How to make a
* tag auto-resize I have this li which has a height of 60px.
But if I put my content with has more than 200 letters, the content goes outside the li.
How to make li grow by itself?

 #myUL li
{
    height: 60px;

    word-wrap: break-word;
    max-height: auto;
}

   ljcbnvkdsjbvdskjbvdskjbvdskjvbsdkjbvksdjvbsdkjvbsdkjvbsdkjvbdskjvbdskjbvsdbvsdkjdbvdskjbvdksjvbsdkjbvsdkjvbsdkjvbsdkjvbsdkjvbsdkvjbsdkjvbdskjvbsdkjvbsdkjvbsdkjvbsdkjvbsdkjvbsdkvjbsdvkjbsdkvjbsdvkjdsbv

   ×

   By Mera Yahan
    @  11:21 pm

A: Your code has:
#myUL li
{
  height: 60px;
  word-wrap: break-word;
  max-height: auto;
}

You should have:
#myUL li
{
  min-height: 60px;
  word-wrap: break-word;
  height: auto;
}

A:  #myUL li
{
    height:60px;
     overflow:auto;
    word-wrap: break-word;
    max-height: auto;
}

You can add overflow property to get a desired result.
or simply
#myUL li
{
    height:auto;

    word-wrap: break-word;

}


text:
Q: How to display one dot every second in C before quitting the process? I am trying to display ... (three dots), but each dot then a second delay then a second dot then a second delay then a third dot.
I tried this
for(int i = 0;i < 3;i++)
{
sleep(1);
printf(".");
sleep(1);
}

But this just waits for 6 seconds and then prints the three dots all together but I don't want that. Is there a fix for this. I want
. second delay . second delay .
but it will appear
...

A: Try:
#include <stdio.h>
#include <unistd.h>

int main() {
    for(int i = 0;i < 3;i++)
    {
        printf(".");
        fflush(stdout);
        sleep(1);
    }
}

printf() prints to stdout which is bufferred. Flush out the buffer after each printf().
<< std::flush; is the C++ equivalent to this.

A: Are you on Linux or Windows?
If you are on Windows, the function called should be
Sleep(1000);

This is because Windows treat its "Sleep" function as in milliseconds, that is x * 1000 where 'x' is the amount of seconds you want your program to tick. Your example was every second, therefor you say 1 * 1000 which is 1000, so the function should be as described above, to make your program tick every second.
Here's the full code.
#include <windows.h>
    for(int i = 0;i < 3;i++)
    {
        //Sleep(1000); pre-pause 1 second before print
        printf(".");
        //Sleep(1000); post-pause 1 second after print
    }
}


text:
Q: How to send SMS (using Twilio channel) from Microsoft Bot Framework? Currently my bot is on Facebook messenger, used by employees.
I'd like my bot to send one SMS to a person to welcome him / her to our team and with its credentials.
I know Microsoft Bot Framework integrates Twilio, so I integrated Twilio channel following this: https://learn.microsoft.com/en-us/bot-framework/channel-connect-twilio, so I have a phone, and everything is well configured because I can send manually SMS (from the Twilio's dashboard), it works.
Problem is that I don't know how to use it right now, in the bot.
const confirmPerson = (session, results) => {
  try {
    if (results.response && session.userData.required) {

      // Here I want to send SMS

      session.endDialog('SMS sent ! (TODO)');
    } else {
      session.endDialog('SMS cancelled !');
    }
  } catch (e) {
    console.error(e);
    session.endDialog('I had a problem while sending SMS :/');
  }
};

How to achieve this ?
EDIT: Precision, the person welcoming employee is a coach, just sending SMS from bot with the credentials to use in the webapp the bot connects after first usage by the user welcomed

A: Twilio developer evangelist here.
You can do this in bot framework by sending an ad-hoc proactive message. It seems you'd need to create an address for the user that you want to send messages to though and I can't find in the documentation what an address should look like.
Since you're in a Node environment, you could use Twilio's API wrapper to this though. Just install twilio to your project with:
npm install twilio

Then gather your account credentials and use the module like so:
const Twilio = require('twilio');

const confirmPerson = (session, results) => {
  try {
    if (results.response && session.userData.required) {

      const client = new Twilio('your_account_sid','your_auth_token');

      client.messages.create({
        to: session.userData.phoneNumber,   // or whereever it's stored.
        from: 'your_twilio_number',
        body: 'Your body here'
      }).then(function() {
        session.endDialog('SMS sent ! (TODO)');
      }).catch(function() {
        session.endDialog('SMS could not be sent.');
      })

    } else {
      session.endDialog('SMS cancelled !');
    }
  } catch (e) {
    console.error(e);
    session.endDialog('I had a problem while sending SMS :/');
  }
};

Let me know how this goes.


text:
Q: Split rows and columns in SQL server and insert into temporary table? I have data in one column of a particular table which has the following format:
item1 char(1) value1 char(1) value2 char(0) item2 char(1) value3 char(1) value4 char(0)

Note:
char(0) and char(1) and the characters themselves. There is also no spaces.
What I need to do is to split the column of the original table:

*

*first into rows by splitting using char(0)

*then for each row in (1) split again using char(1)
The result should be a table with 2 colums and x rows:
column1 column2 colum3
----------------------
item1   value1  value2
item2   value3  value4

I'm writing a CLR function to split the data:
public partial class Functions
{
    public static IEnumerable SplitData(SqlString value)
    {
        string[] rows = value.Value.Split('\n');

        for (int i = 0, n = rows.Length; i < n; i++)
        {

        }

        return rows;
    }
}

Each row will contain text, for example:
item char(1) value1 char(1) value2

The second step is to split each row (which is easy).
But how can the function return the table above so that it can be processed further in SQL server?

A: I think the easiest way to achieve this is to create your split function as a clr. In .NET you will have access to much better toolset of stringfunctions with decent performance. Probably better performance than you'll get if you do it in t-sql.

A: Test table and data:
DECLARE @t table(id int identity(1,1), col1 varchar(max))
insert @t values
('item'+char(1)+ 'value1'+char(1)+'value4'+char(1)+char(0)+ 'item'+char(1)+'value1'+char(1)+ 'value2'+char(1)+char(0)),
('item'+char(1)+ 'value1'+char(1)+'value2'+char(1)+char(0)+ 'item2'+char(1)+'value1'+char(1)+ 'value2'+char(1)+char(0))

Query:
;WITH SplitByRow as
(
        SELECT id, t.c.value('.', 'VARCHAR(2000)') colx
        FROM (
            SELECT id, x = CAST('<t>' +
                REPLACE(REPLACE(col1, char(1), '!new row!'), char(0), '</t><t>') + '</t>' AS XML)
        FROM @t
        ) a
        CROSS APPLY x.nodes('/t') t(c)
), SplitByColumn as
(
  SELECT
    id,
    (row_number() over (order by (select 1))+2)/3 rowx,
    (row_number() over (order by (select 1))+2)%3 colx,
    t.c.value('.', 'VARCHAR(2000)') value
    FROM
    (
        SELECT id, x = CAST('<t>' +
            REPLACE(colx, '!new row!', '</t><t>') + '</t>' AS XML)
        FROM SplitByRow
    ) a
    CROSS APPLY x.nodes('/t') t(c)
    WHERE t.c.value('.', 'VARCHAR(2000)') <> ''
)
SELECT
  id, [0] col1,[1] col2,[2] col3
FROM
  SplitByColumn
INTO
  #temp
PIVOT
    (min([value]) FOR colx
    in([0],[1],[2])
)AS p

Result:
SELECT * FROM #temp

id  col1    col2    col3
1   item    value1  value4
1   item    value1  value2
2   item    value1  value2
2   item2   value1  value2


text:
Q: Computing the tangent map using partial derivatives Let $G$ be a Lie group and let $\mu: G\times G \rightarrow G$ be a smooth map. I want to compute the tangent map $T_{(e,e)}\mu: T_{e}G\times T_{e}G\rightarrow T_{e}G$ of $\mu$.
In a proof in my notes they use the partial derivatives to compute the tangent map of $\mu$ given by $(x,y)\rightarrow xy$
Is there a general formula for this?  Reference?


text:
Q: ggplot annotate brakes axis i want to insert a text into my ggplot chart. The text got a subscript and a supersubscript like X[X} = 1,00*Y R^2 = 0,90. For that i used the funktion paste(expression()) into annotate(label=()).
In the graphics pane the whole plot looks fine, like i needed. But if i want to save the plot into a svg using the svg.save function the plot missing the Axis and the annotate Text.
Without annotate the whole svg is fine. So i guess, the soloution is fixing the paste(expression()) function. But i didnt found a solution for that.

Data <- read.csv2("Data.csv", header = TRUE, sep = ";", dec = ",")
Data$ï..Date <- as.Date(Data$ï..Date, format = "%d.%m.%Y")

Gesamt_Plot1 <- ggplot() +
  geom_point(aes(X$EC,Y$BC), show.legend = FALSE, shape = 1, size = 1.5, na.rm = TRUE)+
  geom_abline(linetype = "dashed")+
  geom_segment(aes(x = 0.19,xend = 5.49, y = G1_slp*0.19,  yend = G1_slp*5.49), color = "black", size = 1.2, na.rm = TRUE)+
   annotate(geom="text", x = 4, y=6.4, parse = T, label=paste(expression(EBC~"="~"0,92*"*EC[TOR]~~R²~"="~"0,89")), color="black")+
   annotate(geom="text", x=0.1, y=7, label="a)", color="black")+
   labs(colour = "", x=expression(EC[TOR]~"in"~mu*g~m^-3), y=expression(EBC~"in"~mu*g~m^-3))+
    theme_bw()+
    theme(axis.text.y=element_text(size = 12), axis.text.x = element_text(size = 12),
        axis.title = element_text(size = 12), legend.position = "bottom", panel.grid.minor = element_blank())+
    scale_x_continuous(limit = c(0,7),
                     breaks = c(0, 1, 2, 3, 4, 5, 6, 7)
    )+
    scale_y_continuous(limit = c(0,7),
                     breaks = c(0, 1, 2, 3, 4, 5, 6, 7)
    )

https://i.stack.imgur.com/9axhZ.png
Using R Version 4.0.5 and ggplot v3.3.3.

A: Not sure I can reproduce your problem, but I think you should not be using paste(expression(..)), just use expression(..). (Incidentally, I changed from your R² to R^2 in the expression; I'm not certain if it's a UTF problem in my emacs/ess or not. Try it both ways if you prefer.)
ggplot(mtcars, aes(mpg, disp)) +
  geom_point() +
  annotate(geom="text", x=20, y=60,
           label=expression(EBC~"="~"0,92*"*EC[TOR]~~R^2~"="~"0,89"))
# Warning in is.na(x) :
#   is.na() applied to non-(list or vector) of type 'expression'

In the R graphics pane, I see

Saving to svg:
ggsave(filename="mt.svg")
# Warning in is.na(x) :
#   is.na() applied to non-(list or vector) of type 'expression'

which then shows

Note: due to a long-standing ... bug/feature (?) in ggplot2, it warns about expressions. Granted, it's just a warning (and it plots fine), so it can be ignored. See Why does ggplot annotate throw this warning: In is.na(x) : is.na() applied to non-(list or vector) of type 'expression'. Another method is this:
ggplot(mtcars, aes(mpg, disp)) +
  geom_point() +
  annotate(geom="text", x=20, y=60,
           label=list('EBC~"="~"0,92*"*EC[TOR]~~R^2~"="~"0,89"'),
           parse=TRUE) +
  labs(colour = "", x=expression(EC[TOR]~"in"~mu*g~m^-3), y=expression(EBC~"in"~mu*g~m^-3)) +
  theme_bw()

(using list('...') instead of expression(...), and adding parse=TRUE). This produces the same effect.


text:
Q: How do I convert RGBA raw buffer to PNG file in Javascript? In Node.js I would like to compress a save a PNG image file from an array of raw RGBA pixel values.
  for (var x = 0; x < pixelSize; x++)
    for (var y = 0; y < pixelSize; y++) {
      const offset = (y * pixelSize + x) * 4 // RGBA = 4 bytes
      buffer[offset    ] = x    // R
      buffer[offset + 1] = y    // G
      buffer[offset + 2] = 0    // B
      buffer[offset + 3] = 255  // Alpha
    }

How do I convert it to a PNG image file on disk?

A: Use jimp for example:
var Jimp = require('jimp')

const pixelSize = 256
var image = new Jimp(pixelSize, pixelSize, function (err, image) {
  let buffer = image.bitmap.data
  for (var x = 0; x < pixelSize; x++) {
    for (var y = 0; y < pixelSize; y++) {
      const offset = (y * pixelSize + x) * 4 // RGBA = 4 bytes
      buffer[offset    ] = x    // R
      buffer[offset + 1] = y    // G
      buffer[offset + 2] = 0    // B
      buffer[offset + 3] = 255  // Alpha
    }
  }
  image.write('image.png')
})


text:
Q: The norm of a bounded linear functional on a Hilbert space is the norm of the vector? If $L$ is a bounded linear functional on a Hilbert space $H$, then we know that
$$Lx=(x,y),\quad \forall x\in H,$$
for some $y\in H$. Is it true that $\|L\|=\|y\|$?
We have by Cauchy-Schwarz that
$$|Lx|=|(x,y)|\leq\|x\|\|y\|,$$
so $\|L\|\leq\|y\|$, but what about the other inequality?

A: Yes. Unless $y=0$, we have
$$\|L\|=\sup_{\|x\|=1}|(x,y)|\geq|(y/\|y\|,y)|=\|y\|.$$
If $y=0$, then $\|L\|=0=\|y\|$.


text:
Q: Detect when UISplitViewController changes display mode I'm trying to use a UISplitViewController where the secondary controller should expose a "close" function (via a button or button bar item) whenever the UISplitViewController is in side-by-side mode, but should hide the function at other times. I tried putting this in the secondary view controller:
override func viewWillAppear(_ animated: Bool) {
    if splitViewController!.primaryHidden {
        // hide the "close" UI artifact
    } else {
        // show the "close" UI artifact
    }
}

This correctly sets the visibility of the "close" function when the secondary view is first displayed, but if the UISplitViewController switches between expanded and collapsed (say, by rotating an iPhone 6s Plus), then this function is not called again (which makes sense, as the secondary controller remains visible). Consequently, the "close" function remains in its initial state--hidden or shown--even as the UISplitViewController changes mode.
How can I get the "close" function to hide or show in reaction to changes in the mode of the UISplitViewController?

A: There is the UIViewControllerShowDetailTargetDidChangeNotification notification for that:
// Sometimes view controllers that are using showViewController:sender and
// showDetailViewController:sender: will need to know when the split view
// controller environment above it has changed. This notification will be
// posted when that happens (for example, when a split view controller is
// collapsing or expanding). The NSNotification's object will be the view
// controller that caused the change.
UIKIT_EXTERN NSNotificationName const UIViewControllerShowDetailTargetDidChangeNotification NS_AVAILABLE_IOS(8_0);

Use as follows
- (void)viewDidLoad{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showDetailTargetDidChange:) name:UIViewControllerShowDetailTargetDidChangeNotification object:self.splitViewController];
}

- (void)showDetailTargetDidChange:(NSNotification *)notification{
    // changed from collapsed to expanded or vice versa
}

This Apple sample demonstrates how the table cell accessory changes from a disclosure indicator in portrait (denoting that a push will happen) to it being removed when changing to landscape split view:
https://developer.apple.com/library/archive/samplecode/AdaptivePhotos/Introduction/Intro.html
Note on iOS 13 beta, use addObserver with object nil because there currently is a bug they send the notification using the wrong object. They use their new UISplitViewControllerPanelImpl from the internal class cluster instead of the UISplitViewController object.
http://www.openradar.appspot.com/radar?id=4956722791710720

A: For future reference:
What about using the UISplitViewControllerDelegate??
It has a method called
splitViewController:willChangeToDisplayMode:

that should do exactly what you where looking for.
Documentation here

A: Okay, I found a simple solution. I was making a novice mistake. The trick is to override viewWillLayoutSubviews() instead of viewWillAppear(animated:). Then everything works as I want. It seems that viewWillLayoutSubviews() is called (sometimes more than once) every time the containing UISplitViewController changes its display mode, and that's exactly what I need to respond to. The only gotcha is that splitViewController might be nil on some of those calls, so it needs to be implemented like this:
override func viewWillAppear(_ animated: Bool) {
    if let svc = splitViewController {
        if svc.primaryHidden {
            // hide the "close" UI artifact
        } else {
            // show the "close" UI artifact
        }
    }
}

As part of my stumbling around to find a solution, I tried overriding traitCollectionDidChange(previousTraitCollection:). (I tried this because I wanted to react to device rotations.) At first I thought I was onto something, because this function also get called whenever the device rotates. Interestingly (and, frustratingly) I found that my view's splitViewController property was nil when this function is called. It seems odd that this should be so, since neither viewDidDisappear(animated:) nor viewWillAppear(animated:) is called when the UISplitViewController reconfigures itself. But why it should be nil is, I suppose, a question for another day.


text:
Q: Contradiction when solving a linear system with Gauss-Jordan elimination Consider a linear system with an unknown constant $a$:
$$
\left\{
\begin{aligned}
x+(a-1)y+az&=1 \\
ax+ay+az&=1 \\
a^2x+y+z&=a
\end{aligned}
\right.
$$
This gives us an augmented matrix:
$$A= \left[
\begin{array}{ccc|c}
  1&a-1&a&1\\
  a&a&a&1\\
  a^2&1&1&a
\end{array}
\right] $$
From the augmented matrix, it is clear to me that when $a = 1$, we will have one parameter, since there are three unknowns but only two equations.
Let $a = 1$:
$$ \left[
\begin{array}{ccc|c}
  1&0&1&1\\
  1&1&1&1\\
  1&1&1&1
\end{array}
\right] \xrightarrow{R_3 - R_2}
\left[
\begin{array}{ccc|c}
  1&0&1&1\\
  1&1&1&1\\
  0&0&0&0
\end{array}
\right] \xrightarrow{R_2 - R_1}
\left[
\begin{array}{ccc|c}
  1&0&1&1\\
  0&1&0&0\\
  0&0&0&0
\end{array}
\right]
 $$
So we get the solution $z = s, y = 0, x = 1 - s \implies \text{Infinite number of solutions}$.
However, if instead I don't consider $a = 1$ but only $a \ne 0$, then I can proceed with Gauss-Jordan elimination to eventually get the following RREF after these series of elementary row operations:
$$
\frac1aR_2\longrightarrow
R_1 \leftrightarrow R_2 \longrightarrow
R_2-R_1 \longrightarrow
R_1-\frac{1}{a^2}R_3 \longrightarrow
\frac{1}{a^2}R_3 \longrightarrow
R_3+R_1 \longrightarrow
a^2R_1 \longrightarrow
\frac{1}{a^2-1}R_1 \longrightarrow
R_2-aR_1 \longrightarrow
R_2+2R_1 \longrightarrow
R_3\leftrightarrow
R_1 \longrightarrow
R_2\leftrightarrow
R_1 \longrightarrow
R_3-R_2 \longrightarrow
R_2-R_1
$$
$$A_\text{RREF}=
\left[
\begin{array}{ccc|c}
  1&0&0&\frac1a\\
  0&1&0&\frac{-(a-1)}{a}\\
  0&0&1&\frac{a-1}{a}
\end{array}
\right]
$$
I had assumed that there was an error in my Gauss-Jordan elimination because this RREF implies that when $a = 1$, we have one and only one unique solution of $x = 1, y = 0, z = 0$. However, I plugged this matrix into MatLab and got the same RREF.
How can it be that when $a = 1$, we get two different solutions from the two row-equivalent matrices?

A: The contradiction here, if any, is between your expectation of what MatLab does and what it actually does. You are correct that there are multiple cases to be considered, but MatLab and other software plunges ahead without taking potential divisions by zero into account when the matrix elements involve unbound variables. From the MatLab documentation for rref:

If the elements of a matrix contain free symbolic variables, rref regards the matrix as nonzero.

In fact there are more cases to consider than the two you mentioned. If $a=0$, then the second RREF in your question involves division by zero, so you need to examine that case separately, too.

A: In the case $a=1$, the rows 2 and 3 of the $3\times 3$ matrix are the same and so the matrix has rank 2 and there are infinitely many solutions (the solution set is a line).
If $a\ne 1$, the $3\times 3$ matrix has rank 3 and there is unique solution.

A: If you want to rref and avoid any division at all you'll get
$$\begin{pmatrix}
a(a-2)(a^2-1)& 0 & 0 & (a-2)(a^2-1)\\
0 & -a(a-2)(a+1) & 0 & (a-2)(a^2-1)\\
0 & 0 & a(a^2-1) & (a+1)(a-1)^2
\end{pmatrix}.$$
From here it's eazy to consider all different cases.


text:
Q: Why is Twig sending HTML file from previous response? I'm using Klein for routing and Twig as template engine. I created 2 routes that work as intended. But When I redirect to /test it sends response from previous /[:name] (Just html, not sql) and /test as well, both stacked on each other (first previous /[:name] then /test).
I tried messing with .htaccess file, but with no success. For INFO I'm using xampp for my localhost and I set up virtual host.
Php code (index.php)

use Application\Database\connect;
use Application\DisplayData;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;

//Require autoload.php
require_once __DIR__ . '/vendor/autoload.php';

//Twig API
$loader = new FilesystemLoader(__DIR__.'\views\HTML');
$twig = new Environment($loader);

//Db connection global variable
$connect = new DisplayData();

//Klein router code
$klein = new \Klein\Klein();

//Home root
$klein->respond('GET', '/', function () use ($twig, $connect, $klein) {
    echo $twig->render('index.html', ['name' => $connect->getData("SELECT * FROM Zapis")]);
});

//Zapisnik seperate page
$klein->respond('GET', '/[:name]', function ($request) use ($twig, $connect, $klein){
    echo $twig->render('zapis.html', ['data' => $connect->GetSeperateData(
        "SELECT * FROM Zapis Where NaslovZapisa = ? limit 1",
        $request->name
    )]);

});

$klein->respond('GET', '/test', function(){
    return "Hello";
});

$klein->dispatch();

.Htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html !-f
RewriteRule . index.php [L]

A: So basicly, problem was that /[:name] and /test send response at the same time beacuse router didn't know the difference between /test that was sent from /[:name] and /test. So I just added /category/[:name] and left /test unchanged. Now It works fine.


text:
Q: Why is TIMEOUT= argument not recognized within SAS PROC HTTP? I'm trying to account for missing files at a specific URL. For example, running PROC HTTP to get the following Excel file https://www2.census.gov/programs-surveys/cps/tables/time-series/historical-poverty-thresholds/thresh17.xls runs without timing out, eventually returning a 304 code. The SAS documentation clearly lists TIMEOUT= as an optional argument, but when I try to use it I get a syntax error:

ERROR 22-322: Syntax error, expecting one of the following: ;, AUTH_ANY, AUTH_BASIC, AUTH_NEGOTIATE, AUTH_NONE, AUTH_NTLM, CLEAR_CACHE, CLEAR_CONN_CACHE, CLEAR_COOKIES, CT, EXPECT_100_CONTINUE,
                FOLLOWLOC, HEADERIN, HEADEROUT, HEADEROUT_OVERWRITE, HTTP_TOKENAUTH, IN, METHOD, NOFOLLOW, NOFOLLOWLOC, NO_CONN_CACHE, NO_COOKIES, OUT, PROXYHOST, PROXYPASSWORD, PROXYPORT,
                PROXYUSERNAME, PROXY_AUTH_BASIC, PROXY_AUTH_NEGOTIATE, PROXY_AUTH_NONE, PROXY_AUTH_NTLM, URL, VERBOSE, WEBAUTHDOMAIN, WEBPASSWORD, WEBUSERNAME.
  ERROR 202-322: The option or parameter is not recognized and will be ignored.

Here is my code:
filename resp "C:\response";
    proc http
        url="https://www2.census.gov/programs-surveys/cps/tables/time-series/historical-poverty-thresholds/thresh17.xls";
        method="GET"
        out=resp
        TIMEOUT=5;
    run;

Is there a different way to account for timeout issues within SAS?

A: Most likely you are not running SAS version 9.4M5.
The 9.4 What's new documentation states in 9.4M5 (September 2017)

PROC HTTP adds a DEBUG statement, the OAUTH_BEARER= procedure option and TIMEOUT= procedure option, and response status macro variables.


text:
Q: How to redirect to remote server web page from another java application using POST request I have a requirement wherein I have to send a POST request from my java web application to another remote server and the only information I have of the other remote server is the way they submit their request which is as follows:
<form action = "https://xyz.php" method="post">
    <input type="hidden" name=" param1 "  value="$param1" />
    <input type="hidden" name=" param2 "  value=" param2" />
    <input type="submit" name="submit" value="Submit" />
</form>

I tried sending the request through "HTTPURLConnection" and I am able to get the response code 200 which is OK. But the main thing I want to do is to open the remote server web page on the new tab.I am not able to make out how to do that. Please provide your valuable inputs

A: did n't quite sure what you ask for
<form action = "https://xyz.php" method="post" target="_blank">
it is used to open in a new tab.

A: You can do something like this:
var frm = $('<form   method="get" action="' + link + '" target="_blank"></form>')
$("body").append(frm);
frm.submit().remove();

From jsfiddle: https://jsfiddle.net/b039wc1h/93/


text:
Q: functions on sets proof (injective/surjective/bijective) question I have to prove the following three statements:
Let $A$ and $B$ be finite sets and let $f: A \rightarrow B$.
A. $f$ is one-to-one.
B. $f$ is onto.
C. $|A|=|B|$.
Prove that $(1)$ if A and B are true, then C is true, $(2)$ if A and C are true, then B is true, and $(3)$ if B and C are true, then A is true.
So far I have this:
(1). If $f$ is one-to-one, then for all $(x,b), (y,b) \in f$, $x=y$. If $f$ is onto, then for every $b \in B$ there is an $a \in A$ s.t. $f(a)=b$. This means that every value in the set $A$ maps to a distinct value in the set $B$. Thus, the sets have the same cardinalities, so, $|A|=|B|$.
(2). If $f$ is one-to-one, then for all $(x,b), (y,b) \in f$, $x=y$. And if $|A|=|B|$ then that means that every value of A maps to a distinct value in B. So, for every $b \in B$ there is an $a \in A$ s.t. $f(a)=b$, meaning $f$ is onto.
(3). If $f$ is onto, then for every $b \in B$ there is an $a \in A$ s.t. $f(a)=b$. And if $|A|=|B|$ then that means that every value of B must map to a distinct value in A. So, that means $f$ is one-to-one because there is no $(x,b),(y,b) \in f$ s.t. $x \neq y$.
But I don't know if I wrote enough for them?

A: Your attempts at (2) and (3) are incomplete. Why? In (2) if $A$ and $B$ are not assumed to be finite the conclusion that $f$ is onto is invalid. How did you use the finiteness?
Suppose we assume that "$A$ is finite" means that there does  not exist a  one-to-one function  from $A$ to  a proper subset of $A$. Now $|A|=|B|$ implies there exists a bijection $g:B\to A$. So in (2) if $f$ is not onto then $(gf)$ is a one-to-one function from $B$ to a proper subset of $B$.


text:
Q: How do I convert unicode code to string in Python? One of my string variables contains unicode code \u0631\u064e\u062c\u0627.
I want to convert it to a string and see what characters were encoded by it.
Is it possible and how can I do it in python?

A: That's just an internal representation. If you print it, you will get what you want:
>>> print("\u0631\u064e\u062c\u0627")
رَجا

In short, this is how Python stores the characters رَ and جا. If you tell Python to print them, you'll see them converted back to their human-readable form.

A: Decode using unicode_escape encoding:
In Python 2.x:
>>> text = r'\u0631\u064e\u062c\u0627'
>>> print(text)
\u0631\u064e\u062c\u0627
>>> print(text.decode('unicode-escape'))
رَجا

In Python 3.x:
>>> text = r'\u0631\u064e\u062c\u0627'
>>> print(text.encode().decode('unicode-escape'))
رَجا

A: >>> print u"\u0631\u064e\u062c\u0627"
رَجا


text:
Q: Setting up the cmake and package.xml of navigation stack I´m currently finishing my degree thesis which consists on developing an autonomous robot as cheap as possible. For this, I have been using a camera, a couple of motor drivers (Roboclaw 2x15A), a camera, 4 motors, aruco nodes for localization and 2 RPis (3B+ and 4). Right, everything works OK: camera topics publish info gathered from the aruco tag detection, etc.
The main problem is that I have my navigation package from navigation stack ros already created but I can´t come up with the dependencies of the package. So I would like to know which dependencies should have the CMake file and the package.xml.

A: Solved. I have just created another package with the dependencies I thought that were necessary and then copy the CMake changing the project name.
For the package.xml, just add:
<build_depend>your_dependency</build_depend>
<exec_depend>your_dependency</exec_depend>

As many times as dependencies you want to add.


text:
Q: do both json.load() and json.dump() at once in Python I am trying to do something like this which uses reading , appending and writing at the same time.
with open("data.json", mode="a+") as file:
            # 1.Reading old data
            data = json.load(file)
            # 2. Updating old data with new data
            data.update(new_dict)
            # 3.Writing into json file
            json.dump(data,file,indent=4)

But it shows json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

A: First you need to open the file in mode="r+". Update the old data with new, then seek(0) to the beginning of the file, write your updated json data, and then truncate the rest:
with open("data.json", mode="r+") as file:
    file.seek(0, 2)
    if file.tell():
        file.seek(0)
        data = json.load(file)
        data.update(new_dict)
    else:
        data = new_dict
    file.seek(0)
    json.dump(data, file, indent=4)
    file.truncate()

Reason it doesn't work with a+ mode is that it will always write at the end of the file, irrespective of seek(0). So your updated json data just gets appended to the older one  like a normal text data, but since its not a valid json syntax, it causes JSON Decode error.
Check here for more detailed info on how the different open modes work.


text:
Q: string split in LINQ This is wat i tried using split
string[] req_info_texts = Regex.Matches(model_file_string_qts_corrected,
                                          "RequirementInfo.*\"")
                               .OfType<Match>()
                               .Select(m=> m.Groups[0].Value.Split('\'').ToString())
                               .ToArray();

RequirementInfo.*\" Lines in the string "model_file_string_qts_corrected" is similar to
RequirementInfo   "{'1' 2' 3'4 '5' 6'7' 8'syed_syed' 'SRDD_PFC_047602' } %GIDa_033022bd_8058_4216_8b9d_71454ba5f896"

There were n no of lines like above in the string .
I need syed_syed in the array req_info_texts .
But wat i get is index out of range exception.
Can u say wat the mistake is?

A: string[] req_info_texts = Regex.Matches(input,@"RequirementInfo.*\"")
                               .Cast<Match>()
                               .Select(m=> m.Value
                                            .Split(''')
                                            .Where(x=>x.Contains("syed_syed"))
                                            .Single()
                                      ).ToArray();

A: Given your input string is

RequirementInfo    "{'other' ' ' '' 'true' 'syed_syed_GRP001' 'klajdskfjadklsjfklsa' } %GIDa_ed66dae7_2d68_4d07_9c67_a1cf1cb614cc" RequirementInfo     "{'other' ' ' '' 'true' 'syed_syed_GRP001' 'klajdskfjadklsjfklsa' } %GIDa_b9a766f9_2b2b_4ca8_98f4_f693055b4792" RequirementInfo     "{'other' ' ' '' 'true' 'syed_syed_GRP004' 'klajdskfjadklsjfklsa' } %GIDa_271d5326_cb57_4d87_8cd9_66687c0a1d32" RequirementInfo     "{'other' ' ' '' 'true' 'syed_syed_GRP03' 'klajdskfjadklsjfklsa' } %GIDa_07ed6119_91d2_41f9_94dc_69d518503d64"

just with newlines, as you said in a comment on another question, you just need two splits:
var infosString = "RequirementInfo   \"{'other' ' ' '' 'true' 'syed_syed_GRP001' 'klajdskfjadklsjfklsa' } %GIDa_ed66dae7_2d68_4d07_9c67_a1cf1cb614cc\"\nRequirementInfo  \"{'other' ' ' '' 'true' 'syed_syed_GRP001' 'klajdskfjadklsjfklsa' } %GIDa_b9a766f9_2b2b_4ca8_98f4_f693055b4792\"\n RequirementInfo     \"{'other' ' ' '' 'true' 'syed_syed_GRP004' 'klajdskfjadklsjfklsa' } %GIDa_271d5326_cb57_4d87_8cd9_66687c0a1d32\"\n RequirementInfo     \"{'other' ' ' '' 'true' 'syed_syed_GRP03' 'klajdskfjadklsjfklsa' } %GIDa_07ed6119_91d2_41f9_94dc_69d518503d64";
var result = infosString.Split('\n').Select(line => line.Split('\'')[9]).ToArray();

result is now

The first Split creates an array with the strings starting with RequirementInfo, and the Select splits these strings again and takes the 10th items (the ones starting with syed_syed).


text:
Q: Who exactly is the Valeyard, considering the events of Time of The Doctor? In the Sixth Doctor serial The Trial of a Time Lord, we encounter the prosecutor, The Valeyard, who later turns out to be "an amalgamation of the Doctor's darker sides from between his twelfth and final incarnations", at least according to the Master.
Now according to the new count, Smith's Doctor was the thirteenth, so the Valeyard must have come between Tennant's and Smith's. Then the question is: what did we miss? I didn't see any Valeyard spring into existence?
So, was the Master making that up, to confuse matters? Was the Valeyard simply someone else, who had reasons of his own to want the Doctor dead?
Or is the Valeyard now officially part of an alternate timeline, which we will never experience in the canonical series?
Or... is the Valeyard actually the human Doctor that was created from his hand in Journey's End, a.k.a. the meta-crisis Doctor? He did, after all, live in an alternate universe, which might accidentally have been the same as the one Gallifrey was sent to... This also explains why the Valeyard was so hungry for a new set of regenerations.

A: In "The Name of the Doctor", the Great Intelligence said that the Doctor would be called Valeyard "before the end". From the GI's perspective, the Doctor's timeline ended on Trenzalore in "The Time of the Doctor". So either the GI was wrong and the Valeyard was not going to happen before the end, the Valeyard did occur between "Name" and "Time" and we didn't see it, or the Valeyard was going to occur but something altered the Doctor's fate.
Now in "The Day of the Doctor" we saw 12, even though by the normal count there shouldn't have been a 12 because 11 was out of regenerations. Bit of a paradox there. 12 helped save Gallifrey, and later Gallifrey created 12. And 11 wouldn't have died on Trenzalore if 12 hadn't existed to save Gallifrey, because 11 would never have had cause to go to Trenzalore! And if the War Doctor had actually used the Moment, Trenzalore would again never have happened, because again, no Gallifrey.
So we can assume that the events of "Day" did not alter the Doctor's fate as GI saw it, because they must have "already happened" for the Doctor's tomb to be on Trenzalore. The only reasonable point of divergence that could prevent the Valeyard is something Clara did in the Doctor's timestream, or maybe something 11 did or saw himself while there.
Either way, Valeyard may yet happen, but not as GI saw it.
Of course, I prefer to think that the Valeyard was just a historical anomaly that the GI somehow became aware of, not that he was prognosticating. Or maybe that "Valeyard" is a common word that means "He who sucks" or something, and the Doctor may be called it without actually being the Valeyard.

A: I always thought that the origin of the Valeyard was when David Tennant's Doctor went a bit nuts and power hungry during the events of Water of Mars calling himself the 'Timelord Victorious.' I figured that if it wasn't for the intervention of the Ood insisting that it was time for his regeneration, than 10 would've become the Valeyard. This happens at the right time too, because as we know now, Tennant was the 12th incarnation and he was soon to change into his final one. Presumably, someone created the Valeyard by intervening at this moment, allowing Tennant to continue on this darker path, only to finally regenerate into the Valeyard as seen by six.

A: Unknown / timey-wimey / TBA.
The Valeyard's origins have not been elaborated on in the new series. Since "between his twelfth and final incarnations" could now mean "any time from here on out" (the Doctor's got a lot more "incarnations" to go through), we could learn more about it in the future.
Leaving that aside, the notion that the Meta-Crisis Doctor is the Valeyard has a lot of merit, but like every other theory it is currently unsupported by any on-screen evidence.
The War Doctor is almost certainly not the Valeyard though. He's self-loathing, not self-venerating, and the key trait of the Valeyard is that he considers himself better than his other selves.
It's possible that the Valeyard, by failing in his own scheme, was relegated to a potential future never realized.
Alternately, he could be a Watcher (the manifestation of a potential Time Lord whose duty is to ensure the wellbeing of his real-life counterpart) gone wrong.

A: If I am correct, the Master said incarnations, not regenerations. So as a recount, the unveiling of the War Doctor bumped all the new doctors up one making Matt Smith's 11th actually 12; since 10 only regenerated but kept the same face.And according to the Great Intelligence, when talking about the Doctor's dark sides and dark future, one of his regeneration forms would be the Valeyard.
I think the Valeyard is still coming "before the end" but not just yet.On another note when talking about series 8 with Capaldi, it was announced that this doctor was darker. I guess we can only wait and find out.

A: No one seems to have mentioned the theory I've seen a lot (here for example): that the Dream Lord from the episode "Amy's Choice", who was a kind of personification of all the darker aspects of the Doctor's subconscious given power by some "psychic pollen" trapped in the TARDIS time rotor, was somehow able to manifest in the physical world after that episode, and become the Valeyard. (or maybe the Valeyard was never physical at all, just a collective hallucination experienced by everyone in the room with him!) This would fit the Master's comment in "The Ultimate Foe" (transcript here) that the Valeyard was "an amalgamation of the darker side of the Doctor's nature", since in "Amy's Choice" (transcript here) the Doctor described the Dream Lord in similar terms: "The Dream Lord was me. Psychic pollen. It's a mind parasite. It feeds on everything dark in you, gives it a voice, turns it against you. I'm nine hundred and seven. It had a lot to go on."
In addition, this theory could fit the Master's comment that the Valeyard came from "somewhere between your twelfth and final incarnation", especially if "somewhere between" is meant to express uncertainty rather than saying he was literally created in the process of the twelfth incarnation regenerating into the thirteenth. As we learned in "Time of the Doctor", the Matt Smith Doctor was really the 13th incarnation, since the War Doctor and the regeneration that spawned the Meta-Crisis Doctor (which allowed the David Tennant Doctor to regenerate into the same body, by making use of his own severed hand from "The Christmas Invasion") both "counted". I suppose it's also possible that the Dream Lord really did begin to manifest in the Doctor's subconscious during the process of the David Tennant Doctor regenerating into the Matt Smith Doctor (perhaps because Tennant's Doctor feeling that he didn't "want to go" immediately before regenerating), and the psychic pollen just further solidified him and gave him the power to affect the dreams of others.

A: As with so much from the classic series, the Valeyard has become an anomoly that has no legitimate explanation. In-universe, all we have to go on are two almost throw-away lines that describe his origins:

*

*The Master, in Trial of a Time Lord, gives the only on-screen information we have about his origin: "somewhere between your twelfth and final incarnation.".

*The Great Intelligence also mentions The Valeyard as one of the names that The Doctor will eventually be known as.

Unfortunately, both of those directly contradict the events of David Tennant and Matt Smith's tenures as the Doctor. By The Eleventh Doctor's own count, the Tenth Doctor was actually both the 11th and 12th incarnations, and he was supposed to be the "final" and was going to die. (Note that, on TV, the Master says "twelfth and final incarnation", but when the episode was turned into a novel, it was changed to "twelfth and thirteenth regenerations", which is even worse.) This means there is no opportunity for the Valeyard to come into being, if we interpret The Master's meaning in the most obvious way.
There are, however, a few alternative ways we can look at the Valeyard to try and force him to fit into canon:

*

*There's a popular theory that meta-crisis Tenth Doctor will become the Valeyard, which was explored in some supplemental materials (a comic book series, I think) but quickly rejected again. I don't see much support for this idea, since there's no indication that "Doctor" could get back to our universe, or that he could ever regenerate if he did.

*It's possible that the Valeyard was created off-screen at some point already, and we just didn't see it. Not very satisfying, but hard to argue against.

*It's possible that the Valeyard is yet to come, since Eleven is no longer the "final" incarnation. It's even possible that The Master was using The Doctor's own not-yet-created messed up numbering, and really meant "the Twelfth Doctor", despite being the 14th incarnation (13th if you count "distinct" incarnations).

Personally, I think The Valeyard is never going to happen, but that's based partly on information from the one of the audio productions, which is always sketchy canon-wise. In "Trial of the Valeyard" he explains that he was created by the "Thirteenth Doctor" as part of his attempts to get more regenerations illegally. After the events of "Time of the Doctor", there's no reason the Thirteenth Doctor (regardless if you consider that to be Matt Smith or the person that will follow Peter Capaldi) will need to try to bypass the regeneration limit, so there's no reason the Valeyard needs to occur.
In other words, there has been enough change in the Doctor's own future since "Trial of a Time Lord", including the Time War, rebooting the Universe, getting more regenerations, etc; that the Valeyard can likely be relegated to a remnant of an old, now-defunct timeline.

Out of Universe, the Valeyard is an absolute disaster, even for the famously canon-immune Doctor Who. For example, the New Adventures book series (the one with the Seventh Doctor in it) specifically forbade authors from mentioning anything about the Valeyard, calling it a  "continuity nightmare".
Even the Doctor Who production team was pretty unhappy with the continuity mess created by The Valeyard. The original ending did, in fact, have The Doctor eventually become The Valeyard directly, and thus become a villain. The producers objects to this so strongly that the original script writer that created The Valeyard quit, and refused to let anyone use his script or and of its ideas in the show. So, if it seems like the Valeyard was a half-thought-out idea that was just kind of dropped on the floor -- that's exactly what happened, for legal reasons :)

A: I was under the impression that an incantation of the doctor is different to regeneration of the doctor. Incantation of the doctor means when the doctor actually calls himself the doctor. I had this thought when I watched the 50 th anniversary. Where we might have seen two regenerations that do not call themselves by the name of the doctor. This makes me wonder whether the doctor might change his name in the future.
The war doctor classes as regeneration because he is a new face, but he is not an incantation of the doctor because he does not call himself the doctor. If this is the case then neither does the meta-crisis doctor class as an incantation because he is a person that has taken the role before which means Peter Capaldi is the twelfth incantations and all the others I said before do not bump up the incantations.
The curator could be the doctor as he said to his eleventh incantation that he will revisit his favourite ones. Now you may be wondering about where I lie with the quandary of the valyard I think the valyard is a life in his cycle one that is evil. I think the valyard has to be the next life because the master was trying to stop the doctor being charged for crimes he did not commit. He might actually be saying a truth. The valyard is a regeneration where he does not call himself the doctor again. Which means the incantation can mean only on thing that the valyard is referred to his next regeneration and again he will not be known as the doctor.

A: It's possible Jo Martin (The Timeless Child) is actually the Valeyard considering she, just like in "The Trial of a Time Lord", seems to help the Master who narrates just about everything, (highly suspicious) and when the real Doctor tries to ask the supposed other Doctor about it, she doesn't answer. Sounds like the Master and the other Doctor were working together to mess up the real Doctor.

A: Smith's Doctor wasn't the "final" incarnation spoken of by the Master. Notice he doesn't say "thirteenth". Smith's Doctor may have been the thirteenth regeneration, but he was the twelfth "incarnation" when you count the War Doctor.
So it seems his new regeneration cycle was somewhat already fated, since The Great Intelligence knew about his future title and since the events of Trial of a Time Lord already took place in the timeline that ended with Smith...

A: @user30567: Capaldi is actually the 14th incarnation, seeing as Tennant's first regeneration counts as a change (even though he didn't change), because he still used up what could've been his 12th incarnation. So when the time came for him to regenerate in the End of Time, he naturally changed into his 13th incarnation (Smith). Capaldi is known as the 12th Doctor, because he came straight after the incarnation called the 11th Doctor, but because of the new regeneration cycle, he's actually the 14th incarnation so far, and the 1st incarnation of the second cycle. Capaldi is the start of a new generation of Doctor Who. Either, the Valeyard won't exist, or he'll appear again much later. I don't think the Doctor will necessarily become him, but he probably will have moments (like in the Waters of Mars), where he acts like him.

A: I always thought the Valeyard was an incarnation of the dark aspects of the Doctor's possible futures. Back in the day, PBS was constantly re-playing its stock of Dr Who: all of Tom Baker over and over, then they eventually bought the tapes of Peter Davidson, then finally Colin Baker. So I saw all episodes many times.  Anyway, when I watched Trial of a Time Lord, I immediately thought of a "Watcher gone wrong" scenario, as only one other person suggested. I always thought the Valeyard did not come back to the Trial from the Drs future, but that he was created AT THE TIME OF THE TRIAL, sort of distilled from the Dr's possible future incarnations, by the Time Lord officials who were covering their political butts by framing the Dr with help from his "future" dark side. Right? This potential future Doctor's payment would be to give HIM those actual future incarnations, thus making him a real boy.

A: This hasn't been answered in the series yet. However, the Valeyard is an "amalgamation" of aspects of different incarnations of the Doctor, not an incarnation himself. This means that he may have been created for the purpose of the trial, and not actually expected to appear between the two incarnations mentioned.
But there is something else that seems to have been missed:

"an amalgamation of the Doctor's darker sides from between his twelfth and final incarnations"

Firstly, it says "incarnations", not "regenerations". So the writers could, with hindsight disregard the silly "meta-crisis" regeneration, because it did not result in a new "incarnation". Arguably though, the 'War Doctor', who is not counted as the 9th because he did not use the name "The Doctor", is arguably an "incarnation", especially as the Valeyard represents the Doctors "darker sides", which the War Doctor most definitely was.
Retroscripting then, the "twelfth incarnation" could refer either to Matt Smith's Doctor or Peter Capaldi's, depending on whether or not you count the War Doctor. But who is the "final" incarnation? They never said the thirteenth. So, as The Doctor has been granted a whole new regeneration cycle (another 12?) we are yet to know who the "final" incarnation will be. The existence of 'The Curator' implies there could be countless future generations to come.
The Valeyard will probably never be mentioned again, but if he were, there are plenty of ways that he could be explained.

A: The actual answer is that the Valeyard still has the potential to re-appear at some point in the future. Due to an accidental script distinction that probably didn't mean at the time, what it now means. (Aside from the fact that he survived the final episode of "The Trial of a Time Lord" and may still just be... "Out there somewhere" just waiting for a bored Exec Producer with writers block to re-introduce.)
In "The Trial of a Time Lord", the Valeyard is described as being an amalgamation of the Doctor's darker side from between his Twelfth and FINAL incarnation. The distinction between "Final" and "Thirteenth" may not have been deliberate at the time, given that the episode in which it appears was from a draft by Robert Holmes who died before being able to script it, and was written as a mash between John Nathan Turner and Eric Saward (who hated Turner and had already quit the show but agreed to stay to help finish Holmes' script) its hard to know exactly what was going on with that very troubled production, let alone trace the meaning behind a single line of dialogue, (which Anthony Ainley may well have even improvised...)
Now that the Doctor has bypassed his Twelfth incarnation, and has many more ahead of her, that distinction means at any point between his Twelfth, and their final, body the Valeyard might just pop up.

A: Well, In terms of the Great Intelligence mentioning that the Valeyard is known in the future, it is well shown that the Doctor will use that name pretty freely.
He has listed it among his names and achievements many times when trying to establish that he is not be messed with so I don't find it a far stretch for some Doctor of the future to either use the name as an alias or mention himself as the Valeyard in a well documented moment like a history changing speech.
I just think that the Doctor comfort in owning up to that identity as his own makes what the Great Intelligence said strong suggestion of the Valeyard future existence but not proof.
PS. The master refers to the Valeyard as "An an amalgamation of the Doctor's darker sides from between HIS twelfth and final incarnations".
This could be referring to the future form of the current Doctor in the room(6)  and his gender currently. Or it could be a hint as to which Doctor he and the Valeyard identify as the 13th.
My personal belief is that sometime in the future, something happens that causes the Valeyard to sever from the Doctor and take a physical form but without his memories. This Doctor would then find out about his other form and check up on his mishaps such as when the old man in the gallery above the UNIT vault met with the 11th Doctor and suggested that he was a future Doctor.
Then, this anti Doctor would end up discovering all the things that caused him to become the sentient voice in the back of the Doctors head that wanted to break free. This would cause him to turn into the Valeyard we see in the show who is intent on destroying the Doctor and becoming powerful.
I like the idea that the Master found the Anti Doctor and tricked him into Becoming the Valeyard. Then once an opportunity presented itself, he allowed the Valeyard to become known the the High Counsel of Gallifrey and for the events of the 6th Doctor's trial to take place.

A: Using a modified version of Rule #1, The Master lies, it's possible the Valeyard from Trial is NOT the Doctor at all, but another Time Lord that took one of the Doctor's "names".

A: Incarnations are not the same as regenerations. Tennant was the 11th incarnation and Smith was the 12th incarnation. Even though Tennant regenerated twice, he kept the same face for one of them, therefore same the incarnation. So that means that Capaldi is the 13th incarnation and the Valeyard would have to appear during Capaldi's run as the Doctor!

A: I think the meta-crisis doctor is the valeyard. He was already a bit insane. Ad he apperently escaped "rose's dimension" and went back to gallifrey to prosecute the doctor.

A: I like the theory that the "Dream Lord" may become the Valeyard. I do not believe the "meta-crisis Doctor" would work here. Although he may find a way to leave the parallel universe, I don't think he would willingly leave Rose. Also, I seem to remember him telling Rose he wasn't capable of regeneration at all. The "Dream Lord" theory just seems to fit better to me. He seemed to have an over-abundant disgust of the Doctor. It was very reminiscent of the hatred that the Valeyard showed of the Doctor. To be quite honest, I don't think it would set well with Who fans if the Doctor became a total villain. We can handle his dark side, but it must be tempered with his usual compassion. Master/Mistress is a big enough Time Lord villain. Plus...who knows...Rasselon may still be out there, and he is a maniacal Time Lord with a God complex. Of course, there is much merit in the above comments concerning the Valeyard possibly being an entity from a previous timeline which has now been changed, thus eliminating him altogether. We may never know for sure. However, with Steven Moffat....nothing surprises me. He thrives on taking Doctor Who into unexpected territory.

A: What I believe would make for the best story is the meta crisis persona. It possessed the best ability to neatly tie the story together. Recently Davros makes a comment about a prophecy concerning a combination of time lord and another race which would create a superior being. If you were the meta crisis being what would you do. Simply sit back and let all you knew go to waste or put it to use. Also, he was not called the doctor and Rose would have made an excellent first victim of Jack the Ripper. I do know that if I were him one of the first things I would be doing is building a TARDIS and somewhere down the line a way to navigate to parallel universes.

A: Is it possible that the Tenth Doctor didn't use a regeneration to keep his body because he had "vanity issues" but because he was worried that he would otherwise regenerate into the Valeyard? Think about it, Tennant's Doctor could be very aggressive, as was the Meta-Crisis Doctor, so it would make sense he would fear that he could become the Valeyard in his next regeneration.


text:
Q: Regarding Springboot Security returning login page inside UI I am making Rest calls to Springboot controllers and have security configuration which need authorization and roles for accessing certain URL.
http.authorizeRequests()
        .antMatchers("/api/admin/**").access("hasRole('Admin')")    //
        .antMatchers("/api/user/**").hasAnyRole("Admin","User")
        //.antMatchers("/api/user/**").access("hasRole('User')")
        //.and().logout()
        .and().formLogin()
        .loginPage("/login").usernameParameter("userName").passwordParameter("password")

Now the issue is when i gets logout from Spring controller side (like application restarted OR timeout etc), when User gets this call, it returned me whole login page UI. I want Spring to return me some status code and some message saying that session time out OR something which i can get user to call logout.

A: So i was able to sort the things in traditional way as Spring does not gives me any specific status code but 200 in this case.
I made an instanceof check in my AngularJS controller code like this-
if(response.data instanceof Object){
   self.list = response.data;
 }
else{
  logout();
 }

This solved my case. If there is better way, please comment.


text:
Q: Valgrind multiple "invalid write/read of size 1" errors My program reads in people from a file and saves their information to a Person structure that looks like this:
struct person
{
    char *fname;
    char *lname;
    int id;
};
typedef struct person Person;

These people are held in an array of Persons and the function to fill that array looks like this (the total variable is the total number of Persons counted from the file):
Person* fillArray(int total, FILE *fin)
{
    rewind(fin);
    int i;
    char temp[50];
    char temp2[50];
    Person *p = (Person*) calloc(total, sizeof(Person));
    for(i = 0; i < total; i++)
    {
        fscanf(fin, "%s", temp);
        p[i].fname = (char *) calloc(strlen(temp)+1, sizeof(char));
        strcpy(p[i].fname, temp);
        fscanf(fin, "%s", temp2);
        p[i].lname = (char *) calloc(strlen(temp)+1, sizeof(char));
        strcpy(p[i].lname, temp2);
        fscanf(fin, "%d", &(p + i)->id);
    }
    return p;
}

I cleanup all my memory used and I calloc for the '\0' at the end of the temp strings. Not sure why I get these errors:
HEAP SUMMARY:
==4736==     in use at exit: 0 bytes in 0 blocks
==4736==   total heap usage: 8 allocs, 8 frees, 414 bytes allocated
==4736==
==4736== All heap blocks were freed -- no leaks are possible
==4736==
==4736== ERROR SUMMARY: 10 errors from 2 contexts (suppressed: 0 from 0)
==4736==
==4736== 3 errors in context 1 of 2:
==4736== Invalid write of size 1
==4736==    at 0x402C6E8: strcpy (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==4736==    by 0x804898E: fillArray (cscd240_s13_lab11Functions.c:30)
==4736==    by 0x8048731: main (cscd240_s13_lab11Tester.c:13)
==4736==  Address 0x41ef24f is 3 bytes after a block of size 4 alloc'd
==4736==    at 0x402A5E6: calloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==4736==    by 0x804896A: fillArray (cscd240_s13_lab11Functions.c:29)
==4736==    by 0x8048731: main (cscd240_s13_lab11Tester.c:13)
==4736==
==4736==
==4736== 7 errors in context 2 of 2:
==4736== Invalid write of size 1
==4736==    at 0x402C6C3: strcpy (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==4736==    by 0x804898E: fillArray (cscd240_s13_lab11Functions.c:30)
==4736==    by 0x8048731: main (cscd240_s13_lab11Tester.c:13)
==4736==  Address 0x41ef24c is 0 bytes after a block of size 4 alloc'd
==4736==    at 0x402A5E6: calloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==4736==    by 0x804896A: fillArray (cscd240_s13_lab11Functions.c:29)
==4736==    by 0x8048731: main (cscd240_s13_lab11Tester.c:13)
==4736==
==4736== ERROR SUMMARY: 10 errors from 2 contexts (suppressed: 0 from 0)

Thank you for the help. I have looked through several threads and most of them are about not calloc/mallocing for the '\0' at the end of chars. I do this however I still get these errors and many more when I sort the Person array with qsort(). I apologize if this is the same problem that has been asked before, I could not find the thread.

A: You're using the wrong length for the allocation of the second part,
fscanf(fin, "%s", temp2);
p[i].lname = (char *) calloc(strlen(temp)+1, sizeof(char));
strcpy(p[i].lname, temp2);

That should use strlen(temp2); there.


text:
Q: How to get the applications icon from the Google play dynamically I'm developing an application that show a list of applications, and I want to get the Icon of this applications from the Google play store to show it in the list, so if there are any way to do that please tell me.

A: I had to tackle this problem myself recently in updating my portfolio website, so i even have some code for you :) What i did was in php but i'm not sure what you want to use. First i checked the source of the page with my app on it using view->developer->developer tools (on chrome). Then using that i could traverse the DOM looking for something i could use to identify the app icon. I found this:

what this showed is that the app icon was held inside a div with class "doc-banner-icon" - I couldn't find this class anywhere else, so i take it for granted that it is the only div with that class. Then in my php code i used simpledomparser to load the url, locate the icon and spit out it's url, like so:
<?php
include('simple_html_dom.php');

$html = file_get_html("https://play.google.com/store/apps/details?id=com.smithyproductions.swissarmycarrot"); //put your app id here

$bannerImage = $html->find('.doc-banner-icon'); //the class we found before

$img = $bannerImage[0]->find('img'); //find the img tag inside the div

$imgUrl = $img[0]->src; //get its src url

$arr = array(); //in my own example I filled this array with other things like the title an screenshots

$arr['imgUrl'] = $imgUrl;

echo json_encode($arr); //output it in an easy to read format

?>

resulting in something like
  {'imgUrl','https://lh6.ggpht.com/1WMU4E3lnbjz5yxLHxsPrJAJPw3uYZ8LXk3QkD1EKOxwOcHu0W9QyGlpM5AfrKYEVzzi=w124'}
Just one thing to bear in mind about this approach: Google could change the way everything is presented and laid out at any time so prepare to update your app when this happens :)

A: I modified the code by roarster to get working with new web page of the play store and i simplified it:
<?php
include('simple_html_dom.php');

$play_link = $_GET['playlink']; //Play store link

$html = file_get_html($play_link); //put your app id here

$bannerImage = $html->find('div.cover-container'); //the class we found before

$img = $bannerImage[0]->find('img'); //find the img tag inside the div

$imgUrl = $img[0]->src; //get its src url

$arr = array(); //in my own example I filled this array with other things like the title an screenshots

$arr['imgUrl'] = $imgUrl;

echo json_encode($arr); //output it in an easy to read format

?>

Now you load for example: yourwebpage.com/script.php?playlink=https://play.google.com/store/apps/details?id=com.igg.android.im
and you get the result ;)

A: The problem Google keep changing the structure of the page, so far I couldn't find any resource in how to handle this in an official way similar to Apple Store.
Anyway, below is the php code that I use as of today (June 2019)
PS: in my code, once I manage to get the icon URL I cache it in my database so I don't have to look it up again in google play store
          try{
            $lookupData = @file_get_contents('https://play.google.com/store/apps/details?id=com.google.android.gm&hl=en');
            // Not valid any more
            $pregString = '/<meta itemprop="image" content="(.*?)"\/>/';

            //June 2019
            $pregString = '/<img src="(.*?)" srcset=".*" class=".*" aria-hidden="true" alt="Cover art" itemprop="image">/';
            preg_match($pregString, $lookupData, $output);

        } catch (\Throwable $e) {
            $error = $e->getMessage();
            if (strpos($error, '404 Not Found') === false) {
                //unknown error
            }else{
                //Package not found, use default icon or something
            }
        }
        if(isset($output[1])){
            //Store $output[1];
        }else{
            //icon not found, use default icon or something
        }


text:
Q: Serial Port Trigger DataReceived when certain amounts of bytes received I am trying to write a program that updates a windows form every time new data comes in on a serial port, but am struggling with understanding how the serial port works, and how I can use it in a way I want it.
I have an external device sending 8 bytes at 1Hz to my serial port, and wish to use the DataReceived event from the SerialPort Class. When I debug my code, the event is more or less triggered randomly based on what the program is doing at a certain time. The code as is is below:
    private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        //byte[] rxbyte = new byte[1];
        byte[] rxbyte = new byte[8];
        byte currentbyte;
        port.Read(rxbyte, 0, port.BytesToRead);

        currentbyte = rxbyte[0];

        int channel = (currentbyte >> 6) & 3; //3 = binary 11, ANDS the last 2 bits
        int msb_2bit = (currentbyte >> 0) & 255; //AND compare all bits in a byte
        currentbyte = rxbyte[1];
        int val = ((msb_2bit << 8) | (currentbyte << 0));

        //Extra stuff

        SetText_tmp1(val.ToString());
    }

I want to be able to have exactly 8 bytes in the receive buffer before I call the Read function, but I am not sure how to do this (never used SerialPort class before), and want to do all manipulation of data only when I have the entire 8 bytes. Is there a built in way to toggle the event only when a certain amount of bytes are in the buffer? Or is there another way to obtain only 8 bytes, but not more, and leave the remaining bytes to the next instance?

A: Yeah, you are not coding this correctly.  You cannot predict how many bytes you are going to receive.  So just don't process the received bytes until you've got them all.  Like this:
private byte[] rxbyte = new byte[8];
private int rxcount = 0;

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    rxcount += port.Read(rxbyte, rxcount, 8 - rxcount);
    if (rxcount < 8) return;
    rxcount = 0;
    // Process rxbyte content
    //...
}

A: Set the ReceivedBytesThreshold property to 8. As in port.ReceivedBytesThreshold = 8;

A: An effective way to handle this is to add a timer to the class that ticks along at maybe 9 times a second. Eliminate the serial port event handler completely.
At each timer tick have the code check the serial port for bytes received from the serial port. If there are some there then grab them out of the serial port and append them to the end of buffer maintained in the class as a data member.
When the buffer has eight or more characters in it then timer tick logic would take the first 8 bytes out of the buffer and use them to update the user interface window. Any remaining bytes in the buffer can be moved up to the head of the buffer.
The timer tick routine can also maintain a counter value that increments each time the tick comes in and there is no data ready at the serial port at this tick. When this counter reaches a value of say 3 or 4 the code would reset the data buffer to empty and reset the counter back to zero. When data is actually seen from the serial port this counter is reset to zero. The purpose of this counter mechanism is to synchronize the data receive buffer with the 1Hz data stream coming in so the receive process does not get out of sync with what data represents the start of the 8-byte message.
Note that this method is superior to the serial port received data event because it allows your program to stay in control of things. I've already described the ability to synchronize with the data stream bursts - which is not possible to do with trying to set the serial port received data threshold to a count like 8. Another advantage is that the timer tick code can include additional handling functions such as signalling a timeout if no data arrives from the serial port in say 2 or 3 seconds.


text:
Q: MobileFirst Application Center Console App Icon for Native Apps I tried to deploy a native iOS app on MobileFirst Application Center Console and the app icon is not showing on the application center, instead its just showing the default icon.
I deployed 3 apps built on different frameworks on MFP Application Center and here are the results:

*

*MFP App - App created on MobileFirst

*

*Icon is showing on App Center Console as long as there is an image icon on the application resources.

*Ionic App - App created purely on Ionic with no MFP

*

*Icon is showing on App Center Console as long as there is an image icon on the application resources.

*Native App - App created directly on Xcode

*

*Does not show the app icon and only displays the default app center console icon.

Why is the icon not showing for native apps? We are currently deploying a native app and we want that the app icon will also appear on the app center console. We are using MFP v7.0

A: We are working on a fix for this. Fix will be delivered in couple of days.

A: This issue was fixed in the latest MobileFirst iFix.


text:
Q: Can I use a session cookie for API authentication? I want to build a web application with a Single Page Application as the front end and an API as the back end. The front-end SPA will read and write data to the API.
The SPA and the API will be hosted on two different domains:

*

*SPA: https://my-spa.com

*API: https://my-api.com
The API needs to be private so only authenticated users can use it.
I wonder if I should use a simple cookie session mechanism or OAuth for the authentication.
Oauth seems to be the standard for this kind of app, but it also seems more prone to security breaches because it is more complex to implement.
My questions:

*

*Can I use a simple session cookie, or is there any technical blocker for it? By session cookie, I mean having a sign-in endpoint that will generate and save a random string in the database and set it as a cookie. Then in each API request, I would get the user information from the database using the session cookie random string to manage permissions. I understand the session cookie should be set with the secure and sameSite=None attributes because the SPA and the API are not on the same domain. Is that a problem?

*Why OAuth seems more used in this situation if it is more complex to implement and could lead to more security issues?

A: You can and some systems do use this method, but it has some flaws you will have to deal with.

*

*You will need to expire it to avoid man in the middle attacks gaining permanent access.

*You will need to validate it against a central database or service. This limits your scalability.

OAuth addresses these and other concerns. There are many existing libraries that implement it, so you don't have to write it all you self and risk mistakes.


text:
Q: PHP not encoding quoted_printable_encode correctly I'm trying to add an emoticon(fire) in email subject. Below is the code I'm using:
$subject = "Test email \xF0\x9F\x94\xA5";
$charset = "UTF-8";
$subject = sprintf('=?%s?Q?%s?=', $charset, quoted_printable_encode($subject));
// send email....

This is adding a fire emoticon to the email subject successfully. But when I try to get the subject from database like:
$subject = $themeArray['templateSubject']; // Test email \xF0\x9F\x94\xA5
$charset = "UTF-8";
$subject = sprintf('=?%s?Q?%s?=', $charset, quoted_printable_encode($subject));
// send email....

This is not converting the characters to emoticon. Instead I'm getting the subject in email as
Test email \xF0\x9F\x94\xA5
Why its not converting when I get subject from database?
Can anyone help me to fix this? Thanks in advance.


text:
Q: Performance in reading dicom files with SimpleITK and PyTorch I want to directly load image from memory to python in pytorch tensor format.
I modified GetArrayViewFromImage() function by replacing those lines:
image_memory_view = _GetMemoryViewFromImage(image)
array_view = numpy.asarray(image_memory_view).view(dtype = dtype)

by:
image_memory_view = _GetMemoryViewFromImage(image)
array_view = torch.as_tensor(image_memory_view, dtype = dtype)

in practise it is so slow I replaced it with:
image_memory_view = _GetMemoryViewFromImage(image)
array_view = numpy.asarray(image_memory_view).view(dtype = dtype)
array_view  = torch.as_tensor(array_view)

Now I have two questions:

*

*it is much slower, and I don't really know why reading it with numpy and converting it is faster.

*even though I add the dtype argument and it returns a tensor with a correct dtype it reads it wrong (ex. -1000 in numpy is read as 252 no matter what torch.dtype I choose) which is not a problem when reading with numpy and converting, why is that happening?

A: While this does not directly answer your question, I strongly recommend using the torchio package, instead of dealing with these IO issues yourself (torchio uses SimpleITK under the hood).


text:
Q: Is it correct to use "train has surfaced"? Can you say The train has surfaced to describe the moment when a train emerges from a tunnel?

A: I would probably say:

The train has emerged…

or, more simply:

The train has exited…

…as long as the context is clear.

A: It's not particularly common phrasing, but here are a few written instances.
Personally, I'm barely comfortable with trains "surfacing" from extended sections of underground track. I wouldn't use the word for a train coming out of a few hundred metres of tunnel through a small hillside, for example.
For me, things normally surface out of liquid. If I get off an underground train and climb the stairs to street level, I'd say "I emerged", or "I arrived at the surface", rather than "I surfaced".

A: Emerged - as Cameron - is generally better, however some tube trains do come out of tunnels into surface tracks, so in these cases, it might be appropriate to say "surfaced". However this is more in the context of "is now running on surface rails" than "has just emerged from a tunnel". It would be equally valid if the train was in an uncovered cutting - technically under ground level, but not in a tunnel.

A: I'd say yes, but only if this was a tunnel with upward slope, like a tunnel under a river or end of a subway line in otherwise flat terrain. If the tunnel is in a mountain side, or some hill, and the train emerges horizontally, then Cameron's answer is the correct one.


text:
Q: What is Holder's Inequality? I have done some research on the internet about the inequality called Holder, but I've encountered some explanations in sites like Turkis Math Wikipedia or Wolfram but none of those explanations were helpful enough, I want to be able to define what Holder's Inequality is and solve inequality questions using Holder's, I need an elementary level explanation, I do not know integrals, I am not very well informed about series (at least in some level), I am a Turkish high school student in preparation for Maths Olympiad, so I know about Cauchy-Schwarz, AM-GM and all these other concepts, if I am not advanced enough to understand the definition of it or put it to application, what topics should I study first?
What are your suggestions?
Thank you:)

A: For Math Olympiad purposes you just need basic algebra to understand Hölder's inequality, so if you're familiar with means inequalities and Cauchy-Schwarz you're just fine.
Anyway, this is Hölder's inequality, as I know it. Let $p$, $q$ be positive real numbers such that $\frac{1}{p} + \frac{1}{q} = 1$. Also, let $a_1, \: \dots, \: a_n$ and $b_1, \: \dots, \: b_n$ be nonnegative real numbers. Then $$\sum_{i = 1}^n a_ib_i \le \left(\sum_{i = 1}^n a_i^p\right)^{1/p}  \left(\sum_{i = 1}^n b_i^q\right)^{1/q}$$


text:
Q: Only select ID if certain conditions apply I only want to select a client ID if the client status is equal to 1 (active) on the latest (!) timestamp; if not, than do not show it.
I am able to get the relative latest timestamps where the client is active, but that is not what I need.
Any ideas?

A: You can use NOT EXISTS()
SELECT * FROM YourTable t
WHERE status = 1
  AND NOT EXISTS(SELECT 1 FROM YourTable s
                 WHERE t.client_id = s.client_id
                   AND s.timestamp > t.timestamp)

Of course all this names are a guess due to lack of information on your question, so adjust it to your data.

A: Give a row number based on clientId and descending order of date column.
Then,
Query
select t.ClientId, t.`status`, t.`timestamp` from
(
    select ClientId, `status`, `timestamp`,
    (
        case ClientId when @curA
        then @curRow := @curRow + 1
        else @curRow := 1 and @curA := ClientId end
    ) as rn
    from your_table_name t,
    (select @curRow := 0, @curA := '') r
    order by ClientId, `timestamp` desc
)t
where t.rn = 1 and t.`status` = 1;

A: Are you trying to get the latest timestamp relative to the client_id, or for the entire table?
Depending on which, I would comment / leave uncommented line from this:
SELECT *
FROM your_table t
WHERE status = 1
AND timestamp =
( SELECT MAX(t2.timestamp)
  FROM your_table t2
  WHERE t2.client_id = t.client_id //comment this line
);


text:
Q: Can you generate an x86 hash value when running in x64 mode? I was bit this week by a bug that occurred when my code was hosted in an x64 process. I am using a hash value for lookup and I am storing that hash value in a database. The hash value that has been generated in the past was a x86 hash and now that x64 hashes are being generated I am getting errors because the lookup values don't match anymore.
I am highly skeptical of this, but I thought I'd ask anyway. Is there a way to generate an x86 hash value if my code is running in an x64 process?
For reference, I am running on .NET 4.0 using C#.
Edit:
Here's the problem I've been running into: String.GetHashCode() returns different values
You can duplicate the problem by creating a console app with the following code:
"DDD.Events.Application.ApplicationReferenceCreated".GetHashCode()

Run the app with x86 platform, then run it with the x64 platform.
I just want to get consistent values across platforms. However, I may just create a pre-compiled list of hashes so I can fail over in the event I need to. I just wanted to know if there were a way to get consistent values from GetHashCode(). I don't think so, but if it is possible it would be the easiest solution in my case.

A: I'm afraid if you are using the default implementation in .NET then this is not possible. They do not even guarantee it will return the same id between different versions of .NET; and explicitly state it must not be used as a unique identifier.
Have a read of this on MSDN


text:
Q: If you sacrifice yourself on The Sacrifice in expert realism mode, do you get the "Real Deal" achievement? The title says it all. But i'll describe further.
You are playing The Sacrifice in Left 4 Dead 2. You are playing realism mode on the expert level. You hope to get the Real Deal achievement, which involves "surviving a campaign on expert difficulty with realism mode enabled."
You sacrifice yourself (as someone has to) to complete the campaign.
Do you get "The Real Deal"?

A: No.
Well, that shouldn't come as a surprise, since you don't exactly fulfill the "surviving" part.
It's your funeral, so, you're an acceptable casualty :)


text:
Q: Stripe php trying to add customers to plan[very simple] For some reason my code isn't working and i have no idea why. On Stripe i can see every log, but they are all POST/v1/tokens.
Here is my Index.php:
<!DOCTYPE html>
<html lang='en'>
<head>
   <meta charset="UTF-8"/>
   <title> Stripe Test </title>
 <form action="process.php" method="POST">
  <script
   src="https://checkout.stripe.com/checkout.js" class="stripe-button"
   data-key="pk_test_MRCHJP8k2C6KajdgXeOu9TUA"
   data-amount="9000"
   data-name="Test"
   data-description="Shirt"
   data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
   data-locale="auto"
   data-currency="cad">
  </script>
 </form>
</body>
</html>

Here is my process.php which doesn't really seem to be called and the code appears on page when submitting the stripe method:
<?php
 require_once('autoload.php');//empty php
\Stripe\Stripe::setApiKey("sk_test_bztUVzRlSqW2wWDVpXM6qNX4");
\Stripe\Stripe::setApiKey("sk_test_bztUVzRlSqW2wWDVpXM6qNX4");
\Stripe\Subscription::create(array(
   "customer" => "cus_BLVgYrfhMNVAi8",
      "items" => array(
       array(
      "plan" => "1month",//id
      ),
 ),
));
?>


text:
Q: Why variables need to be declare but sometimes don't in Python? I know that Python variables could be used when it first declared like Example 1, but when I try Example 2 without the line total = 0, it will appear NameError: 'name' total is not defined. Why?
Example 1
dmil = float(input("Enter the distance (miles): "))
dis = dmil * 1.61
print("The distance in miles {} is equal to {} in
kilometer.".format(dmil,dis))

Example 2
total = 0  #why I necessarily need this?
for i in range (1,4):
    h = float(input("Enter the {} height: ".format(i)))
    total = h + total
avg = total/3
print("The average height of the 3 cousins is ",avg)

It really confused me when I type programmes, is there a definition about when should I declare var at first and when should not?

A: total = h + total is intending to add the value of h to what total currently is.
Without having previously stated what total currently is, there is no value to add h.
In simpler terms, if you remove the total = 0 statement, walk through the code line-by-line and when you reach total = h + total, what should h + total be, it's undefined.

A: total = 0 is not a declaration per se: it's an initialization. It is needed because when you get to the line
    total = h + total

the value of total on the RHS would be unknown. Python tries to look up the value and finds nothing by that name at that point in your program, so it complains.