问:
Combining/Merging Boolean properties multiple Objects C#
I have got a ton of Objects, all of the same type. The only contain an int Id Property, the rest of the Properties are Boolean flags, also a ton of them.

Question: How can one combine them and create a new Object with flag[x] = true, where at least one of the objects has flag[x] = true, else flag[x] = false. (Sorry for this bad description, my English is not that good...)

Example (Pseudo-Code):

```<code>lst[0] = {0815, **true**, false, false, false}

lst[1] = {0815, false, false, **true**, false}

lst[2] = {0815, false, false, false, **true**}
</code>```

shall result in

```<code>result = {0815, **true**, false, **true**, **true**}
</code>```

I thought about grouping the Source using LINQ and then iterate through the groups, creating the new object manually.

Is there a better way?

答:
One solution could be to iterate through your collection and check whether a true exists :

```<code>bool hasFirstPropertyTrue = false;
bool hasSecondProprertyTrue = false;
[...]
foreach(item in yourCollection)
{
hasFirstProprertyTrue |= item.FirstProperty;
hasSecondPropertyTrue |= item.SecondProperty;
[...]
}
</code>```

Then hasFirstPropertyTrue, hasSecondPropertyTrue ... will be true if there is at least one true in your properties

Body:
I have got a ton of Objects, all of the same type. The only contain an int Id Property, the rest of the Properties are Boolean flags, also a ton of them.

Question: How can one combine them and create a new Object with flag[x] = true, where at least one of the objects has flag[x] = true, else flag[x] = false. (Sorry for this bad description, my English is not that good...)

Example (Pseudo-Code):

lst[0] = {0815, **true**, false, false, false}

lst[1] = {0815, false, false, **true**, false}

lst[2] = {0815, false, false, false, **true**}

shall result in

result = {0815, **true**, false, **true**, **true**}

I thought about grouping the Source using LINQ and then iterate through the groups, creating the new object manually.

Is there a better way?

Body:
One solution could be to iterate through your collection and check whether a true exists :

bool hasFirstPropertyTrue = false;
bool hasSecondProprertyTrue = false;
[...]
foreach(item in yourCollection)
{
hasFirstProprertyTrue |= item.FirstProperty;
hasSecondPropertyTrue |= item.SecondProperty;
[...]
}

Then hasFirstPropertyTrue, hasSecondPropertyTrue ... will be true if there is at least one true in your properties


来源: stackexchange

问:
how to read terminal input in node.js?
I want to do some local node test before push the code to server.

how can I read terminal input as a input for my js script?
    readline or something

答:
I think there is no need to use third party library, if you just want to get command line params.

You can use process.argv property of process node core object.

just use process.argv & you are good to go.It returns an array in which by default there is 2 element, at 0 index Node execution directory & at 1 index working directory, so cmd line params start from 2nd index.

So in nutshell, you can access cmd line params using process.argv[2] onwards.

ContentLicense: CC BY-SA 3.0

Title: how to read terminal input in node.js?


问:
Symfony Parent Child category relation
I have a Product Category table, where I have stored categories if parent_id is null then assume this is parent category if not null then it has child categories. Now the issue is I can't show parent category name in listing page, so can someone have an idea how to make a relation in Product Category entity?

Symfony version: 3.3

Table Structure:(product_category)

```<code>  id
  parent_id
  slug
  title
</code>```

I have tried this code in ProductCategory entity but it doesn't show any relational data:

```<code>class ProductCategory
{
    /**
    * @ORM\OneToMany(targetEntity="ProductCategory", mappedBy="parent")
    * @ORM\JoinColumn(name="parent_id", referencedColumnName="id", nullable=true)
    */
    private $parent;
</code>```

答:
Using entity with self reference, as Alessandro described, then let's say you have all your records extracted with doctrine using $qb->(bla bla bla)->getResult(); into a variable called $categories. Then you just have to iterate through it like that:

```<code>foreach($categories as $category) {
   echo $category->getTitle() . ' has parent ' . ($category->getParent() ? $category->getParent()->getTitle() : 'none');
}
</code>```

To understand more about array collection, read: http://www.doctrine-project.org/api/common/2.3/class-Doctrine.Common.Collections.ArrayCollection.html

Title: Symfony Parent Child category relation

Body:
I have a Product Category table, where I have stored categories if parent_id is null then assume this is parent category if not null then it has child categories. Now the issue is I can't show parent category name in listing page, so can someone have an idea how to make a relation in Product Category entity?

Symfony version: 3.3

Table Structure:(product_category)

  id
  parent_id
  slug
  title

I have tried this code in ProductCategory entity but it doesn't show any relational data:

