问:
My PHP redirect for mobile isn't working
Help!  I've tried some different code, but nothing works to redirect to mobile.  I am on a godaddy server, and here is my code, in index.php

```<code><?php
$iphone = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
$android = strpos($_SERVER['HTTP_USER_AGENT'],"Android");
$palmpre = strpos($_SERVER['HTTP_USER_AGENT'],"webOS");
$berry = strpos($_SERVER['HTTP_USER_AGENT'],"BlackBerry");
$ipod = strpos($_SERVER['HTTP_USER_AGENT'],"iPod");

if ($iphone || $android || $palmpre || $ipod || $berry == true)
{
header('Location: http://mobile.practicallunacy.com/');
}
?>
</code>```

---Edit---
This is what I've changed it to.  Try to go easy on me, I don't know much about php.

```<code><?php
    $iphone = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
    $android = strpos($_SERVER['HTTP_USER_AGENT'],"Android");
    $palmpre = strpos($_SERVER['HTTP_USER_AGENT'],"webOS");
    $berry = strpos($_SERVER['HTTP_USER_AGENT'],"BlackBerry");
    $ipod = strpos($_SERVER['HTTP_USER_AGENT'],"iPod");

if ($iphone = true) if ($android = true) if ($palmpre = true) if ($ipod =     true) if ($berry = true)
{
header('Location: http://mobile.practicallunacy.com/');
}
?>
</code>```

----Edit----

Based on something someone else told me to do, this is the new code I've put in...  It still isn't working.

```<code><?php
$iphone = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
$android = strpos($_SERVER['HTTP_USER_AGENT'],"Android");
$palmpre = strpos($_SERVER['HTTP_USER_AGENT'],"webOS");
$berry = strpos($_SERVER['HTTP_USER_AGENT'],"BlackBerry");
$ipod = strpos($_SERVER['HTTP_USER_AGENT'],"iPod");

if ($iphone == true)
{
header('Location: http://mobile.practicallunacy.com/');
}
if ($android == true)
{
header('Location: http://mobile.practicallunacy.com/');
}
if ($palmpre == true)
{
header('Location: http://mobile.practicallunacy.com/');
}
if ($ipod == true)
{
header('Location: http://mobile.practicallunacy.com/');
}
if ($berry == true)
{
header('Location: http://mobile.practicallunacy.com/');
}
?>
</code>```

答:
Your syntax is all wrong, this code would not have run. Your final attempt was syntactically correct, but did not account for the vagaries of strpos() which can return 0 in case of a match.

```<code><?php
$iphone  = strpos($_SERVER['HTTP_USER_AGENT'], "iPhone");
$android = strpos($_SERVER['HTTP_USER_AGENT'], "Android");
$palmpre = strpos($_SERVER['HTTP_USER_AGENT'], "webOS");
$berry   = strpos($_SERVER['HTTP_USER_AGENT'], "BlackBerry");
$ipod    = strpos($_SERVER['HTTP_USER_AGENT'], "iPod");

if ($iphone !== false || $android !== false || $palmpre !== false || $ipod !== false || $berry !== false) {
    header("Location: http://mobile.practicallunacy.com/");
}
</code>```

Note the use of strict equality checks; 0 == true but 0 !== true.

Though, this is a good use for a regular expression search:

```<code><?php
if (preg_match("/iphone|android|webos|blackberry|ipod/i", $_SERVER['HTTP_USER_AGENT'])) {
    header("Location: http://mobile.practicallunacy.com/");
}
</code>```

Body:
Help!  I've tried some different code, but nothing works to redirect to mobile.  I am on a godaddy server, and here is my code, in index.php

<?php
$iphone = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
$android = strpos($_SERVER['HTTP_USER_AGENT'],"Android");
$palmpre = strpos($_SERVER['HTTP_USER_AGENT'],"webOS");
$berry = strpos($_SERVER['HTTP_USER_AGENT'],"BlackBerry");
$ipod = strpos($_SERVER['HTTP_USER_AGENT'],"iPod");

if ($iphone || $android || $palmpre || $ipod || $berry == true)
{
header('Location: http://mobile.practicallunacy.com/');
}
?>

---Edit---
This is what I've changed it to.  Try to go easy on me, I don't know much about php.

<?php
    $iphone = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
    $android = strpos($_SERVER['HTTP_USER_AGENT'],"Android");
    $palmpre = strpos($_SERVER['HTTP_USER_AGENT'],"webOS");
    $berry = strpos($_SERVER['HTTP_USER_AGENT'],"BlackBerry");
    $ipod = strpos($_SERVER['HTTP_USER_AGENT'],"iPod");

if ($iphone = true) if ($android = true) if ($palmpre = true) if ($ipod =     true) if ($berry = true)
{
header('Location: http://mobile.practicallunacy.com/');
}
?>

----Edit----

Based on something someone else told me to do, this is the new code I've put in...  It still isn't working.

<?php
$iphone = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
$android = strpos($_SERVER['HTTP_USER_AGENT'],"Android");
$palmpre = strpos($_SERVER['HTTP_USER_AGENT'],"webOS");
$berry = strpos($_SERVER['HTTP_USER_AGENT'],"BlackBerry");
$ipod = strpos($_SERVER['HTTP_USER_AGENT'],"iPod");

if ($iphone == true)
{
header('Location: http://mobile.practicallunacy.com/');
}
if ($android == true)
{
header('Location: http://mobile.practicallunacy.com/');
}
if ($palmpre == true)
{
header('Location: http://mobile.practicallunacy.com/');
}
if ($ipod == true)
{
header('Location: http://mobile.practicallunacy.com/');
}
if ($berry == true)
{
header('Location: http://mobile.practicallunacy.com/');
}
?>

Body:
Your syntax is all wrong, this code would not have run. Your final attempt was syntactically correct, but did not account for the vagaries of strpos() which can return 0 in case of a match.

<?php
$iphone  = strpos($_SERVER['HTTP_USER_AGENT'], "iPhone");
$android = strpos($_SERVER['HTTP_USER_AGENT'], "Android");
$palmpre = strpos($_SERVER['HTTP_USER_AGENT'], "webOS");
$berry   = strpos($_SERVER['HTTP_USER_AGENT'], "BlackBerry");
$ipod    = strpos($_SERVER['HTTP_USER_AGENT'], "iPod");

if ($iphone !== false || $android !== false || $palmpre !== false || $ipod !== false || $berry !== false) {
    header("Location: http://mobile.practicallunacy.com/");
}

Note the use of strict equality checks; 0 == true but 0 !== true.

Though, this is a good use for a regular expression search:

<?php
if (preg_match("/iphone|android|webos|blackberry|ipod/i", $_SERVER['HTTP_USER_AGENT'])) {
    header("Location: http://mobile.practicallunacy.com/");
}


来源: stackexchange

问:
Any Good way of securing assets and video file store internal in android or react-native
We are building completely offline commercial eLearning app. we have to store some important video locally in the app and we don't want that to be stolen by extracting apk.

Is there any good way to achieve this with encryption/decryption or password protection etc on native android or react-native.

We are trying various solutions but a better way from you will help us in saving time and learning.

答:
You can't do it.

You can encrypt it, but application will need key to decrypt it. Key can be sniffed or extracted from bytecode. Or even screen can be recorded without any key extraction.

Don't spend time on making troubles for anyone, spend time on great content.

ContentLicense: CC BY-SA 3.0


问:
SQL Server - Combining OUTER and INNER joins
I have 3 tables and I have to inner join Table A with Table B but a left outer between Table A and Table C.

Can I combine outer and inner join in the same query? I can nest queries and attain the desired result but I am unable to do both the joins in the same query. It appears that in other SQL languages, the order of joining is important. Is this the case in SQL Server as well?

Ok, here's the scenario.

Consider 3 tables. Table A, Table F, Table D.

