问:
ImageView not changing with setImageResource()?
Here's the code:

```<code>public class MainActivity extends AppCompatActivity implements View.OnClickListener{

  ImageView button;

 @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button = (ImageView)findViewById(R.id.startButton);
    button.setOnClickListener(this);
    button.setImageResource(R.drawable.play);
}
    public void onClick(View v) {
        button.setImageResource(R.drawable.pause);
    }
}
</code>```

Apparently if I put the button.setImageResource(R.drawable.pause);in the onCreate it works and changes images but not in the onClick? I tried debugging it and it ran the onClick code but didn't change the button image. I'm probably making a very stupid mistake but I can't figure it out.

xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.larry.app.MainActivity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
   <ImageView
        android:id="@+id/startButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true" />
</LinearLayout>
</code>```

答: In the OnClick there is a switch statement, and when I put the button.setImageResource(R.drawable.pause); before the switch it doesn't always activate even when OnClick activates. When I click one button android.os.SystemClock.sleep is executed which prevents the image from swapping. When the other button is pressed the clock doesn't sleep, so the image can switch successfully.

Body:
Here's the code:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

  ImageView button;

 @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button = (ImageView)findViewById(R.id.startButton);
    button.setOnClickListener(this);
    button.setImageResource(R.drawable.play);
}
    public void onClick(View v) {
        button.setImageResource(R.drawable.pause);
    }
}

Apparently if I put the button.setImageResource(R.drawable.pause);in the onCreate it works and changes images but not in the onClick? I tried debugging it and it ran the onClick code but didn't change the button image. I'm probably making a very stupid mistake but I can't figure it out.

xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.larry.app.MainActivity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
   <ImageView
        android:id="@+id/startButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true" />
</LinearLayout>


来源: stackexchange

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

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

Ok, here's the scenario.

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

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

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

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

答:
Sure you can do the join in the same query:-</p>

```<code>FROM TableA a
INNER JOIN Table b ON a.TableA_ID = b.TableA_ID
LEFT OUTER JOIN Table c ON a.TableA_ID = c.TableA_ID
</code>```

OwnerDisplayName: Bob Smith

ContentLicense: CC BY-SA 3.0

Body:
Sure you can do the join in the same query:-

FROM TableA a
INNER JOIN Table b ON a.TableA_ID = b.TableA_ID
LEFT OUTER JOIN Table c ON a.TableA_ID = c.TableA_ID

OwnerDisplayName: AnthonyWJones

ContentLicense: CC BY-SA 2.5


问:
How to calculate running time from status and time using python
I have a circulation pump that I check wither it's on or off on and this is not by any fixed interval what so ever. For a single day that could give me a dataset looking like this where 'value' represents the pump being on or off.

```<code>data=(
 {'value': 0, 'time': datetime.datetime(2011, 1, 18, 7, 58, 25)},
 {'value': 1, 'time': datetime.datetime(2011, 1, 18, 8, 0, 3)},
 {'value': 0, 'time': datetime.datetime(2011, 1, 18, 8, 32, 10)},
 {'value': 0, 'time': datetime.datetime(2011, 1, 18, 9, 22, 7)},
 {'value': 1, 'time': datetime.datetime(2011, 1, 18, 9, 30, 58)},
 {'value': 1, 'time': datetime.datetime(2011, 1, 18, 12, 2, 23)},
 {'value': 0, 'time': datetime.datetime(2011, 1, 18, 15, 43, 11)},
 {'value': 1, 'time': datetime.datetime(2011, 1, 18, 20, 14, 55)})
</code>```

The format is not that important and can be changed.

What I do want to know is how to calculate how many minutes ( or timespan or whatever) the 'value' has been 0 or 1 (or ON or OFF)?

This is just a small sample of the data, it stretches over several years so there could be a lot.
I have been using numpy/mathplotlib for plotting some graphs and there might be something in numpy to do this but I'm not good enough at it.

Edit

What I would like to see as an output to this would be a sum of the time in the different states. Something like...

```<code>0 04:42:13
1 07:34:17
</code>```

答:
It really depends on how you're going to treat this data points, are they representative of what? Generally, to know when switch occur  you could use itertools.groupby like this:

```<code>>>> from itertools import groupby
>>> for i, grp in groupby(data, key=lambda x: x['value']):
    lst = [x['time'] for x in grp]
    print(i, max(lst) - min(lst))

0 0:00:00
1 0:00:00
0 0:49:57
1 2:31:25
0 0:00:00
1 0:00:00
</code>```

This is the example of minimal time you can be sure your system was up or down (assuming no interruptions between measurement).

Once you decide how to treat your points, modification to this algorithm would be trivial.

EDIT: since you only need sums of up/down-time, here is the simpler version:

```<code>>>> sums = {0:datetime.timedelta(0), 1:datetime.timedelta(0)}
>>> for cur, nex in zip(data, data[1:]):
    sums[cur['value']] += nex['time'] - cur['time']

>>> for i, j in sums.items():
    print(i, j)

0 5:32:10
1 6:44:20
</code>```

If you expect long-periods of continuous up/down-time, you might still benefit of the itertools.groupby. This is py3k version, so it won't be particularly efficient in py2k.

Body:
I have a circulation pump that I check wither it's on or off on and this is not by any fixed interval what so ever. For a single day that could give me a dataset looking like this where 'value' represents the pump being on or off.

data=(
 {'value': 0, 'time': datetime.datetime(2011, 1, 18, 7, 58, 25)},
 {'value': 1, 'time': datetime.datetime(2011, 1, 18, 8, 0, 3)},
 {'value': 0, 'time': datetime.datetime(2011, 1, 18, 8, 32, 10)},
 {'value': 0, 'time': datetime.datetime(2011, 1, 18, 9, 22, 7)},
 {'value': 1, 'time': datetime.datetime(2011, 1, 18, 9, 30, 58)},
 {'value': 1, 'time': datetime.datetime(2011, 1, 18, 12, 2, 23)},
 {'value': 0, 'time': datetime.datetime(2011, 1, 18, 15, 43, 11)},
 {'value': 1, 'time': datetime.datetime(2011, 1, 18, 20, 14, 55)})

The format is not that important and can be changed.

What I do want to know is how to calculate how many minutes ( or timespan or whatever) the 'value' has been 0 or 1 (or ON or OFF)?

This is just a small sample of the data, it stretches over several years so there could be a lot.
I have been using numpy/mathplotlib for plotting some graphs and there might be something in numpy to do this but I'm not good enough at it.

Edit

What I would like to see as an output to this would be a sum of the time in the different states. Something like...

0 04:42:13
1 07:34:17

Body:
It really depends on how you're going to treat this data points, are they representative of what? Generally, to know when switch occur  you could use itertools.groupby like this:

>>> from itertools import groupby
>>> for i, grp in groupby(data, key=lambda x: x['value']):
    lst = [x['time'] for x in grp]
    print(i, max(lst) - min(lst))

0 0:00:00
1 0:00:00
0 0:49:57
1 2:31:25
0 0:00:00
1 0:00:00

This is the example of minimal time you can be sure your system was up or down (assuming no interruptions between measurement).

Once you decide how to treat your points, modification to this algorithm would be trivial.

EDIT: since you only need sums of up/down-time, here is the simpler version:

>>> sums = {0:datetime.timedelta(0), 1:datetime.timedelta(0)}
>>> for cur, nex in zip(data, data[1:]):
    sums[cur['value']] += nex['time'] - cur['time']

>>> for i, j in sums.items():
    print(i, j)

0 5:32:10
1 6:44:20

If you expect long-periods of continuous up/down-time, you might still benefit of the itertools.groupby. This is py3k version, so it won't be particularly efficient in py2k.


问:
Returning multiple parameters
I'm trying to return multiple parameters, if that's how to word it. I'm trying to "translate" Python code into C#.

I'm actually not quite sure what exact term I'm searching for, but I know how to do it in Python so I'll just show my code.

```<code>class Staff
{
    public String name;
    public int age;

    /* Now in Python, you can easily write this following, but I have no
       idea how this works in C#. I basically want to return all the values
       for each employee in the "Staff" class */

    def desc(self):
        desc_str = "%s is %s years old." % (self.name, self.age)
        return desc_str

}

class Program
{
    public static void Main()
    {
        Staff Jack = new Staff();
        Jack.name = "Jack";
        Jack.age = 40;

        Staff Jill = new Staff();
        Jill.name = "Jill";
        Jill.age = 50;

        Console.WriteLine(Jack.desc());
        Console.WriteLine(Jill.desc());
        Console.ReadKey();
    }
}
</code>```

EDIT: I figured out that what I was searching for was get, set and ToString() and will look into it now.
The code I've translated looks like the following now:

```<code>class Staff
{
    private string name;
    private int age;
    private string yearsold = " years old.";

    public string Name
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
        }
    }

    public int Age
    {
        get
        {
            return age;
        }
        set
        {
            age = value;
        }
    }

    public string YearsOld
    {
        get
        {
            return yearsold;
        }
        set
        {
            yearsold = value;
        }
    }

    public override string ToString()
    {
        return "Employee " + Name + " is " + Age + YearsOld;
    }
}