class ProductCategory
{
    /**
    * @ORM\OneToMany(targetEntity="ProductCategory", mappedBy="parent")
    * @ORM\JoinColumn(name="parent_id", referencedColumnName="id", nullable=true)
    */
    private $parent;

Body:
Using entity with self reference, as Alessandro described, then let's say you have all your records extracted with doctrine using $qb->(bla bla bla)->getResult(); into a variable called $categories. Then you just have to iterate through it like that:

foreach($categories as $category) {
   echo $category->getTitle() . ' has parent ' . ($category->getParent() ? $category->getParent()->getTitle() : 'none');
}

To understand more about array collection, read: http://www.doctrine-project.org/api/common/2.3/class-Doctrine.Common.Collections.ArrayCollection.html


问:
Kotlin unexpected `unresolved reference`
I'm a beginner to Kotlin, and here's my code:

```<code>class C(val boy: Int = 0) {
    fun <T, E> boy(i: Int) = i
}

fun girl(b1: Boolean, b2: Boolean) = println("boy($b1, $b2)")

fun main(args: Array<String>): Unit {
    val A = 234 // see? A defined!
    val B = 345 // see? B defined!
    val c = C(123) // c is also defined!

    girl(c.boy < A, B > A) // hey look at here
}
</code>```

IntelliJ IDEA gives me:

unresolved reference: A

unresolved reference: B

unresolved reference: c

At the line hey look at here.

I think my code is syntactically correct, what's wrong?

答:
Well.. I solved these errors by adding a pair of braces:

```<code>fun main(args: Array<String>): Unit {
    val A = 234
    val B = 345
    val c = C(123)

    girl((c.boy < A), B > A) // hey look at here
}
</code>```

But I still wonder why my code above doesn't work

Edit: see the other answer

Body:
I'm a beginner to Kotlin, and here's my code:

class C(val boy: Int = 0) {
    fun <T, E> boy(i: Int) = i
}

fun girl(b1: Boolean, b2: Boolean) = println("boy($b1, $b2)")

fun main(args: Array<String>): Unit {
    val A = 234 // see? A defined!
    val B = 345 // see? B defined!
    val c = C(123) // c is also defined!

    girl(c.boy  A) // hey look at here
}

IntelliJ IDEA gives me:

unresolved reference: A

unresolved reference: B

unresolved reference: c

At the line hey look at here.

I think my code is syntactically correct, what's wrong?

Body:
Well.. I solved these errors by adding a pair of braces:

fun main(args: Array<String>): Unit {
    val A = 234
    val B = 345
    val c = C(123)

    girl((c.boy < A), B > A) // hey look at here
}

But I still wonder why my code above doesn't work

Edit: see the other answer


问:
Django - backend logic vs database logic
I wonder if a good habit is to have some logic in MySQL database (triggers etc.) instead of logic in Django backend. I'm aware of fact that some functionalities may be done both in backend and in database but I would like to do it in accordance with good practices. I'm not sure I should do some things manually or maybe whole database should be generated by Django (is it possible)? What are the best rules to do it as well as possible? I would like to know the opinion of experienced people.</p>

答:
It is true that if you used a database for your business logic you could get maximum possible performance and security optimizations. However, you would also risk many things such as

No separation of concerns

Being bound to the database vendor

etc.

Also, whatever logic you write in your database won't be version controlled with your app. Thus, whenever you change your database, you will have to create all those things once again.

Instead, use Django ORM. It will create and manage your database based on your models by itself. As a result, whenever you recreate your database, you will just have to run migrations with one single command and you are done.

This will cover most of the situations. And whenever you will need those speeds of stored procedures, Django ORM has you covered as well.

In short, I believe that business logic should be kept out of the database as much as possible.


问:
Sort ObservableCollection<string> through C#
I have below ObservableCollection<string>. I need to sort this alphabetically.

```<code>private ObservableCollection<string> _animals = new ObservableCollection<string>
{
    "Cat", "Dog", "Bear", "Lion", "Mouse",
    "Horse", "Rat", "Elephant", "Kangaroo", "Lizard",
    "Snake", "Frog", "Fish", "Butterfly", "Human",
    "Cow", "Bumble Bee"
};
</code>```

I tried _animals.OrderByDescending. But I don't know how to use it correctly.

```<code>_animals.OrderByDescending(a => a.<what_is_here_?>);
</code>```

How can I do this?

答:
```<code>myObservableCollection.ToList().Sort((x, y) => x.Property.CompareTo(y.Property));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have below ObservableCollection<string>. I need to sort this alphabetically.

private ObservableCollection<string> _animals = new ObservableCollection<string>
{
    "Cat", "Dog", "Bear", "Lion", "Mouse",
    "Horse", "Rat", "Elephant", "Kangaroo", "Lizard",
    "Snake", "Frog", "Fish", "Butterfly", "Human",
    "Cow", "Bumble Bee"
};

I tried _animals.OrderByDescending. But I don't know how to use it correctly.

_animals.OrderByDescending(a => a.<what_is_here_?>);

How can I do this?


问:
Retrieve part of json file from an external website (sparkfun)
This question might be quite specific to sparkfun, but I still wish to make it as a general question due to my limited experience in javascript.

I have been using the follow html and javascript (d3.js) file to load json data from sparkfun data server:

index.html

```<code><!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>

var data_sensor;
var url =   "https://data.sparkfun.com/output/w5nEnw974mswgrx0ALOE.json"
d3.json(url,  function (error,json) {
    if (error) throw error;
    data_sensor=json;
    console.log(data_sensor)
})
</script>

</body>
</code>```

After running the script, i will end up with all data array stored in variable data_sensor for post-analyse.

What i wish to do now is to create a dash board that downloads and stores only the latest value. i understand that i could just use the first value in the data_sensor to do so (i.e., data_sensor[0]) but such method becomes quite inefficient with the growth of data.

Thanks!

答:
When I've wanted to load JSON from somewhere I've always used jQuery:

Import jQuery like this:

```<code><script src="jquery-3.2.1.min.js"></script>
</code>```

Then you can do something like this to get your JSON file:

```<code>var data_sensor;
var url = "https://data.sparkfun.com/output/w5nEnw974mswgrx0ALOE.json"
$.getJSON(url, function(data) {
  data_sensor = data;
  console.log(data_sensor)
});
</code>```

Hope that helps!

Body:
This question might be quite specific to sparkfun, but I still wish to make it as a general question due to my limited experience in javascript.

I have been using the follow html and javascript (d3.js) file to load json data from sparkfun data server:

index.html

<!DOCTYPE html>
<meta charset="utf-8">

After running the script, i will end up with all data array stored in variable data_sensor for post-analyse.

What i wish to do now is to create a dash board that downloads and stores only the latest value. i understand that i could just use the first value in the data_sensor to do so (i.e., data_sensor[0]) but such method becomes quite inefficient with the growth of data.

Thanks!

Body:
When I've wanted to load JSON from somewhere I've always used jQuery:

Import jQuery like this:

<script src="jquery-3.2.1.min.js"></script>

Then you can do something like this to get your JSON file:

var data_sensor;
var url = "https://data.sparkfun.com/output/w5nEnw974mswgrx0ALOE.json"
$.getJSON(url, function(data) {
  data_sensor = data;
  console.log(data_sensor)
});

Hope that helps!


问:
Methods vs Computed in Vue
What is the main difference between a method and a computed value in Vue.js?

They seem the same and interchangeable to me.

答:
From the docs

..computed properties are cached based on their dependencies. A computed property will only re-evaluate when some of its dependencies have changed.

If you want data to be cached use Computed properties on the other hand if you don't want data to be cached use simple Method properties.

Title: Methods vs Computed in Vue


问:
Ruby XML : Give existing XML unique nodes to read
Here's my problem.  I am calling a service that is returning several identical nodes which contain different values.  I need to get the GUID values from these nodes and store them as a variable in my script to use later.

Example of the XML I write from the service:

```<code><ShippingMethod>
    <Description>Description Goes Here</Description>
    <HandlingCharge>16.98</HandlingCharge>
    <ShippingMethodId>GUID</ShippingMethodId>
    <ShippingMethodName>Express Overnight</ShippingMethodName>
  </ShippingMethod>
<ShippingMethod>
    <Description>Description2 Goes Here</Description>
    <HandlingCharge>19.98</HandlingCharge>
    <ShippingMethodId>GUID2</ShippingMethodId>
    <ShippingMethodName>More Express Overnight</ShippingMethodName>
  </ShippingMethod>
</code>```

I have several of these per request and they are dynamic.  I don't want to chop this up using regex based on the values I currently have.  That's hacky and will bite me later.  The only thing I'm interested in at this point is reading this XML and pulling back all the  values per request and putting them into an array which I can map in my code.  My question is this, if you had this chunk of XML and you needed to get GUID and GUID2 to be stored as variables in a Ruby script what would you suggest using to parse it and do you have an example of reading it in and stripping the value?

ROXML, REXML, Nokogiri, Regex???

I appreciate  your help!

~Regards Uninspired

答:
Here's some ways I'd do it:</p>

```<code>require 'nokogiri'

xml = '<xml><ShippingMethod>
    <Description>Description Goes Here</Description>
    <HandlingCharge>16.98</HandlingCharge>
    <ShippingMethodId>GUID</ShippingMethodId>
    <ShippingMethodName>Express Overnight</ShippingMethodName>
</ShippingMethod>
<ShippingMethod>
    <Description>Description2 Goes Here</Description>
    <HandlingCharge>19.98</HandlingCharge>
    <ShippingMethodId>GUID2</ShippingMethodId>
    <ShippingMethodName>More Express Overnight</ShippingMethodName>
</ShippingMethod></xml>
'
doc = Nokogiri::XML(xml)
doc.css('ShippingMethodId').inject([]){ |m,a| m << a.text } # => ["GUID", "GUID2"]
(doc / '//ShippingMethodId').map{ |n| n.text }              # => ["GUID", "GUID2"]
doc.search('//ShippingMethodId').map(&:text)                # => ["GUID", "GUID2"]
doc.search('//ShippingMethodId/text()').map{ |n| n.text }   # => ["GUID", "GUID2"]
doc.search('//ShippingMethodId/text()').map(&:to_s)         # => ["GUID", "GUID2"]
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Here's my problem.  I am calling a service that is returning several identical nodes which contain different values.  I need to get the GUID values from these nodes and store them as a variable in my script to use later.

Example of the XML I write from the service:

<ShippingMethod>
    <Description>Description Goes Here</Description>
    <HandlingCharge>16.98</HandlingCharge>
    <ShippingMethodId>GUID</ShippingMethodId>
    <ShippingMethodName>Express Overnight</ShippingMethodName>
  </ShippingMethod>
<ShippingMethod>
    <Description>Description2 Goes Here</Description>
    <HandlingCharge>19.98</HandlingCharge>
    <ShippingMethodId>GUID2</ShippingMethodId>
    <ShippingMethodName>More Express Overnight</ShippingMethodName>
  </ShippingMethod>

I have several of these per request and they are dynamic.  I don't want to chop this up using regex based on the values I currently have.  That's hacky and will bite me later.  The only thing I'm interested in at this point is reading this XML and pulling back all the  values per request and putting them into an array which I can map in my code.  My question is this, if you had this chunk of XML and you needed to get GUID and GUID2 to be stored as variables in a Ruby script what would you suggest using to parse it and do you have an example of reading it in and stripping the value?

ROXML, REXML, Nokogiri, Regex???

I appreciate  your help!

~Regards Uninspired

Body:
Here's some ways I'd do it:

require 'nokogiri'

xml = '<xml><ShippingMethod>
    <Description>Description Goes Here</Description>
    <HandlingCharge>16.98</HandlingCharge>
    <ShippingMethodId>GUID</ShippingMethodId>
    <ShippingMethodName>Express Overnight</ShippingMethodName>
</ShippingMethod>
<ShippingMethod>
    <Description>Description2 Goes Here</Description>
    <HandlingCharge>19.98</HandlingCharge>
    <ShippingMethodId>GUID2</ShippingMethodId>
    <ShippingMethodName>More Express Overnight</ShippingMethodName>
</ShippingMethod></xml>
'
doc = Nokogiri::XML(xml)
doc.css('ShippingMethodId').inject([]){ |m,a| m << a.text } # => ["GUID", "GUID2"]
(doc / '//ShippingMethodId').map{ |n| n.text }              # => ["GUID", "GUID2"]
doc.search('//ShippingMethodId').map(&:text)                # => ["GUID", "GUID2"]
doc.search('//ShippingMethodId/text()').map{ |n| n.text }   # => ["GUID", "GUID2"]
doc.search('//ShippingMethodId/text()').map(&:to_s)         # => ["GUID", "GUID2"]


问:
Java - TimeZone conversion issue with SQL timestamp
I am using MySQL database on the Server. My Web application Server is in US/Chicago but I want my DateTime values to be saved in Africa/Lagos time.

I got part of this code here from Stack Overflow but when I update a record it still shows Chicago time in the database record.
Please what am I doing wrong here?

```<code>public static boolean saveImageFileName(int id, String fileName) throws SQLException, IOException, IllegalArgumentException, ClassNotFoundException
{
    try(Connection conn = Config.getDatabaseConnection())
    {
        //Create a timezone object based on Africa/Lagos time zone
        SimpleTimeZone timeZone = new SimpleTimeZone(1, "Africa/Lagos");
        //Create a calendar object using the timezone object
        GregorianCalendar calendar = new GregorianCalendar(timeZone);
        //Create a timestamp object using the calendar's date and time
        Timestamp timestamp = new Timestamp(calendar.getTime().getTime());
        //Create an SQL query String
        String sql = "UPDATE `requests` SET `filename` = ?, `uploaded_date` = ? WHERE `id` = ?";
        //Create a prepared statement object from database connection
        PreparedStatement pst = conn.prepareStatement(sql);
        //Set prepared statement parameters
        pst.setString(1, fileName);
        pst.setTimestamp(2, timestamp, calendar); //Set TimeStamp and Calendar
        pst.setInt(3, id);
        //Update the record
        int update = pst.executeUpdate();
        //return update result
        return update == 1;
    }
}
</code>```

答:
You need to pass Calendar object with TimeZone in setTimeZone method, as mentioned in this javadoc, try this:

```<code>pst.setTimestamp(2, timestamp, Calendar.getInstance(TimeZone.getTimeZone("Africa/Lagos")));
</code>```

Body:
I am using MySQL database on the Server. My Web application Server is in US/Chicago but I want my DateTime values to be saved in Africa/Lagos time.

I got part of this code here from Stack Overflow but when I update a record it still shows Chicago time in the database record.
Please what am I doing wrong here?

public static boolean saveImageFileName(int id, String fileName) throws SQLException, IOException, IllegalArgumentException, ClassNotFoundException
{
    try(Connection conn = Config.getDatabaseConnection())
    {
        //Create a timezone object based on Africa/Lagos time zone
        SimpleTimeZone timeZone = new SimpleTimeZone(1, "Africa/Lagos");
        //Create a calendar object using the timezone object
        GregorianCalendar calendar = new GregorianCalendar(timeZone);
        //Create a timestamp object using the calendar's date and time
        Timestamp timestamp = new Timestamp(calendar.getTime().getTime());
        //Create an SQL query String
        String sql = "UPDATE `requests` SET `filename` = ?, `uploaded_date` = ? WHERE `id` = ?";
        //Create a prepared statement object from database connection
        PreparedStatement pst = conn.prepareStatement(sql);
        //Set prepared statement parameters
        pst.setString(1, fileName);
        pst.setTimestamp(2, timestamp, calendar); //Set TimeStamp and Calendar
        pst.setInt(3, id);
        //Update the record
        int update = pst.executeUpdate();
        //return update result
        return update == 1;
    }
}

Body:
You need to pass Calendar object with TimeZone in setTimeZone method, as mentioned in this javadoc, try this:

pst.setTimestamp(2, timestamp, Calendar.getInstance(TimeZone.getTimeZone("Africa/Lagos")));


答:
Not an expert here, but their docs state tat you can use paging to get the first 250kb of data:

```<code>var url = "https://data.sparkfun.com/output/w5nEnw974mswgrx0ALOE.json?page=1";
</code>```

You can get your first object/set of data, and I'm afraid there's no general way to take only part of any API response - request is request, it could send you every possible data depending on architecture, from "OK" string to 200MB of data. Carefully reading docs is your best bet.

Title: Retrieve part of json file from an external website (sparkfun)

Body:
Not an expert here, but their docs state tat you can use paging to get the first 250kb of data:

var url = "https://data.sparkfun.com/output/w5nEnw974mswgrx0ALOE.json?page=1";

You can get your first object/set of data, and I'm afraid there's no general way to take only part of any API response - request is request, it could send you every possible data depending on architecture, from "OK" string to 200MB of data. Carefully reading docs is your best bet.


问:
Using same component for similar routes - refresh issues
I have two routes (react-router v4):

```<code><Route exact path='/' component={HomePage}/>
<Route exact path='/tag/:tag' component={HomePage}/>
</code>```

where the top route shows a list of places and the second route shows a list of places that contain a specific tag. I wanted to set things up like this to reuse the HomePage component.

However, if I'm viewing places with a tag and then click on a link <Link to="/">Homepage</Link> then it doesn't reload all places (Axios/Redux) because (I assume) the Homepage component is already in use.

Should I force a reload in some way, make a second component that's very similar to HomePage and duplicate code or is there an even better way?

答:
You can use the lifecycle method componentWillReceiveProps(nextProps){}.
Inside this method you will get the path inside this.props and after getting path you can write your logic to modify the component on the basis of route received.</p>

Body:
I have two routes (react-router v4):

<Route exact path='/' component={HomePage}/>
<Route exact path='/tag/:tag' component={HomePage}/>

where the top route shows a list of places and the second route shows a list of places that contain a specific tag. I wanted to set things up like this to reuse the HomePage component.

However, if I'm viewing places with a tag and then click on a link <Link to="/">Homepage</Link> then it doesn't reload all places (Axios/Redux) because (I assume) the Homepage component is already in use.

Should I force a reload in some way, make a second component that's very similar to HomePage and duplicate code or is there an even better way?


问:
C# Coding a Tie in Tic Tac Toe
I've developed a game of tic tac toe in C# and set a function for the win conditions, but I can't seem to figure out how to set the condition for a tie when the grid is full. When I tried to input, the tie would occur randomly. I wonder if it's how I set the or and and operators.Here's what I tried. </p>

```<code>public bool Ended()
{
    if (grid[0, 0] == 'X' && grid[0, 1] == 'X' && grid[0, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[1, 0] == 'X' && grid[1, 1] == 'X' && grid[1, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[2, 0] == 'X' && grid[2, 1] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'X' && grid[1, 0] == 'X' && grid[2, 0] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 1] == 'X' && grid[1, 1] == 'X' && grid[2, 1] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 2] == 'X' && grid[1, 2] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'X' && grid[1, 1] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 2] == 'X' && grid[1, 1] == 'X' && grid[2, 0] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[0, 1] == 'O' && grid[0, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[1, 0] == 'O' && grid[1, 1] == 'O' && grid[1, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[2, 0] == 'O' && grid[2, 1] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[1, 0] == 'O' && grid[2, 0] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 1] == 'O' && grid[1, 1] == 'O' && grid[2, 1] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 2] == 'O' && grid[1, 2] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[1, 1] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 2] == 'O' && grid[1, 1] == 'O' && grid[2, 0] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    else if (grid[0, 0] == 'X' || grid[0, 0] == 'O' &&
        grid[0, 1] == 'X' || grid[0, 1] == 'O' &&
        grid[0, 2] == 'X' || grid[0, 2] == 'O' &&
        grid[1, 0] == 'X' || grid[1, 0] == 'O' &&
        grid[1, 1] == 'X' || grid[1, 1] == 'O' &&
        grid[1, 2] == 'X' || grid[1, 2] == 'O' &&
        grid[2, 0] == 'X' || grid[2, 0] == 'O' &&
        grid[2, 1] == 'X' || grid[2, 1] == 'O' &&
        grid[2, 2] == 'X' || grid[2, 2] == 'O')
    { Console.WriteLine("It's a Tie"); return true; }
    return false;
}
</code>```

Title: C# Coding a Tie in Tic Tac Toe

Body:
I've developed a game of tic tac toe in C# and set a function for the win conditions, but I can't seem to figure out how to set the condition for a tie when the grid is full. When I tried to input, the tie would occur randomly. I wonder if it's how I set the or and and operators.Here's what I tried.

public bool Ended()
{
    if (grid[0, 0] == 'X' && grid[0, 1] == 'X' && grid[0, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[1, 0] == 'X' && grid[1, 1] == 'X' && grid[1, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[2, 0] == 'X' && grid[2, 1] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'X' && grid[1, 0] == 'X' && grid[2, 0] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 1] == 'X' && grid[1, 1] == 'X' && grid[2, 1] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 2] == 'X' && grid[1, 2] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'X' && grid[1, 1] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 2] == 'X' && grid[1, 1] == 'X' && grid[2, 0] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[0, 1] == 'O' && grid[0, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[1, 0] == 'O' && grid[1, 1] == 'O' && grid[1, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[2, 0] == 'O' && grid[2, 1] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[1, 0] == 'O' && grid[2, 0] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 1] == 'O' && grid[1, 1] == 'O' && grid[2, 1] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 2] == 'O' && grid[1, 2] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[1, 1] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 2] == 'O' && grid[1, 1] == 'O' && grid[2, 0] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    else if (grid[0, 0] == 'X' || grid[0, 0] == 'O' &&
        grid[0, 1] == 'X' || grid[0, 1] == 'O' &&
        grid[0, 2] == 'X' || grid[0, 2] == 'O' &&
        grid[1, 0] == 'X' || grid[1, 0] == 'O' &&
        grid[1, 1] == 'X' || grid[1, 1] == 'O' &&
        grid[1, 2] == 'X' || grid[1, 2] == 'O' &&
        grid[2, 0] == 'X' || grid[2, 0] == 'O' &&
        grid[2, 1] == 'X' || grid[2, 1] == 'O' &&
        grid[2, 2] == 'X' || grid[2, 2] == 'O')
    { Console.WriteLine("It's a Tie"); return true; }
    return false;
}