I will need the recordset to contain all rows in D irrespective of whether it exists in F (after it's inner joined with A). So, a outer join comes to mind. What I would need is:

First do a inner join between A and F to get a set (this may be a null set)

Then do a outer join with the recordset in (1) with D

答: Yes you can do both is the same query, and yes the order is important.</p>

OwnerDisplayName: Bob Smith

OwnerDisplayName: Eppz

ContentLicense: CC BY-SA 2.5


问:
What would be involved in creating a template system in C#
I'm creating a project in C# and I want to be able to define "template" files that define the layout that will be produced in an ASP web page. This means from an interface people are able to click certain "areas" and add text, images or a video.

I can only think of using the coordinates to achieve this. Any better ways? Any tips would be good.

答: have a look at MasterPages in ASP.NET, it's exactly what you are looking for, content regions to be editable in pages associated with the main masterpage.</p>


问:
Pdf generation using itext for Bangla text in android
I am using i-text for generating pdf from my android application. But it worked fine for English fonts. When I was trying to generate pdf for my locale, Bangla, I got some problems. After getting some tips from some blog I have got the implementation in the way mentioned bellow:

```<code>String fontName = "Nikosh.ttf";
    InputStream is = context.getAssets().open(fontName);
    int size = is.available();
    byte[] buffer = new byte[size];
    int a = is.read(buffer);
    BaseFont customFont = BaseFont.createFont(fontName, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, true, buffer, buffer);
    Font banglaFont = new Font(customFont, 12);
</code>```

Now the output looks like this:

This is the output for Bangla text using a bangla font

But the output text is broken. Whereas the original one looks like this one:

Original text in Bangla

Any help regarding how to solve this type of problem for unicode in android would be highly appreciated.
N.B. I am using i-text 5.5.x

答:
Use font that display as well.

```<code>BaseFont base = BaseFont.createFont("c:/windows/fonts/arial.ttf", BaseFont.WINANSI);
Font font = new Font(base, 11f, Font.BOLD);
</code>```

Body:
I am using i-text for generating pdf from my android application. But it worked fine for English fonts. When I was trying to generate pdf for my locale, Bangla, I got some problems. After getting some tips from some blog I have got the implementation in the way mentioned bellow:

String fontName = "Nikosh.ttf";
    InputStream is = context.getAssets().open(fontName);
    int size = is.available();
    byte[] buffer = new byte[size];
    int a = is.read(buffer);
    BaseFont customFont = BaseFont.createFont(fontName, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, true, buffer, buffer);
    Font banglaFont = new Font(customFont, 12);

Now the output looks like this:

This is the output for Bangla text using a bangla font

But the output text is broken. Whereas the original one looks like this one:

Original text in Bangla

Any help regarding how to solve this type of problem for unicode in android would be highly appreciated.
N.B. I am using i-text 5.5.x

Body:
Use font that display as well.

BaseFont base = BaseFont.createFont("c:/windows/fonts/arial.ttf", BaseFont.WINANSI);
Font font = new Font(base, 11f, Font.BOLD);


问:
How to get transfer confirmation from bank(by PHP)?
currently in progress making my first website, about selling something.
But, i want the payments via offline. The first is direct payment and second is via bank transfer (to certain account, my account).

how the get the transaction confirmation from bank to my machine(server) and then my machine automatically send confirmation to customer?
or the bank send automatically send the confirmation right after transaction?(make some agreement to the bank)

答:
currently in progress making my first website, about selling something. But, i want the payments via offline. The first is direct payment and second is via bank transfer (to certain account, my account).

You Can try the code below sir!..replace my email and test it!..

https://www.sandbox.paypal.com/cgi-bin/webscr'; // Test Paypal API URL
$paypal_id='itprowenkz@gmail.com'; // Business email ID
?>


问:
c# Lambda expression to VB.Net
I want to convert

```<code>cfind.OnResponseReceived = (DicomCFindRequest rq, DicomCFindResponse rp) => {
    Console.WriteLine("Study UID: {0}", rp.Dataset.Get<string>(DicomTag.StudyInstanceUID));
};
</code>```

to VB.Net

but,
neither

```<code>AddHandler cfind.OnResponseReceived, AddressOf onResponse
</code>```

nor

```<code>AddHandler cfind.OnResponseReceived, Sub(rq, rp)
        onCFindResponse(rq, rp)
End Sub
</code>```

thing works..
How can I convert it?

答:
This should be the equivalent VB.NET:   </p>

```<code>cfind.OnResponseReceived = Sub(rq As DicomCFindRequest, rp As DicomCFindResponse)
    Console.WriteLine("Study UID: {0}", rp.Dataset.[Get](Of String)(DicomTag.StudyInstanceUID))

End Sub
</code>```

Title: c# Lambda expression to VB.Net

Body:
I want to convert

cfind.OnResponseReceived = (DicomCFindRequest rq, DicomCFindResponse rp) => {
    Console.WriteLine("Study UID: {0}", rp.Dataset.Get<string>(DicomTag.StudyInstanceUID));
};

to VB.Net

but,
neither

AddHandler cfind.OnResponseReceived, AddressOf onResponse

nor

AddHandler cfind.OnResponseReceived, Sub(rq, rp)
        onCFindResponse(rq, rp)
End Sub

thing works..
How can I convert it?

Body:
This should be the equivalent VB.NET:

cfind.OnResponseReceived = Sub(rq As DicomCFindRequest, rp As DicomCFindResponse)
    Console.WriteLine("Study UID: {0}", rp.Dataset.[Get](Of String)(DicomTag.StudyInstanceUID))

End Sub


问:
C++ unwanted destruction
Can somebody explain why when c finishes construction, the destructor of b (member of c) is called, while d is destructed - as expected - when c's destructor is called ?

```<code>#include <iostream>

using namespace std;

class A
{
public:
    int a, b;
};

class B
{
public:
    A* array[10];
    B()
    {
        for(int i = 0 ; i < 10 ; i++)
            array[i] = new A();
    }
    ~B()
    {
        for(int i = 0 ; i < 10 ; i++)
            delete array[i];
    }
};

class C
{
public:
    B b;
    B* d;
    C()
    {
        b = B();
    }
    ~C()
    {
            delete d;
    }
};

int main()
{
    B b = B();
    C c = C();
    cout << "Ashlamish" << endl;
    system("pause");
    return 0;
}
</code>```

答:
You have committed here a cardinal sin - not obeying the rule of 3.

Your B needs a destructor but does not implement copying and assignment.

You then go ahead and compound the error by actually doing an assignment.

You also go on to delete an uninitialised pointer. (It would be fine if d were NULL but there is no reason why it should be).

You also need to implement copy-construction, especially as your compiler may well choose to use it for the above constructs, although it probably won't actually do so.

Title: C++ unwanted destruction

Body:
Can somebody explain why when c finishes construction, the destructor of b (member of c) is called, while d is destructed - as expected - when c's destructor is called ?

#include <iostream>

using namespace std;

class A
{
public:
    int a, b;
};

class B
{
public:
    A* array[10];
    B()
    {
        for(int i = 0 ; i < 10 ; i++)
            array[i] = new A();
    }
    ~B()
    {
        for(int i = 0 ; i < 10 ; i++)
            delete array[i];
    }
};

class C
{
public:
    B b;
    B* d;
    C()
    {
        b = B();
    }
    ~C()
    {
            delete d;
    }
};

int main()
{
    B b = B();
    C c = C();
    cout << "Ashlamish" << endl;
    system("pause");
    return 0;
}


问:
Pandas for inserting a columns as index
When reading from excel to pandas, it shows like this

```<code>t0001   Albania 0.03914382317658349
0   t0001   Algeria 0.298994
1   t0001   Austria 1.01137
2   t0001   Belgium 0.306369
</code>```

What I want to achieve is inserting a columns of 'time','region','value', and it should be shows like below

```<code>    time    region  value
0   t0001   Albania 0.0391438
1   t0001   Algeria 0.298994
2   t0001   Austria 1.01137
3   t0001   Belgium 0.306369
</code>```

Is it possible to achieve in the pandas?

答:
Header = None is the proper solution but as an alternative solution you can also do :

```<code>df.loc[-1] = df.columns
df.index += 1
df.columns =  ['time', 'region', 'value']
df.value = df.value.astype(float)
</code>```

```
   time   region                value
1  t0001  Algeria             0.298994
2  t0001  Austria              1.01137
3  t0001  Belgium             0.306369
0  t0001  Albania             0.039143
```

Title: Pandas for inserting a columns as index

Body:
When reading from excel to pandas, it shows like this

t0001   Albania 0.03914382317658349
0   t0001   Algeria 0.298994
1   t0001   Austria 1.01137
2   t0001   Belgium 0.306369

What I want to achieve is inserting a columns of 'time','region','value', and it should be shows like below

    time    region  value
0   t0001   Albania 0.0391438
1   t0001   Algeria 0.298994
2   t0001   Austria 1.01137
3   t0001   Belgium 0.306369

Is it possible to achieve in the pandas?

Body:
Header = None is the proper solution but as an alternative solution you can also do :

df.loc[-1] = df.columns
df.index += 1
df.columns =  ['time', 'region', 'value']
df.value = df.value.astype(float)

   time   region                value
1  t0001  Algeria             0.298994
2  t0001  Austria              1.01137
3  t0001  Belgium             0.306369
0  t0001  Albania             0.039143


问:
Waterfall Model and Modified Waterfall Model
What is the difference between Waterfall model and Modified Waterfall Model when it comes to software development processes?

It is said that the Modified Waterfall Model has overcome the shortcomings of Waterfall Model. But how?

答:
Modified Waterfall model has slight difference comparing with traditional waterfall model, When we are considering as software development methodology. .

Waterfall model contains certain steps .

1>Requirements gathering   +(Verification and Validation phase(Modified Waterfall model))

2>Design (UFX and UI Team)+(Verification and Validation phase(Modified Waterfall model))

3>Coding(Development)   +(Verification and Validation phase(Modified Waterfall model))

4>QA(Testing)   +(Verification and Validation phase(Modified Waterfall model))

5>Maintenance  +(Verification and Validation phase(Modified Waterfall model))

"Verification and Validation phases" are add on in Modified Waterfall model .

ContentLicense: CC BY-SA 4.0


问:
NodeList Data is not getting removed
I have an array object which has 3 objects. I want to remove all the objects except the first one.

Here is my data which I got from XML:

```<code>mrArr[0] = <Data>
                <G> "Val" = "5" </G>
           </Data>
mrArr[1] = <Data>
                <G> "Val" = "6" </G>
           </Data>
mrArr[2] = <Data>
                <G> "Val" = "7" </G>
           </Data>
</code>```

I have created a loop to try and do this but it is only removing one element. What is wrong with my loop?:

```<code>for(var i = 1; i < myArr.length; i++){
    myArr[i].remove();
}
</code>```

It is removing only one element.

答:
Array does not have a function remove. You can use Array#splice like myArray.splice(1);

const myArray = [1, 2, 3];
console.log(myArray);

myArray.splice(1);
console.log(myArray);```
</div>
</div>
</p>

<p>If you want to remove not the first item, you need to get the index of the searched item and pass into the <code>splice</code> like</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const myArray = [1, 2, 3];
const index = myArray.indexOf(2);
myArray.splice(index, 1);

console.log(myArray);</code>```

or just use Array#filter and pass the predicate

const myArray = [1, 2, 3];
const filteredArray = myArray.filter(item => item !== 2);

console.log(filteredArray);```

Title: NodeList Data is not getting removed

Body:
I have an array object which has 3 objects. I want to remove all the objects except the first one.

Here is my data which I got from XML:

mrArr[0] = <Data>
                <G> "Val" = "5" </G>
           </Data>
mrArr[1] = <Data>
                <G> "Val" = "6" </G>
           </Data>
mrArr[2] = <Data>
                <G> "Val" = "7" </G>
           </Data>

I have created a loop to try and do this but it is only removing one element. What is wrong with my loop?:

for(var i = 1; i < myArr.length; i++){
    myArr[i].remove();
}

It is removing only one element.

Body:
Array does not have a function remove. You can use Array#splice like myArray.splice(1);

const myArray = [1, 2, 3];
console.log(myArray);

myArray.splice(1);
console.log(myArray);

If you want to remove not the first item, you need to get the index of the searched item and pass into the splice like

const myArray = [1, 2, 3];
const index = myArray.indexOf(2);
myArray.splice(index, 1);

console.log(myArray);

or just use Array#filter and pass the predicate

const myArray = [1, 2, 3];
const filteredArray = myArray.filter(item => item !== 2);

console.log(filteredArray);


问:
What is the purpose of this `data[0]` declaration in struct?
In the C, syntax of flexible array member like this:

```<code>struct s
{
    int n;
    double d[];  // flexible array member
};
</code>```

And, Zero size array illegal in C.

If I declare array like this:

```<code>struct s
{
    double d[0];  // Zero size array
};
</code>```

GCC give warning:

```<code>warning: ISO C forbids zero-size array 'd' [-Wpedantic]
</code>```

So, I'm going to my main question.

I saw following code here.

```<code>struct squashfs_xattr_entry {
    __le16          type;
    __le16          size;
    char            data[0];
};
</code>```

In C zero-size array illegal.

Then,

What is the purpose of this data[0] declaration in struct?

What does data[0] do here?

答:
Prior to C99 (the ISO standard version of C released in 1999) the only way to implement a flexible array member was if the compiler supported it as an extension. GCC supported it by using a static length of 0, hence foo buffer[0].

C99 made it legal, but they decided to prescribe the syntax foo buffer[] instead of retaining GCC's [0] version.

GCC still supports buffer[0] for compatibility with code written before C99.

This is explained in GCC's documentation: https://gcc.gnu.org/onlinedocs/gcc-4.4.4/gcc/Zero-Length.html (emphasis mine):

Zero-length arrays are allowed in GNU C

Note that "GNU C" (the GCC implementation of C) has its own extensions on-top of ISO C.

Body:
In the C, syntax of flexible array member like this:

struct s
{
    int n;
    double d[];  // flexible array member
};

And, Zero size array illegal in C.

If I declare array like this:

struct s
{
    double d[0];  // Zero size array
};

GCC give warning:

warning: ISO C forbids zero-size array 'd' [-Wpedantic]

So, I'm going to my main question.

I saw following code here.

struct squashfs_xattr_entry {
    __le16          type;
    __le16          size;
    char            data[0];
};

In C zero-size array illegal.

Then,

What is the purpose of this data[0] declaration in struct?

What does data[0] do here?


问:
Link inside a button not working in Firefox
I have two links inside a button but the links don't seem to work on Firefox.

```<code><button class="btn login">
    <a href="/login"><b>Log In</b></a>
          |
<a href="/signup"><b>Sign Up</b></a>
</button>
</code>```

I tried JavaScript onclick and redirecting - even that is not working.

答:
Use javascript: window.location for the button.</p>

```<code><div class="product">
<button onClick="javascript: window.location='/checkout/outfield-
banner/1'">Add to Cart</button>
</div>
</code>```

Body:
I have two links inside a button but the links don't seem to work on Firefox.

<button class="btn login">
    Log In
          |
Sign Up
</button>

I tried JavaScript onclick and redirecting - even that is not working.

Body:
Use javascript: window.location for the button.

<div class="product">
<button onClick="javascript: window.location='/checkout/outfield-
banner/1'">Add to Cart</button>
</div>


问:
Json.Net unexpected characters ("\") when serializing my entities
I am using the excellent Json.Net library to serialize my entities generated by entity framework. I use the following code to do so :

```<code>using (MyVoucherEntities context = new MyVoucherEntities())
{
  List<MyObject> list = context.MyObjects.ToList();
  string json = JsonConvert.SerializeObject(list);
}
</code>```

Everything goes well I mean, the objects are correctly serialized except one think : it adds escape characters "\" that makes me having nightmare when deserializing on the client side.

```<code> [
     {
         \"$id\": \"1\",
         \"CreationDate\": \"\\\/Date(1293186324257+0000)\\\/\",
        \"ImageUrl\": \"http:\/\/www.google.com\",
         \"Title\": \"Here is a title\"
     } ]
</code>```

Does anybody know why and how I can get rid of these escape characters slash "\" ?

答:
I should note that you have not completely quoted the outputted stuff (I got the url to work in your answer - that should have been edited into your question rather than put as an answer). The string I got back in a file was this:

```<code>"[{\"$id\":\"1\",\"CreationDate\":\"\\\/Date(1293186324257+0000)\\\/\",\"ImageUrl\":\"http:\/\/www.c-tina.com\/MyVoucherAdmin\/Images\/shop22\/burger.jpg\",\"Title\":\"Get one burger for free\",\"Description\":\"Bla lbzlfpzkfgmzke\\rdmjdgmj\\r\\r\\rlgfpzkegmkzepk\",\"ShopId\":22,\"PromotionId\":15,\"Shop\":null,\"Features\":[],\"SingleStats\":[],\"WhatsHots\":[],\"EntityKey\":{\"$id\":\"2\",\"EntitySetName\":\"Promotions\",\"EntityContainerName\":\"MyVoucherEntities\",\"EntityKeyValues\":[{\"Key\":\"PromotionId\",\"Type\":\"System.Int32\",\"Value\":\"15\"}]}}]"
</code>```

the key thing to me is that there are unescaped quotes at the front and end which makes me think that whatever is outputting it is deciding it needs to be quoted and if you are surrounding it in quotes you ahve to escape the quotes that are inside it.

Without seeing the full output its hard to say if the problem is in teh code you've quoted above to generate the JSON or if there is a problem at a later step of processing this which is causing the quoting. Have you debugged and confirmed that the output of your serialize call is definitely producing the escaped version rather than it being done at a later stage potentially? If you're not used to the debugger then pay attention to Jon Skeet's suggest of dumping it to file or console to make sure there is no confusion that way.

Body:
I am using the excellent Json.Net library to serialize my entities generated by entity framework. I use the following code to do so :

using (MyVoucherEntities context = new MyVoucherEntities())
{
  List<MyObject> list = context.MyObjects.ToList();
  string json = JsonConvert.SerializeObject(list);
}

Everything goes well I mean, the objects are correctly serialized except one think : it adds escape characters "\" that makes me having nightmare when deserializing on the client side.

 [
     {
         \"$id\": \"1\",
         \"CreationDate\": \"\\\/Date(1293186324257+0000)\\\/\",
        \"ImageUrl\": \"http:\/\/www.google.com\",
         \"Title\": \"Here is a title\"
     } ]

Does anybody know why and how I can get rid of these escape characters slash "\" ?

Body:
I should note that you have not completely quoted the outputted stuff (I got the url to work in your answer - that should have been edited into your question rather than put as an answer). The string I got back in a file was this:

"[{\"$id\":\"1\",\"CreationDate\":\"\\\/Date(1293186324257+0000)\\\/\",\"ImageUrl\":\"http:\/\/www.c-tina.com\/MyVoucherAdmin\/Images\/shop22\/burger.jpg\",\"Title\":\"Get one burger for free\",\"Description\":\"Bla lbzlfpzkfgmzke\\rdmjdgmj\\r\\r\\rlgfpzkegmkzepk\",\"ShopId\":22,\"PromotionId\":15,\"Shop\":null,\"Features\":[],\"SingleStats\":[],\"WhatsHots\":[],\"EntityKey\":{\"$id\":\"2\",\"EntitySetName\":\"Promotions\",\"EntityContainerName\":\"MyVoucherEntities\",\"EntityKeyValues\":[{\"Key\":\"PromotionId\",\"Type\":\"System.Int32\",\"Value\":\"15\"}]}}]"

the key thing to me is that there are unescaped quotes at the front and end which makes me think that whatever is outputting it is deciding it needs to be quoted and if you are surrounding it in quotes you ahve to escape the quotes that are inside it.

Without seeing the full output its hard to say if the problem is in teh code you've quoted above to generate the JSON or if there is a problem at a later step of processing this which is causing the quoting. Have you debugged and confirmed that the output of your serialize call is definitely producing the escaped version rather than it being done at a later stage potentially? If you're not used to the debugger then pay attention to Jon Skeet's suggest of dumping it to file or console to make sure there is no confusion that way.


问:
Use Mule message properties in MMC alert
Is it possible to use mule message properties (like payload and flowvars) in a Mule Management Console notification body or subject?</p>

答:
Yes you can use it. Mule provide various properties common to all alerts from class com.mulesoft.console.alert.RaisedAlert that can be used in defining the certain values such as
Flow identifier
Flow name
You may refer to mule documentation for it
https://docs.mulesoft.com/mule-management-console/v/3.7/defining-slas-and-alerts#DefiningSLAsandAlerts-PropertiesUsedinAlertExpressions</p>


问:
Add a custom field to Woocommerce general setting in store address section
I'm looking to add a Phone number field to the Woocommerce settings page. I can get the field to add to the settings list, but it gets appended to the bottom of the entire tab. Ideally I'd like to add the field in the Store Address sections on the general tab.

Here's what I'm using now (trimmed down):

```<code>add_filter('woocommerce_general_settings', 'woocommerce_add_phone');

function woocommerce_add_phone($settings) {

    $settings[] = array(
        'title'    => 'Phone Number',
        'type'     => 'text',
    );

    $sections[] = array( 'type' => 'sectionend', 'id' => 'store_address' );

    return $settings;

}
</code>```

I made an attempt at using array_splice but couldn't get anywhere with it.

Any advice would be greatly appreciated.

答:
This code will add your phone number after the post code element in the Store Address section.  I borrowed the splice function from here.</p>

```<code>add_filter('woocommerce_general_settings', 'woocommerce_general_settings_add_phone_number');

function woocommerce_general_settings_add_phone_number($settings) {

    $phone_number = array(
        'title'    => __( 'Phone Number', 'woocommerce' ),
        'desc'     => __( 'Add your phone number.', 'woocommerce' ),
        'id'       => 'woocommerce_store_phone_number',
        'default'  => '',
        'type'     => 'text',
        'desc_tip' => false,
    );

    $array_pos = 0;

    foreach ($settings as $key => $value) {
       if ( $value['id'] == 'woocommerce_store_postcode' ) {
            $array_pos = $key;
            break;
       }
    }

    $settings = array_insert( $settings, $phone_number, $array_pos + 1 );

    return $settings;
}

/*
    Array insert
    @array      the array to add an element to
    @element    the element to add to the array
    @position   the position in the array to add the element
 */
if(!function_exists('array_insert')) {
    function array_insert($array, $element, $position) {
        // if the array is empty just add the element to it
        if(empty($array)) {
            $array[] = $element;
        // if the position is a negative number
        } elseif(is_numeric($position) && $position < 0) {
            // if negative position after count
            if(count($array) + $position < 0) {
                $position = 0;
            } else {
                $position = count($array) + $position;
            }
            // try again with a positive position
            $array = array_insert($array, $element, $position);
        // if array position already set
        } elseif(isset($array[$position])) {
            // split array into two parts
            $split1 = array_slice($array, 0, $position, true);
            $split2 = array_slice($array, $position, null, true);
            // add new array element at between two parts
            $array = array_merge($split1, array($position => $element), $split2);
        // if position not set add to end of array
        } elseif(is_null($position)) {
            $array[] = $element;
        // if the position is not set
        } elseif(!isset($array[$position])) {
            $array[$position] = $element;
        }
        // clean up indexes
        $array = array_values($array);
        return $array;
    }
}
</code>```

Body:
I'm looking to add a Phone number field to the Woocommerce settings page. I can get the field to add to the settings list, but it gets appended to the bottom of the entire tab. Ideally I'd like to add the field in the Store Address sections on the general tab.

Here's what I'm using now (trimmed down):

add_filter('woocommerce_general_settings', 'woocommerce_add_phone');

function woocommerce_add_phone($settings) {

    $settings[] = array(
        'title'    => 'Phone Number',
        'type'     => 'text',
    );

    $sections[] = array( 'type' => 'sectionend', 'id' => 'store_address' );

    return $settings;

}

I made an attempt at using array_splice but couldn't get anywhere with it.

Any advice would be greatly appreciated.

Body:
This code will add your phone number after the post code element in the Store Address section.  I borrowed the splice function from here.

add_filter('woocommerce_general_settings', 'woocommerce_general_settings_add_phone_number');

function woocommerce_general_settings_add_phone_number($settings) {

    $phone_number = array(
        'title'    => __( 'Phone Number', 'woocommerce' ),
        'desc'     => __( 'Add your phone number.', 'woocommerce' ),
        'id'       => 'woocommerce_store_phone_number',
        'default'  => '',
        'type'     => 'text',
        'desc_tip' => false,
    );

    $array_pos = 0;

    foreach ($settings as $key => $value) {
       if ( $value['id'] == 'woocommerce_store_postcode' ) {
            $array_pos = $key;
            break;
       }
    }

    $settings = array_insert( $settings, $phone_number, $array_pos + 1 );

    return $settings;
}

/*
    Array insert
    @array      the array to add an element to
    @element    the element to add to the array
    @position   the position in the array to add the element
 */
if(!function_exists('array_insert')) {
    function array_insert($array, $element, $position) {
        // if the array is empty just add the element to it
        if(empty($array)) {
            $array[] = $element;
        // if the position is a negative number
        } elseif(is_numeric($position) && $position < 0) {
            // if negative position after count
            if(count($array) + $position < 0) {
                $position = 0;
            } else {
                $position = count($array) + $position;
            }
            // try again with a positive position
            $array = array_insert($array, $element, $position);
        // if array position already set
        } elseif(isset($array[$position])) {
            // split array into two parts
            $split1 = array_slice($array, 0, $position, true);
            $split2 = array_slice($array, $position, null, true);
            // add new array element at between two parts
            $array = array_merge($split1, array($position => $element), $split2);
        // if position not set add to end of array
        } elseif(is_null($position)) {
            $array[] = $element;
        // if the position is not set
        } elseif(!isset($array[$position])) {
            $array[$position] = $element;
        }
        // clean up indexes
        $array = array_values($array);
        return $array;
    }
}


问:
App won't run when apk is shared with friend
My Android app is working fine on the emulator, and even on the device when I connect it using a USB cable. However, when I generate the apk file and share it with others, the app won't work. It crashes after the splash screen is launched.

Here is my app/build.gradle:

```<code>apply plugin: 'com.android.application'
android {
    compileSdkVersion 25
    buildToolsVersion '25.0.0'
    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        applicationId 'com.test'
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 2
        versionName "1.1"

        multiDexEnabled true

        def serverPropertiesFile = rootProject.file("server.properties")

        // Initialize a new Properties() object called keystoreProperties.
        def serverProperties = new Properties()

        // Load your keystore.properties file into the serverProperties object.
        serverProperties.load(new FileInputStream(serverPropertiesFile))

        buildConfigField("String", "HOST", serverProperties['SERVER_URL'])
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            debuggable true
        }
    }
    productFlavors {
    }
    lintOptions {
        abortOnError false
} } dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.nineoldandroids:library:2.4.0'
    compile 'com.daimajia.swipelayout:library:1.2.0@aar'
    compile 'com.daimajia.androidanimations:library:1.1.2@aar'
    compile 'com.google.android.gms:play-services-maps:10.0.1'
    compile 'com.google.android.gms:play-services-gcm:10.0.1'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'com.google.code.gson:gson:2.8.2'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}