class TestPerson
{
    static void Main()
    {
        // Create a new Person object:
        Staff person = new Staff();

        person.Name = "Jack";
        person.Age = 40;
        Console.WriteLine(person);

        person.Name = "Jill";
        person.Age = 50;
        Console.WriteLine(person);

        Console.ReadKey();
    }
}
</code>```

答:
Since you have a class, you can override the ToString function and use the string.Format function like so:

```<code>class Staff
{
    public string name;
    public int age;

    public Staff(string _name, int _age)
    {
        this.name = _name;
        this.age = _age;
    }

    public override string ToString()
    {
        return string.Format("{0} is {1} years old.", this.name, this.age);
    }
}
</code>```

Then to print:

```<code>Staff Jack = new Staff("Jack", 40);
Console.WriteLine(Jack); // implicitly calls Jack.ToString()
</code>```

Hope that helps.

Title: Returning multiple parameters

Body:
I'm trying to return multiple parameters, if that's how to word it. I'm trying to "translate" Python code into C#.

I'm actually not quite sure what exact term I'm searching for, but I know how to do it in Python so I'll just show my code.

class Staff
{
    public String name;
    public int age;

    /* Now in Python, you can easily write this following, but I have no
       idea how this works in C#. I basically want to return all the values
       for each employee in the "Staff" class */

    def desc(self):
        desc_str = "%s is %s years old." % (self.name, self.age)
        return desc_str

}

class Program
{
    public static void Main()
    {
        Staff Jack = new Staff();
        Jack.name = "Jack";
        Jack.age = 40;

        Staff Jill = new Staff();
        Jill.name = "Jill";
        Jill.age = 50;

        Console.WriteLine(Jack.desc());
        Console.WriteLine(Jill.desc());
        Console.ReadKey();
    }
}

EDIT: I figured out that what I was searching for was get, set and ToString() and will look into it now.
The code I've translated looks like the following now:

class Staff
{
    private string name;
    private int age;
    private string yearsold = " years old.";

    public string Name
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
        }
    }

    public int Age
    {
        get
        {
            return age;
        }
        set
        {
            age = value;
        }
    }

    public string YearsOld
    {
        get
        {
            return yearsold;
        }
        set
        {
            yearsold = value;
        }
    }

    public override string ToString()
    {
        return "Employee " + Name + " is " + Age + YearsOld;
    }
}

class TestPerson
{
    static void Main()
    {
        // Create a new Person object:
        Staff person = new Staff();

        person.Name = "Jack";
        person.Age = 40;
        Console.WriteLine(person);

        person.Name = "Jill";
        person.Age = 50;
        Console.WriteLine(person);

        Console.ReadKey();
    }
}

Body:
Since you have a class, you can override the ToString function and use the string.Format function like so:

class Staff
{
    public string name;
    public int age;

    public Staff(string _name, int _age)
    {
        this.name = _name;
        this.age = _age;
    }

    public override string ToString()
    {
        return string.Format("{0} is {1} years old.", this.name, this.age);
    }
}

Then to print:

Staff Jack = new Staff("Jack", 40);
Console.WriteLine(Jack); // implicitly calls Jack.ToString()

Hope that helps.


问:
How to add onPress events on Cards (on native base)?
I'm trying to make those cards clickable to redirect to another screen, but I cant figure it out  </p>

```<code> let cards = this.state.items.map(item => (
            <Card key={item.id} onPress={() => Actions.dogScreen()}>
                <CardItem bordered>
                    <Left>
                        <Thumbnail square source={item.image ? { uri: "data:image/jpeg;base64," + item.image } : logo} />
                        <Body>
                            <Text>Name: {item.name}, Age: {item.age}</Text>
                            <Text note>Gender: {item.gender.name} Race: {item.race.name}</Text>
                        </Body>
                    </Left>
                </CardItem>
            </Card>))
</code>```

答:
You can make <Card /> clickable by wrapping the whole card by TouchableOpacity. Also don't forget to add pointerEvents="none" for each card.

```<code>import { TouchableOpacity } from 'react-native';

let cards = this.state.items.map(item => (
     <TouchableOpacity key={item.id} onPress={() => Actions.dogScreen()}>

          <Card pointerEvents="none">
                <CardItem bordered>
                    <Left>
                        <Thumbnail square source={item.image ? { uri: "data:image/jpeg;base64," + item.image } : logo} />
                        <Body>
                            <Text>Name: {item.name}, Age: {item.age}</Text>
                            <Text note>Gender: {item.gender.name} Race: {item.race.name}</Text>
                        </Body>
                    </Left>
                </CardItem>
            </Card>

       </TouchableOpacity>
))
</code>```

Body:
I'm trying to make those cards clickable to redirect to another screen, but I cant figure it out

 let cards = this.state.items.map(item => (
            <Card key={item.id} onPress={() => Actions.dogScreen()}>
                <CardItem bordered>
                    <Left>
                        <Thumbnail square source={item.image ? { uri: "data:image/jpeg;base64," + item.image } : logo} />

                            <Text>Name: {item.name}, Age: {item.age}</Text>
                            <Text note>Gender: {item.gender.name} Race: {item.race.name}</Text>

                    </Left>
                </CardItem>
            </Card>))

Body:
You can make <Card /> clickable by wrapping the whole card by TouchableOpacity. Also don't forget to add pointerEvents="none" for each card.

import { TouchableOpacity } from 'react-native';

let cards = this.state.items.map(item => (
     <TouchableOpacity key={item.id} onPress={() => Actions.dogScreen()}>

          <Card pointerEvents="none">
                <CardItem bordered>
                    <Left>
                        <Thumbnail square source={item.image ? { uri: "data:image/jpeg;base64," + item.image } : logo} />
                        <Body>
                            <Text>Name: {item.name}, Age: {item.age}</Text>
                            <Text note>Gender: {item.gender.name} Race: {item.race.name}</Text>
                        </Body>
                    </Left>
                </CardItem>
            </Card>

       </TouchableOpacity>
))


问:
XPath / XQuery: find text in a node, but ignoring content of specific descendant elements
I am trying to find a way to search for a string within nodes, but excluding ythe content of some subelements of those nodes. Plain and simple, I want to search for a string in paragraphs of a text, excluding the footnotes which are children elements of the paragraphs.

For example,

My document being:

```<code><document>
   <p n="1">My text starts here/</p>
   <p n="2">Then it goes on there<footnote>It's not a very long text!</footnote></p>
</document>
</code>```

When I'm searching for "text", I would like the Xpath / XQuery to retrieve the first p element, but not the second one (where "text" is contained only in the footnote subelement).

I have tried the contains() function, but it retrieves both p elements.

Any help would be much appreciated :)

答:
I want to search for a string in
  paragraphs of a text, excluding the
  footnotes which are children elements
  of the paragraphs

An XPath 1.0 - only solution:

Use:

```<code>//p//text()[not(ancestor::footnote) and contains(.,'text')]
</code>```

Against the following XML document (obtained from yours but added p s within a footnote to make this more interesting):

```<code><document>
    <p n="1">My text starts here/</p>
    <p n="2">Then it goes on there
        <footnote>It's not a very long text!
           <p>text</p>
        </footnote>
    </p>
</document>
</code>```

this XPath expression selects exactly the wanted text node:

```<code>My text starts here/
</code>```

Body:
I am trying to find a way to search for a string within nodes, but excluding ythe content of some subelements of those nodes. Plain and simple, I want to search for a string in paragraphs of a text, excluding the footnotes which are children elements of the paragraphs.

For example,

My document being:

<document>

My text starts here/

Then it goes on there<footnote>It's not a very long text!</footnote>

</document>

When I'm searching for "text", I would like the Xpath / XQuery to retrieve the first p element, but not the second one (where "text" is contained only in the footnote subelement).

I have tried the contains() function, but it retrieves both p elements.

Any help would be much appreciated :)

Body:
I want to search for a string in
  paragraphs of a text, excluding the
  footnotes which are children elements
  of the paragraphs

An XPath 1.0 - only solution:

Use:

//p//text()[not(ancestor::footnote) and contains(.,'text')]

Against the following XML document (obtained from yours but added p s within a footnote to make this more interesting):

<document>
    <p n="1">My text starts here/</p>
    <p n="2">Then it goes on there
        <footnote>It's not a very long text!
           <p>text</p>
        </footnote>
    </p>
</document>

this XPath expression selects exactly the wanted text node:

My text starts here/


问:
Java - How do I check for a straight in a poker hand without sorting?
This is not a duplicate. I understand how easy this is if you can sort, but I am not allowed to use the sort method for arrays and I am not allowed to write my own. I can't find any help with this anywhere, including StackOverflow.

In this scenario, I have a method that is supposed to check whether or not a five card hand is a straight. I have a card object that holds a value (integer) and a suit (integer). I also have some rules about implementing this method.

There are no face cards besides the ace

The ace can count as either a 1 or a 10 but not both

A straight cannot wrap around

You cannot use the sorting method for arrays or write your own sorting method

That last rule is what is killing me. I have an array of cards. If I could just sort it, this would be so easy but I can't even write my own method to sort the array. For my other methods it simple to iterate through the hand and store the information about the hand in two separate arrays like this:

```<code>private static int[] cardValues = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
private static int[] cardSuits = {0, 0, 0, 0, 0};