Body:
|| operator has lower priority than &&. put or conditions in brackets:

if ((grid[0, 0] == 'X' || grid[0, 0] == 'O') &&
    (grid[0, 1] == 'X' || grid[0, 1] == 'O') &&
    (grid[0, 2] == 'X' || grid[0, 2] == 'O') &&
    (grid[1, 0] == 'X' || grid[1, 0] == 'O') &&
    (grid[1, 1] == 'X' || grid[1, 1] == 'O') &&
    (grid[1, 2] == 'X' || grid[1, 2] == 'O') &&
    (grid[2, 0] == 'X' || grid[2, 0] == 'O') &&
    (grid[2, 1] == 'X' || grid[2, 1] == 'O') &&
    (grid[2, 2] == 'X' || grid[2, 2] == 'O'))
{
    Console.WriteLine("It's a Tie");
    return true;
}


问:
Parallel processing in golang
Given the following code:

```<code>package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    for i := 0; i < 3; i++ {
        go f(i)
    }

    // prevent main from exiting immediately
    var input string
    fmt.Scanln(&input)
}

func f(n int) {
    for i := 0; i < 10; i++ {
        dowork(n, i)
        amt := time.Duration(rand.Intn(250))
        time.Sleep(time.Millisecond * amt)
    }
}

func dowork(goroutine, loopindex int) {
    // simulate work
    time.Sleep(time.Second * time.Duration(5))
    fmt.Printf("gr[%d]: i=%d\n", goroutine, loopindex)
}
</code>```

Can i assume that the 'dowork' function will be executed in parallel?

Is this a correct way of achieving parallelism or is it better to use channels and separate 'dowork' workers for each goroutine?

答:
f() will be executed concurrently but many dowork() will be executed sequentially within each f(). Waiting on stdin is also not the right way to ensure that your routines finished execution. You must spin up a channel that each f() pushes a true on when the f() finishes.
At the end of the main() you must wait for n number of true's on the channel. n being the number of f() that you have spun up.

Title: Parallel processing in golang

Body:
Given the following code:

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    for i := 0; i < 3; i++ {
        go f(i)
    }

    // prevent main from exiting immediately
    var input string
    fmt.Scanln(&input)
}

func f(n int) {
    for i := 0; i < 10; i++ {
        dowork(n, i)
        amt := time.Duration(rand.Intn(250))
        time.Sleep(time.Millisecond * amt)
    }
}

func dowork(goroutine, loopindex int) {
    // simulate work
    time.Sleep(time.Second * time.Duration(5))
    fmt.Printf("gr[%d]: i=%d\n", goroutine, loopindex)
}

Can i assume that the 'dowork' function will be executed in parallel?

Is this a correct way of achieving parallelism or is it better to use channels and separate 'dowork' workers for each goroutine?


问:
Binding to changes on global variable in electron
For an electron-app I use a global variable to store some constantly changing values in my administration panel (mainly status information received from various clients).

So in my main process I collect this data and write it to a variable

```<code>global.sharedObject = {
    Clients:[]
}
//on receiving information via ipc
global.sharedObject.Clients.push(data);
</code>```

this works flawless, and gives me a array of Objects with my client status data. For example [{"id":"abe289c8-71ae-4764-87d8-1eb7b8adde7f","IP":"192.168.0.2","type":"Client Type 1","MachineName":"HP4711"}]

In my renderer process there is a page where this data is displayed live via ractive:

```<code>const remote = require('electron').remote;
let ClientList = remote.getGlobal('sharedObject').Clients;
let ractive = new Ractive({
    el: '#clientBoxes',
    template: myTemplate,
    twoway: false,
    //magic: true,
    data: {
        Clients: ClientList //or with same result:
        Clients: remote.getGlobal('sharedObject').Clients;
    });
</code>```

The data is rendered correct, but only updates if I reload the page. If I use magic: trueI get a error TypeError: Cannot redefine property: id
    at Function.defineProperty (<anonymous>)
    at ...\ractive\ractive.js:10637:11

Has anyone got an idea, or knows a better way to store rapidly changing values globally in electron?

答:
Documentation for remote says:

Note: Arrays and Buffers are copied over IPC when accessed via the remote module. Modifying them in the renderer process does not modify them in the main process and vice versa.

This means that when you call remote.getGlobal('sharedObject') you just get the state of shareObject at that moment in time. Your view doesn't update because the array simply didn't change on the renderer side.

You could just send a message via win.webContents.send every time shareObject gets updated. In the renderer you listen for those messages and then just update the reactive component.

Body:
For an electron-app I use a global variable to store some constantly changing values in my administration panel (mainly status information received from various clients).

So in my main process I collect this data and write it to a variable

global.sharedObject = {
    Clients:[]
}
//on receiving information via ipc
global.sharedObject.Clients.push(data);