</code>```

Manifest.xml:

```<code><uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!--
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
     Google Maps Android API v2, but you must specify either coarse or fine
     location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
</code>```

Any help?

答: I think you need to add some classes to your pro-guard file. Gson for example won't handle obfuscated very well. To see if this actually causes the problem, remove minifyEnabled true.

Body:
My Android app is working fine on the emulator, and even on the device when I connect it using a USB cable. However, when I generate the apk file and share it with others, the app won't work. It crashes after the splash screen is launched.

Here is my app/build.gradle:

apply plugin: 'com.android.application'
android {
    compileSdkVersion 25
    buildToolsVersion '25.0.0'
    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        applicationId 'com.test'
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 2
        versionName "1.1"

        multiDexEnabled true

        def serverPropertiesFile = rootProject.file("server.properties")

        // Initialize a new Properties() object called keystoreProperties.
        def serverProperties = new Properties()

        // Load your keystore.properties file into the serverProperties object.
        serverProperties.load(new FileInputStream(serverPropertiesFile))

        buildConfigField("String", "HOST", serverProperties['SERVER_URL'])
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            debuggable true
        }
    }
    productFlavors {
    }
    lintOptions {
        abortOnError false
} } dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.nineoldandroids:library:2.4.0'
    compile 'com.daimajia.swipelayout:library:1.2.0@aar'
    compile 'com.daimajia.androidanimations:library:1.1.2@aar'
    compile 'com.google.android.gms:play-services-maps:10.0.1'
    compile 'com.google.android.gms:play-services-gcm:10.0.1'
    compile 'com.mcxiaoke.volley:library:1.0.19'
    compile 'com.google.code.gson:gson:2.8.2'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}

Manifest.xml:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Any help?


问:
How to move Trello cards when Jira issues status is updated
We have Zapier basic account and the only zap we have seen is creating trello cards when new jira issues is created.

We also tried creating a custom zap but there is no trigger for updates. Everything is only upon creating new issues, new projects, and new users.
Our Jira account is on cloud.

We know about other premium add-ons and premium third party sources but we already have Zapier basic.

Thanks in Advance.

答: According to their website, it appears that there is now a trigger from JIRA when issues are updated.</p>


问:
Find non-awaited async method calls
I've just stumbled across a rather dangerous scenario while migrating an ASP.NET application to the async/await model.

The situation is that I made a method async: async Task DoWhateverAsync(), changed the declaration in the interface to Task DoWhateverAsync() and hoped that the compiler would tell me where the code now is wrong, via that Warning. Well, tough luck. Wherever that object gets injected via the interface, the warning doesn't happen. :-(

This is dangerous. Is there any way to check automatically for non-awaited methods that return tasks? I don't mind a few warnings too many, but I wouldn't want to miss one.

Here's an example:

```<code>using System.Threading.Tasks;
namespace AsyncAwaitGames
{
    // In my real case, that method just returns Task.
    public interface ICallee { Task<int> DoSomethingAsync(); }