private static void evaluationHelper(Card[] cards) {
    for (int i = 0; i < cardValues.length; i++) {
        cardValues[i] = 0;
    }

    for (int i = 0; i <cardSuits.length; i++) {
        cardSuits[i] = 0;
    }

    for (int i = 0; i < 5; i++) {
        cardValues[cards[i].getValue() - 1]++;
        cardSuits[cards[i].getSuit()]++;

        if (cards[i].getValue() == 1) {
            cardValues[9]++;
        }
    }
}
</code>```

So in my first attempt to solve this issue I tried something like this:

```<code>public static boolean hasStraight(Card [] cards) {
    int sequenCounter = 0;
    evaluationHelper(cards);

    for (int i = 0; i < cardValues.length; i++) {
        if (sequenCounter != 5) {
            if (cardValues[i] != 0) {
                sequenCounter++;
            } else {
                sequenCounter = 0;
            }
        } else {
            return true;
        }
    }
    return false;
}
</code>```

That didn't work. So then I tried this:

```<code>public static boolean hasStraight(Card [] cards) {
    int min = 100, max = 0;
    boolean seenSix = false, seenAce = false;
    evaluationHelper(cards);

    for (int i = 0; i < cards.length; i++) {
        if (cards[i].getValue() > max) {
            max = cards[i].getValue();
        }

        if (cards[i].getValue() < min) {
            min = cards[i].getValue();
        }

        if (cards[i].getValue() == 6) {
            seenSix = true;
        }

        if (cards[i].getValue() == 1) {
            seenAce = true;
        }
    }

    if (seenSix && seenAce) {
        max = 10;
    }

    if (max - min == 4) {
        return true;
    }
    return false;
}
</code>```

That doesn't work either. I'm getting frustrated as both of these attempts went through many different changes over the course of overs and nothing has worked. I can't even figure out why they aren't working. The only information I have is that this method isn't spitting out the correct value. I don't know what values are being passed to the method. I don't know what the method is spitting out during the test. It could be spitting out false when it's supposed to be spitting true or vice versa. Please help!

答:
Rules:

max_value - min_value must be 4

Other 3 cards' value must be between min and max

All 5 cards must have the same suit

Assumes there are no duplicates of a suit-number.

If none of these rules are violate then you have a straight.

The only tricky thing if the Ace.  Ace can be a 10?  What about the number 10 card?  Is Ace 1 or 10, or 1 or 11?

Body:
This is not a duplicate. I understand how easy this is if you can sort, but I am not allowed to use the sort method for arrays and I am not allowed to write my own. I can't find any help with this anywhere, including StackOverflow.

In this scenario, I have a method that is supposed to check whether or not a five card hand is a straight. I have a card object that holds a value (integer) and a suit (integer). I also have some rules about implementing this method.

There are no face cards besides the ace

The ace can count as either a 1 or a 10 but not both

A straight cannot wrap around

You cannot use the sorting method for arrays or write your own sorting method

That last rule is what is killing me. I have an array of cards. If I could just sort it, this would be so easy but I can't even write my own method to sort the array. For my other methods it simple to iterate through the hand and store the information about the hand in two separate arrays like this:

private static int[] cardValues = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
private static int[] cardSuits = {0, 0, 0, 0, 0};

private static void evaluationHelper(Card[] cards) {
    for (int i = 0; i < cardValues.length; i++) {
        cardValues[i] = 0;
    }

    for (int i = 0; i <cardSuits.length; i++) {
        cardSuits[i] = 0;
    }

    for (int i = 0; i < 5; i++) {
        cardValues[cards[i].getValue() - 1]++;
        cardSuits[cards[i].getSuit()]++;

        if (cards[i].getValue() == 1) {
            cardValues[9]++;
        }
    }
}

So in my first attempt to solve this issue I tried something like this:

public static boolean hasStraight(Card [] cards) {
    int sequenCounter = 0;
    evaluationHelper(cards);

    for (int i = 0; i < cardValues.length; i++) {
        if (sequenCounter != 5) {
            if (cardValues[i] != 0) {
                sequenCounter++;
            } else {
                sequenCounter = 0;
            }
        } else {
            return true;
        }
    }
    return false;
}

That didn't work. So then I tried this:

public static boolean hasStraight(Card [] cards) {
    int min = 100, max = 0;
    boolean seenSix = false, seenAce = false;
    evaluationHelper(cards);

    for (int i = 0; i < cards.length; i++) {
        if (cards[i].getValue() > max) {
            max = cards[i].getValue();
        }

        if (cards[i].getValue() < min) {
            min = cards[i].getValue();
        }

        if (cards[i].getValue() == 6) {
            seenSix = true;
        }

        if (cards[i].getValue() == 1) {
            seenAce = true;
        }
    }

    if (seenSix && seenAce) {
        max = 10;
    }

    if (max - min == 4) {
        return true;
    }
    return false;
}

That doesn't work either. I'm getting frustrated as both of these attempts went through many different changes over the course of overs and nothing has worked. I can't even figure out why they aren't working. The only information I have is that this method isn't spitting out the correct value. I don't know what values are being passed to the method. I don't know what the method is spitting out during the test. It could be spitting out false when it's supposed to be spitting true or vice versa. Please help!


问:
Stream output with Jenkins Pipeline + Docker/VM
I'm using Jenkins Pipeline for my jobs and they run either in a Docker container or a VM.

The problem is that I have some tasks that last some time and I would like to stream the output of the commands in the console while the job is running.

Indeed, in the groovy script, I do this kind of stuff:

```<code> stage('test') {
  TEST = sh (
     script: '''cd $WORKSPACE
                make test
             ''',
     returnStdout: true
  ).trim()
  echo "TEST: ${TEST}"
}
</code>```

With these lines, the output is printed in the job console only after the command has finished. If "make test" takes a long time, that's not great...

Any idea?

答:
Just remove all the code and it will do what you want. :)</p>

```<code>stage('test') {
  sh (
    '''cd $WORKSPACE
        make test
    '''
  )
}
</code>```

Body:
I'm using Jenkins Pipeline for my jobs and they run either in a Docker container or a VM.

The problem is that I have some tasks that last some time and I would like to stream the output of the commands in the console while the job is running.

Indeed, in the groovy script, I do this kind of stuff:

 stage('test') {
  TEST = sh (
     script: '''cd $WORKSPACE
                make test
             ''',
     returnStdout: true
  ).trim()
  echo "TEST: ${TEST}"
}

With these lines, the output is printed in the job console only after the command has finished. If "make test" takes a long time, that's not great...

Any idea?

Body:
Just remove all the code and it will do what you want. :)

stage('test') {
  sh (
    '''cd $WORKSPACE
        make test
    '''
  )
}


问:
Robust relative paths in doctests
I have a function that takes a path to a file as an argument.

```<code>output = process('path/to/file.txt')
</code>```

I was wondering if I could easily doctest such a function. I supply an example input file somewhere along the source code, and I can compare the output to what I expect (a string, a python object, or possibly the content of another file).

The issue is that the path in my test is necessarily relative. Relative to the working directory of the calling script that is.

This means that all the paths in the docstring must be aware of the test suite's entry point. Clearly that is not ideal. In a more sophisticated testing environment I would be able to use __file__ to make the path absolute, but in a doctest, __file__ does not exist.

What is the usual set-up when supplying stimuli as a file?

I hope to hear some better solutions than just 'always run the test suite from the same working directory'.

EDIT: I'd like to run the doctests from a centralized test suite entry point.

```<code>import doctest
import mymodule

doctest.testmod(mymodule)
</code>```

答:
Since you are doing this at the module level, I assume that you have also packaged your modules as a proper Python package using something like setuptools and be deployed onto some environment where the tests will then be executed.  Also, you are only partially correct in the assumption where __file__ doesn't exist - it also is not defined for a module imported from a zipped Python egg (which are getting more rare as wheels became the de facto packaging method, but they can and do exist).

There are a number of possible approaches, varying in complexity and trade offs and whether it works depend on how the module(s) to be tested are structured.

1) (Not recommended, but included anyway because sometimes this works best in the cases of simplest examples.) The laziest, but the most stable, self-contained and cross platform way - and it assumes that the file opening methods is only done in that one module that was to be tested and are done using the same call (e.g. open), the usage of extraglobs argument can be used to substitute the open call.  e.g.

```<code>from io import StringIO
import doctest
import mymodule

files = {
    'path/to/file1.txt': '... contents of file1.txt ...',
    'path/to/file2.txt': '... contents of file2.txt ...',
}

def lazyopen(p, flag='r'):
    result = StringIO(files[p] if flag == 'r' else '')
    result.name = p
    return result

doctest.testmod(mymodule, extraglobs={'open': lazyopen})
</code>```

2) Create a real testsuite, rather than using the builtin ones through doctest.testmod

While the shorthand is useful, it is too limited as it is standalone, it cannot be used in conjunction with other testsuites that might get built.  Consider creating a dedicated test module (e.g. mymodule/tests.py).  I generally prefer creating a directory named mymodule/tests, with unittests named something like test_mysubmodule.py, and a __init__.py that contain the test_suite setup like so

```<code>def make_suite():
    import mymodule
    import os

    def setUp(suite):
        suite.olddir = os.getcwd()  # save the current working directory
        os.chdir(targetdir)  # need to define targetdir

    def tearDown(suite):
        os.chdir(suite.olddir)  # restore the original working directory

    return doctest.DocTestSuite(mymodule, setUp=setUp, tearDown=tearDown)
</code>```

So we have covered the basic, but targetdir needs to be defined.  Again, multiple things you can consider:

1) Create a temporary directory and populate the directory with the required files using setup, and os.chdir to that, and remove the temporary directory in tearDown.  Either manually write data stored as strings inside the test module, copy from your project or extract from an archive, but how do we actually get those?  Which leads to...

2) If the source files are inside your project, and setuptools is available/installed in the environment, simply use pkg_resources.resource_filename to get the location, and assign targetdir to that.  The setUp might now look something like

```<code>    def setUp(suite):
        suite.olddir = os.getcwd()
        targetdir = pkg_resources.resource_filename('mymodule', '')
        os.chdir(targetdir)
</code>```

Also, finally, as this is now a real test suite that is produced by the make_suite function within mymodules.tests, the execution of that must be done using a testrunner, which fortunately is included as part of the default unittest framework as a simple command which can be done like so:

```<code>$ python -m unittest mymodule.tests.make_suite
.
----------------------------------------------------------------------
Ran 1 test in 0.014s

OK
</code>```

Also, as that is a real test suite, it can be integrated with the testsuite globbing from the unittest module to combine everything into a single complete test suite for your entire package.

```<code>def make_suite():
    # ... the other setup code

    # this loads all unittests in mymodule from `test_*.py` files
    # inside `mymodule.tests`
    test_suite = test_loader.discover(
        'mymodule.tests', pattern='test_*.py')
    test_suite.addTest(
        doctest.DocTestSuite(mymodule, setUp=setUp, tearDown=tearDown))
    return test_suite