this works flawless, and gives me a array of Objects with my client status data. For example [{"id":"abe289c8-71ae-4764-87d8-1eb7b8adde7f","IP":"192.168.0.2","type":"Client Type 1","MachineName":"HP4711"}]

In my renderer process there is a page where this data is displayed live via ractive:

const remote = require('electron').remote;
let ClientList = remote.getGlobal('sharedObject').Clients;
let ractive = new Ractive({
    el: '#clientBoxes',
    template: myTemplate,
    twoway: false,
    //magic: true,
    data: {
        Clients: ClientList //or with same result:
        Clients: remote.getGlobal('sharedObject').Clients;
    });

The data is rendered correct, but only updates if I reload the page. If I use magic: trueI get a error TypeError: Cannot redefine property: id
    at Function.defineProperty (<anonymous>)
    at ...\ractive\ractive.js:10637:11

Has anyone got an idea, or knows a better way to store rapidly changing values globally in electron?


问:
How to add a menu with submenues in Wordpress
I'm trying to add a menu with submenues in Wordpress, but so far my attempts don't seem to work:

```<code>add_filter( 'wp_nav_menu_items', 'practice_areas', 11, 3 );

function practice_areas( $items, $args ) {
    $items .= '<ul><a href="'. addslashes("#") . '">Practice Areas</a>';
    $items .= '<li><a href="'. addslashes("#") . '">Practice Areas</a></li>';
    $items .= '</ul>';
    return $items;
}
</code>```

How can I go about adding a menue with submenues?

Thank you all in advance.

答:
You should do the code this way to find it working.</p>

```<code>add_filter( 'wp_nav_menu_items', 'practice_areas', 11, 3 );

function practice_areas( $items, $args ) {
    $items .= '<li id="menu-item-25" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-25"><a href="http://test-main-menu">Test main menu</a>
<ul>
<li><a href="#test-submenu">Test submenu</a></li>
</ul>
</li>';
    return $items;
}
</code>```

Body:
I'm trying to add a menu with submenues in Wordpress, but so far my attempts don't seem to work:

add_filter( 'wp_nav_menu_items', 'practice_areas', 11, 3 );

function practice_areas( $items, $args ) {
    $items .= '
Practice Areas';
    $items .= '
Practice Areas
';
    $items .= '
';
    return $items;
}

How can I go about adding a menue with submenues?

Thank you all in advance.

Body:
You should do the code this way to find it working.

add_filter( 'wp_nav_menu_items', 'practice_areas', 11, 3 );

function practice_areas( $items, $args ) {
    $items .= '<li id="menu-item-25" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-25"><a href="http://test-main-menu">Test main menu</a>
<ul>
<li><a href="#test-submenu">Test submenu</a></li>
</ul>
</li>';
    return $items;
}


问:
Javafx: Reusable collections using FXML
I'd like to bind a single collection to multiple ChoiceBox's in FXML.
However the only way I know how is using:

<ChoiceBox fx:id="cb00" prefWidth="150.0" GridPane.rowIndex="0" GridPane.columnIndex="0">
    <items>
        <FXCollections fx:id="test" fx:factory="observableArrayList">
            <String fx:value="1" />
            <String fx:value="2" />
            <String fx:value="3" />
            <String fx:value="4" />
            <String fx:value="5" />
            <String fx:value="6" />
            <String fx:value="7" />
            <String fx:value="8" />
            <String fx:value="9" />
        </FXCollections>
    </items>
</ChoiceBox>
```

Is it possible to declare the collection in the controller and refer to it in FXML instead of copying the collection for each ChoiceBox?

答:
You can define the items in the controller:

```<code>public class Controller {

    private ListProperty<String> choiceBoxItems = new SimpleListProperty(FXCollections.observableArrayList());

    public Controller() {
        IntStream.range(1,10).mapToObj(i -> Integer.toString(i))
            .forEach(choiceBoxItems::add);
    }

    public ListProperty<String> choiceBoxItemsProperty() {
        return choiceBoxItems ;
    }

    public ObservableList<String> getChoiceBoxItems() {
        return choiceBoxItemsProperty().get() ;
    }

    public void setComboBoxItems(ObservableList<String> choiceBoxItems) {
        choiceBoxItemsProperty().set(choiceBoxItems) ;
    }

    // ...
}
</code>```

and then (this is not tested, but I think it will work):

<ChoiceBox fx:id="cb00" items="${controller.choiceBoxItems}" prefWidth="150.0" GridPane.rowIndex="0" GridPane.columnIndex="0">
```

<p>See expression binding in the FXML documentation. (It's not actually documented that the controller is available in the FXML namespace with key <code>controller</code>, but I think it is safe to use this.)</p>

<p>You can also just define the list in the FXML using <code>fx:define</code>:</p>

<pre class="lang-xml prettyprint-override"><code><fx:define>

    <FXCollections fx:id="choiceBoxItems" fx:factory="observableArrayList">
        <String fx:value="1"/>
        <String fx:value="2"/>
        <String fx:value="3"/>
        <!-- ... -->
    </FXCollections>

</fx:define>
</code>```

and then refer to it in each choice box:

<ChoiceBox fx:id="cb00" items="${choiceBoxItems}" prefWidth="150.0" GridPane.rowIndex="0" GridPane.columnIndex="0">
```

Title: Javafx: Reusable collections using FXML

Body:
I'd like to bind a single collection to multiple ChoiceBox's in FXML.
However the only way I know how is using:

<ChoiceBox fx:id="cb00" prefWidth="150.0" GridPane.rowIndex="0" GridPane.columnIndex="0">
    <items>
        <FXCollections fx:id="test" fx:factory="observableArrayList">
            <String fx:value="1" />
            <String fx:value="2" />
            <String fx:value="3" />
            <String fx:value="4" />
            <String fx:value="5" />
            <String fx:value="6" />
            <String fx:value="7" />
            <String fx:value="8" />
            <String fx:value="9" />
        </FXCollections>
    </items>
</ChoiceBox>

Is it possible to declare the collection in the controller and refer to it in FXML instead of copying the collection for each ChoiceBox?

Body:
You can define the items in the controller:

public class Controller {

    private ListProperty<String> choiceBoxItems = new SimpleListProperty(FXCollections.observableArrayList());

    public Controller() {
        IntStream.range(1,10).mapToObj(i -> Integer.toString(i))
            .forEach(choiceBoxItems::add);
    }

    public ListProperty<String> choiceBoxItemsProperty() {
        return choiceBoxItems ;
    }

    public ObservableList<String> getChoiceBoxItems() {
        return choiceBoxItemsProperty().get() ;
    }

    public void setComboBoxItems(ObservableList<String> choiceBoxItems) {
        choiceBoxItemsProperty().set(choiceBoxItems) ;
    }

    // ...
}

and then (this is not tested, but I think it will work):

<ChoiceBox fx:id="cb00" items="${controller.choiceBoxItems}" prefWidth="150.0" GridPane.rowIndex="0" GridPane.columnIndex="0">

See expression binding in the FXML documentation. (It's not actually documented that the controller is available in the FXML namespace with key controller, but I think it is safe to use this.)

You can also just define the list in the FXML using fx:define:

<fx:define>

    <FXCollections fx:id="choiceBoxItems" fx:factory="observableArrayList">
        <String fx:value="1"/>
        <String fx:value="2"/>
        <String fx:value="3"/>
        <!-- ... -->
    </FXCollections>

</fx:define>

and then refer to it in each choice box:

<ChoiceBox fx:id="cb00" items="${choiceBoxItems}" prefWidth="150.0" GridPane.rowIndex="0" GridPane.columnIndex="0">


问:
bash execute commands as different user with su
I have the most simple issue and I am so not certain what I am doing wrong.

I have a simple shell script using /bin/sh

inside the script I have the following:

```<code>exec_as_wwwdata() {
 if [ $(whoami) = ${WWW_USER} ]]; then
    $@
  else
    su -s /bin/sh -c '$@' ${WWW_USER}
  fi
}
</code>```

I am calling it with

```<code>exec_as_wwwdata composer config -g github-oauth.github.com $COMPOSER_GITHUB_TOKEN
</code>```

it just does nothing, no error message nothing.
If I call the following directly inside the script

```<code>su -s /bin/sh -c 'composer config -g github-oauth.github.com $COMPOSER_GITHUB_TOKEN' ${WWW_USER}
</code>```

it works.

What am I doing wrong here?

Based on feedback I have changed it to this

```<code>exec_as_wwwdata() {
 if [ $(whoami) = ${WWW_USER} ]]; then
    $@
  else
    su -s /bin/sh -c '"$@"' "$WWW_USER" _ "$@"
  fi
}
</code>```

Although when I am calling it with the following arguments

```<code>exec_as_wwwdata /usr/local/bin/php /usr/local/bin/composer create-project --repository-url=xxxx .
</code>```

I receive the following error message

```<code>su: unrecognized option '--repository-url=
</code>```

I think there is issue with -- in the string. How can I escape that ?

答:
There are two overlapping uses of $@ here, and you've inadvertently stumbled on a partial correct solution. -c expects a single word, while "$@" would produce multiple distinct words. The correct solution would be

```<code>su -s /bin/sh -c '"$@"' "$WWW_USER" _ "$@"
</code>```

The short version: you don't want to build a command string from the current parameters; you want to pass them as arguments to a hard-coded command string to let the new shell expand things appropriately.

A breakdown:

-s /bin/sh - use /bin/sh instead of the appropriate users's login shell

-c '"$@"' run the command "$@", as desired. Note this is a hard-coded value; the new shell will expand its positional parameters correctly once it has started.

"$WWW_USER" - specify the user to run the shell as

_ - specify the value of $0 in the shell being run. You probably don't care what this value is; you just need some placeholder to prevent your first real argument from being treated as the value for $0.

"$@" pass the current positional parameters as arguments to the new shell, which will expand its "$@" to these values.

Body:
I have the most simple issue and I am so not certain what I am doing wrong.

I have a simple shell script using /bin/sh

inside the script I have the following:

exec_as_wwwdata() {
 if [ $(whoami) = ${WWW_USER} ]]; then
    $@
  else
    su -s /bin/sh -c '$@' ${WWW_USER}
  fi
}

I am calling it with

exec_as_wwwdata composer config -g github-oauth.github.com $COMPOSER_GITHUB_TOKEN

it just does nothing, no error message nothing.
If I call the following directly inside the script

su -s /bin/sh -c 'composer config -g github-oauth.github.com $COMPOSER_GITHUB_TOKEN' ${WWW_USER}

it works.

What am I doing wrong here?

Based on feedback I have changed it to this

exec_as_wwwdata() {
 if [ $(whoami) = ${WWW_USER} ]]; then
    $@
  else
    su -s /bin/sh -c '"$@"' "$WWW_USER" _ "$@"
  fi
}

Although when I am calling it with the following arguments

exec_as_wwwdata /usr/local/bin/php /usr/local/bin/composer create-project --repository-url=xxxx .

I receive the following error message

su: unrecognized option '--repository-url=

I think there is issue with -- in the string. How can I escape that ?

Body:
There are two overlapping uses of $@ here, and you've inadvertently stumbled on a partial correct solution. -c expects a single word, while "$@" would produce multiple distinct words. The correct solution would be

su -s /bin/sh -c '"$@"' "$WWW_USER" _ "$@"

The short version: you don't want to build a command string from the current parameters; you want to pass them as arguments to a hard-coded command string to let the new shell expand things appropriately.

A breakdown:

-s /bin/sh - use /bin/sh instead of the appropriate users's login shell

-c '"$@"' run the command "$@", as desired. Note this is a hard-coded value; the new shell will expand its positional parameters correctly once it has started.

"$WWW_USER" - specify the user to run the shell as

_ - specify the value of $0 in the shell being run. You probably don't care what this value is; you just need some placeholder to prevent your first real argument from being treated as the value for $0.

"$@" pass the current positional parameters as arguments to the new shell, which will expand its "$@" to these values.


问:
Android Studio Random.org
I'm new to APIs and Libraries and I want to know how I can implement Random.org into my app. I need a random number from 1 to 6 (I'm making a dice app) and I only need one number to be generated. I've got my API key, bu I don't know what to do next. Random.org itself isn't all that clear on what to do next exactly. Does anyone of you know the exact steps to make a TextView which generates a new number at the press of a button?