    public class Callee: ICallee
    {
        public async Task<int> DoSomethingAsync() => await Task.FromResult(0);
    }
    public class Caller
    {
        public void DoCall()
        {
            ICallee xxx = new Callee();

            // In my real case, the method just returns Task,
            // so there is no type mismatch when assigning a result
            // either.
            xxx.DoSomethingAsync(); // This is where I had hoped for a warning.
        }
    }
}
</code>```

答:
You can add a specific warning in VS Project properties as one that throws a compilation error, like described here

You can add a semi-colon separated list of warning codes e.g. CS4014, and the compiler will fail to compile if you're not awaiting an async method.

Here's a screenshot with VS2017:
VS2017 configuration to throw compiler errors for warning CS4014

Title: Find non-awaited async method calls

Body:
I've just stumbled across a rather dangerous scenario while migrating an ASP.NET application to the async/await model.

The situation is that I made a method async: async Task DoWhateverAsync(), changed the declaration in the interface to Task DoWhateverAsync() and hoped that the compiler would tell me where the code now is wrong, via that Warning. Well, tough luck. Wherever that object gets injected via the interface, the warning doesn't happen. :-(

This is dangerous. Is there any way to check automatically for non-awaited methods that return tasks? I don't mind a few warnings too many, but I wouldn't want to miss one.

Here's an example:

using System.Threading.Tasks;
namespace AsyncAwaitGames
{
    // In my real case, that method just returns Task.
    public interface ICallee { Task<int> DoSomethingAsync(); }

    public class Callee: ICallee
    {
        public async Task<int> DoSomethingAsync() => await Task.FromResult(0);
    }
    public class Caller
    {
        public void DoCall()
        {
            ICallee xxx = new Callee();

            // In my real case, the method just returns Task,
            // so there is no type mismatch when assigning a result
            // either.
            xxx.DoSomethingAsync(); // This is where I had hoped for a warning.
        }
    }
}


问:
Having trouble using Arraylist.get method and it's showing "Incompatible operand types Object and int"
I was trying to take an unknown number of integers from the user (until the user enters 0), and count the number of occurrences of each of the integers entered. I figured, to count after I'm done taking the integers, I'd have to store them in an array. And I did some research and realized that the only way to create an Array with an unspecified length, ArrayList is the only way. But my this part of the code is showing error:</p>

```<code>import java.util.Scanner;

import java.util.ArrayList;

public class IntegersOccurence {

    public static void main(String[] args) {
        Scanner input = new Scanner (System.in);

        System.out.print("Enter the integers between 1 and 100: ");
        ArrayList list = new ArrayList();
        System.out.println(list.get(0));
        //eclipse is showing an error in the line right below
        while (list.get(list.size() - 1) != 0) {
            list.add(input.nextInt());
        }
    }
}
</code>```

答:
You are using raw type so type of the list is Object which cannot be compared to int (0) so use

```<code> ArrayList<Integer> list = new ArrayList<>();
</code>```

Read , What is a raw type and why shouldn't we use it?

As mentioned : you are adding no element in list  and invoking get will cause a crash because

From docs

IndexOutOfBoundsException - if the index is out of range (index < 0 ||
  index >= size()

here index>=size() is true (list size is 0,no element) so hence exception

Body:
I was trying to take an unknown number of integers from the user (until the user enters 0), and count the number of occurrences of each of the integers entered. I figured, to count after I'm done taking the integers, I'd have to store them in an array. And I did some research and realized that the only way to create an Array with an unspecified length, ArrayList is the only way. But my this part of the code is showing error:

import java.util.Scanner;

import java.util.ArrayList;

public class IntegersOccurence {

    public static void main(String[] args) {
        Scanner input = new Scanner (System.in);

        System.out.print("Enter the integers between 1 and 100: ");
        ArrayList list = new ArrayList();
        System.out.println(list.get(0));
        //eclipse is showing an error in the line right below
        while (list.get(list.size() - 1) != 0) {
            list.add(input.nextInt());
        }
    }
}

Body:
You are using raw type so type of the list is Object which cannot be compared to int (0) so use

 ArrayList<Integer> list = new ArrayList<>();

Read , What is a raw type and why shouldn't we use it?

As mentioned : you are adding no element in list  and invoking get will cause a crash because

From docs

IndexOutOfBoundsException - if the index is out of range (index < 0 ||
  index >= size()

here index>=size() is true (list size is 0,no element) so hence exception


问:
How to set text in GMSAutocompleteViewController in Google Place AutocompleteViewController
I need help to set text in searchBar of GMSAutocompleteViewController when open in my App. I am using GMSAutocompleteViewController in Google Place AutocompleteViewController.

答:
```<code>- (void)viewDidLoad {
    [super viewDidLoad];

    acController = [[GMSAutocompleteViewController alloc] init];

    acController.delegate = self;
}