</code>```

Again, the python -m unittest command may be used to execute the tests returned by the complete test suite.

Title: Robust relative paths in doctests

Body:
I have a function that takes a path to a file as an argument.

output = process('path/to/file.txt')

I was wondering if I could easily doctest such a function. I supply an example input file somewhere along the source code, and I can compare the output to what I expect (a string, a python object, or possibly the content of another file).

The issue is that the path in my test is necessarily relative. Relative to the working directory of the calling script that is.

This means that all the paths in the docstring must be aware of the test suite's entry point. Clearly that is not ideal. In a more sophisticated testing environment I would be able to use __file__ to make the path absolute, but in a doctest, __file__ does not exist.

What is the usual set-up when supplying stimuli as a file?

I hope to hear some better solutions than just 'always run the test suite from the same working directory'.

EDIT: I'd like to run the doctests from a centralized test suite entry point.

import doctest
import mymodule

doctest.testmod(mymodule)

Body:
Since you are doing this at the module level, I assume that you have also packaged your modules as a proper Python package using something like setuptools and be deployed onto some environment where the tests will then be executed.  Also, you are only partially correct in the assumption where __file__ doesn't exist - it also is not defined for a module imported from a zipped Python egg (which are getting more rare as wheels became the de facto packaging method, but they can and do exist).

There are a number of possible approaches, varying in complexity and trade offs and whether it works depend on how the module(s) to be tested are structured.

1) (Not recommended, but included anyway because sometimes this works best in the cases of simplest examples.) The laziest, but the most stable, self-contained and cross platform way - and it assumes that the file opening methods is only done in that one module that was to be tested and are done using the same call (e.g. open), the usage of extraglobs argument can be used to substitute the open call.  e.g.

from io import StringIO
import doctest
import mymodule

files = {
    'path/to/file1.txt': '... contents of file1.txt ...',
    'path/to/file2.txt': '... contents of file2.txt ...',
}

def lazyopen(p, flag='r'):
    result = StringIO(files[p] if flag == 'r' else '')
    result.name = p
    return result

doctest.testmod(mymodule, extraglobs={'open': lazyopen})

2) Create a real testsuite, rather than using the builtin ones through doctest.testmod

While the shorthand is useful, it is too limited as it is standalone, it cannot be used in conjunction with other testsuites that might get built.  Consider creating a dedicated test module (e.g. mymodule/tests.py).  I generally prefer creating a directory named mymodule/tests, with unittests named something like test_mysubmodule.py, and a __init__.py that contain the test_suite setup like so

def make_suite():
    import mymodule
    import os

    def setUp(suite):
        suite.olddir = os.getcwd()  # save the current working directory
        os.chdir(targetdir)  # need to define targetdir

    def tearDown(suite):
        os.chdir(suite.olddir)  # restore the original working directory

    return doctest.DocTestSuite(mymodule, setUp=setUp, tearDown=tearDown)

So we have covered the basic, but targetdir needs to be defined.  Again, multiple things you can consider:

1) Create a temporary directory and populate the directory with the required files using setup, and os.chdir to that, and remove the temporary directory in tearDown.  Either manually write data stored as strings inside the test module, copy from your project or extract from an archive, but how do we actually get those?  Which leads to...

2) If the source files are inside your project, and setuptools is available/installed in the environment, simply use pkg_resources.resource_filename to get the location, and assign targetdir to that.  The setUp might now look something like

    def setUp(suite):
        suite.olddir = os.getcwd()
        targetdir = pkg_resources.resource_filename('mymodule', '')
        os.chdir(targetdir)

Also, finally, as this is now a real test suite that is produced by the make_suite function within mymodules.tests, the execution of that must be done using a testrunner, which fortunately is included as part of the default unittest framework as a simple command which can be done like so:

$ python -m unittest mymodule.tests.make_suite
.
----------------------------------------------------------------------
Ran 1 test in 0.014s

OK

Also, as that is a real test suite, it can be integrated with the testsuite globbing from the unittest module to combine everything into a single complete test suite for your entire package.

def make_suite():
    # ... the other setup code

    # this loads all unittests in mymodule from `test_*.py` files
    # inside `mymodule.tests`
    test_suite = test_loader.discover(
        'mymodule.tests', pattern='test_*.py')
    test_suite.addTest(
        doctest.DocTestSuite(mymodule, setUp=setUp, tearDown=tearDown))
    return test_suite

Again, the python -m unittest command may be used to execute the tests returned by the complete test suite.


问:
Android Studio Database connection using Response and JSON
I'm trying to make a conection with my remote Database using a PHP file and JSONObject, but the code is skiping the Response.Listener and I don't know why...
Here my Main that contains the Response.Listener:

```<code>Response.Listener<String> responseListener = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {

                        Toast.makeText(Register.this, "Test00", Toast.LENGTH_SHORT).show();

                        JSONObject jsonObject = new JSONObject(response);
                        boolean success = jsonObject.getBoolean("success");

                        if(success)
                        {
                            Toast.makeText(Register.this, "Test01", Toast.LENGTH_SHORT).show();
                        }
                        else
                        {
                            Toast.makeText(Register.this, "Error", Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            };

            RegisterRequest registerRequest = new RegisterRequest(email, username, usernick, password, birthdate, gender, responseListener);
            RequestQueue queue = Volley.newRequestQueue(Register.this);
            queue.add(registerRequest);
</code>```

and here my RegisterRequest class:

```<code>public class RegisterRequest extends StringRequest {

private static final String REGISTER_REQUEST_URL = "kameo.com.br/control/ayzac_control_signin_mobile.php";
private Map<String, String> params;

public RegisterRequest(String email, String name, String nickname, String password, String date, String gender, Response.Listener<String> listener)
{
    super(Method.POST, REGISTER_REQUEST_URL, listener, null);
    params = new HashMap<>();
    params.put("userEmail", email);
    params.put("userName", name);
    params.put("userNickname", nickname);
    params.put("userPassword", password);
    params.put("userBirth", date);
    params.put("userGender", gender);
}

@Override
public Map<String, String> getParams() {
    return params;
}
}
</code>```

答:
I tested your URL and there is an error there: kameo.com.br/control/ayzac_control_signin_mobile.php

Also you need to read the error from your server response, try to create an error listener:

```<code>Response.Listener<String> errorListener = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Error : " + error.getMessage());
            }
       };
</code>```

And pass into your RegisterRequest constructor

Body:
I'm trying to make a conection with my remote Database using a PHP file and JSONObject, but the code is skiping the Response.Listener and I don't know why...
Here my Main that contains the Response.Listener:

Response.Listener<String> responseListener = new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {

                        Toast.makeText(Register.this, "Test00", Toast.LENGTH_SHORT).show();

                        JSONObject jsonObject = new JSONObject(response);
                        boolean success = jsonObject.getBoolean("success");

                        if(success)
                        {
                            Toast.makeText(Register.this, "Test01", Toast.LENGTH_SHORT).show();
                        }
                        else
                        {
                            Toast.makeText(Register.this, "Error", Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            };

            RegisterRequest registerRequest = new RegisterRequest(email, username, usernick, password, birthdate, gender, responseListener);
            RequestQueue queue = Volley.newRequestQueue(Register.this);
            queue.add(registerRequest);

and here my RegisterRequest class:

public class RegisterRequest extends StringRequest {

private static final String REGISTER_REQUEST_URL = "kameo.com.br/control/ayzac_control_signin_mobile.php";
private Map<String, String> params;

public RegisterRequest(String email, String name, String nickname, String password, String date, String gender, Response.Listener<String> listener)
{
    super(Method.POST, REGISTER_REQUEST_URL, listener, null);
    params = new HashMap<>();
    params.put("userEmail", email);
    params.put("userName", name);
    params.put("userNickname", nickname);
    params.put("userPassword", password);
    params.put("userBirth", date);
    params.put("userGender", gender);
}

@Override
public Map<String, String> getParams() {
    return params;
}
}

Body:
I tested your URL and there is an error there: kameo.com.br/control/ayzac_control_signin_mobile.php

Also you need to read the error from your server response, try to create an error listener:

Response.Listener<String> errorListener = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Error : " + error.getMessage());
            }
       };

And pass into your RegisterRequest constructor


问:
Compute multivariate normal density for multiple datapoints
If I have N datapoints, each with D dimensions, is there a way to quickly compute the value of multivariate gaussian pdf for each datapoint without using a for loop? For one datapoint x with D dimensions, I can calculate the value of the pdf as follows (scipy):

```<code>multivariate_normal.pdf(x, mean, cov)
</code>```

where x is 1xD, mean is 1xD, cov is DxD. I want to compute this so that I get an array of pdfs, length N, by doing something like:

```<code>multivariate_normal.pdf(X, mean, cov)
</code>```

where X is NxD. Each datapoint has the same mean and covariance. What is the most efficient way of doing this?

答:
Just pass a suitable array x, there are no issues. Here the pdf is evaluated at 5 random points of 2-dimensional space.

```<code>mean = np.array([3, 2])
cov = np.array([[4, 1], [1, 5]])
x = np.random.uniform(size=(5, 2))

multivariate_normal.pdf(x, mean, cov)
</code>```

returns

```<code>array([ 0.01424279,  0.01537563,  0.01758953,  0.01994425,  0.01584357])
</code>```

Body:
If I have N datapoints, each with D dimensions, is there a way to quickly compute the value of multivariate gaussian pdf for each datapoint without using a for loop? For one datapoint x with D dimensions, I can calculate the value of the pdf as follows (scipy):

multivariate_normal.pdf(x, mean, cov)

where x is 1xD, mean is 1xD, cov is DxD. I want to compute this so that I get an array of pdfs, length N, by doing something like:

multivariate_normal.pdf(X, mean, cov)

where X is NxD. Each datapoint has the same mean and covariance. What is the most efficient way of doing this?

Body:
Just pass a suitable array x, there are no issues. Here the pdf is evaluated at 5 random points of 2-dimensional space.

mean = np.array([3, 2])
cov = np.array([[4, 1], [1, 5]])
x = np.random.uniform(size=(5, 2))

multivariate_normal.pdf(x, mean, cov)

returns

array([ 0.01424279,  0.01537563,  0.01758953,  0.01994425,  0.01584357])


问:
How to check subsequent elements of string in python using iterators?
I have a sentence that I want to parse to check for some conditions:

a) If there is a period and it is followed by a whitespace followed by a lowercase letter

b) If there is a period internal to a sequence of letters with no adjacent whitespace (i.e. www.abc.com)

c) If there is a period followed by a whitespace followed by an uppercase letter and preceded by a short list of titles (i.e. Mr., Dr. Mrs.)

Currently I am iterating through the string (line) and using the next() function to see whether the next character is a space or lowercase, etc. And then I just loop through the line. But how would I check to see what the next, next character would be? And how would I find the previous ones?

```<code>line = "This is line.1 www.abc.com. Mr."

t = iter(line)
b = next(t)

for i in line[:len(line)-1]:
    a = next(t)
    if i == "." and (a.isdigit()): #for example, this checks to see if the     value after the period is a number
         print("True")
</code>```

Any help would be appreciated. Thank you.

答:
You can use multiple next operations to get more data

```<code>line = "This is line.1 www.abc.com. Mr."

t = iter(line)
b = next(t)

for i in line[:len(line)-1]:
    a = next(t)
    c = next(t)
    if i == "." and (a.isdigit()): #for example, this checks to see if the     value after the period is a number
         print("True")
</code>```

You can get previous ones by saving your iterations to a temporary list

Body:
I have a sentence that I want to parse to check for some conditions:

a) If there is a period and it is followed by a whitespace followed by a lowercase letter

b) If there is a period internal to a sequence of letters with no adjacent whitespace (i.e. www.abc.com)

c) If there is a period followed by a whitespace followed by an uppercase letter and preceded by a short list of titles (i.e. Mr., Dr. Mrs.)

Currently I am iterating through the string (line) and using the next() function to see whether the next character is a space or lowercase, etc. And then I just loop through the line. But how would I check to see what the next, next character would be? And how would I find the previous ones?

line = "This is line.1 www.abc.com. Mr."

t = iter(line)
b = next(t)

for i in line[:len(line)-1]:
    a = next(t)
    if i == "." and (a.isdigit()): #for example, this checks to see if the     value after the period is a number
         print("True")

Any help would be appreciated. Thank you.

Body:
You can use multiple next operations to get more data

line = "This is line.1 www.abc.com. Mr."

t = iter(line)
b = next(t)

for i in line[:len(line)-1]:
    a = next(t)
    c = next(t)
    if i == "." and (a.isdigit()): #for example, this checks to see if the     value after the period is a number
         print("True")

You can get previous ones by saving your iterations to a temporary list


问:
yasm movsx, movsxd invalid size for operand 2
I am trying to assemble the code below using yasm. I have put 'here' comments where yasm reports the error "error: invalid size for operand 2". Why is this error happening ?</p>

```<code>segment .data
    a db 25
    b dw 0xffff
    c dd 3456
    d dq -14