答:
First of all, why do you need random.org?

Secondly, you can easily generate a random number using the Java Random Class.

```<code>Random rnd = new Random();
int randomNumber = rnd.nextInt(6) + 1;
</code>```

This gives a random integer between 1,2,3,4,5 or 6.

Hope it helps.

Title: Android Studio Random.org

Body:
First of all, why do you need random.org?

Secondly, you can easily generate a random number using the Java Random Class.

Random rnd = new Random();
int randomNumber = rnd.nextInt(6) + 1;

This gives a random integer between 1,2,3,4,5 or 6.

Hope it helps.


问:
Change the value of the list object in the recursion function
```<code>def divide(alist):
    # when the list have only one element, it should return the 0
    if len(alist) == 1:
        alist[:] = list([0])

    else:
        middle = len(alist) / 2
        divide(alist[:middle])
        divide(alist[middle:])
temp = [1, 2, 3, 4, 5, 6]
divide(temp)
print temp
</code>```

In my function, after the recursion, i want to get the [0, 0, 0, 0, 0, 0],but  temp is still the [1, 2, 3, 4, 5, 6]. And i also use alist[:] = list([0])to ensure the alist to be re-assigned.

Why? Is there something wrong with the reference?

答:
Your code doesn't work becuase slicing as in divide(alist[:middle]) creates a new list, so alist after the first recursion doesn't refer to temp anymore.

It is more common to return results rather than trying to create side effects in the calling arguments, e.g.:

```<code>def divide(alist):
    # when the list have only one element, it should return the 0
    if len(alist) == 1:
        return [0]
    middle = len(alist) // 2
    return divide(alist[:middle]) + divide(alist[middle:])

print(divide(temp))
# [0, 0, 0, 0, 0, 0]
</code>```

Obviously, this is relatively nonsense but I'm assuming you are just setting up the structure to do something specific.

If you really wanted to do this with side effects (not recommended!!!) then you would need to keep a left and right index and use that to eventually assign the [0], e.g.:

```<code>def divide(alist, left, right):
    middle = (right - left) // 2

    # when the list have only one element, it should return the 0
    if middle == 0:
        alist[left:right] = [0]
    else:
        divide(alist, left, left+middle)
        divide(alist, left+middle, right)

temp = [1, 2, 3, 4, 5, 6]
divide(temp, 0, len(temp))
print(temp)
# [0, 0, 0, 0, 0, 0]
</code>```

If you want to keep the original calling signature then you can use an _inner() function to handle the recursion, which would allow you to default the args but in reality you could just return _inner(0, len(alist)) without them:

```<code>def divide(alist):
    def _inner(left=0, right=len(alist)):  # default args based on comment @EricDuminil
        middle = (right - left) // 2
        # when the list have only one element, it should return the 0
        if middle == 0:
            alist[left:right] = [0]
        else:
            _inner(left, left+middle)
            _inner(left+middle, right)
    return _inner()

temp = [1, 2, 3, 4, 5, 6]
divide(temp)
print(temp)
# [0, 0, 0, 0, 0, 0]
</code>```

Body:
def divide(alist):
    # when the list have only one element, it should return the 0
    if len(alist) == 1:
        alist[:] = list([0])

    else:
        middle = len(alist) / 2
        divide(alist[:middle])
        divide(alist[middle:])
temp = [1, 2, 3, 4, 5, 6]
divide(temp)
print temp

In my function, after the recursion, i want to get the [0, 0, 0, 0, 0, 0],but  temp is still the [1, 2, 3, 4, 5, 6]. And i also use alist[:] = list([0])to ensure the alist to be re-assigned.

Why? Is there something wrong with the reference?

Body:
Your code doesn't work becuase slicing as in divide(alist[:middle]) creates a new list, so alist after the first recursion doesn't refer to temp anymore.

It is more common to return results rather than trying to create side effects in the calling arguments, e.g.:

def divide(alist):
    # when the list have only one element, it should return the 0
    if len(alist) == 1:
        return [0]
    middle = len(alist) // 2
    return divide(alist[:middle]) + divide(alist[middle:])

print(divide(temp))
# [0, 0, 0, 0, 0, 0]

Obviously, this is relatively nonsense but I'm assuming you are just setting up the structure to do something specific.

If you really wanted to do this with side effects (not recommended!!!) then you would need to keep a left and right index and use that to eventually assign the [0], e.g.:

def divide(alist, left, right):
    middle = (right - left) // 2

    # when the list have only one element, it should return the 0
    if middle == 0:
        alist[left:right] = [0]
    else:
        divide(alist, left, left+middle)
        divide(alist, left+middle, right)

temp = [1, 2, 3, 4, 5, 6]
divide(temp, 0, len(temp))
print(temp)
# [0, 0, 0, 0, 0, 0]

If you want to keep the original calling signature then you can use an _inner() function to handle the recursion, which would allow you to default the args but in reality you could just return _inner(0, len(alist)) without them:

def divide(alist):
    def _inner(left=0, right=len(alist)):  # default args based on comment @EricDuminil
        middle = (right - left) // 2
        # when the list have only one element, it should return the 0
        if middle == 0:
            alist[left:right] = [0]
        else:
            _inner(left, left+middle)
            _inner(left+middle, right)
    return _inner()

temp = [1, 2, 3, 4, 5, 6]
divide(temp)
print(temp)
# [0, 0, 0, 0, 0, 0]


问:
What does IRP stand for?
The Microsoft MASM language has an IRP directive. It's a synonym of the FOR directive which defines a "for each item" assembly loop.

I find the name perplexing. A search reveals nothing about the meaning of these 3 letters.

What does IRP stand for?

答:
IRP means Indefinite Repeat. This is a longstanding conventional name in assembly languages. It goes back to at least 1972.

The MACRO-11 manual from June 1972 says:

An indefinite repeat is essentially a macro definition which has only one dummy argument and is expanded for every real argument supplied.

The directive accepts a variable or indefinite number of items. Its body is repeated once for each item. The dummy argument takes on the value of the current item each iteration.

This contrasts with a simple repeat block which takes exactly 1 argument (a definite number of arguments) interpreted as a count and repeats the specified number of times.

Title: What does IRP stand for?


问:
How can I access to a button inside a customized AlertDialog?
I'm pretty new in Android programming, so I hope this question is easy for you guys.

I'm opening a custom AlertDialog with an extra button and a seekbar in order to display the progress of playing a song. My problem is that I cannot access to the onClick method of that button.

I'm opening the AlertDialog with the following code:

```<code>public void openAudioPlayer(View view){

    new AlertDialog.Builder(this)
            .setTitle(R.string.audio_player_title)
            .setMessage(R.string.audio_player_description)
            .setView(R.layout.dialog_audio_player)
            .setPositiveButton(R.string.confirm,null)
            .setNegativeButton(R.string.cancel, null).show();

}
</code>```

Where dialog_audio_player is the custom XLM file:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/playerBox"
        android:layout_centerVertical="true">

        <ToggleButton
            android:id="@+id/playStateButton"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:background="@drawable/toggle_player"
            android:onClick="onPlayerClicked"
            android:checked="false"
            android:focusable="false"
            android:focusableInTouchMode="false"
            android:textOff=""
            android:textOn="" />

        <SeekBar
            android:id="@+id/seekBar"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@id/playStateButton" />
        </RelativeLayout>
</LinearLayout>
</code>```

So, I want to control the pushing of that button with my customized onPlayerCLicked method, which is included in the same activity that openAudioPlayer:

```<code>public void onPlayerClicked(View view){
    Toast.makeText(this,"clicked",Toast.LENGTH_LONG).show();
}
</code>```

But the program never enters there. In fact, the app closes.

How can I do it?

The crash is the following:

```<code>06-04 12:47:13.587 3928-3928/vmc.songbook E/AndroidRuntime: FATAL EXCEPTION: main
                                                        Process: vmc.songbook, PID: 3928
                                                        java.lang.IllegalStateException: Could not execute method for android:onClick
                                                            at android.view.View$DeclaredOnClickListener.onClick(View.java:4698)
                                                            at android.view.View.performClick(View.java:5610)
                                                            at android.widget.CompoundButton.performClick(CompoundButton.java:122)
                                                            at android.view.View$PerformClick.run(View.java:22265)
                                                            at android.os.Handler.handleCallback(Handler.java:751)
                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                            at android.os.Looper.loop(Looper.java:154)
                                                            at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                                                         Caused by: java.lang.reflect.InvocationTargetException
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at android.view.View$DeclaredOnClickListener.onClick(View.java:4693)
                                                            at android.view.View.performClick(View.java:5610)
                                                            at android.widget.CompoundButton.performClick(CompoundButton.java:122)
                                                            at android.view.View$PerformClick.run(View.java:22265)
                                                            at android.os.Handler.handleCallback(Handler.java:751)
                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                            at android.os.Looper.loop(Looper.java:154)
                                                            at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                                                         Caused by: java.lang.RuntimeException: stop failed.
                                                            at android.media.MediaRecorder.stop(Native Method)
                                                            at vmc.songbook.RecordAudio.stopRecording(RecordAudio.java:121)
                                                            at vmc.songbook.RecordAudio.onToggleClicked(RecordAudio.java:84)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at android.view.View$DeclaredOnClickListener.onClick(View.java:4693)
                                                            at android.view.View.performClick(View.java:5610)
                                                            at android.widget.CompoundButton.performClick(CompoundButton.java:122)
                                                            at android.view.View$PerformClick.run(View.java:22265)
                                                            at android.os.Handler.handleCallback(Handler.java:751)
                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                            at android.os.Looper.loop(Looper.java:154)
                                                            at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