- (IBAction)btnSearch1:(id)sender {
    [self presentViewController:acController animated:YES completion:nil];
}

- (void)didRequestAutocompletePredictions:(GMSAutocompleteViewController *)viewController {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    UIView *Views = viewController.view;

    NSArray *Aar2 = [[Views subviews][0] subviews];

    UIView *View2 = Aar2[1];

    UIView *View3 = [View2 subviews][2];

    UISearchBar *Search = [[View3 subviews] firstObject];

    Search.text = @"Your text";

    [Search.delegate searchBar:Search textDidChange:txtAddress.text];
}
</code>```

<p>// Cools enjoy man</p>

Body:
- (void)viewDidLoad {
    [super viewDidLoad];

    acController = [[GMSAutocompleteViewController alloc] init];

    acController.delegate = self;
}

- (IBAction)btnSearch1:(id)sender {
    [self presentViewController:acController animated:YES completion:nil];
}

- (void)didRequestAutocompletePredictions:(GMSAutocompleteViewController *)viewController {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    UIView *Views = viewController.view;

    NSArray *Aar2 = [[Views subviews][0] subviews];

    UIView *View2 = Aar2[1];

    UIView *View3 = [View2 subviews][2];

    UISearchBar *Search = [[View3 subviews] firstObject];

    Search.text = @"Your text";

    [Search.delegate searchBar:Search textDidChange:txtAddress.text];
}

// Cools enjoy man


问:
How to return properly?
I am having trouble returning the answer properly.

Is the return roll_dice(x) syntax correct, or do I need to replace x with something else in the parentheses?

I am a beginner and would like some help with this problem:

My code:

```<code>import numpy as np

def roll_dice(x):
    totmoney = 0

    for a in range(x):
        throw_one = np.random.randint(6)
        throw_two = np.random.randint(6)

        if throw_one % 2 != 0 or throw_two % 2 != 0:
            totmoney += throw_one + throw_two
            print throw_one,"|",throw_two,"|",totmoney
        else:
            totmoney -= throw_one + throw_two
            print throw_one,"|",throw_two,"|",totmoney

        return roll_dice(x)
</code>```

答:
Without doing too much modifications, I think what you wanted to do is:

```<code>import random

def roll_dice(x):
    totmoney = 0
    result_matrix = []

    for a in range(x):
        throw_one = random.randint(1, 6)
        throw_two = random.randint(1, 6)

        if throw_one % 2 != 0 or throw_two % 2 != 0:
            totmoney += throw_one + throw_two
            print throw_one,"|",throw_two,"|",totmoney
        else:
            totmoney -= throw_one + throw_two
            print throw_one,"|",throw_two,"|",totmoney

        result_matrix.append([throw_one, throw_two, totmoney])

    return result_matrix

example = roll_dice(2)
print example
</code>```

(I have used the random module because I don't have numpy installed)

You create the matrix one row at a time each time you go through the loop and at the end this matrix is what you return.

But I would add some additional modifications:

```<code>import random

def roll_dice(x):
    totmoney = 0
    result_matrix = []

    for a in range(x):
        throws = [random.randint(1, 6), random.randint(1, 6)]

        if throws[0] % 2 != 0 or throws[1] % 2 != 0:
            totmoney += sum(throws)
        else:
            totmoney -= sum(throws)

        print throws[0],"|",throws[1],"|",totmoney

        result_matrix.append([throws[0], throws[1], totmoney])

    return result_matrix

example = roll_dice(2)
print example
</code>```

Here's what I have put in place:

I have put your two throws into a list named throws

I have used the sum function to add these two throws

I have put your print statement outside of your if statement

We could go much further, but I'm getting tired and I don't want to confuse you with more advanced stuff.

Title: How to return properly?

Body:
I am having trouble returning the answer properly.

Is the return roll_dice(x) syntax correct, or do I need to replace x with something else in the parentheses?

I am a beginner and would like some help with this problem:

My code:

import numpy as np

def roll_dice(x):
    totmoney = 0

    for a in range(x):
        throw_one = np.random.randint(6)
        throw_two = np.random.randint(6)

        if throw_one % 2 != 0 or throw_two % 2 != 0:
            totmoney += throw_one + throw_two
            print throw_one,"|",throw_two,"|",totmoney
        else:
            totmoney -= throw_one + throw_two
            print throw_one,"|",throw_two,"|",totmoney

        return roll_dice(x)

Body:
Without doing too much modifications, I think what you wanted to do is:

import random

def roll_dice(x):
    totmoney = 0
    result_matrix = []

    for a in range(x):
        throw_one = random.randint(1, 6)
        throw_two = random.randint(1, 6)

        if throw_one % 2 != 0 or throw_two % 2 != 0:
            totmoney += throw_one + throw_two
            print throw_one,"|",throw_two,"|",totmoney
        else:
            totmoney -= throw_one + throw_two
            print throw_one,"|",throw_two,"|",totmoney

        result_matrix.append([throw_one, throw_two, totmoney])

    return result_matrix

example = roll_dice(2)
print example

(I have used the random module because I don't have numpy installed)

You create the matrix one row at a time each time you go through the loop and at the end this matrix is what you return.

But I would add some additional modifications:

import random

def roll_dice(x):
    totmoney = 0
    result_matrix = []

    for a in range(x):
        throws = [random.randint(1, 6), random.randint(1, 6)]

        if throws[0] % 2 != 0 or throws[1] % 2 != 0:
            totmoney += sum(throws)
        else:
            totmoney -= sum(throws)

        print throws[0],"|",throws[1],"|",totmoney

        result_matrix.append([throws[0], throws[1], totmoney])

    return result_matrix

example = roll_dice(2)
print example

Here's what I have put in place:

I have put your two throws into a list named throws

I have used the sum function to add these two throws

I have put your print statement outside of your if statement

We could go much further, but I'm getting tired and I don't want to confuse you with more advanced stuff.


问:
No value accessor for form control
I'm using Angular2-rc5, and I'm currently getting an error on my login page. I'm trying to make a form but the console throws exceptions telling me that it can't find my formcontrolls even though I create it on init. Any idea why I'm getting this error?

login component

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';
import { LoginService } from './login.service';
import { User } from '../../models/user';

@Component({
    selector: 'login',
    providers: [LoginService],
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
    private loginForm: FormGroup; // our model driven form
    private submitted: boolean; // keep track on whether form is submitted
    private events: any[] = []; // use later to display form changes

    constructor(private fb: FormBuilder, private ls:LoginService){}
    ngOnInit(){
        this.loginForm = new FormGroup({
            email: new FormControl('',[<any>Validators.required]),
            password: new FormControl('', [<any>Validators.required, <any>Validators.minLength(6)]),
            rememberMe: new FormControl()
        });
    }
    save(model: User, isValid: boolean) {
        console.log("Test");
        console.log(model, isValid);
    }
    // Login in user
    login(email: any, password: any){
        this.ls.login(email, password, false);
    }
}
```
<p><strong>Page.html</strong></p>
<pre class="lang-html prettyprint-override"><code><div id="login-page">
    <div class="form-wrapper">
        <form class="login-form" [formGroup]="loginForm" novalidate (ngSubmit)="save(loginForm.value, loginForm.valid)">
            <div >
                <div class="input-field col s12 center">
                    <p class="center login-form-text">Login page</p>
                </div>
            </div>
            <div >
                <div class="input-field col s12">
                    <input id="email" type="email">
                    <label class="center-align" for="email" formControlName="email">Email</label>
                </div>
            </div>
            <div >
                <div class="input-field col s12">
                    <input id="password" type="password">
                    <label class="center" for="password" formControlName="password">Password</label>
                </div>
            </div>
            <div >
                <div class="input-field col s12 m12 l12 login-text">
                    <input id="remember-me" type="checkbox" formControlName="rememberMe">
                    <label for="remember-me">Remember me</label>
                </div>
            </div>
            <div >
                <div class="input-field col s12">
                    <ahref="index.html">Login</a>
                </div>
            </div>
            <div >
                <div >
                    <p>Register Now!</p>
                </div>
                <div >
                    <p>Forgot password ?</p>
                </div>
            </div>
        </form>
    </div>
</div>
</code>```

Exception

EXCEPTION: Uncaught (in promise): Error: Error in ./LoginComponent
class LoginComponent - inline template:13:45 caused by: No value
accessor for form control with name: 'email'.....

答:
For UnitTest angular 2 with angular material you have to add MatSelectModule module in imports section.

```<code>import { MatSelectModule } from '@angular/material';

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ CreateUserComponent ],
      imports : [ReactiveFormsModule,
        MatSelectModule,
        MatAutocompleteModule,......

      ],
      providers: [.........]
    })
    .compileComponents();
  }));