segment .bss
    res resq 1

segment .text
    global _start

_start:
    movsx rax, [a] ; here
    movsx rbx, [b] ; here
    movsxd rcx, [c] ; here
    mov rdx, [d]
    add rcx, rdx
    add rbx, rcx
    add rax, rbx
    mov [res], rax
    ret
</code>```

答:
For most instructions, the width of the register operand implies the width of the memory operand, because both operands have to be the same size.  e.g. mov rdx, [d] implies mov rdx, qword [d] because you used a 64-bit register.

But the same movsx / movzx mnemonics are used for the byte-source and word-source opcodes, so it's ambiguous unless the source is a register (like movzx eax, cl).  Another example is crc32 r32, r/m8 vs. r/m16 vs. r/m32.  (Unlike movsx/zx, its source size can be as wide as the operand-size.)

movsx / movzx with a memory source always need the width of the memory operand specified explicitly.

The movsxd mnemonic is supposed to imply a 32-bit source size.  movsxd rcx, [c] assembles with NASM, but apparently not with YASM.  YASM requires you to write dword, even though it doesn't accept byte, word, or qword there, and it doesn't accept movsx  rcx, dword [c] either (i.e. it requires the movsxd mnemonic for 32-bit source operands).

In NASM, movsx  rcx, dword [c] assembles to movsxd, but movsxd   rcx, word [c] is still rejected.  i.e. in NASM, plain movsx is fully flexible, but movsxd is still rigid.  I'd still recommend using dword to make the width of the load explicit, for the benefit of humans.

```<code>movsx    rax,  byte [a]
movsx    rbx,  word [b]
movsxd   rcx, dword [c]
</code>```

Note that the "operand size" of the instruction (as determined by the operand-size prefix to make it 16-bit, or REX.W=1 to make it 64-bit) is the destination width for movsx / movzx.  Different source sizes use different opcodes.

In case it's not obvious, there's no movzxd because 32-bit mov already zero-extends to 64-bit implicitly.  movsxd  eax, ecx is encodeable, but not recommended (use mov instead).

In AT&T syntax, you need to explicitly specify both the source and destination width in the mnemonic, like movsbq (%rsi), %rax.  GAS won't let you write movsb (%rsi), %eax to infer a destination width (operand-size) because movsb/movsw/etc are the mnemonics for string-move instructions with implicit (%rsi), (%rdi) operands.

Fun fact: GAS and clang do allow it for things like movzb (%rsi), %eax as movzbl, but GAS only has extra logic to allow disambiguation (not just inferring size) based on operands when it's necessary, like movsd (%rsi), %xmm0 vs. movsd.  (Clang12.0.1 actually does accept movsb (%rcx), %eax as movsbl, but GAS 2.36.1 doesn't, so for portability it's best to be explicit with sign-extension, and not a bad idea for zero-extension too.)

Other stuff about your source code:

NASM/YASM allow you to use the segment keyword instead of section, but really you're giving ELF section names, not executable segment names.  Also, you can put read-only data in section .rodata (which is linked as part of the text segment).  What's the difference of section and segment in ELF file format.

You can't ret from _start.  It's not a function, it's your ELF entry point.  The first thing on the stack is argc, not a valid return address.  Use this to exit cleanly:

```<code>xor    edi,edi
mov    eax, 231
syscall            ; sys_exit_group(0)
</code>```

See the x86 tag wiki for links to more useful guides (and debugging tips at the bottom).

Body:
I am trying to assemble the code below using yasm. I have put 'here' comments where yasm reports the error "error: invalid size for operand 2". Why is this error happening ?

segment .data
    a db 25
    b dw 0xffff
    c dd 3456
    d dq -14

segment .bss
    res resq 1

segment .text
    global _start

_start:
    movsx rax, [a] ; here
    movsx rbx, [b] ; here
    movsxd rcx, [c] ; here
    mov rdx, [d]
    add rcx, rdx
    add rbx, rcx
    add rax, rbx
    mov [res], rax
    ret

Body:
For most instructions, the width of the register operand implies the width of the memory operand, because both operands have to be the same size.  e.g. mov rdx, [d] implies mov rdx, qword [d] because you used a 64-bit register.

But the same movsx / movzx mnemonics are used for the byte-source and word-source opcodes, so it's ambiguous unless the source is a register (like movzx eax, cl).  Another example is crc32 r32, r/m8 vs. r/m16 vs. r/m32.  (Unlike movsx/zx, its source size can be as wide as the operand-size.)

movsx / movzx with a memory source always need the width of the memory operand specified explicitly.

The movsxd mnemonic is supposed to imply a 32-bit source size.  movsxd rcx, [c] assembles with NASM, but apparently not with YASM.  YASM requires you to write dword, even though it doesn't accept byte, word, or qword there, and it doesn't accept movsx  rcx, dword [c] either (i.e. it requires the movsxd mnemonic for 32-bit source operands).

In NASM, movsx  rcx, dword [c] assembles to movsxd, but movsxd   rcx, word [c] is still rejected.  i.e. in NASM, plain movsx is fully flexible, but movsxd is still rigid.  I'd still recommend using dword to make the width of the load explicit, for the benefit of humans.

movsx    rax,  byte [a]
movsx    rbx,  word [b]
movsxd   rcx, dword [c]

Note that the "operand size" of the instruction (as determined by the operand-size prefix to make it 16-bit, or REX.W=1 to make it 64-bit) is the destination width for movsx / movzx.  Different source sizes use different opcodes.

In case it's not obvious, there's no movzxd because 32-bit mov already zero-extends to 64-bit implicitly.  movsxd  eax, ecx is encodeable, but not recommended (use mov instead).

In AT&T syntax, you need to explicitly specify both the source and destination width in the mnemonic, like movsbq (%rsi), %rax.  GAS won't let you write movsb (%rsi), %eax to infer a destination width (operand-size) because movsb/movsw/etc are the mnemonics for string-move instructions with implicit (%rsi), (%rdi) operands.

Fun fact: GAS and clang do allow it for things like movzb (%rsi), %eax as movzbl, but GAS only has extra logic to allow disambiguation (not just inferring size) based on operands when it's necessary, like movsd (%rsi), %xmm0 vs. movsd.  (Clang12.0.1 actually does accept movsb (%rcx), %eax as movsbl, but GAS 2.36.1 doesn't, so for portability it's best to be explicit with sign-extension, and not a bad idea for zero-extension too.)

Other stuff about your source code:

NASM/YASM allow you to use the segment keyword instead of section, but really you're giving ELF section names, not executable segment names.  Also, you can put read-only data in section .rodata (which is linked as part of the text segment).  What's the difference of section and segment in ELF file format.

You can't ret from _start.  It's not a function, it's your ELF entry point.  The first thing on the stack is argc, not a valid return address.  Use this to exit cleanly:

xor    edi,edi
mov    eax, 231
syscall            ; sys_exit_group(0)

See the x86 tag wiki for links to more useful guides (and debugging tips at the bottom).

ContentLicense: CC BY-SA 4.0


问:
3D model (dae format) shows in SceneKit editor, but not at runtime
I grabbed a simple pool table made in Blender from the web, exported it to dae format, added it into a scene by dragging the file and dropping it into the scene editor. The pool table shows fine there, however, when testing it on device/sim the model isn't visible and I just get a black screen. I can confirm it's something related to that model since I created a sphere from the primitive shapes in scene editor and that shows up fine. Also somehow the 3D model is there because the sphere sits on top of it. The sphere has a rigid body setup and its affected by gravity and it doesn't fall because of the pool table.</p>

答:
I had the same problem when I dragged and dropped a .obj file into XCode (into the scene.scnassets folder). The model would appear in the scene editor but wouldn't be there at runtime (on the simulator or on a device).

Solved the problem by adding the .obj file to the scene.scnassets folder in Finder, rather than XCode. The file then appears in XCode (refreshes automatically). I then selected the .obj file within XCode and clicked Editor > Convert to .scn file.

The texture will not be there, so you need to do the same process of copying the .png file into the scene.scnassets folder in Finder, and then dragging and dropping the .png file onto the Diffuse property.


问:
PHP: Cast variable to null
I just stumbled upon a thing in the PHP manual that is new to me...

Casting a variable to null will remove the variable and unset its value. (Source)

Now I wonder how this can be done... I tried (null) and (NULL) but it seems to be interpreted as the value null, not the type null.
I know this question must sound ridiculous, but does somebody know how to cast to null?

答: use (unset) instead of (null).</p>

Title: PHP: Cast variable to null

Body: use (unset) instead of (null).


问:
Iterate Through and Rename All Tables w/ Object Qualifiers MSSQL
I need to iterate through all of the tables that begin with a specific prefix to rename them.  The code I've tried is below, but it ends with one of two results, either it crashes SSMS (sometimes), or I get the error message below for each table.  I've tried with and with out dbo.

Can anyone tell me what I'm doing wrong or perhaps suggest a better way to do this?

No item by the name of 'dbo.prefix_TableName' could be found in the current database 'DatabaseName', given that @itemtype was input as '(null)'.

Here's the code I'm running...

```<code>SET NOCOUNT ON;
USE [DatabaseName];

DECLARE @oq NVARCHAR(5), @tableName NVARCHAR(128), @newTableName NVARCHAR(128);
SET @oq = N'prefix_';

/*
    find and rename all tables
*/

DECLARE [tableCursor] CURSOR FOR
    SELECT [TABLE_NAME] FROM INFORMATION_SCHEMA.TABLES
    WHERE [TABLE_TYPE] = 'BASE TABLE' AND [TABLE_NAME] LIKE @oq + '%'
    ORDER BY [TABLE_NAME];

OPEN [tableCursor]