</code>```

答:
Update your method openAudioPlayer() as below:

```<code>public void openAudioPlayer(View view){

    LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    // Custom dialog layout
    View dialogView = layoutInflater.inflate(R.layout.dialog_audio_player, null);

    // PLAY/PAUSE button
    ToggleButton playStateButton = (ToggleButton) dialogView.findViewById(R.id.playStateButton);
    playStateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // DO something...
        }
    });

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(R.string.audio_player_title)
           .setMessage(R.string.audio_player_description)
           .setView(dialogView)
           .setPositiveButton(R.string.confirm, null)
           .setNegativeButton(R.string.cancel, null);

    // Create dialog
    AlertDialog alertDialog = builder.create();

    // Show dialog
    alertDialog.show();
}
</code>```

Body:
I'm pretty new in Android programming, so I hope this question is easy for you guys.

I'm opening a custom AlertDialog with an extra button and a seekbar in order to display the progress of playing a song. My problem is that I cannot access to the onClick method of that button.

I'm opening the AlertDialog with the following code:

public void openAudioPlayer(View view){

    new AlertDialog.Builder(this)
            .setTitle(R.string.audio_player_title)
            .setMessage(R.string.audio_player_description)
            .setView(R.layout.dialog_audio_player)
            .setPositiveButton(R.string.confirm,null)
            .setNegativeButton(R.string.cancel, null).show();

}

Where dialog_audio_player is the custom XLM file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/playerBox"
        android:layout_centerVertical="true">

        <ToggleButton
            android:id="@+id/playStateButton"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:background="@drawable/toggle_player"
            android:onClick="onPlayerClicked"
            android:checked="false"
            android:focusable="false"
            android:focusableInTouchMode="false"
            android:textOff=""
            android:textOn="" />

        <SeekBar
            android:id="@+id/seekBar"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@id/playStateButton" />
        </RelativeLayout>
</LinearLayout>

So, I want to control the pushing of that button with my customized onPlayerCLicked method, which is included in the same activity that openAudioPlayer:

public void onPlayerClicked(View view){
    Toast.makeText(this,"clicked",Toast.LENGTH_LONG).show();
}

But the program never enters there. In fact, the app closes.

How can I do it?

The crash is the following:

06-04 12:47:13.587 3928-3928/vmc.songbook E/AndroidRuntime: FATAL EXCEPTION: main
                                                        Process: vmc.songbook, PID: 3928
                                                        java.lang.IllegalStateException: Could not execute method for android:onClick
                                                            at android.view.View$DeclaredOnClickListener.onClick(View.java:4698)
                                                            at android.view.View.performClick(View.java:5610)
                                                            at android.widget.CompoundButton.performClick(CompoundButton.java:122)
                                                            at android.view.View$PerformClick.run(View.java:22265)
                                                            at android.os.Handler.handleCallback(Handler.java:751)
                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                            at android.os.Looper.loop(Looper.java:154)
                                                            at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                                                         Caused by: java.lang.reflect.InvocationTargetException
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at android.view.View$DeclaredOnClickListener.onClick(View.java:4693)
                                                            at android.view.View.performClick(View.java:5610)
                                                            at android.widget.CompoundButton.performClick(CompoundButton.java:122)
                                                            at android.view.View$PerformClick.run(View.java:22265)
                                                            at android.os.Handler.handleCallback(Handler.java:751)
                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                            at android.os.Looper.loop(Looper.java:154)
                                                            at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                                                         Caused by: java.lang.RuntimeException: stop failed.
                                                            at android.media.MediaRecorder.stop(Native Method)
                                                            at vmc.songbook.RecordAudio.stopRecording(RecordAudio.java:121)
                                                            at vmc.songbook.RecordAudio.onToggleClicked(RecordAudio.java:84)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at android.view.View$DeclaredOnClickListener.onClick(View.java:4693)
                                                            at android.view.View.performClick(View.java:5610)
                                                            at android.widget.CompoundButton.performClick(CompoundButton.java:122)
                                                            at android.view.View$PerformClick.run(View.java:22265)
                                                            at android.os.Handler.handleCallback(Handler.java:751)
                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                            at android.os.Looper.loop(Looper.java:154)
                                                            at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

Body:
Update your method openAudioPlayer() as below:

public void openAudioPlayer(View view){

    LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    // Custom dialog layout
    View dialogView = layoutInflater.inflate(R.layout.dialog_audio_player, null);

    // PLAY/PAUSE button
    ToggleButton playStateButton = (ToggleButton) dialogView.findViewById(R.id.playStateButton);
    playStateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // DO something...
        }
    });

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(R.string.audio_player_title)
           .setMessage(R.string.audio_player_description)
           .setView(dialogView)
           .setPositiveButton(R.string.confirm, null)
           .setNegativeButton(R.string.cancel, null);

    // Create dialog
    AlertDialog alertDialog = builder.create();

    // Show dialog
    alertDialog.show();
}


问:
Too many hconnections of my hbase client
In order to get max throughoutput, I use batch puts and increments to put data into hbase,
code sample:

```<code>Configuration configuration = HBaseConfiguration.create();
configuration.set("hbase.zookeeper.quorum", "10.2.1.12:2181");
configuration.set("hbase.zookeeper.znode.parent", "/hbase");
Connection connection = ConnectionFactory.createConnection(configuration);
Table table = null;
try {
   table = connection.getTable(TableName.valueOf("test"));
   Object[] results = new Object[incrementList.size()];
   table.batch(incrementList, results);
   for (Object result : results) {
       if (null == result) {
           failed++;
       } else {
           //System.out.println("Batch operation result: " + result);
       }
   }
   System.out.println("Batch operation failed: " + failed);
} catch (Exception ex) {
   throw new RPCCallException("Hbase put error: " + ex.getMessage(), ex);
} finally {
   table.close();
}
connection.close();
</code>```

There are 233 hconnections.
and the thread stack:

hbase-client version:

```<code><dependency>
  <groupId>org.apache.hbase</groupId>
  <artifactId>hbase-client</artifactId>
  <version>1.3.0</version>
</dependency>
</code>```

答: I found the problem, the default config of thread pool of hbase connection is: core = max = 256, so the thread count will increase up to 256</p>

Body:
In order to get max throughoutput, I use batch puts and increments to put data into hbase,
code sample:

Configuration configuration = HBaseConfiguration.create();
configuration.set("hbase.zookeeper.quorum", "10.2.1.12:2181");
configuration.set("hbase.zookeeper.znode.parent", "/hbase");
Connection connection = ConnectionFactory.createConnection(configuration);
Table table = null;
try {
   table = connection.getTable(TableName.valueOf("test"));
   Object[] results = new Object[incrementList.size()];
   table.batch(incrementList, results);
   for (Object result : results) {
       if (null == result) {
           failed++;
       } else {
           //System.out.println("Batch operation result: " + result);
       }
   }
   System.out.println("Batch operation failed: " + failed);
} catch (Exception ex) {
   throw new RPCCallException("Hbase put error: " + ex.getMessage(), ex);
} finally {
   table.close();
}
connection.close();

There are 233 hconnections.
and the thread stack:

hbase-client version:

<dependency>
  <groupId>org.apache.hbase</groupId>
  <artifactId>hbase-client</artifactId>
  <version>1.3.0</version>
</dependency>


问:
Understanding a MIPS algorithm
I'm very new into coding and we started with MIPS. We were kind of "thrown in to the cold water" and had to implement an algorithm that checks whether the elements of an array are sorted in ascending order. If it is sorted, a 1 is to be stored in $v0, otherwise a 0.
The solution that was given us:

```<code>.data
A: .word 1, 2, 3, 4, 5
l: .word 5

.text
main:
la $s0, A #address of A
lw $s1, l
add $t0, $0, $0 #counter for loop
addi $v0, $0, 1
sub $s1, $s1, $v0
for:
beq $t0, $s1, done
sll $t1, $t0, 2 #byte offset
add $t1, $t1, $s0
lw $t1, 0($t1) #$t1 = A[j]
addi $t2, $t0, 1
sll $t2, $t2, 2
add $t2, $t2, $s0
lw $t2, 0($t2) #$t2 = A[j + 1]
sub $t3, $t2, $t1 #$s3 = A[j+1] - A[j]?
slt $t4, $t3, $0
addi $t3, $0, 1
beq $t3, $t4 unsort #A isn’t sorted if A[j+1] - A[j] has a negative value
addi $t0, $t0, 1 #$t0 = $t0 + 1
j for

unsort:
add $v0, $0, $0 #set $v0 if array isn’t sorted