</code>```

Title: No value accessor for form control

Body:
I'm using Angular2-rc5, and I'm currently getting an error on my login page. I'm trying to make a form but the console throws exceptions telling me that it can't find my formcontrolls even though I create it on init. Any idea why I'm getting this error?

login component

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';
import { LoginService } from './login.service';
import { User } from '../../models/user';

@Component({
    selector: 'login',
    providers: [LoginService],
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
    private loginForm: FormGroup; // our model driven form
    private submitted: boolean; // keep track on whether form is submitted
    private events: any[] = []; // use later to display form changes

    constructor(private fb: FormBuilder, private ls:LoginService){}
    ngOnInit(){
        this.loginForm = new FormGroup({
            email: new FormControl('',[<any>Validators.required]),
            password: new FormControl('', [<any>Validators.required, <any>Validators.minLength(6)]),
            rememberMe: new FormControl()
        });
    }
    save(model: User, isValid: boolean) {
        console.log("Test");
        console.log(model, isValid);
    }
    // Login in user
    login(email: any, password: any){
        this.ls.login(email, password, false);
    }
}

Page.html

        <form class="login-form" [formGroup]="loginForm" novalidate (ngSubmit)="save(loginForm.value, loginForm.valid)">

Login page

                    <input id="email" type="email">
                    Email

                    <input id="password" type="password">
                    Password

                    <input id="remember-me" type="checkbox" formControlName="rememberMe">
                    Remember me

                    <ahref="index.html">Login

Register Now!

Forgot password ?

        </form>

Exception

EXCEPTION: Uncaught (in promise): Error: Error in ./LoginComponent
class LoginComponent - inline template:13:45 caused by: No value
accessor for form control with name: 'email'.....

Body:
For UnitTest angular 2 with angular material you have to add MatSelectModule module in imports section.

import { MatSelectModule } from '@angular/material';

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ CreateUserComponent ],
      imports : [ReactiveFormsModule,
        MatSelectModule,
        MatAutocompleteModule,......

      ],
      providers: [.........]
    })
    .compileComponents();
  }));


问:
In react router 4, how does one negate a route / path using regex?
Say i have a route switch statement like the following:

```<code>render () {
    ```
        <Switch>
            <Route path="/foo" render={render}>
            <Route path="/bar" render={renderBar}>
            <Route path="/" render={renderHome}>

            {/* How do i express everything except the home page ?*/}

            <Route render={renderFourOhFour}>
        </Switch>
    ```
}
</code>```

How do i write a route that excludes everything except the home page given the above example? Do i just write a regex? If so i've tried something like

path={^(?!.*(home))}

with the regex react router v4 tester: https://pshrmn.github.io/route-tester/#/

答:
You can use the render method on the Route, which gets passed the location as a prop. So:

```<code><Route render={({location}) => {
  return location.pathname !== '/' ? <p>Not home</p> : ''
}} />
</code>```

Body:
Say i have a route switch statement like the following:

render () {

        <Switch>
            <Route path="/foo" render={render}>
            <Route path="/bar" render={renderBar}>
            <Route path="/" render={renderHome}>

            {/* How do i express everything except the home page ?*/}

            <Route render={renderFourOhFour}>
        </Switch>

}

How do i write a route that excludes everything except the home page given the above example? Do i just write a regex? If so i've tried something like

path={^(?!.*(home))}

with the regex react router v4 tester: https://pshrmn.github.io/route-tester/#/

Body:
You can use the render method on the Route, which gets passed the location as a prop. So:

<Route render={({location}) => {
  return location.pathname !== '/' ? <p>Not home</p> : ''
}} />


问:
Cat command didn't work correctly with execvp
1) I can't use some commands in this code, such as : cat somefile.txt > somefile2.txt
also I can't use : cat somefile.txt | less

2) When I use commands like : ( cd ../) (cd ./Desktop) and then I want to exit the program, I need to execute exit commands more than one time: ie "if I use 3 cd command, I will need 3 exit commands to end the program"

```<code>#define MAX_ARGS 5

// Global Declarations

// Mini Functions

void remove_new_line_char(char line[])
{
    int i=0;
    while(line[i]!= '\n')
        i++;
    line[i] = '\0';
}

// Grand Functions

int read_line(char line[])
{
    fgets(line, 10000, stdin); // File Get String
    remove_new_line_char(line); // Remove New Line Charactere
    if (strlen(line) > 512)
    {
        fprintf(stderr,"The Command exceeded available line length\n");
        return 0;
    }
    if (strcmp(line, "exit") == 0)
        exit(0);
    return 1;
}

int parse_line(char* args[], char line[])
{
    int i=0;
    args[i] = strtok(line, " ");
    if(args[i] == NULL)
    {
        printf("Command Line is Empty!\n");
        return -1;
    }
    while (args[i] != NULL)
    {
        int flag = 0;
        if(strcmp(args[i],"&") == 0)
            flag = 1;
        i++;
        args[i] = strtok(NULL, " "); // NULL maintains a static pointer to the previously passed string.
        if (args[i] == NULL && flag == 1)
        {
            args[i-1] = NULL; // Remove & From Argument List and Set Background Flag.
            return 1;
        }
    }
    return 0;
}

// Main

int main()
{
    char* args[MAX_ARGS]; // Array of Strings
    char line[10000]; // String
    while(1)
    {
        printf("Shell> ");
        if(read_line(line) == 1) // No Errors
        {
            int background = parse_line(args, line);
            if(background != -1) // Command Line isn't Empty
            {
                // Fork and Execute
                pid_t child_pid = fork();
                if(child_pid == 0) // Child
                {
                    if (strcmp(args[0], "cd") == 0 && args[1]!= NULL && args[2] == NULL)  // Special Handling For CD
                    {
                        //printf("%s\n",args[2]);
                        int check = chdir(args[1]);
                        if(check == -1)
                            fprintf(stderr, "Invalid Directory\n");
                    }
                    // Handle if args[1]== NULL, Don't even execvp()
                    else   // Other Functions
                    {
                        execvp(args[0], args); // args[0] is actually the command.
                        fprintf(stderr,"an error occured in execution\n%s\n",strerror(errno));
                        //fprintf(stderr,"Invalid Instruction\n");
                    }
                }
                else // Parent
                {
                    if(background == 0)
                        waitpid(child_pid, 0);
                    wait(1000);
                }
            }
        }
    }
    return 0;
}
</code>```

I suspect that I can't use any command that has characters like: > < |

Thanks in advance

答:
1) i can't use some commands in this code as : cat somefile.txt > somefile2.txt also i can't use : cat somefile.txt | less

In the standard shell, the > and | are operators interpreted by the shell, not arguments to the command.  Since in this case the shell is your program itself, if you must support those operators then you'll need to implement the appropriate redirections yourself.  Refer to open(), pipe(), and dup2(), and for the pipe case you'll also need judicious application of close().

2)when i use commands like : ( cd ../) (cd ./Desktop) and then i want to exit the program, i need to execute exit command more than one time "if i use 3 cd command i will need 3 exit command to end the program"

In the special case of the cd command, you fork and then change directory in the child process, but the child does not terminate or exec another process.  That leaves you with two copies of your shell running.  You need to exit both before control returns to whatever process launched your program.  Possibly in that case you want to instead execute chdir without forking (or waiting for a child).

Body:
1) I can't use some commands in this code, such as : cat somefile.txt > somefile2.txt
also I can't use : cat somefile.txt | less

2) When I use commands like : ( cd ../) (cd ./Desktop) and then I want to exit the program, I need to execute exit commands more than one time: ie "if I use 3 cd command, I will need 3 exit commands to end the program"

#define MAX_ARGS 5

// Global Declarations

// Mini Functions

void remove_new_line_char(char line[])
{
    int i=0;
    while(line[i]!= '\n')
        i++;
    line[i] = '\0';
}

// Grand Functions

int read_line(char line[])
{
    fgets(line, 10000, stdin); // File Get String
    remove_new_line_char(line); // Remove New Line Charactere
    if (strlen(line) > 512)
    {
        fprintf(stderr,"The Command exceeded available line length\n");
        return 0;
    }
    if (strcmp(line, "exit") == 0)
        exit(0);
    return 1;
}

int parse_line(char* args[], char line[])
{
    int i=0;
    args[i] = strtok(line, " ");
    if(args[i] == NULL)
    {
        printf("Command Line is Empty!\n");
        return -1;
    }
    while (args[i] != NULL)
    {
        int flag = 0;
        if(strcmp(args[i],"&") == 0)
            flag = 1;
        i++;
        args[i] = strtok(NULL, " "); // NULL maintains a static pointer to the previously passed string.
        if (args[i] == NULL && flag == 1)
        {
            args[i-1] = NULL; // Remove & From Argument List and Set Background Flag.
            return 1;
        }
    }
    return 0;
}

// Main

int main()
{
    char* args[MAX_ARGS]; // Array of Strings
    char line[10000]; // String
    while(1)
    {
        printf("Shell> ");
        if(read_line(line) == 1) // No Errors
        {
            int background = parse_line(args, line);
            if(background != -1) // Command Line isn't Empty
            {
                // Fork and Execute
                pid_t child_pid = fork();
                if(child_pid == 0) // Child
                {
                    if (strcmp(args[0], "cd") == 0 && args[1]!= NULL && args[2] == NULL)  // Special Handling For CD
                    {
                        //printf("%s\n",args[2]);
                        int check = chdir(args[1]);
                        if(check == -1)
                            fprintf(stderr, "Invalid Directory\n");
                    }
                    // Handle if args[1]== NULL, Don't even execvp()
                    else   // Other Functions
                    {
                        execvp(args[0], args); // args[0] is actually the command.
                        fprintf(stderr,"an error occured in execution\n%s\n",strerror(errno));
                        //fprintf(stderr,"Invalid Instruction\n");
                    }
                }
                else // Parent
                {
                    if(background == 0)
                        waitpid(child_pid, 0);
                    wait(1000);
                }
            }
        }
    }
    return 0;
}

I suspect that I can't use any command that has characters like: > < |

Thanks in advance


问:
JavaFX MediaPlayer - seek() method makes the player hang
I've been looking for ages for direction on this matter and I finally post here.

I have a JavaFX application with MediaPlayer. One day, seeking at a later position in video (that had not been accessed previously) started hanging the player. No status change before it gets to PLAYING, the buffer is loaded, status at READY before I call seek().

First I thought it is because I went out of Application thread, tried to put the MediaPlayer back on the root to be sure, and the seek method worked as before, fast enough for me.
But then for a reason I can't get, it started hanging again all the time, with same symptoms.
Now, even with the most simple code, it hangs too.

I'm desperate, the waiting time can be 30 seconds to reach a position 2 minutes later in the video. Looks like the Media Player is scanning again all video until it finds the good position it's seeking, thus taking more time for a later position. If the position has been accessed before though, seek() won't hang...

Am I the only one with this problem?

I'm on Mac os EL Capitan, but tried on Windows VM too and I get the same behaviour.

Here is a standalone code, but I don't see how it will help, I don't even hope for ppl to reproduce:

```<code>public class VideoPlayerExample extends Application {
public static void main(String[] args) throws Exception {
    launch(args);
}

@Override
public void start(final Stage stage) throws Exception {

    File file = new FileChooser().showOpenDialog(stage);
    Media media = new Media(file.toURI().toString());
    MediaPlayer mp = new MediaPlayer(media);
    mp.statusProperty().addListener(new ChangeListener<MediaPlayer.Status>() {
        @Override
        public void changed(ObservableValue<? extends Status> observable, Status oldValue, Status newValue) {
            System.out.println(newValue);
        }
    });

    Group gp = new Group(new MediaView(mp));

    Button buttonTest = new Button("It's gonna hang...");
    buttonTest.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            mp.pause();
            System.out.println(mp.getCurrentTime().toMillis());
            mp.seek(new Duration(mp.getCurrentTime().toMillis() +10000));

            mp.play();
        }
    });

    gp.getChildren().add(buttonTest);
    stage.setScene(new Scene(gp, 540, 208));
    stage.show();
}
}
</code>```

Any help will be so greatly appreciated!

答: You're right - I can't reproduce your problem.  I have macOS Sierra 10.12.6.  All I can say is check the type of movie you're trying to play - not all encodings are supported.  Also, according to the documentation, if the movie's duration is Duration.INDEFINITE, seek() will have no effect.</p>

Body:
I've been looking for ages for direction on this matter and I finally post here.

I have a JavaFX application with MediaPlayer. One day, seeking at a later position in video (that had not been accessed previously) started hanging the player. No status change before it gets to PLAYING, the buffer is loaded, status at READY before I call seek().

First I thought it is because I went out of Application thread, tried to put the MediaPlayer back on the root to be sure, and the seek method worked as before, fast enough for me.
But then for a reason I can't get, it started hanging again all the time, with same symptoms.
Now, even with the most simple code, it hangs too.

I'm desperate, the waiting time can be 30 seconds to reach a position 2 minutes later in the video. Looks like the Media Player is scanning again all video until it finds the good position it's seeking, thus taking more time for a later position. If the position has been accessed before though, seek() won't hang...

Am I the only one with this problem?

I'm on Mac os EL Capitan, but tried on Windows VM too and I get the same behaviour.

Here is a standalone code, but I don't see how it will help, I don't even hope for ppl to reproduce:

public class VideoPlayerExample extends Application {
public static void main(String[] args) throws Exception {
    launch(args);
}

@Override
public void start(final Stage stage) throws Exception {

    File file = new FileChooser().showOpenDialog(stage);
    Media media = new Media(file.toURI().toString());
    MediaPlayer mp = new MediaPlayer(media);
    mp.statusProperty().addListener(new ChangeListener<MediaPlayer.Status>() {
        @Override
        public void changed(ObservableValue<? extends Status> observable, Status oldValue, Status newValue) {
            System.out.println(newValue);
        }
    });

    Group gp = new Group(new MediaView(mp));

    Button buttonTest = new Button("It's gonna hang...");
    buttonTest.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            mp.pause();
            System.out.println(mp.getCurrentTime().toMillis());
            mp.seek(new Duration(mp.getCurrentTime().toMillis() +10000));

            mp.play();
        }
    });

    gp.getChildren().add(buttonTest);
    stage.setScene(new Scene(gp, 540, 208));
    stage.show();
}
}

Any help will be so greatly appreciated!


问:
Running shell commands within .java file using ProcessBuilder
I'm running into a pesky little error and I'm not sure how to solve it. What I'm trying to do is pretty simple: Run an external .java file using ProcessBuilder. Just like that tittle suggests.

The problem is that the file that runs and creates this ProcessBuilder is in a different directory than the other file I want to run.

What I'm trying to do to get around this is:

```<code>String command[] = {"javac",JAVA_FILE_LOCATION};
ProcessBuilder processBuilder = new ProcessBuilder("cd");
Process process0 = processBuilder.start();
</code>```

to reset the directory and

```<code>processBuilder = new ProcessBuilder(command);
Process process = processBuilder.start();
</code>```

to compile the other file

```<code>if( process.getErrorStream().read() != -1 ){
    print("Compilation Errors",process.getErrorStream());
}
</code>```

and just some error handling here. However it doesn't get past this error handle part. I can't figure out the proper way of doing this. Here's the error message:

```<code>my_PC:Processes user$ java -jar process.jar
************* Compilation Errors***********************
avac: file not found: /Users/Desktop/Piano.java
Usage: javac <options> <source files>
use -help for a list of possible options
Exception in thread "main" java.lang.IllegalThreadStateException: process hasn't exited
at java.lang.UNIXProcess.exitValue(UNIXProcess.java:423)
at my.package.address.Main.main(Main.java:28)
</code>```

Does anyone know what I'm doing wrong ? Also I can post the whole code if needed, but I figured it's not really relevant here.

UPDATED: added my code

```<code>package some.random.package;