FETCH NEXT FROM [tableCursor] INTO @tableName

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @newTableName = REPLACE(@tableName, @oq, N'');
    EXEC('EXEC sp_rename ''dbo.' + @tableName + ''', ''' + @newTableName + '''');
END

CLOSE [tableCursor];
DEALLOCATE [tableCursor];
</code>```

答:
A simpler solution without cursors

```<code>declare @oq nvarchar(max) = N'prefix_'
declare @cmd nvarchar(max)
select @cmd = a from (
    select 'EXEC sp_rename ''' + TABLE_NAME + ''', ''' + REPLACE(TABLE_NAME, @oq, N'') + ''' '
    from INFORMATION_SCHEMA.TABLES
    for xml path('')
) t(a)
exec sp_executesql @cmd
</code>```

In your example nvarchar(5) causes truncation, you probably need nvarchar(7) or nvarchar(max).

Body:
I need to iterate through all of the tables that begin with a specific prefix to rename them.  The code I've tried is below, but it ends with one of two results, either it crashes SSMS (sometimes), or I get the error message below for each table.  I've tried with and with out dbo.

Can anyone tell me what I'm doing wrong or perhaps suggest a better way to do this?

No item by the name of 'dbo.prefix_TableName' could be found in the current database 'DatabaseName', given that @itemtype was input as '(null)'.

Here's the code I'm running...

SET NOCOUNT ON;
USE [DatabaseName];

DECLARE @oq NVARCHAR(5), @tableName NVARCHAR(128), @newTableName NVARCHAR(128);
SET @oq = N'prefix_';

/*
    find and rename all tables
*/

DECLARE [tableCursor] CURSOR FOR
    SELECT [TABLE_NAME] FROM INFORMATION_SCHEMA.TABLES
    WHERE [TABLE_TYPE] = 'BASE TABLE' AND [TABLE_NAME] LIKE @oq + '%'
    ORDER BY [TABLE_NAME];

OPEN [tableCursor]

FETCH NEXT FROM [tableCursor] INTO @tableName

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @newTableName = REPLACE(@tableName, @oq, N'');
    EXEC('EXEC sp_rename ''dbo.' + @tableName + ''', ''' + @newTableName + '''');
END

CLOSE [tableCursor];
DEALLOCATE [tableCursor];

Body:
A simpler solution without cursors

declare @oq nvarchar(max) = N'prefix_'
declare @cmd nvarchar(max)
select @cmd = a from (
    select 'EXEC sp_rename ''' + TABLE_NAME + ''', ''' + REPLACE(TABLE_NAME, @oq, N'') + ''' '
    from INFORMATION_SCHEMA.TABLES
    for xml path('')
) t(a)
exec sp_executesql @cmd

In your example nvarchar(5) causes truncation, you probably need nvarchar(7) or nvarchar(max).


问:
Can't integrate INNER JOIN in my query
Hello I'm using the query below to select the latest message from each unique conversation. Everything works perfectly except when I try to integrate an INNER JOIN to try to link the user's user_id with their username in the users table.

I've tried pretty much every combination to integrate the INNER JOIN so I decided to separate it from the working query until I get help.

I made a Fiddle http://sqlfiddle.com/#!9/a9bbc/1   I just want user_id on the right to print the user's username

```<code>SELECT message_id,
       msg,
       user_id
FROM   messages
   JOIN (SELECT user_id,
                Max(dat) m
         FROM   ((SELECT message_id,
                         recipient_id user_id,
                         dat
                  FROM   messages
                  WHERE  owner_id = 1)
                 UNION
                 (SELECT message_id,
                         owner_id user_id,
                         dat
                  FROM   messages
                  WHERE  recipient_id = 1)) t1
         GROUP  BY user_id) t2
     ON ( ( owner_id = 1
            AND recipient_id = user_id )
           OR ( owner_id = user_id
                AND recipient_id = 1 ) )
        AND ( dat = m )
 ORDER  BY dat DESC
</code>```

.

```<code>users.username INNER JOIN users ON messages.user_id = users.user_id;
</code>```

答:
When you have joined any tables or subqueries, you really really really need to include table name or table aliases with all column references. I changed the maximum dat to maxdat below so I could use m for messages. </p>

```<code>SELECT
      m.message_id
    , m.msg
    , m.user_id
FROM messages m
JOIN (
      SELECT
            user_id
          , MAX(dat) maxdat
      FROM (
            (SELECT
                  message_id
                , recipient_id user_id
                , dat
            FROM messages
            WHERE owner_id = 1)
            UNION
            (SELECT
                  message_id
                , owner_id user_id
                , dat
            FROM messages
            WHERE recipient_id = 1)
      ) t1
      GROUP BY
            user_id
) t2 ON (
         (m.owner_id = 1 AND m.recipient_id = t2.user_id)
      OR (m.owner_id = t2.user_id AND m.recipient_id = 1)
        )
      AND (m.dat = t2.maxdat)
ORDER BY
      m.dat DESC
</code>```

Title: Can't integrate INNER JOIN in my query

Body:
Hello I'm using the query below to select the latest message from each unique conversation. Everything works perfectly except when I try to integrate an INNER JOIN to try to link the user's user_id with their username in the users table.

I've tried pretty much every combination to integrate the INNER JOIN so I decided to separate it from the working query until I get help.

I made a Fiddle http://sqlfiddle.com/#!9/a9bbc/1   I just want user_id on the right to print the user's username

SELECT message_id,
       msg,
       user_id
FROM   messages
   JOIN (SELECT user_id,
                Max(dat) m
         FROM   ((SELECT message_id,
                         recipient_id user_id,
                         dat
                  FROM   messages
                  WHERE  owner_id = 1)
                 UNION
                 (SELECT message_id,
                         owner_id user_id,
                         dat
                  FROM   messages
                  WHERE  recipient_id = 1)) t1
         GROUP  BY user_id) t2
     ON ( ( owner_id = 1
            AND recipient_id = user_id )
           OR ( owner_id = user_id
                AND recipient_id = 1 ) )
        AND ( dat = m )
 ORDER  BY dat DESC

.

users.username INNER JOIN users ON messages.user_id = users.user_id;

Body:
When you have joined any tables or subqueries, you really really really need to include table name or table aliases with all column references. I changed the maximum dat to maxdat below so I could use m for messages.

SELECT
      m.message_id
    , m.msg
    , m.user_id
FROM messages m
JOIN (
      SELECT
            user_id
          , MAX(dat) maxdat
      FROM (
            (SELECT
                  message_id
                , recipient_id user_id
                , dat
            FROM messages
            WHERE owner_id = 1)
            UNION
            (SELECT
                  message_id
                , owner_id user_id
                , dat
            FROM messages
            WHERE recipient_id = 1)
      ) t1
      GROUP BY
            user_id
) t2 ON (
         (m.owner_id = 1 AND m.recipient_id = t2.user_id)
      OR (m.owner_id = t2.user_id AND m.recipient_id = 1)
        )
      AND (m.dat = t2.maxdat)
ORDER BY
      m.dat DESC


答:
If I understand correctly, you want the most recent messages where the send or recipient is "1" and associated user names.

That suggests:

```<code>select m.*, ur.username as recipient_name, us.username as sender_name
from messages m join
     users ur
     on m.recipient_id = ur.user_id join
     users us
     on m.sender_id = us.user_id
where m.date = (select max(m2.dat)
                from messages m2
                where 1 in (m2.recipient_id, m2.sender_id)
               ) and
      1 in (m.recipient_id, m.sender_id);
</code>```

EDIT:

Based on your SQL Fiddle the above understanding is not correct.  You want to consider pairs of recipients, so I think you want:

```<code>select m.*, ur.username as recipient_name, us.username as sender_name
from messages m left join
     users ur
     on m.recipient_id = ur.user_id left join
     users us
     on m.owner_id = us.user_id
where m.dat = (select max(m2.dat)
               from messages m2
               where (m2.recipient_id, m2.owner_id) = (m.recipient_id, m.owner_id) or
                     (m2.recipient_id, m2.owner_id) = (m.owner_id, m.recipient_id)
              ) and
      1 in (m.recipient_id, m.owner_id);
</code>```

Here is the SQL Fiddle.

If the ordering of the pair is import (so (1, 2) is different from (2, 1) remove the second condition in the innermost where clause.

Title: Can't integrate INNER JOIN in my query

Body:
If I understand correctly, you want the most recent messages where the send or recipient is "1" and associated user names.

That suggests:

select m.*, ur.username as recipient_name, us.username as sender_name
from messages m join
     users ur
     on m.recipient_id = ur.user_id join
     users us
     on m.sender_id = us.user_id
where m.date = (select max(m2.dat)
                from messages m2
                where 1 in (m2.recipient_id, m2.sender_id)
               ) and
      1 in (m.recipient_id, m.sender_id);

EDIT:

Based on your SQL Fiddle the above understanding is not correct.  You want to consider pairs of recipients, so I think you want:

select m.*, ur.username as recipient_name, us.username as sender_name
from messages m left join
     users ur
     on m.recipient_id = ur.user_id left join
     users us
     on m.owner_id = us.user_id
where m.dat = (select max(m2.dat)
               from messages m2
               where (m2.recipient_id, m2.owner_id) = (m.recipient_id, m.owner_id) or
                     (m2.recipient_id, m2.owner_id) = (m.owner_id, m.recipient_id)
              ) and
      1 in (m.recipient_id, m.owner_id);

Here is the SQL Fiddle.

If the ordering of the pair is import (so (1, 2) is different from (2, 1) remove the second condition in the innermost where clause.


问:
nodejs/npm/webpack: adding dependency as "file:/some/path" doesn't work
In /project-a, I have a tiny, default exported class that I have built, transpiled and successfully output into a /dist folder. The "main" entry for that project's package.json is therefore "./dist/index.js".

I wanted to try it out before publishing to npm (I am new at this).

In /project-b, I update the dependencies in the package.json:

```<code>"dependencies": {
...
"project-a": "file:C:\\foo\\bar\\project-a"
}
</code>```

And I do:

```<code>import MyClass from 'project-a';
</code>```

On build with webpack, I get an error along the lines of:

Module not found: Error: Can't resolve 'project-a' in 'C:\webpack\configfile\entry\point'

So basically, the path to the dependency inside my package.json is being completely ignored! Why? What am I doing wrong?

答:
OK so I figured it out. The tutorial I had been following only showed the end result of the package.json file... so I thought we just had to edit package.json directly with the needed path dependency. But it turns out you're supposed to let the package manager do the edits for you:

So the fix was:

delete my manual edits to package.json

run npm install file:../path/to/project-a

That seemed to make the package system aware of where everything was, and webpack in turn was able to find what it needed to build successfully

Body:
In /project-a, I have a tiny, default exported class that I have built, transpiled and successfully output into a /dist folder. The "main" entry for that project's package.json is therefore "./dist/index.js".

I wanted to try it out before publishing to npm (I am new at this).

In /project-b, I update the dependencies in the package.json:

"dependencies": {
...
"project-a": "file:C:\\foo\\bar\\project-a"
}

And I do:

import MyClass from 'project-a';

On build with webpack, I get an error along the lines of:

Module not found: Error: Can't resolve 'project-a' in 'C:\webpack\configfile\entry\point'

So basically, the path to the dependency inside my package.json is being completely ignored! Why? What am I doing wrong?


答:
Update: Since posting this 9 years ago, casting to unset has changed behavior and is deprecated.  The last defined behavior was equivalent to setting the variable equal to NULL.  You can either set the variable equal to NULL to retain the variable but indicate it has no value, or you can call the unset function to remove it entirely.

Original Answer:

```<code>$a = (unset) $a;
</code>```

See type casting.

Title: PHP: Cast variable to null

Body:
I just stumbled upon a thing in the PHP manual that is new to me...

Casting a variable to null will remove the variable and unset its value. (Source)

Now I wonder how this can be done... I tried (null) and (NULL) but it seems to be interpreted as the value null, not the type null.
I know this question must sound ridiculous, but does somebody know how to cast to null?

Body:
Update: Since posting this 9 years ago, casting to unset has changed behavior and is deprecated.  The last defined behavior was equivalent to setting the variable equal to NULL.  You can either set the variable equal to NULL to retain the variable but indicate it has no value, or you can call the unset function to remove it entirely.

Original Answer:

$a = (unset) $a;

See type casting.


问:
How can i draw bounding box and not use the normalized coordinate in tensorflow object-detection api
How can I draw bounding box and not use the normalized coordinate in tensorflow object-detection api? in object_detection_tutorial.ipynb , I noticed that default coordinate is in normalize coordinate and form of boxes is [xmin,ymin,xmax,ymax] and how to convert them to [image_lengthxmin, image_widthymin,image_lengthxmax,image_widthymax]?
I try to use

```<code>        boxes[0]=boxes[0]*200
        boxes[1]=boxes[1]*100
        boxes[2]=boxes[2]*200
        boxes[3]=boxes[3]*100
</code>```

but error happens:

```<code>---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-72-efcec9615ee3> in <module>()
     30                   feed_dict={image_tensor: image_np_expanded})
     31                 boxes[0]=boxes[0]*200
---> 32                 boxes[1]=boxes[1]*100
     33                 boxes[2]=boxes[2]*200
     34                 boxes[3]=boxes[3]*100
IndexError: index 1 is out of bounds for axis 0 with size 1
</code>```

答:
if you look at research/object_detection/utils/visualization_utils.py the boxes[0] is ymin not xmin when you multiply these coordinates with 100 or 200 make sure it is still in the image boundary (im_width, im_height).

 You can try boxes[0]* 100, boxes[1]* -200, boxes[2]* -100, boxes[3]* 200, this is similar to this code.

```<code>ymin = boxes[0]*100
xmin = boxes[1]*-200
ymax = boxes[2]*-100
xmax = boxes[3]*200

draw = ImageDraw.Draw(image)
im_width, im_height = image.size
(left, right, top, bottom) = (xmin * im_width, xmax * im_width,
                              ymin * im_height, ymax * im_height)

draw.line([(left, top), (left, bottom), (right, bottom),
               (right, top), (left, top)], width=thickness, fill=color)
</code>```

Body:
How can I draw bounding box and not use the normalized coordinate in tensorflow object-detection api? in object_detection_tutorial.ipynb , I noticed that default coordinate is in normalize coordinate and form of boxes is [xmin,ymin,xmax,ymax] and how to convert them to [image_lengthxmin, image_widthymin,image_lengthxmax,image_widthymax]?
I try to use

        boxes[0]=boxes[0]*200
        boxes[1]=boxes[1]*100
        boxes[2]=boxes[2]*200
        boxes[3]=boxes[3]*100

but error happens:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-72-efcec9615ee3> in <module>()
     30                   feed_dict={image_tensor: image_np_expanded})
     31                 boxes[0]=boxes[0]*200
---> 32                 boxes[1]=boxes[1]*100
     33                 boxes[2]=boxes[2]*200
     34                 boxes[3]=boxes[3]*100
IndexError: index 1 is out of bounds for axis 0 with size 1

Body:
if you look at research/object_detection/utils/visualization_utils.py the boxes[0] is ymin not xmin when you multiply these coordinates with 100 or 200 make sure it is still in the image boundary (im_width, im_height).

 You can try boxes[0]* 100, boxes[1]* -200, boxes[2]* -100, boxes[3]* 200, this is similar to this code.

ymin = boxes[0]*100
xmin = boxes[1]*-200
ymax = boxes[2]*-100
xmax = boxes[3]*200

draw = ImageDraw.Draw(image)
im_width, im_height = image.size
(left, right, top, bottom) = (xmin * im_width, xmax * im_width,
                              ymin * im_height, ymax * im_height)

draw.line([(left, top), (left, bottom), (right, bottom),
               (right, top), (left, top)], width=thickness, fill=color)


问:
how to use supervisor when I should running a celery in django which is in a virtualenv?
Yesterday, I deployed a Django project with nginx, uwsgi, celery, supervisor. All seemed fine.

But I have some questions come about it.

Generally saying, this time i deployed a Django project and used the local python installation, but if i must use the python in a virtual environment, what should i do ?

For example, i code some task (with django-celery) which will be used by django site to control some timing task, and the django project based python3 (the python3 environment is in a virtualenv).

So the celery should be used by python3, which is in a virtualenv, not the local python environment.

It means that if i set the command in supervisor as:

```<code>command=python ****/manage.py celery
</code>```

then an error would occur.

The uwsgi has some setting about this, where I can set the path of virtualenv.

But in supervisor, I could not see some setting or some way to use the virtualenv.

Help please?

答:
Include the path to your virtual environment in the command:</p>

```<code>command=/path/to/venv/bin/python celery worker
</code>```

Body:
Yesterday, I deployed a Django project with nginx, uwsgi, celery, supervisor. All seemed fine.

But I have some questions come about it.

Generally saying, this time i deployed a Django project and used the local python installation, but if i must use the python in a virtual environment, what should i do ?

For example, i code some task (with django-celery) which will be used by django site to control some timing task, and the django project based python3 (the python3 environment is in a virtualenv).

So the celery should be used by python3, which is in a virtualenv, not the local python environment.

It means that if i set the command in supervisor as:

command=python ****/manage.py celery

then an error would occur.

The uwsgi has some setting about this, where I can set the path of virtualenv.

But in supervisor, I could not see some setting or some way to use the virtualenv.

Help please?

Body:
Include the path to your virtual environment in the command:

command=/path/to/venv/bin/python celery worker


问:
How to use nofollow link in script tag
This is my script code:

```

I want to make crawler not to follow or index example.com/js/infolinks_main.js.

How can I do this task? I have robots.txt in my root, but that URL is an external URL.

NB: I do not want to use iframe.

答:
The script element can’t have a rel attribute, so nofollow can’t be used. Even if it could be used, note that nofollow is not about disallowing bots to crawl/index the URL.

To disallow crawling the script, you have to use robots.txt:

User-agent: *
Disallow: /js/infolinks_main.js
```

<p>Or if you want to disallow crawling of all your scripts:</p>

<pre class="lang-none prettyprint-override"><code>User-agent: *
Disallow: /js/
</code>```

You have to use the robots.txt file of the host where the scripts are hosted. It doesn’t necessarily have to be the host where your HTML documents are hosted.

(Note that this doesn’t disallow indexing the script. If you want to disallow indexing, you can use the X-Robots-Tag header with a noindex value, but then you have to allow crawling. As scripts are typically not indexed by general-purpose search engines, you probably want to prevent crawling, not indexing.)

Title: How to use nofollow link in script tag

Body:
This is my script code:

I want to make crawler not to follow or index example.com/js/infolinks_main.js.

How can I do this task? I have robots.txt in my root, but that URL is an external URL.

NB: I do not want to use iframe.

Body:
The script element can’t have a rel attribute, so nofollow can’t be used. Even if it could be used, note that nofollow is not about disallowing bots to crawl/index the URL.

To disallow crawling the script, you have to use robots.txt:

User-agent: *
Disallow: /js/infolinks_main.js

Or if you want to disallow crawling of all your scripts:

User-agent: *
Disallow: /js/

You have to use the robots.txt file of the host where the scripts are hosted. It doesn’t necessarily have to be the host where your HTML documents are hosted.

(Note that this doesn’t disallow indexing the script. If you want to disallow indexing, you can use the X-Robots-Tag header with a noindex value, but then you have to allow crawling. As scripts are typically not indexed by general-purpose search engines, you probably want to prevent crawling, not indexing.)


问:
Change to and from speaker using CallKit
I am creating a CallKit app that only does outbound calls.
We are doing our own interface, not using the built in UI.
I need to put a speaker button on the screen that will switch from speaker/no-speaker mode.

I have followed Apple's guidelines and example CallKit code and
it appears to be working well enough.

I could not find much information on how to switch to and from speaker mode.  I am using the following function to change the audio route.
Does anyone have experience doing this? Will this work reliably?

```<code>func speaker(on: Bool) {
    let audioSession = AVAudioSession.sharedInstance()
    do {
        // not sure I need this ...
        try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
        if on {
            // does this trigger a change to the audio route?
            try audioSession.overrideOutputAudioPort(.speaker)
        } else {
            // is this how to switch back to the phone speaker?
            try audioSession.overrideOutputAudioPort(.none)
        }
    } catch {
        // Audio session change failure
        print("failed to change speaker phone")
    }
}
</code>```

答: You'll need to add the following at the end of your do block: audioSession.setActive(true)

Body:
I am creating a CallKit app that only does outbound calls.
We are doing our own interface, not using the built in UI.
I need to put a speaker button on the screen that will switch from speaker/no-speaker mode.

I have followed Apple's guidelines and example CallKit code and
it appears to be working well enough.

I could not find much information on how to switch to and from speaker mode.  I am using the following function to change the audio route.
Does anyone have experience doing this? Will this work reliably?

func speaker(on: Bool) {
    let audioSession = AVAudioSession.sharedInstance()
    do {
        // not sure I need this ...
        try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
        if on {
            // does this trigger a change to the audio route?
            try audioSession.overrideOutputAudioPort(.speaker)
        } else {
            // is this how to switch back to the phone speaker?
            try audioSession.overrideOutputAudioPort(.none)
        }
    } catch {
        // Audio session change failure
        print("failed to change speaker phone")
    }
}


答:
I assume you understand the purpose of the evaluationHelper() method; if not, I suggest you view the contents of the two arrays after it is run.

You need to find the first non-zero value in the cardValues[] array.  If that entry and the subsequent 4 are all one, then return true; else return false.

In the future if you need to find a straight flush, you would first confirm one of the cardSuit[] entries equals 5 (i.e. all 5 must be the same suit); if not, then return false.

Title: Java - How do I check for a straight in a poker hand without sorting?

Body:
This is not a duplicate. I understand how easy this is if you can sort, but I am not allowed to use the sort method for arrays and I am not allowed to write my own. I can't find any help with this anywhere, including StackOverflow.

In this scenario, I have a method that is supposed to check whether or not a five card hand is a straight. I have a card object that holds a value (integer) and a suit (integer). I also have some rules about implementing this method.

There are no face cards besides the ace

The ace can count as either a 1 or a 10 but not both

A straight cannot wrap around

You cannot use the sorting method for arrays or write your own sorting method

That last rule is what is killing me. I have an array of cards. If I could just sort it, this would be so easy but I can't even write my own method to sort the array. For my other methods it simple to iterate through the hand and store the information about the hand in two separate arrays like this:

private static int[] cardValues = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
private static int[] cardSuits = {0, 0, 0, 0, 0};

private static void evaluationHelper(Card[] cards) {
    for (int i = 0; i < cardValues.length; i++) {
        cardValues[i] = 0;
    }

    for (int i = 0; i <cardSuits.length; i++) {
        cardSuits[i] = 0;
    }

    for (int i = 0; i < 5; i++) {
        cardValues[cards[i].getValue() - 1]++;
        cardSuits[cards[i].getSuit()]++;

        if (cards[i].getValue() == 1) {
            cardValues[9]++;
        }
    }
}

So in my first attempt to solve this issue I tried something like this:

public static boolean hasStraight(Card [] cards) {
    int sequenCounter = 0;
    evaluationHelper(cards);

    for (int i = 0; i < cardValues.length; i++) {
        if (sequenCounter != 5) {
            if (cardValues[i] != 0) {
                sequenCounter++;
            } else {
                sequenCounter = 0;
            }
        } else {
            return true;
        }
    }
    return false;
}

That didn't work. So then I tried this:

public static boolean hasStraight(Card [] cards) {
    int min = 100, max = 0;
    boolean seenSix = false, seenAce = false;
    evaluationHelper(cards);

    for (int i = 0; i < cards.length; i++) {
        if (cards[i].getValue() > max) {
            max = cards[i].getValue();
        }

        if (cards[i].getValue() < min) {
            min = cards[i].getValue();
        }

        if (cards[i].getValue() == 6) {
            seenSix = true;
        }

        if (cards[i].getValue() == 1) {
            seenAce = true;
        }
    }

    if (seenSix && seenAce) {
        max = 10;
    }

    if (max - min == 4) {
        return true;
    }
    return false;
}

That doesn't work either. I'm getting frustrated as both of these attempts went through many different changes over the course of overs and nothing has worked. I can't even figure out why they aren't working. The only information I have is that this method isn't spitting out the correct value. I don't know what values are being passed to the method. I don't know what the method is spitting out during the test. It could be spitting out false when it's supposed to be spitting true or vice versa. Please help!


问:
Is there a react-native checkbox example?
Are there any simple examples of implementing a react-native CheckBox? Facebook does not provided any examples. The CheckBox component that I am referring to can be found in the documentation here: http://facebook.github.io/react-native/docs/checkbox.html</p>

答:
Using react-native-elements, the mission is easier and examples are available : </p>

```<code> import { CheckBox } from 'react-native-elements'

<CheckBox
  title='Click Here'
  checked={this.state.checked}
/>

<CheckBox
  center
  title='Click Here'
  checked={this.state.checked}
/>

<CheckBox
  center
  title='Click Here'
  checkedIcon='dot-circle-o'
  uncheckedIcon='circle-o'
  checked={this.state.checked}
/>

<CheckBox
  center
  title='Click Here to Remove This Item'
  iconRight
  iconType='material'
  checkedIcon='clear'
  uncheckedIcon='add'
  checkedColor='red'
  checked={this.state.checked}
/>
</code>```

Body:
Using react-native-elements, the mission is easier and examples are available :

 import { CheckBox } from 'react-native-elements'

<CheckBox
  title='Click Here'
  checked={this.state.checked}
/>

<CheckBox
  center
  title='Click Here'
  checked={this.state.checked}
/>

<CheckBox
  center
  title='Click Here'
  checkedIcon='dot-circle-o'
  uncheckedIcon='circle-o'
  checked={this.state.checked}
/>

<CheckBox
  center
  title='Click Here to Remove This Item'
  iconRight
  iconType='material'
  checkedIcon='clear'
  uncheckedIcon='add'
  checkedColor='red'
  checked={this.state.checked}
/>


问:
Android studio 3 cannot download repository (error: Failed to download SHA1 for resource)
i use android studio version 3.0.0.

before update i use SDK manager for update support library. but after update android studio 3 i should update via https://dl.google.com/dl/android/maven2/. so i need support library 26.1.0.

on async gradle i have this error:

```<code>Unable to resolve dependency for ':app@debugAndroidTest/compileClasspath': Could not resolve junit:junit:4.12.

Could not resolve junit:junit:4.12.
Required by:
    project :app > com.android.support.test:runner:1.0.1
 > Could not resolve junit:junit:4.12.
    > Failed to download SHA1 for resource 'https://dl.google.com/dl/android/maven2/junit/junit/4.12/junit-4.12.pom'.
          > For input string: "<!"
</code>```

why cannot download this: https://dl.google.com/dl/android/maven2/junit/junit/4.12/junit-4.12.pom ?

i use proxy but cannot download.

this error is show for all dependencies library (appcampatv7, design, annonations and etc)

how to fix this Failed to download SHA1 for resource ?

UPDATE:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

and

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"
    defaultConfig {
        applicationId "com.example.testtesttest"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:design:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
</code>```

答:
fixed this problem after a lot of search. in gradle.propertices file set proxy both http and https and sync again.

```<code>systemProp.http.proxyHost=127.0.0.1
systemProp.https.proxyPort=12345
org.gradle.jvmargs=-Xmx1234m
systemProp.https.proxyHost=127.0.0.1
systemProp.http.proxyPort=12345
</code>```

Body:
i use android studio version 3.0.0.

before update i use SDK manager for update support library. but after update android studio 3 i should update via https://dl.google.com/dl/android/maven2/. so i need support library 26.1.0.

on async gradle i have this error:

Unable to resolve dependency for ':app@debugAndroidTest/compileClasspath': Could not resolve junit:junit:4.12.

Could not resolve junit:junit:4.12.
Required by:
    project :app > com.android.support.test:runner:1.0.1
 > Could not resolve junit:junit:4.12.
    > Failed to download SHA1 for resource 'https://dl.google.com/dl/android/maven2/junit/junit/4.12/junit-4.12.pom'.
          > For input string: "<!"

why cannot download this: https://dl.google.com/dl/android/maven2/junit/junit/4.12/junit-4.12.pom ?

i use proxy but cannot download.

this error is show for all dependencies library (appcampatv7, design, annonations and etc)

how to fix this Failed to download SHA1 for resource ?

UPDATE:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

and

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"
    defaultConfig {
        applicationId "com.example.testtesttest"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:design:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

Body:
fixed this problem after a lot of search. in gradle.propertices file set proxy both http and https and sync again.

systemProp.http.proxyHost=127.0.0.1
systemProp.https.proxyPort=12345
org.gradle.jvmargs=-Xmx1234m
systemProp.https.proxyHost=127.0.0.1
systemProp.http.proxyPort=12345


答:
Regular expressions is what you want.

Since your going to check for a pattern in a string, you can make use of the python's builtin support for regular expressions through re library.

Example:

```<code>#To check if there is a period internal to a sequence of letters with no adjacent whitespace
import re
str = 'www.google.com'
pattern = '.*\..*'
obj = re.compile(pattern)
if obj.search(str):
    print "Pattern matched"
</code>```

Similarly generate patterns for the conditions you want to check in your string.

```<code>#If there is a period and it is followed by a whitespace followed by a lowercase letter
regex = '.*\. [a-z].*'
</code>```

You can generate and test your regular expressions online using this simple tool

Read more extensively about re library here

Title: How to check subsequent elements of string in python using iterators?

Body:
I have a sentence that I want to parse to check for some conditions:

a) If there is a period and it is followed by a whitespace followed by a lowercase letter

b) If there is a period internal to a sequence of letters with no adjacent whitespace (i.e. www.abc.com)

c) If there is a period followed by a whitespace followed by an uppercase letter and preceded by a short list of titles (i.e. Mr., Dr. Mrs.)

Currently I am iterating through the string (line) and using the next() function to see whether the next character is a space or lowercase, etc. And then I just loop through the line. But how would I check to see what the next, next character would be? And how would I find the previous ones?

line = "This is line.1 www.abc.com. Mr."

t = iter(line)
b = next(t)

for i in line[:len(line)-1]:
    a = next(t)
    if i == "." and (a.isdigit()): #for example, this checks to see if the     value after the period is a number
         print("True")

Any help would be appreciated. Thank you.

Body:
Regular expressions is what you want.

Since your going to check for a pattern in a string, you can make use of the python's builtin support for regular expressions through re library.

Example:

#To check if there is a period internal to a sequence of letters with no adjacent whitespace
import re
str = 'www.google.com'
pattern = '.*\..*'
obj = re.compile(pattern)
if obj.search(str):
    print "Pattern matched"

Similarly generate patterns for the conditions you want to check in your string.

#If there is a period and it is followed by a whitespace followed by a lowercase letter
regex = '.*\. [a-z].*'

You can generate and test your regular expressions online using this simple tool

Read more extensively about re library here