done:
</code>```

I'm having trouble understanding this code/algorithm. First of all what is an Array and why do we need specifically 5 of them?
But much more important to me is understanding this code/algorithm. So I need someone who is kind enough and explains to me step by step and in simple word :D, how this code works.

Would be very helpful and thanks in advance.

答:
Short answer

Basically, this program iterates over the array A in a loop with loop counter, say i. The index i is initialized with 0 and in every loop iteration incremented by 1 until it reaches l-1, where l is the size/length of the array A. In every iteration the algorithm checks if A[i] < A[i + 1] (i.e. if the i-th and the (i+1)-th element in A are in ascending order and thus are sorted). If so, it continues execution and $v0 remains 1. Otherwise it sets $v0 to 0 and terminates.

Long answer

Arrays and memory

An array is basically an ordered list of data – in this case it is an ordered list of words (a word in MIPS means: 32-bit value, and it consists of 4 bytes, each of which has 8 bits of information). So in this case, every word represents a 32-bit integer.

If we have an array A of length l, the elements are indexed from 0 to l-1. The first element in an array A (notation: A[0]) is saved at a certain address in memory, let's call it addr. The i-th element in A (A[i]) is then saved at the memory address addr + 4*i. This is because memory in MIPS is byte-addressable, i.e., every byte has his own address and because a word consists of 4 bytes, word addresses are offset by 4 (see below).

.data section

```<code>A: .word 1, 2, 3, 4, 5
l: .word 5
</code>```

With that you will realize that you don't have 5 arrays but only one (called A) and it contains the values 1, 2, 3, 4 and 5. Thus, the length is 5 and it is specified in the word l. You could add more values to your array but then you would have to adjust the length because otherwise, strange things will happen (or at least the result will be random). Your data is specified in this .data section and is therefore somewhere stored in your program's memory space.

MIPS assembly

In order to understand the code in the .text section, you have to understand MIPS assembly. If I write about a register, just think about it as a placeholder for a 32-bit value. For example, $0 is the zero register and it always stores a 32-bit 0. Other registers are used to temporarily store values used in your program. The instructions you use are:

la rd, label ("load address")

(rd = address of label; stores the address of the word specified by "label" in the destination register rd)

lw rd, label ("load word")

or

lw rd, offset(rs)

(load data specified by label, or data at address rs+offset into destination register rd)

add rd, rs, rt

(rd = rs + rt; adds source registers rs and rt and stores result in destination register rd)

addi rd, rs, imm  ("add immediate")

(rd = rs + imm; adds source register rs and immediate (16-bit constant) value and stores result in destination register rd)

sub rd, rs, rt  ("subtract")

(rd = rs - rt; subtracts source register rt from source register rs and stores result in destination register rd)

beq rs, rt, label  ("branch if equal")

(if value in rs is equal to value in rt, jump to label)

sll rd, rs, shamt ("shift logic left")

(rd = rs << 2; shift value in rs by two bits the left and store it in rd)

slt rd, rs, rt ("set less than")

(rd = (rs < rt) ? 1 : 0; if the value in rs is smaller than the value in rt, set rd to 32-bit 1, otherwise to 32-bit 0)

j label ("jump")

(jump to label)

.text section

```<code>main:
la $s0, A
lw $s1, l
add $t0, $0, $0
addi $v0, $0, 1
sub $s1, $s1, $v0

for:
beq $t0, $s1, done
sll $t1, $t0, 2 #byte offset
add $t1, $t1, $s0
lw $t1, 0($t1) #$t1 = A[j]
addi $t2, $t0, 1
sll $t2, $t2, 2
add $t2, $t2, $s0
lw $t2, 0($t2) #$t2 = A[j + 1]
sub $t3, $t2, $t1 #$s3 = A[j+1] - A[j]?
slt $t4, $t3, $0
addi $t3, $0, 1
beq $t3, $t4 unsort #A isn’t sorted if A[j+1] - A[j] has a negative value
addi $t0, $t0, 1 #$t0 = $t0 + 1
j for

unsort:
add $v0, $0, $0 #set $v0 if array isn’t sorted

done:
</code>```

This assembly code is equivalent to the pseudocode (if you are not used to pseudocode or to while loops, please look it up in the internet):

```<code>s0 <- address of first element in A
s1 <- l
t0 <- 0
v0 <- 1
s1 <- s1-1

while (t0 != s1) do
    t1 <- 4 * t0
    t1 <- t1 + s0
    t1 <- word at address t1
    t2 <- t0 + 1
    t2 <- 4 * t2
    t2 <- t2 + s0
    t2 <- word at address t2
    t3 <- t2 - t1
    if (t3 < 0) then t4 <- 1
    else t4 <- 0
    t3 <- 1
    if (t3 == t4) then
        v0 <- 0
        return
    else t0 <- t0 + 1
</code>```

Hope, this helped. I think it is quite ambitious to start with assembly code if you haven't coded before. Good luck!

Title: Understanding a MIPS algorithm

Body:
I'm very new into coding and we started with MIPS. We were kind of "thrown in to the cold water" and had to implement an algorithm that checks whether the elements of an array are sorted in ascending order. If it is sorted, a 1 is to be stored in $v0, otherwise a 0.
The solution that was given us:

.data
A: .word 1, 2, 3, 4, 5
l: .word 5

.text
main:
la $s0, A #address of A
lw $s1, l
add $t0, $0, $0 #counter for loop
addi $v0, $0, 1
sub $s1, $s1, $v0
for:
beq $t0, $s1, done
sll $t1, $t0, 2 #byte offset
add $t1, $t1, $s0
lw $t1, 0($t1) #$t1 = A[j]
addi $t2, $t0, 1
sll $t2, $t2, 2
add $t2, $t2, $s0
lw $t2, 0($t2) #$t2 = A[j + 1]
sub $t3, $t2, $t1 #$s3 = A[j+1] - A[j]?
slt $t4, $t3, $0
addi $t3, $0, 1
beq $t3, $t4 unsort #A isn’t sorted if A[j+1] - A[j] has a negative value
addi $t0, $t0, 1 #$t0 = $t0 + 1
j for

unsort:
add $v0, $0, $0 #set $v0 if array isn’t sorted

done:

I'm having trouble understanding this code/algorithm. First of all what is an Array and why do we need specifically 5 of them?
But much more important to me is understanding this code/algorithm. So I need someone who is kind enough and explains to me step by step and in simple word :D, how this code works.

Would be very helpful and thanks in advance.

Body:
Short answer

Basically, this program iterates over the array A in a loop with loop counter, say i. The index i is initialized with 0 and in every loop iteration incremented by 1 until it reaches l-1, where l is the size/length of the array A. In every iteration the algorithm checks if A[i] < A[i + 1] (i.e. if the i-th and the (i+1)-th element in A are in ascending order and thus are sorted). If so, it continues execution and $v0 remains 1. Otherwise it sets $v0 to 0 and terminates.

Long answer

Arrays and memory

An array is basically an ordered list of data – in this case it is an ordered list of words (a word in MIPS means: 32-bit value, and it consists of 4 bytes, each of which has 8 bits of information). So in this case, every word represents a 32-bit integer.

If we have an array A of length l, the elements are indexed from 0 to l-1. The first element in an array A (notation: A[0]) is saved at a certain address in memory, let's call it addr. The i-th element in A (A[i]) is then saved at the memory address addr + 4*i. This is because memory in MIPS is byte-addressable, i.e., every byte has his own address and because a word consists of 4 bytes, word addresses are offset by 4 (see below).

.data section

A: .word 1, 2, 3, 4, 5
l: .word 5

With that you will realize that you don't have 5 arrays but only one (called A) and it contains the values 1, 2, 3, 4 and 5. Thus, the length is 5 and it is specified in the word l. You could add more values to your array but then you would have to adjust the length because otherwise, strange things will happen (or at least the result will be random). Your data is specified in this .data section and is therefore somewhere stored in your program's memory space.

MIPS assembly

In order to understand the code in the .text section, you have to understand MIPS assembly. If I write about a register, just think about it as a placeholder for a 32-bit value. For example, $0 is the zero register and it always stores a 32-bit 0. Other registers are used to temporarily store values used in your program. The instructions you use are:

la rd, label ("load address")

(rd = address of label; stores the address of the word specified by "label" in the destination register rd)

lw rd, label ("load word")

or

lw rd, offset(rs)

(load data specified by label, or data at address rs+offset into destination register rd)

add rd, rs, rt

(rd = rs + rt; adds source registers rs and rt and stores result in destination register rd)

addi rd, rs, imm  ("add immediate")

(rd = rs + imm; adds source register rs and immediate (16-bit constant) value and stores result in destination register rd)

sub rd, rs, rt  ("subtract")

(rd = rs - rt; subtracts source register rt from source register rs and stores result in destination register rd)

beq rs, rt, label  ("branch if equal")

(if value in rs is equal to value in rt, jump to label)

sll rd, rs, shamt ("shift logic left")

(rd = rs << 2; shift value in rs by two bits the left and store it in rd)

slt rd, rs, rt ("set less than")

(rd = (rs < rt) ? 1 : 0; if the value in rs is smaller than the value in rt, set rd to 32-bit 1, otherwise to 32-bit 0)

j label ("jump")

(jump to label)

.text section

main:
la $s0, A
lw $s1, l
add $t0, $0, $0
addi $v0, $0, 1
sub $s1, $s1, $v0

for:
beq $t0, $s1, done
sll $t1, $t0, 2 #byte offset
add $t1, $t1, $s0
lw $t1, 0($t1) #$t1 = A[j]
addi $t2, $t0, 1
sll $t2, $t2, 2
add $t2, $t2, $s0
lw $t2, 0($t2) #$t2 = A[j + 1]
sub $t3, $t2, $t1 #$s3 = A[j+1] - A[j]?
slt $t4, $t3, $0
addi $t3, $0, 1
beq $t3, $t4 unsort #A isn’t sorted if A[j+1] - A[j] has a negative value
addi $t0, $t0, 1 #$t0 = $t0 + 1
j for

unsort:
add $v0, $0, $0 #set $v0 if array isn’t sorted

done:

This assembly code is equivalent to the pseudocode (if you are not used to pseudocode or to while loops, please look it up in the internet):

s0 <- address of first element in A
s1 <- l
t0 <- 0
v0 <- 1
s1 <- s1-1

while (t0 != s1) do
    t1 <- 4 * t0
    t1 <- t1 + s0
    t1 <- word at address t1
    t2 <- t0 + 1
    t2 <- 4 * t2
    t2 <- t2 + s0
    t2 <- word at address t2
    t3 <- t2 - t1
    if (t3 < 0) then t4 <- 1
    else t4 <- 0
    t3 <- 1
    if (t3 == t4) then
        v0 <- 0
        return
    else t0 <- t0 + 1

Hope, this helped. I think it is quite ambitious to start with assembly code if you haven't coded before. Good luck!


问:
What does ... means in c code
I'm reading the code of wiredtiger.  I see a function definition as

WT_CURSOR::set_key(WT_CURSOR *  cursor, ...)

what does the '...' means here?   how can the compiler compile such code?

Thanks

答:
It means that the function accepts a variable number of arguments after the named arguments (possibly zero).  The function would use a va_list and the associated functions (va_start, va_arg, and va_end) to process the arguments.

An example:

```<code>#include <stdio.h>
#include <stdarg.h>

// n: number of doubles
// ... list of doubles
double average(int n, ...)
{
    double accum = 0.0;
    int i;
    va_list vl;
    va_start(vl, n);

    for(i = 0; i < n; i++)
    {
        accum += va_arg(vl, double);
    }
    va_end(vl);
    return accum/(double)n;
}