import java.io.*;

public class Main {
/**
* Provide absolute JAVA file path
*/
private static final String JAVA_FILE_LOCATION = "/Users/Desktop/piano.java";

    public static void main(String args[]) throws IOException
    {
        String command[] = {"javac",JAVA_FILE_LOCATION};
        ProcessBuilder processBuilder = new ProcessBuilder(command).directory(new File("/Users/Desktop/"));
        Process process = processBuilder.start();
        if( process.getErrorStream().read() != -1 ){
            print("Compilation Errors",process.getErrorStream());
        }
        /**
        * check if compile is successful
        * 0 => successful
        */
        if( process.exitValue() == 0 )
        {
            process = new ProcessBuilder(new String[]{"java","piano"}).directory(new File("/Users/Desktop/")).start();
            if( process.getErrorStream().read() != -1 )
                print("Errors ",process.getErrorStream());
            else
                print("Output ",process.getInputStream());

            /**
            * Check if RuntimeException or Errors encounter during execution then print errors on console
            * Otherwise print Output
            */
        }
    }
    private static void print(String status,InputStream input) throws IOException
    {
        BufferedReader in = new BufferedReader(new InputStreamReader(input));
        System.out.println("************* "+status+"***********************");
        String line = null;
        while((line = in.readLine()) != null ){
        System.out.println(line);
      }
    in.close();
    }
}
</code>```

答:
The cd command you execute with the first ProcessBuilder affects only that child process, it does not change the working directory of the main executing program.
When you run the second ProcessBuilder, it will have the working directory as the main program,
completely unaffected by the cd executed by the previous ProcessBuilder.

To execute a program from a different directory, use the directory(...) method of ProcessBuilder:

```<code>String command[] = {"javac", JAVA_FILE_LOCATION};
ProcessBuilder processBuilder = new ProcessBuilder(command).directory(new File("path/to/dir"));
Process process0 = processBuilder.start();
</code>```

Btw, the path "/Users/Desktop/piano.java" looks very strange.
The path to a user's desktop on a Mac is usually /Users/username/Desktop,
so the path in your code implies that your username is "Desktop",
which is very unusual.

And, to make it easier to work with the program,
I suggest to put the base directory path (/Users/username/Desktop) in a variable,
rather then hardcoding it at multiple places.
That way it will be easier to make changes, no need to edit at multiple places.

Body:
I'm running into a pesky little error and I'm not sure how to solve it. What I'm trying to do is pretty simple: Run an external .java file using ProcessBuilder. Just like that tittle suggests.

The problem is that the file that runs and creates this ProcessBuilder is in a different directory than the other file I want to run.

What I'm trying to do to get around this is:

String command[] = {"javac",JAVA_FILE_LOCATION};
ProcessBuilder processBuilder = new ProcessBuilder("cd");
Process process0 = processBuilder.start();

to reset the directory and

processBuilder = new ProcessBuilder(command);
Process process = processBuilder.start();

to compile the other file

if( process.getErrorStream().read() != -1 ){
    print("Compilation Errors",process.getErrorStream());
}

and just some error handling here. However it doesn't get past this error handle part. I can't figure out the proper way of doing this. Here's the error message:

my_PC:Processes user$ java -jar process.jar
************* Compilation Errors***********************
avac: file not found: /Users/Desktop/Piano.java
Usage: javac <options> <source files>
use -help for a list of possible options
Exception in thread "main" java.lang.IllegalThreadStateException: process hasn't exited
at java.lang.UNIXProcess.exitValue(UNIXProcess.java:423)
at my.package.address.Main.main(Main.java:28)

Does anyone know what I'm doing wrong ? Also I can post the whole code if needed, but I figured it's not really relevant here.

UPDATED: added my code

package some.random.package;

import java.io.*;

public class Main {
/**
* Provide absolute JAVA file path
*/
private static final String JAVA_FILE_LOCATION = "/Users/Desktop/piano.java";

    public static void main(String args[]) throws IOException
    {
        String command[] = {"javac",JAVA_FILE_LOCATION};
        ProcessBuilder processBuilder = new ProcessBuilder(command).directory(new File("/Users/Desktop/"));
        Process process = processBuilder.start();
        if( process.getErrorStream().read() != -1 ){
            print("Compilation Errors",process.getErrorStream());
        }
        /**
        * check if compile is successful
        * 0 => successful
        */
        if( process.exitValue() == 0 )
        {
            process = new ProcessBuilder(new String[]{"java","piano"}).directory(new File("/Users/Desktop/")).start();
            if( process.getErrorStream().read() != -1 )
                print("Errors ",process.getErrorStream());
            else
                print("Output ",process.getInputStream());

            /**
            * Check if RuntimeException or Errors encounter during execution then print errors on console
            * Otherwise print Output
            */
        }
    }
    private static void print(String status,InputStream input) throws IOException
    {
        BufferedReader in = new BufferedReader(new InputStreamReader(input));
        System.out.println("************* "+status+"***********************");
        String line = null;
        while((line = in.readLine()) != null ){
        System.out.println(line);
      }
    in.close();
    }
}

Body:
The cd command you execute with the first ProcessBuilder affects only that child process, it does not change the working directory of the main executing program.
When you run the second ProcessBuilder, it will have the working directory as the main program,
completely unaffected by the cd executed by the previous ProcessBuilder.

To execute a program from a different directory, use the directory(...) method of ProcessBuilder:

String command[] = {"javac", JAVA_FILE_LOCATION};
ProcessBuilder processBuilder = new ProcessBuilder(command).directory(new File("path/to/dir"));
Process process0 = processBuilder.start();

Btw, the path "/Users/Desktop/piano.java" looks very strange.
The path to a user's desktop on a Mac is usually /Users/username/Desktop,
so the path in your code implies that your username is "Desktop",
which is very unusual.

And, to make it easier to work with the program,
I suggest to put the base directory path (/Users/username/Desktop) in a variable,
rather then hardcoding it at multiple places.
That way it will be easier to make changes, no need to edit at multiple places.


问:
When I define functions, in what order should I put the parameters?
I often find it hard to decide and am inconsistent. Are there some rules I could follow?

For example:

```<code>def remove_except(haystack, needle, exclude_value):
    for key in hackstack:
        if key in needle and haystack[key] != exclude_value:
            hackstack.pop(key)
</code>```

could easily be:

```<code>def remove_except(needle, exclude_value, haystack):
    for key in hackstack:
        if key in needle and haystack[key] != exclude_value:
            hackstack.pop(key)