int main()
{
    double avg = average(5, 1.0, 1.0, 6.5, 3.3, -5.8);
    printf("%f\n", avg);
    return 0;
}
</code>```

Output: 1.200000

Title: What does ... means in c code

Body:
It means that the function accepts a variable number of arguments after the named arguments (possibly zero).  The function would use a va_list and the associated functions (va_start, va_arg, and va_end) to process the arguments.

An example:

#include <stdio.h>
#include <stdarg.h>

// n: number of doubles
// ... list of doubles
double average(int n, ...)
{
    double accum = 0.0;
    int i;
    va_list vl;
    va_start(vl, n);

    for(i = 0; i < n; i++)
    {
        accum += va_arg(vl, double);
    }
    va_end(vl);
    return accum/(double)n;
}

int main()
{
    double avg = average(5, 1.0, 1.0, 6.5, 3.3, -5.8);
    printf("%f\n", avg);
    return 0;
}

Output: 1.200000


问:
Flask Jinja tempate loop: error not showing
I am trying to run a googlemaps API map, only when there are GPS values available.

This checks if there are GPS, if not then error1:

```<code>error1 = None
GPS =[]
try:
    GPS = gd.get_gps(request.form['address'])
    if len(GPS) == 0:
        error1 = 'No GPS data'
    else:
        GPS.append(GPS)
except:
    error1 ='No GPS data'
    pass
return render_template('Client_Details.html', error1 =error1,GPS=GPS)
</code>```

this is the template:

```<code>{% if error1 %}
<p class='alert'>{{ error1 }}</p>
{% elif GPS %}
<div id = "location">
<caption> Location <caption>
{{googlemap("map_name", lat=GPS[0], lng= GPS[1], zoom=17, maptype= 'SATELLITE', markers=[(GPS[0], GPS[1])])}}
{% endif %}
</code>```

This works if there are GPS available and the map shows, but if there are no GPS (ie GPS list is empty), it is not showing error1, but giving me this error:

```<code>AttributeError: lat and lng required
</code>```

答:
You are recycling the GPS variable in a strange way, try to avoid that.

```<code>error1 = None
GPS = []

try:
    form_coordinates = gd.get_gps(request.form['address'])
    if not form_coordinates:
        error1 = 'No GPS data'
    else:
        GPS.append(form_coordinates)
except:
    error1 = 'No GPS data'

return render_template('Client_Details.html', error1=error1, GPS=GPS)
</code>```

Also, use the jinja2 length function to check if there are any coordinates.

```<code>{% if GPS is defined and GPS|length > 0 %}
<div id="location">
<caption> Location </caption>
{{googlemap("map_name", lat=GPS[0], lng=GPS[1], zoom=17, maptype='SATELLITE', markers=[(GPS[0], GPS[1])])}}
</div>
{% else %}
<p class='alert'>{{ error1 }}</p>
{% endif %}
</code>```

Body:
I am trying to run a googlemaps API map, only when there are GPS values available.

This checks if there are GPS, if not then error1:

error1 = None
GPS =[]
try:
    GPS = gd.get_gps(request.form['address'])
    if len(GPS) == 0:
        error1 = 'No GPS data'
    else:
        GPS.append(GPS)
except:
    error1 ='No GPS data'
    pass
return render_template('Client_Details.html', error1 =error1,GPS=GPS)

this is the template:

{% if error1 %}

{{ error1 }}

{% elif GPS %}

 Location

{{googlemap("map_name", lat=GPS[0], lng= GPS[1], zoom=17, maptype= 'SATELLITE', markers=[(GPS[0], GPS[1])])}}
{% endif %}

This works if there are GPS available and the map shows, but if there are no GPS (ie GPS list is empty), it is not showing error1, but giving me this error:

AttributeError: lat and lng required

Body:
You are recycling the GPS variable in a strange way, try to avoid that.

error1 = None
GPS = []

try:
    form_coordinates = gd.get_gps(request.form['address'])
    if not form_coordinates:
        error1 = 'No GPS data'
    else:
        GPS.append(form_coordinates)
except:
    error1 = 'No GPS data'

return render_template('Client_Details.html', error1=error1, GPS=GPS)

Also, use the jinja2 length function to check if there are any coordinates.

{% if GPS is defined and GPS|length > 0 %}
<div id="location">
<caption> Location </caption>
{{googlemap("map_name", lat=GPS[0], lng=GPS[1], zoom=17, maptype='SATELLITE', markers=[(GPS[0], GPS[1])])}}
</div>
{% else %}
<p class='alert'>{{ error1 }}</p>
{% endif %}


答: Check if the grid variable does not contain '' (or whatever you use for empty)</p>

Title: C# Coding a Tie in Tic Tac Toe

Body:
I've developed a game of tic tac toe in C# and set a function for the win conditions, but I can't seem to figure out how to set the condition for a tie when the grid is full. When I tried to input, the tie would occur randomly. I wonder if it's how I set the or and and operators.Here's what I tried.

public bool Ended()
{
    if (grid[0, 0] == 'X' && grid[0, 1] == 'X' && grid[0, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[1, 0] == 'X' && grid[1, 1] == 'X' && grid[1, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[2, 0] == 'X' && grid[2, 1] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'X' && grid[1, 0] == 'X' && grid[2, 0] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 1] == 'X' && grid[1, 1] == 'X' && grid[2, 1] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 2] == 'X' && grid[1, 2] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'X' && grid[1, 1] == 'X' && grid[2, 2] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }
    if (grid[0, 2] == 'X' && grid[1, 1] == 'X' && grid[2, 0] == 'X') {  Console.WriteLine("PLayer 1 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[0, 1] == 'O' && grid[0, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[1, 0] == 'O' && grid[1, 1] == 'O' && grid[1, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[2, 0] == 'O' && grid[2, 1] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[1, 0] == 'O' && grid[2, 0] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 1] == 'O' && grid[1, 1] == 'O' && grid[2, 1] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 2] == 'O' && grid[1, 2] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    if (grid[0, 0] == 'O' && grid[1, 1] == 'O' && grid[2, 2] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }
    if (grid[0, 2] == 'O' && grid[1, 1] == 'O' && grid[2, 0] == 'O') { Console.WriteLine("PLayer 2 Wins"); return true; }

    else if (grid[0, 0] == 'X' || grid[0, 0] == 'O' &&
        grid[0, 1] == 'X' || grid[0, 1] == 'O' &&
        grid[0, 2] == 'X' || grid[0, 2] == 'O' &&
        grid[1, 0] == 'X' || grid[1, 0] == 'O' &&
        grid[1, 1] == 'X' || grid[1, 1] == 'O' &&
        grid[1, 2] == 'X' || grid[1, 2] == 'O' &&
        grid[2, 0] == 'X' || grid[2, 0] == 'O' &&
        grid[2, 1] == 'X' || grid[2, 1] == 'O' &&
        grid[2, 2] == 'X' || grid[2, 2] == 'O')
    { Console.WriteLine("It's a Tie"); return true; }
    return false;
}


问:
Swift: Using Int in UILabel inside View Controller
I've set up an if statement which does things depending on an int value stored in a UILabel, however, my code can't determine the value of the int inside the label.

This is because the if statement runs within the viewdidload function. I'm basically looking for how I can pass the label value to my view. I'm struggling to make it work.

Here's the code:

```<code>   override func viewDidLoad()
   {
        // If statement
        var NumberRead = Int(Number.text!)

        if NumberRead! <= 2 {
              Picture.image = Pic1
        } else {
              Picture.image = Pic2
        }
    }

    @IBOutlet weak var Number: UILabel!
</code>```

Any suggestions for better ways to handle this would be amazing.

Thanks

答:
I don't think the problem is that you use this code in viewDidLoad, but that your UILabel is empty when you run the code and the code is unwrapping a nil value. You have to set the UILabel Number to a value before you use the if statement.

I don't know what value you expect in the Number label, but either set it with an initial value, e.g. 0, or when this view controller is called through segueing from another view controller pass on the value the label should have. The code should then work fine.

Body:
I've set up an if statement which does things depending on an int value stored in a UILabel, however, my code can't determine the value of the int inside the label.

This is because the if statement runs within the viewdidload function. I'm basically looking for how I can pass the label value to my view. I'm struggling to make it work.

Here's the code:

   override func viewDidLoad()
   {
        // If statement
        var NumberRead = Int(Number.text!)

        if NumberRead! <= 2 {
              Picture.image = Pic1
        } else {
              Picture.image = Pic2
        }
    }

    @IBOutlet weak var Number: UILabel!

Any suggestions for better ways to handle this would be amazing.

Thanks


问:
Auto add alt on images
When I add

```<code>$(document).ready(function() {
$('#readerareaimg img').each(function(){
var filename = $img.attr('src')
$img.attr('title', filename.substring((filename.lastIndexOf('/'))+1, filename.lastIndexOf('.')));
$img.attr('alt', filename.substring((filename.lastIndexOf('/'))+1, filename.lastIndexOf('.')));
});
</code>```

My website will generate alt and title tags automatically on images based on their file name, but I want to add any word before the file name.
For example file name is comic.jpg and I will display alt="comic", but i want that alt to become alt="read comic".

Can someone explain how to make this? Please, sir :3

答:
It's a simple case of concatenating the string when you set the alt attribute:

```<code>$img.attr('alt', 'read ' + filename.substring((filename.lastIndexOf('/'))+1, filename.lastIndexOf('.')));
</code>```

As for the number request from the comments, you can capture the index argument which is zero based, then +1 it to get 1-n.

```<code>$('#readerareaimg img').each(function(index){
    $(this).attr('alt', 'comic naruto image ' + (index+1));
});
</code>```

Title: Auto add alt on images

Body:
When I add

$(document).ready(function() {
$('#readerareaimg img').each(function(){
var filename = $img.attr('src')
$img.attr('title', filename.substring((filename.lastIndexOf('/'))+1, filename.lastIndexOf('.')));
$img.attr('alt', filename.substring((filename.lastIndexOf('/'))+1, filename.lastIndexOf('.')));
});

My website will generate alt and title tags automatically on images based on their file name, but I want to add any word before the file name.
For example file name is comic.jpg and I will display alt="comic", but i want that alt to become alt="read comic".

Can someone explain how to make this? Please, sir :3

Body:
It's a simple case of concatenating the string when you set the alt attribute:

$img.attr('alt', 'read ' + filename.substring((filename.lastIndexOf('/'))+1, filename.lastIndexOf('.')));

As for the number request from the comments, you can capture the index argument which is zero based, then +1 it to get 1-n.

$('#readerareaimg img').each(function(index){
    $(this).attr('alt', 'comic naruto image ' + (index+1));
});