</code>```

Not a perfect example because I tend to put the variable being modified as the first parameter, e.g. haystack, and that might even be a convention but apart from that I'm unsure what to do.

I'm interested for more languages than just Python.

答:
The only rule is be consistent. That doesn't only mean be consistent between and within the APIs you define, but also be consistent with any APIs commonly used in the environment. Note that this may mean you do things differently in one environment than in another. Try to fit in.

Now, with Python and JavaScript, you can use object orientation to take at least the haystack out of the question, because the haystack will be (or at least, can be) an object you're acting on and so how you do that will be dictated by the language (e.g., delete haystack[needle]; [JavaScript for removing a property from an object] or del haystack[needle] [Python for removing a dictionary entry]). C isn't object-oriented (C++, D, Objective-C, and several other derivatives are) and so you'll need to look for the convention there.

Subjectively speaking, in my experience, the haystack normally comes first, but that may just be my experience. Similarly, my subjective opinion would be that the exclude_value would be the last thing (so, haystack, needle, exclude_value) because there would be other operations that would take haystack, needle, something_else — but that's just an opinion.

Body:
I often find it hard to decide and am inconsistent. Are there some rules I could follow?

For example:

def remove_except(haystack, needle, exclude_value):
    for key in hackstack:
        if key in needle and haystack[key] != exclude_value:
            hackstack.pop(key)

could easily be:

def remove_except(needle, exclude_value, haystack):
    for key in hackstack:
        if key in needle and haystack[key] != exclude_value:
            hackstack.pop(key)

Not a perfect example because I tend to put the variable being modified as the first parameter, e.g. haystack, and that might even be a convention but apart from that I'm unsure what to do.

I'm interested for more languages than just Python.


问:
Send mail with attachment using mailjet in GAS
I am trying to send mail with a PDF attachment using Mailjet from Google Apps Script. I can send regular mail without issue, but not quite sure how to include an attachment.

Mailjet documentation: https://dev.mailjet.com/guides/#sending-with-attached-files

I think my problem is the Base64Content. I don't really understand how to encode the attachment. When I execute the below code, an email is being sent with a PDF attachment, but when I try and open the PDF it displays: "Cannot display PDF (test.pdf is of invalid format)".

```<code>var newDoc = DocumentApp.openById(newDocid)

var attachment = newDoc.getAs(MimeType.PDF);

var mailjeturl = "https://api.mailjet.com/v3.1/send";

var mailjetparams = {
    "Messages":[{
      "From": {"Email": 'myemail@domain.com',"Name": 'Robert'},
      "To": [{"Email": 'theiremail@domain.com'}],
      "Subject": 'subject',
      "HTMLPart": 'this message',
      "Attachments": [{"ContentType": "application/pdf",
                       "Filename": "test.pdf",
                       "Base64Content": Utilities.base64Encode(attachment)}]
    }]
  }

var mailjetoptions = {
    'method': 'post',
    'contentType': 'application/json',
    'payload': JSON.stringify(mailjetparams),
    'headers': {'Authorization': 'Basic ' + Utilities.base64Encode(MAILJET_KEY)}
  };

var response = JSON.parse(UrlFetchApp.fetch(mailjeturl, mailjetoptions))
</code>```

答:
Try to encode like this:</p>

```<code>  var pdf = newDoc.getAs('application/pdf').getBytes();
  var attach = {fileName:'test.pdf',content:pdf, mimeType:'application/pdf'};

  var mailjetparams = {
    "Messages":[{
    "From": {"Email": 'sender@domain.com',"Name": 'Robert'},
    "To": [{"Email": 'reciever@domain.com'}],
    "Subject": 'subject',
    "HTMLPart": 'this message',
    "Attachments": [attach]
   }]
 }
</code>```

Body:
I am trying to send mail with a PDF attachment using Mailjet from Google Apps Script. I can send regular mail without issue, but not quite sure how to include an attachment.

Mailjet documentation: https://dev.mailjet.com/guides/#sending-with-attached-files

I think my problem is the Base64Content. I don't really understand how to encode the attachment. When I execute the below code, an email is being sent with a PDF attachment, but when I try and open the PDF it displays: "Cannot display PDF (test.pdf is of invalid format)".

var newDoc = DocumentApp.openById(newDocid)

var attachment = newDoc.getAs(MimeType.PDF);

var mailjeturl = "https://api.mailjet.com/v3.1/send";

var mailjetparams = {
    "Messages":[{
      "From": {"Email": 'myemail@domain.com',"Name": 'Robert'},
      "To": [{"Email": 'theiremail@domain.com'}],
      "Subject": 'subject',
      "HTMLPart": 'this message',
      "Attachments": [{"ContentType": "application/pdf",
                       "Filename": "test.pdf",
                       "Base64Content": Utilities.base64Encode(attachment)}]
    }]
  }

var mailjetoptions = {
    'method': 'post',
    'contentType': 'application/json',
    'payload': JSON.stringify(mailjetparams),
    'headers': {'Authorization': 'Basic ' + Utilities.base64Encode(MAILJET_KEY)}
  };

var response = JSON.parse(UrlFetchApp.fetch(mailjeturl, mailjetoptions))

Body:
Try to encode like this:

  var pdf = newDoc.getAs('application/pdf').getBytes();
  var attach = {fileName:'test.pdf',content:pdf, mimeType:'application/pdf'};

  var mailjetparams = {
    "Messages":[{
    "From": {"Email": 'sender@domain.com',"Name": 'Robert'},
    "To": [{"Email": 'reciever@domain.com'}],
    "Subject": 'subject',
    "HTMLPart": 'this message',
    "Attachments": [attach]
   }]
 }


Title: Replacing JSON pattern

Body:
My JSON file is like:

{"A":[
{"Timestamp": "2017-11-14 14:39:54", "File": "E.kmp", "C":{....},
{"Timestamp": "2017-11-14 14:40:32", "File": "E.kmp", "L":{....},
{"Timestamp": "2017-11-14 14:41:32", "File": "E.kmp", "L":{....},
................................................................,
{"Timestamp": "2017-11-14 14:42:32", "File": "D.kmp", "L":{....},
{"Timestamp": "2017-11-14 14:43:32", "File": "D.kmp", "L":{....}
]

I want to change all the "File" name as "E.kmp". That's why I need to replace "D.kmp" with "E.kmp".If it is possible with python or R, please help me out. Python is preferable.

Body:
Here is one way in R

library(jsonlite)
library(tidyverse)
res <- fromJSON(json_val) %>%
             map(mutate, File = 'E.kmp') %>%
             toJSON

prettify(res, indent=1)
# {
# "A": [
#  {
#   "Timestamp": "2017-11-14 14:39:54",
#   "File": "E.kmp"
#  },
#  {
#   "Timestamp": "2017-11-14 14:49:54",
#   "File": "E.kmp"
#  },
#  {
#   "Timestamp": "2017-11-14 14:59:54",
#   "File": "E.kmp"
#  }
# ]
#}

data

json_val <- '{"A":[{"Timestamp": "2017-11-14 14:39:54", "File": "E.kmp"},
             {"Timestamp": "2017-11-14 14:49:54", "File": "D.kmp"},
             {"Timestamp": "2017-11-14 14:59:54", "File": "D.kmp"}
            ]}'


问:
Recoverable fatal error: Object of class mysqli could not be converted to string
Been banging my head on a wall for a while.  I read through most of the suggested questions too.  I am trying to pass my mysqli connection into the class contructor and set it to a class variable and am getting: Recoverable fatal error: Object of class mysqli could not be converted to string

PHP:

```<code>$con=mysqli_connect("abc", "abc", "abc", "abc");
if (mysqli_connect_errno()) {
    echo "Failed to connect to MariaDB: " . mysqli_connect_error();
}
/* check connection */
if ($con->connect_errno) {
    printf("Connect failed: %s\n", $con->connect_error);
    exit();
}

$t = new Timer($con);
// lots of irrelevant code
unset($t);

class Timer {
    private $time = null;
    private $con;
    public function __construct($con) {
        $this->$con = $con;
        $this->time = time();
        echo 'Working - please wait..<br/>';
    }

    public function __destruct() {
        $basename = basename($_SERVER['PHP_SELF']);
        $query = "SELECT ScriptID FROM scripts WHERE `ScriptURL` = '$basename';";
        $scriptIDResult = mysqli_fetch_assoc(mysqli_query($con, $query)) or die(mysqli_error($con));
        $t->scriptID = $scriptIDResult['ScriptID'];
        $elapsed = (time()-$this->time);
        echo '<br/>Job finished in '.($elapsed).' seconds.';
        $scriptQuery = "UPDATE `scriptruns` SET `ScriptExecutedTime` = '$elapsed', `ScriptRunDate` = NOW() WHERE `ScriptID` = '$scriptID'";
        $result = mysqli_query($con, $scriptQuery) or die(mysqli_error($con));
    }
}
</code>```

Error is being thrown in the construct function on: $this->$con = $con;.

答:
The problem is here:

```<code>$this->$con = $con;
</code>```

It is just a typo but let's see what happens. $this->$con is the property of $this whose name is stored in the $con variable. Looking for  a name, PHP tries to convert $con to a string; $con is an object of class mysqli (that doesn't implement __toString()) and this is why it triggers the "Object of class mysqli could not be converted to string" error message.

Obviously, the code should read:

```<code>$this->con = $con;
</code>```

You will also get errors in __destruct(). The variable $con you use like a mysqli object is not set. It should be $this->con everywhere in the destructor.

Body:
Been banging my head on a wall for a while.  I read through most of the suggested questions too.  I am trying to pass my mysqli connection into the class contructor and set it to a class variable and am getting: Recoverable fatal error: Object of class mysqli could not be converted to string

PHP:

$con=mysqli_connect("abc", "abc", "abc", "abc");
if (mysqli_connect_errno()) {
    echo "Failed to connect to MariaDB: " . mysqli_connect_error();
}
/* check connection */
if ($con->connect_errno) {
    printf("Connect failed: %s\n", $con->connect_error);
    exit();
}

$t = new Timer($con);
// lots of irrelevant code
unset($t);

class Timer {
    private $time = null;
    private $con;
    public function __construct($con) {
        $this->$con = $con;
        $this->time = time();
        echo 'Working - please wait..
';
    }

    public function __destruct() {
        $basename = basename($_SERVER['PHP_SELF']);
        $query = "SELECT ScriptID FROM scripts WHERE `ScriptURL` = '$basename';";
        $scriptIDResult = mysqli_fetch_assoc(mysqli_query($con, $query)) or die(mysqli_error($con));
        $t->scriptID = $scriptIDResult['ScriptID'];
        $elapsed = (time()-$this->time);
        echo '
Job finished in '.($elapsed).' seconds.';
        $scriptQuery = "UPDATE `scriptruns` SET `ScriptExecutedTime` = '$elapsed', `ScriptRunDate` = NOW() WHERE `ScriptID` = '$scriptID'";
        $result = mysqli_query($con, $scriptQuery) or die(mysqli_error($con));
    }
}

Error is being thrown in the construct function on: $this->$con = $con;.

Body:
The problem is here:

$this->$con = $con;

It is just a typo but let's see what happens. $this->$con is the property of $this whose name is stored in the $con variable. Looking for  a name, PHP tries to convert $con to a string; $con is an object of class mysqli (that doesn't implement __toString()) and this is why it triggers the "Object of class mysqli could not be converted to string" error message.

Obviously, the code should read:

$this->con = $con;

You will also get errors in __destruct(). The variable $con you use like a mysqli object is not set. It should be $this->con everywhere in the destructor.