问:
How do I create a test class that can verify a set of playing cards?
I'm trying to code a card game in Java through the usage of classes. I have to create a test class that verifies the results of the methods called as well as to printing out a banner with each test that states whether the test failed or passed as well as a final banner to see if all the test passed or failed.

PlayingCard Class (This class needs to be made into a tester)

```<code>import java.util.ArrayList;
import java.util.Random;

public class PlayingCards
{
    private ArrayList<Card> m_Cards;
    private Random gen;

    /**
     No-arg constructor initializes m_Cards.

     Initialize the ArrayList head and the random number generator.
     */
    public PlayingCards()
    {
        m_Cards = new ArrayList<Card> ();
        gen = new Random ();
    }

    /**
     Get the number of cards.

     @return number of cards
     */
    public int size()
    {
        return m_Cards.size();
    }

    /**
     Add a card.
     */
    public void addCard(Card newCard)
    {
        m_Cards.add(newCard);
    }

    /**
     Remove a card.

     @return null if there are no cards to remove or the instance field is null.
             Otherwise, returns a reference to a Card.
     */
    public Card removeCard()
    {
        if (m_Cards.size() == 0)
            return null;

        else
            return m_Cards.remove(0);
    }

    /**
     Shuffle the cards.

     This method shuffles the cards.
     */
    public void shuffle()
    {
        if ((m_Cards == null) || (m_Cards.size() < 2))
            return;

        for (int ii = 0; ii < m_Cards.size(); ++ii)
        {
            Card a = m_Cards.get(ii);
            int swapIndex = gen.nextInt(m_Cards.size());

            Card b = m_Cards.get(swapIndex);

            // swap the positions of a and b
            m_Cards.set(ii, b);
            m_Cards.set(swapIndex, a);
        }
    }

    /**
     Implement the toString method to show the contents of a
     PlayingCards object.

     This method relies on Card.toString() method.
     */
    @Override
    public String toString()
    {
        String outPut = "";

        for (int i = 0; i < m_Cards.size(); i++)
        {
            outPut += m_Cards.get(i).toString();
            outPut += "\n";
        }

        return outPut;
    }
}
</code>```

答:
If you do not want to use JUnit:

Write a new class that creates an instance of PlayingCards and then calls methods on that class. Use assert to verify that what you expect to happen happens. For example:

```<code>public class PlayingCardsTest {
  private PlayingCards playingCards;

  PlayingCardsTest() {
    playingCards = new PlayingCards();
  }

  public void testAddCard() {
    playingCards.addCard(new Card());

    assert playingCards.size() == 1;
  }
}
</code>```

You can then create a main that will create a new PlayingCardsTest and call each test method.

You can also use JUnit to make your testing much easier. With JUnit, your test might look like:

```<code>public class PlayingCardsTest {
  private PlayingCards playingCards = new PlayingCards();

  @Test
  public void testAddCard() {
    playingCards.addCard(new Card());

    assertEquals(1, playingCards.size());
  }
}
</code>```

Then you would run your JUnit tests with the JUnitRunner.

Body:
I'm trying to code a card game in Java through the usage of classes. I have to create a test class that verifies the results of the methods called as well as to printing out a banner with each test that states whether the test failed or passed as well as a final banner to see if all the test passed or failed.

PlayingCard Class (This class needs to be made into a tester)

import java.util.ArrayList;
import java.util.Random;

public class PlayingCards
{
    private ArrayList<Card> m_Cards;
    private Random gen;

    /**
     No-arg constructor initializes m_Cards.

     Initialize the ArrayList head and the random number generator.
     */
    public PlayingCards()
    {
        m_Cards = new ArrayList<Card> ();
        gen = new Random ();
    }

    /**
     Get the number of cards.

     @return number of cards
     */
    public int size()
    {
        return m_Cards.size();
    }

    /**
     Add a card.
     */
    public void addCard(Card newCard)
    {
        m_Cards.add(newCard);
    }

    /**
     Remove a card.

     @return null if there are no cards to remove or the instance field is null.
             Otherwise, returns a reference to a Card.
     */
    public Card removeCard()
    {
        if (m_Cards.size() == 0)
            return null;

        else
            return m_Cards.remove(0);
    }

    /**
     Shuffle the cards.

     This method shuffles the cards.
     */
    public void shuffle()
    {
        if ((m_Cards == null) || (m_Cards.size() < 2))
            return;

        for (int ii = 0; ii < m_Cards.size(); ++ii)
        {
            Card a = m_Cards.get(ii);
            int swapIndex = gen.nextInt(m_Cards.size());

            Card b = m_Cards.get(swapIndex);

            // swap the positions of a and b
            m_Cards.set(ii, b);
            m_Cards.set(swapIndex, a);
        }
    }

    /**
     Implement the toString method to show the contents of a
     PlayingCards object.

     This method relies on Card.toString() method.
     */
    @Override
    public String toString()
    {
        String outPut = "";

        for (int i = 0; i < m_Cards.size(); i++)
        {
            outPut += m_Cards.get(i).toString();
            outPut += "\n";
        }

        return outPut;
    }
}

Body:
If you do not want to use JUnit:

Write a new class that creates an instance of PlayingCards and then calls methods on that class. Use assert to verify that what you expect to happen happens. For example:

public class PlayingCardsTest {
  private PlayingCards playingCards;

  PlayingCardsTest() {
    playingCards = new PlayingCards();
  }

  public void testAddCard() {
    playingCards.addCard(new Card());

    assert playingCards.size() == 1;
  }
}

You can then create a main that will create a new PlayingCardsTest and call each test method.

You can also use JUnit to make your testing much easier. With JUnit, your test might look like:

public class PlayingCardsTest {
  private PlayingCards playingCards = new PlayingCards();

  @Test
  public void testAddCard() {
    playingCards.addCard(new Card());

    assertEquals(1, playingCards.size());
  }
}

Then you would run your JUnit tests with the JUnitRunner.


来源: stackexchange

问:
laravel validation update: It must 'required' only if stored record is empty
I have a filed for validation:

```<code>public function update(request $request, Sight $sight)
   {
     $validator = Validator::make($request->all(), [
         'img' => 'required|image|max:3000',
         ...
</code>```

It must be 'required',if only 'img' field in stored record is null.

Is it possible?

答:
Try to use required_if rule

Ex:

```<code>// In the following example the field will be required only if the img
// parameter is empty or null
$validator = Validator::make($request->all(), [
         'img' => 'image|max:3000',
         'field' => 'required_if:img,',
         ...
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a filed for validation:

public function update(request $request, Sight $sight)
   {
     $validator = Validator::make($request->all(), [
         'img' => 'required|image|max:3000',
         ...

It must be 'required',if only 'img' field in stored record is null.

Is it possible?

Body:
Try to use required_if rule

Ex:

// In the following example the field will be required only if the img
// parameter is empty or null
$validator = Validator::make($request->all(), [
         'img' => 'image|max:3000',
         'field' => 'required_if:img,',
         ...


问:
Python script not picking up the correct date selected in the excel Macro
I am trying to run a macro in excel that generates monthly reports.The macro calls the python script without any problems. However no matter the month i choose in the macro the python script always runs for January.

This is where i select the month:

When the python script runs it is always January:

Here is the code in python script.

```<code>#Read the month and year selected in the Monthly Report
pathOfMonthlyReportFile = os.sep.join((os.path.expanduser("~"),
'Desktop'))+'\Monthly Activity Report - Template.xlsm'
wb = openpyxl.load_workbook(pathOfMonthlyReportFile, keep_vba=True)
sheet = wb.get_sheet_by_name('Macro')
MonthOfMonthlyReport = sheet['G10'].value
YearOfMonthlyReport = sheet['J10'].value
print(MonthOfMonthlyReport)

if MonthOfMonthlyReport == "January":
 MonthNumber = 1
elif MonthOfMonthlyReport == "February":
 MonthNumber = 2
elif MonthOfMonthlyReport == "March":
 MonthNumber = 3
elif MonthOfMonthlyReport == "April":
 MonthNumber = 4
elif MonthOfMonthlyReport == "May":
 MonthNumber = 5
elif MonthOfMonthlyReport == "June":
 MonthNumber = 6
elif MonthOfMonthlyReport == "July":
 MonthNumber = 7
elif MonthOfMonthlyReport == "August":
 MonthNumber = 8
elif MonthOfMonthlyReport == "September":
 MonthNumber = 9
elif MonthOfMonthlyReport == "October":
 MonthNumber = 10
elif MonthOfMonthlyReport == "November":
 MonthNumber = 11
elif MonthOfMonthlyReport == "December":
 MonthNumber = 12

MonthlyReportDate =
now.replace(month=MonthNumber,year=int(YearOfMonthlyReport))
if MonthNumber == 12:
last_day_of_month = MonthlyReportDate.replace(day = 31, month=MonthNumber,
year=int(YearOfMonthlyReport))
else:
last_day_of_month = MonthlyReportDate.replace(day=1, month=MonthNumber+1,
year=int(YearOfMonthlyReport)) - datetime.timedelta(days=1)

if MonthNumber >= 10:
    stringenddate = "%s-%s-%s" % (MonthlyReportDate.year,
MonthlyReportDate.month,last_day_of_month.day)
    stringstartdate = "%s-%s-01" % (MonthlyReportDate.year,
MonthlyReportDate.month)
else:
    stringenddate = "%s-0%s-%s" % (MonthlyReportDate.year,
MonthlyReportDate.month,last_day_of_month.day)
    stringstartdate = "%s-0%s-01" % (MonthlyReportDate.year,
MonthlyReportDate.month)

print(stringenddate)

MonthRange = [1,2,3,4,5,6,7,8,9,10,11,12]
ThreeMonthsAgo = 0

for i in range(len(MonthRange)):
   if MonthRange[i] == MonthNumber:
    ThreeMonthsAgo = MonthRange[i-2] #**************
print(ThreeMonthsAgo)

if ThreeMonthsAgo<MonthNumber:
if ThreeMonthsAgo >=10:
    stringthreemonthsagodate = "%s-%s-01"%(MonthlyReportDate.year,
ThreeMonthsAgo)
else:
    stringthreemonthsagodate = "%s-0%s-01"%(MonthlyReportDate.year,
ThreeMonthsAgo)

if ThreeMonthsAgo > MonthNumber:
if ThreeMonthsAgo >=10:
    stringthreemonthsagodate = "%s-%s-01"%(MonthlyReportDate.year - 1,
ThreeMonthsAgo)
else:
    stringthreemonthsagodate = "%s-0%s-01"%(MonthlyReportDate.year - 1,
ThreeMonthsAgo)

date_ranges = [(stringstartdate,
                stringenddate)]
data_ranges_for_three_months = [(stringthreemonthsagodate, stringenddate)]
</code>```

It should run for the selected month but it runs only for the month of January.
I don't really get an error message but it is just not the right month.

It's been fixed. The solution is a bit embarrassing but i'll post it.All i had to do was whenever i change the month in macro, i need to save the .xlsm and then run it.

答:
It looks it's a caching / stale data issue.  If I am understanding you correctly, you run a VBA macro inside your workbook that calls a python script that then looks at a cell inside that same workbook?  Not an ideal structure!

When your python script calls the Excel sheet, here:

```<code>wb = openpyxl.load_workbook(pathOfMonthlyReportFile, keep_vba=True)
</code>```

I think it's looking at the value of G10 when you last saved the file.  Perhaps the month was January on the last save?

I would either:

Restructure your python function so that it takes month and date arguments and pass those values when you call the function from VBA

Try having VBA save your sheet just before VBA calls the python script, thus preserving any changes made to the month and date dropdown.

Note that 1. is much more robust and professional than 2., but may be slightly more complicated to implement.

Body:
I am trying to run a macro in excel that generates monthly reports.The macro calls the python script without any problems. However no matter the month i choose in the macro the python script always runs for January.

This is where i select the month:

When the python script runs it is always January:

Here is the code in python script.

#Read the month and year selected in the Monthly Report
pathOfMonthlyReportFile = os.sep.join((os.path.expanduser("~"),
'Desktop'))+'\Monthly Activity Report - Template.xlsm'
wb = openpyxl.load_workbook(pathOfMonthlyReportFile, keep_vba=True)
sheet = wb.get_sheet_by_name('Macro')
MonthOfMonthlyReport = sheet['G10'].value
YearOfMonthlyReport = sheet['J10'].value
print(MonthOfMonthlyReport)

if MonthOfMonthlyReport == "January":
 MonthNumber = 1
elif MonthOfMonthlyReport == "February":
 MonthNumber = 2
elif MonthOfMonthlyReport == "March":
 MonthNumber = 3
elif MonthOfMonthlyReport == "April":
 MonthNumber = 4
elif MonthOfMonthlyReport == "May":
 MonthNumber = 5
elif MonthOfMonthlyReport == "June":
 MonthNumber = 6
elif MonthOfMonthlyReport == "July":
 MonthNumber = 7
elif MonthOfMonthlyReport == "August":
 MonthNumber = 8
elif MonthOfMonthlyReport == "September":
 MonthNumber = 9
elif MonthOfMonthlyReport == "October":
 MonthNumber = 10
elif MonthOfMonthlyReport == "November":
 MonthNumber = 11
elif MonthOfMonthlyReport == "December":
 MonthNumber = 12

MonthlyReportDate =
now.replace(month=MonthNumber,year=int(YearOfMonthlyReport))
if MonthNumber == 12:
last_day_of_month = MonthlyReportDate.replace(day = 31, month=MonthNumber,
year=int(YearOfMonthlyReport))
else:
last_day_of_month = MonthlyReportDate.replace(day=1, month=MonthNumber+1,
year=int(YearOfMonthlyReport)) - datetime.timedelta(days=1)

if MonthNumber >= 10:
    stringenddate = "%s-%s-%s" % (MonthlyReportDate.year,
MonthlyReportDate.month,last_day_of_month.day)
    stringstartdate = "%s-%s-01" % (MonthlyReportDate.year,
MonthlyReportDate.month)
else:
    stringenddate = "%s-0%s-%s" % (MonthlyReportDate.year,
MonthlyReportDate.month,last_day_of_month.day)
    stringstartdate = "%s-0%s-01" % (MonthlyReportDate.year,
MonthlyReportDate.month)

print(stringenddate)

MonthRange = [1,2,3,4,5,6,7,8,9,10,11,12]
ThreeMonthsAgo = 0

for i in range(len(MonthRange)):
   if MonthRange[i] == MonthNumber:
    ThreeMonthsAgo = MonthRange[i-2] #**************
print(ThreeMonthsAgo)

if ThreeMonthsAgo<MonthNumber:
if ThreeMonthsAgo >=10:
    stringthreemonthsagodate = "%s-%s-01"%(MonthlyReportDate.year,
ThreeMonthsAgo)
else:
    stringthreemonthsagodate = "%s-0%s-01"%(MonthlyReportDate.year,
ThreeMonthsAgo)

if ThreeMonthsAgo > MonthNumber:
if ThreeMonthsAgo >=10:
    stringthreemonthsagodate = "%s-%s-01"%(MonthlyReportDate.year - 1,
ThreeMonthsAgo)
else:
    stringthreemonthsagodate = "%s-0%s-01"%(MonthlyReportDate.year - 1,
ThreeMonthsAgo)

date_ranges = [(stringstartdate,
                stringenddate)]
data_ranges_for_three_months = [(stringthreemonthsagodate, stringenddate)]

It should run for the selected month but it runs only for the month of January.
I don't really get an error message but it is just not the right month.

It's been fixed. The solution is a bit embarrassing but i'll post it.All i had to do was whenever i change the month in macro, i need to save the .xlsm and then run it.

Body:
It looks it's a caching / stale data issue.  If I am understanding you correctly, you run a VBA macro inside your workbook that calls a python script that then looks at a cell inside that same workbook?  Not an ideal structure!

When your python script calls the Excel sheet, here:

wb = openpyxl.load_workbook(pathOfMonthlyReportFile, keep_vba=True)

I think it's looking at the value of G10 when you last saved the file.  Perhaps the month was January on the last save?

I would either:

Restructure your python function so that it takes month and date arguments and pass those values when you call the function from VBA

Try having VBA save your sheet just before VBA calls the python script, thus preserving any changes made to the month and date dropdown.

Note that 1. is much more robust and professional than 2., but may be slightly more complicated to implement.


问:
Select multiple columns from another table depending on value of column
I'm not even sure this is possible, but I have an order table (online store).  Within this table, the shipping and billing address columns are ID's which correspond with the address table.

For E.g.

```<code>OrderID     ShippingAddressID   BillingAddressID
201800194   21183               21182
</code>```

The Address table then lists the address information.

```<code>AddressID   Address1            City        RegionCode
21182       123 Somewhere Dr    Hometown1   Florida
21183       456 Elsewhere Rd    Hometown2   Florida
</code>```

I'd like the resulting listing to show something similar to this:

```<code>OrderID     BillingAddress1     BillingCity BillingRegionCode   ShippingAddress1    ShippingCity    ShippingRegionCode
201800194   123 Somewhere Dr    Hometown1   Florida             456 Elsewhere Rd    Hometown2       Florida
</code>```

Is this even possible?

Thanks..

答:
Yes you can achieve it using join like this - </p>

```<code>SELECT OrderId, Billing.Address1 As BillingAddress1, Shipping.Address1 AS
ShippingAddress1, ... other column
FROM dbo.Order
LEFT JOIN dbo.Address AS Billing ON Order.BillingAddressID = Billing.AddressID
LEFT JOIN dbo.Address AS Shipping ON Order.ShippingAddressID = Shipping.AddressID
</code>```

Body:
I'm not even sure this is possible, but I have an order table (online store).  Within this table, the shipping and billing address columns are ID's which correspond with the address table.

For E.g.

OrderID     ShippingAddressID   BillingAddressID
201800194   21183               21182

The Address table then lists the address information.

AddressID   Address1            City        RegionCode
21182       123 Somewhere Dr    Hometown1   Florida
21183       456 Elsewhere Rd    Hometown2   Florida

I'd like the resulting listing to show something similar to this:

OrderID     BillingAddress1     BillingCity BillingRegionCode   ShippingAddress1    ShippingCity    ShippingRegionCode
201800194   123 Somewhere Dr    Hometown1   Florida             456 Elsewhere Rd    Hometown2       Florida

Is this even possible?

Thanks..

Body:
Yes you can achieve it using join like this -

SELECT OrderId, Billing.Address1 As BillingAddress1, Shipping.Address1 AS
ShippingAddress1, ... other column
FROM dbo.Order
LEFT JOIN dbo.Address AS Billing ON Order.BillingAddressID = Billing.AddressID
LEFT JOIN dbo.Address AS Shipping ON Order.ShippingAddressID = Shipping.AddressID


问:
Last line of code wont execute?
Hi I'm having a problem with the last line of the code. It won't print anything.

```<code>invalid=True
global invalid
def start()
  x = input('Type the correct key:')
  if ("m" == x) or ("M"==x):
   print('Correct!')
  elif x!='m' or x!='M':
   print('Invalid Input.')
   invalid=False
 while invalid:
  start()
print('Next Question')
</code>```

When the input is 'm' or 'M' it should say Correct!

  Next question but it doesn't it just prints Correct!

Thank you in advance!

答:
you have to set the global variable first and then set it as True. This will work

```<code>global invalid
invalid = True
def start():
  x = input('Type the correct key:')
  if ("m" == x) or ("M"==x):
   print('Correct!')
  elif x!='m' or x!='M':
   print('Invalid Input.')
   invalid=False
while invalid:
  start()
print('Next Question')
</code>```

does that solve your problem?

Title: Last line of code wont execute?

Body:
Hi I'm having a problem with the last line of the code. It won't print anything.

invalid=True
global invalid
def start()
  x = input('Type the correct key:')
  if ("m" == x) or ("M"==x):
   print('Correct!')
  elif x!='m' or x!='M':
   print('Invalid Input.')
   invalid=False
 while invalid:
  start()
print('Next Question')

When the input is 'm' or 'M' it should say Correct!

  Next question but it doesn't it just prints Correct!

Thank you in advance!

Body:
you have to set the global variable first and then set it as True. This will work

global invalid
invalid = True
def start():
  x = input('Type the correct key:')
  if ("m" == x) or ("M"==x):
   print('Correct!')
  elif x!='m' or x!='M':
   print('Invalid Input.')
   invalid=False
while invalid:
  start()
print('Next Question')

does that solve your problem?


问:
Xamarin.Android TextView doesn't raise change events when "Link SDK Assemblies" is selected
I'm working on a project in Xamarin with MvvmCross, trying to use the linker to get the app size down for release on Android and iOS (no Forms.)

On Android, when I selected "Link SDK Assemblies Only", the project builds and runs with no crashes or error messages. But none of the EditText controls responds correctly when their text changes, their data bindings don't get updated, and their Changed event handlers don't get called.

When I select "Don't Link", everything works fine. Bindings are updated and event handlers are called.

I have looked at the Xamarin Linker documentation, and I'm aware of how to ensure various assemblies, types and methods are preserved. My problem is I simply don't know what needs to be preserved, nor do I have any idea how to find out. I've tried tools like bitdiffer with no success.

Can anyone help me figure out what I need to preserve if anything?

答:
Add a LinkerPleaseInclude.cs file to your Android project containing the following code:

```<code>public class LinkerPleaseInclude
{
    public void Include(TextView text)
    {
        text.AfterTextChanged += (sender, args) => text.Text = "" + text.Text;
        text.Hint = "" + text.Hint;
    }
}
</code>```

EditText is inheriting from TextView so this will take care of your problem by making the linker think you reference the TextView.AfterTextChanged event. You can find a reference Android LinkerPleaseInclude.cs file here.

Body:
Add a LinkerPleaseInclude.cs file to your Android project containing the following code:

public class LinkerPleaseInclude
{
    public void Include(TextView text)
    {
        text.AfterTextChanged += (sender, args) => text.Text = "" + text.Text;
        text.Hint = "" + text.Hint;
    }
}

EditText is inheriting from TextView so this will take care of your problem by making the linker think you reference the TextView.AfterTextChanged event. You can find a reference Android LinkerPleaseInclude.cs file here.


问:
Count Objects In Image
i want to count the number of objects in images using python
this is my code but it returns only 1
i'm using contours to draw circle on the objects </p>

```<code>import cv2
from matplotlib import pyplot as plt
import numpy as np
kernel = np.ones((5,5), np.uint8)
img = cv2.imread('/home/mfp/Desktop/images/coins.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
mean = cv2.blur(gray , (7,7))
closing = cv2.morphologyEx(mean, cv2.MORPH_CLOSE, kernel)
opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel)

ret, thresh = cv2.threshold(opening, 127, 255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
im2, contours, hierarchy =cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
i =0
for cnt in contours:
cv2.drawContours(img, [cnt], 0, (0, 0, 255), 3)
x, y, w, h = cv2.boundingRect(cnt)
if x>30 and x<60 and y>40 and y<80:
    i=i+1
    #cv2.rectangle(img, (x,y), (x+w,y+h), (0,0,255), 2)

elif x>60 and x<120 and y>80 and y<160:
    i=i+1
    #cv2.rectangle(img, (x,y), (x+w,y+h), (0,0,255), 2)
print(i)

cv2.imshow('Threshold', thresh)
cv2.imshow('Image', img)

cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

答: Check the result of your open and close functions to see if your objects are touching each other as a result of this process. This might cause them to be connected and hence identified as one whole contour. Also, sort the contours obtained based on area before you draw contours or do anything else. It helps avoid choosing too small/too large contours that might be detected. Need your input sample image to tell any further!</p>

Title: Count Objects In Image

Body:
i want to count the number of objects in images using python
this is my code but it returns only 1
i'm using contours to draw circle on the objects

import cv2
from matplotlib import pyplot as plt
import numpy as np
kernel = np.ones((5,5), np.uint8)
img = cv2.imread('/home/mfp/Desktop/images/coins.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
mean = cv2.blur(gray , (7,7))
closing = cv2.morphologyEx(mean, cv2.MORPH_CLOSE, kernel)
opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel)

ret, thresh = cv2.threshold(opening, 127, 255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
im2, contours, hierarchy =cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
i =0
for cnt in contours:
cv2.drawContours(img, [cnt], 0, (0, 0, 255), 3)
x, y, w, h = cv2.boundingRect(cnt)
if x>30 and x<60 and y>40 and y<80:
    i=i+1
    #cv2.rectangle(img, (x,y), (x+w,y+h), (0,0,255), 2)

elif x>60 and x<120 and y>80 and y<160:
    i=i+1
    #cv2.rectangle(img, (x,y), (x+w,y+h), (0,0,255), 2)
print(i)

cv2.imshow('Threshold', thresh)
cv2.imshow('Image', img)

cv2.waitKey(0)
cv2.destroyAllWindows()


问:
Serialize parallel arrays to XML in C# in a specific order
I'm currently tasked with sending data to a web service that has a very odd way of specifying lists. I am not in control of the schema, and my attempts to make the other party change the schema have failed. So I'm pretty much stuck with this.

The way their schema is defined is this (only the relevant bit is included):

```<code><xs:element name="Part">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="List">
        <xs:complexType>
          <xs:sequence maxOccurs="4">
            <xs:element name="Name" type="xs:string" />
            <xs:element name="Data" type="xs:string" />
            <xs:element name="OtherData" type="xs:string" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
  </xs:complexType>
</xs:element>
</code>```

I used xsd.exe to generate a C# class to serialize the structure easily. The generated bit is as follows:

```<code>[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="the namespace")]
public partial class PartList {
    [System.Xml.Serialization.XmlElementAttribute("Name", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string[] Name { get; set; }

    [System.Xml.Serialization.XmlElementAttribute("Data", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string[] Data { get; set; }

    [System.Xml.Serialization.XmlElementAttribute("OtherData", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string[] OtherData  { get; set; }
}
</code>```

Yes, parallel arrays. Now, according to their documents (and anecdotal data from another party that generates the XML through other means), the correct/expected xml should look like this (for example, a list with two items - comments inline added for illustration purposes):

```<code><Part xmlns="">
    <List>
        <Name>Some Test</Name> <!-- first item -->
        <Data>123131313</Data> <!-- first item -->
        <OtherData>0.11</OtherData> <!-- first item -->
        <Name>Other Lama</Name> <!-- second item -->
        <Data>331331313</Data> <!-- second item -->
        <OtherData>0.02</OtherData> <!-- second item -->
    </List>
</Part>
</code>```

However, my autogenerated C# class serializes to:

```<code><Part xmlns="">
    <List>
        <Name>Marcos Test</Name> <!-- first item -->
        <Name>Pepe Lama</Name> <!-- second item -->
        <Data>123131313</Data> <!-- first item -->
        <Data>331331313</Data> <!-- second item -->
        <OtherData>0.11</OtherData> <!-- first item -->
        <OtherData>0.02</OtherData> <!-- second item -->
    </List>
</Part>
</code>```

My XML fails validation against the schema because of the ordering of the items. I'm serializing the class using System.Xml.Serialization.XmlSerializer with the default options. I usually don't have any trouble serializing reasonable schemas for other web services. But for some reason I just can't for the life of me figure out how to do this (if it's even possible).

Any ideas? I already tried using the XmlOrderAttribute, but didn't make a difference in the order of the result.

答:
The basic problem here is that XmlSerializer recursively descends the object graph and maps objects to blocks of XML element(s), but you want to interleave the elements generated by certain objects, namely the public string[] properties.  Unfortunately, this isn't implemented out of the box using only XML serializer attributes.

However, you can generate the XML you need by introducing a surrogate property that can be serialized in the required format.  There are two different ways to do this, as shown in the following two questions:

Serializing a list of KeyValuePair to XML shows how to use the polymorphic list functionality of XmlSerializer to generate an interleaved list of elements from multiple collections.

Xml Sequence deserialization with RestSharp shows how to use an [XmlAnyElement] property to generate an interleaved list of elements.

For instance, here is an implementation of approach #1:

```<code>public partial class PartList
{
    [XmlIgnore]
    public List<string> Name { get; } = new List<string>();

    [XmlIgnore]
    public List<string> Data { get; } = new List<string>();

    [XmlIgnore]
    public List<string> OtherData { get; } = new List<string>();

    [System.Xml.Serialization.XmlElementAttribute("Name", typeof(Name), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    [System.Xml.Serialization.XmlElementAttribute("Data", typeof(Data), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    [System.Xml.Serialization.XmlElementAttribute("OtherData", typeof(OtherData), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public ValueWrapper<string>[] Values
    {
        get
        {
            var list = new List<ValueWrapper<string>>();
            for (int i = 0, count = Math.Max(Name.Count, Math.Max(Data.Count, OtherData.Count)); i < count; i++)
            {
                if (i < Name.Count)
                    list.Add(new Name { Value = Name[i] });
                if (i < Data.Count)
                    list.Add(new Data { Value = Data[i] });
                if (i < OtherData.Count)
                    list.Add(new OtherData { Value = OtherData[i] });
            }
            return list.ToArray();
        }
        set
        {
            if (value == null)
                return;
            Name.AddRange(value.OfType<Name>().Select(v => v.Value));
            Data.AddRange(value.OfType<Data>().Select(v => v.Value));
            OtherData.AddRange(value.OfType<OtherData>().Select(v => v.Value));
        }
    }
}

public class Name : ValueWrapper<string> { }

public class Data : ValueWrapper<string> { }

public class OtherData : ValueWrapper<string> { }

public abstract class ValueWrapper<T> : ValueWrapper where T : IConvertible
{
    public override object GetValue() => Value;

    [XmlText]
    public T Value { get; set; }
}

public abstract class ValueWrapper
{
    public abstract object GetValue();
}
</code>```

Notes:

The original collections are marked with [XmlIgnore].

A surrogate polymorphic array property ValueWrapper<string>[] Values is introduced that can contain multiple types, one for each possible element name.

In creating and returning the array the values from the three collections are interleaved.  In the array setter, the values are split by type and directed to the relevant collections.

Sample fiddle.

Body:
I'm currently tasked with sending data to a web service that has a very odd way of specifying lists. I am not in control of the schema, and my attempts to make the other party change the schema have failed. So I'm pretty much stuck with this.

The way their schema is defined is this (only the relevant bit is included):

<xs:element name="Part">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="List">
        <xs:complexType>
          <xs:sequence maxOccurs="4">
            <xs:element name="Name" type="xs:string" />
            <xs:element name="Data" type="xs:string" />
            <xs:element name="OtherData" type="xs:string" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
  </xs:complexType>
</xs:element>

I used xsd.exe to generate a C# class to serialize the structure easily. The generated bit is as follows:

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="the namespace")]
public partial class PartList {
    [System.Xml.Serialization.XmlElementAttribute("Name", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string[] Name { get; set; }

    [System.Xml.Serialization.XmlElementAttribute("Data", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string[] Data { get; set; }

    [System.Xml.Serialization.XmlElementAttribute("OtherData", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string[] OtherData  { get; set; }
}

Yes, parallel arrays. Now, according to their documents (and anecdotal data from another party that generates the XML through other means), the correct/expected xml should look like this (for example, a list with two items - comments inline added for illustration purposes):

<Part xmlns="">
    <List>
        <Name>Some Test</Name>
        <Data>123131313</Data>
        <OtherData>0.11</OtherData>
        <Name>Other Lama</Name>
        <Data>331331313</Data>
        <OtherData>0.02</OtherData>
    </List>
</Part>

However, my autogenerated C# class serializes to:

<Part xmlns="">
    <List>
        <Name>Marcos Test</Name>
        <Name>Pepe Lama</Name>
        <Data>123131313</Data>
        <Data>331331313</Data>
        <OtherData>0.11</OtherData>
        <OtherData>0.02</OtherData>
    </List>
</Part>

My XML fails validation against the schema because of the ordering of the items. I'm serializing the class using System.Xml.Serialization.XmlSerializer with the default options. I usually don't have any trouble serializing reasonable schemas for other web services. But for some reason I just can't for the life of me figure out how to do this (if it's even possible).

Any ideas? I already tried using the XmlOrderAttribute, but didn't make a difference in the order of the result.

Body:
The basic problem here is that XmlSerializer recursively descends the object graph and maps objects to blocks of XML element(s), but you want to interleave the elements generated by certain objects, namely the public string[] properties.  Unfortunately, this isn't implemented out of the box using only XML serializer attributes.

However, you can generate the XML you need by introducing a surrogate property that can be serialized in the required format.  There are two different ways to do this, as shown in the following two questions:

Serializing a list of KeyValuePair to XML shows how to use the polymorphic list functionality of XmlSerializer to generate an interleaved list of elements from multiple collections.

Xml Sequence deserialization with RestSharp shows how to use an [XmlAnyElement] property to generate an interleaved list of elements.

For instance, here is an implementation of approach #1:

public partial class PartList
{
    [XmlIgnore]
    public List<string> Name { get; } = new List<string>();

    [XmlIgnore]
    public List<string> Data { get; } = new List<string>();

    [XmlIgnore]
    public List<string> OtherData { get; } = new List<string>();

    [System.Xml.Serialization.XmlElementAttribute("Name", typeof(Name), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    [System.Xml.Serialization.XmlElementAttribute("Data", typeof(Data), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    [System.Xml.Serialization.XmlElementAttribute("OtherData", typeof(OtherData), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public ValueWrapper<string>[] Values
    {
        get
        {
            var list = new List<ValueWrapper<string>>();
            for (int i = 0, count = Math.Max(Name.Count, Math.Max(Data.Count, OtherData.Count)); i < count; i++)
            {
                if (i < Name.Count)
                    list.Add(new Name { Value = Name[i] });
                if (i < Data.Count)
                    list.Add(new Data { Value = Data[i] });
                if (i < OtherData.Count)
                    list.Add(new OtherData { Value = OtherData[i] });
            }
            return list.ToArray();
        }
        set
        {
            if (value == null)
                return;
            Name.AddRange(value.OfType<Name>().Select(v => v.Value));
            Data.AddRange(value.OfType<Data>().Select(v => v.Value));
            OtherData.AddRange(value.OfType<OtherData>().Select(v => v.Value));
        }
    }
}

public class Name : ValueWrapper<string> { }

public class Data : ValueWrapper<string> { }

public class OtherData : ValueWrapper<string> { }

public abstract class ValueWrapper<T> : ValueWrapper where T : IConvertible
{
    public override object GetValue() => Value;

    [XmlText]
    public T Value { get; set; }
}

public abstract class ValueWrapper
{
    public abstract object GetValue();
}

Notes:

The original collections are marked with [XmlIgnore].

A surrogate polymorphic array property ValueWrapper<string>[] Values is introduced that can contain multiple types, one for each possible element name.

In creating and returning the array the values from the three collections are interleaved.  In the array setter, the values are split by type and directed to the relevant collections.

Sample fiddle.


问:
How to loop though elements in XML with namespace using XSLT
The topic of this question may be incorrect as I am new in XSLT. I will try to explain with an example. I have the following XML

```<code><?xml version="1.0" encoding="UTF-8"?>

<Recordset Name="Report" xmlns="http://pia.com/xml/ns">
    <Record>
        <TransactionReferenceNumber>T00005546</TransactionReferenceNumber>
        <ExecutingEntityIDCode>724500LY73GPE4GDX159</ExecutingEntityIDCode>
    </Record>
    <Record>
        <TransactionReferenceNumber>P00098080</TransactionReferenceNumber>
        <ExecutingEntityIDCode>66666</ExecutingEntityIDCode>
    </Record>
</Recordset>
</code>```

XLST:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
          xmlns:a="http://pia.com/xml/ns"
          exclude-result-prefixes="a">
  <xsl:output method="xml" version="1.0"
              encoding="UTF-8" omit-xml-declaration="no" indent="yes"  />
  <xsl:template match="/">
      <xsl:for-each select="/a:Recordset/a:Record">
          <TxId>
            <xsl:value-of select="/a:Recordset/a:Record/a:TransactionReferenceNumber"/>
          </TxId><xsl:text>
</xsl:text>
          <ExctgPty>
              <xsl:value-of select="/a:Recordset/a:Record/a:ExecutingEntityIDCode"/>
          </ExctgPty>
          <xsl:text>
</xsl:text>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>
</code>```

With desired output

```<code><?xml version="1.0" encoding="utf-8"?>
<TxId>T00005546</TxId>
<ExctgPty>724500LY73GPE4GDX159</ExctgPty>
<TxId>P00098080</TxId>
<ExctgPty>66666</ExctgPty>
</code>```

But I am getting the first data in both cases.

```<code><?xml version="1.0" encoding="utf-8"?>
<TxId>T00005546</TxId>
<ExctgPty>724500LY73GPE4GDX159</ExctgPty>
<TxId>T00005546</TxId>
<ExctgPty>724500LY73GPE4GDX159</ExctgPty>
</code>```

How do i loop and get the desired output?
NOTE: This is just a small chuck of XML and XSLT code which I am using.

答:
```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:a="http://pia.com/xml/ns" exclude-result-prefixes="a">
<xsl:output method="xml" version="1.0" encoding="UTF-8" omit-xml-declaration="no" indent="yes"/>
<xsl:template match="a:TransactionReferenceNumber">
    <TxId>
        <xsl:value-of select="."/>
        <xsl:text>
</xsl:text>
    </TxId>
</xsl:template>
<xsl:template match="a:ExecutingEntityIDCode">
    <ExctgPty>
        <xsl:value-of select="."/>
        <xsl:text>
</xsl:text>
    </ExctgPty>
</xsl:template>
</xsl:stylesheet>
</code>```

I would

use xsl:apply-templates instead of xsl:for-each

took advantage of default templates that will traverse entire XML tree except attributes

write template only for the elements a:TransactionReferenceNumber and
a:ExecutingEntityIDCode to change element name and add line feed character.

Body:
The topic of this question may be incorrect as I am new in XSLT. I will try to explain with an example. I have the following XML

<?xml version="1.0" encoding="UTF-8"?>

<Recordset Name="Report" xmlns="http://pia.com/xml/ns">
    <Record>
        <TransactionReferenceNumber>T00005546</TransactionReferenceNumber>
        <ExecutingEntityIDCode>724500LY73GPE4GDX159</ExecutingEntityIDCode>
    </Record>
    <Record>
        <TransactionReferenceNumber>P00098080</TransactionReferenceNumber>
        <ExecutingEntityIDCode>66666</ExecutingEntityIDCode>
    </Record>
</Recordset>

XLST:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
          xmlns:a="http://pia.com/xml/ns"
          exclude-result-prefixes="a">
  <xsl:output method="xml" version="1.0"
              encoding="UTF-8" omit-xml-declaration="no" indent="yes"  />
  <xsl:template match="/">
      <xsl:for-each select="/a:Recordset/a:Record">
          <TxId>
            <xsl:value-of select="/a:Recordset/a:Record/a:TransactionReferenceNumber"/>
          </TxId><xsl:text>
</xsl:text>
          <ExctgPty>
              <xsl:value-of select="/a:Recordset/a:Record/a:ExecutingEntityIDCode"/>
          </ExctgPty>
          <xsl:text>
</xsl:text>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

With desired output

<?xml version="1.0" encoding="utf-8"?>
<TxId>T00005546</TxId>
<ExctgPty>724500LY73GPE4GDX159</ExctgPty>
<TxId>P00098080</TxId>
<ExctgPty>66666</ExctgPty>

But I am getting the first data in both cases.

<?xml version="1.0" encoding="utf-8"?>
<TxId>T00005546</TxId>
<ExctgPty>724500LY73GPE4GDX159</ExctgPty>
<TxId>T00005546</TxId>
<ExctgPty>724500LY73GPE4GDX159</ExctgPty>

How do i loop and get the desired output?
NOTE: This is just a small chuck of XML and XSLT code which I am using.

Body:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:a="http://pia.com/xml/ns" exclude-result-prefixes="a">
<xsl:output method="xml" version="1.0" encoding="UTF-8" omit-xml-declaration="no" indent="yes"/>
<xsl:template match="a:TransactionReferenceNumber">
    <TxId>
        <xsl:value-of select="."/>
        <xsl:text>&#xa;</xsl:text>
    </TxId>
</xsl:template>
<xsl:template match="a:ExecutingEntityIDCode">
    <ExctgPty>
        <xsl:value-of select="."/>
        <xsl:text>&#xa;</xsl:text>
    </ExctgPty>
</xsl:template>
</xsl:stylesheet>

I would

use xsl:apply-templates instead of xsl:for-each

took advantage of default templates that will traverse entire XML tree except attributes

write template only for the elements a:TransactionReferenceNumber and
a:ExecutingEntityIDCode to change element name and add line feed character.


问:
PWA with location-triggered push notifications?
I've read that we can use Geolocation and Location-Triggered events to send push notifications to users, to - as an example - send a discount cupom when he/she is walking near a store.

For all I could research, this is only possible using native technology. Is that right? Could I achieve today this same result by making a Progressive Web App with web push notifications? Can the service worker "wake up" based on the user current location?

Thanks a lot,

答: This is called Geofencing. There is a proposal for adding it to the Web, but the discussion has stalled and no vendor seems to be interested any longer. See the page at What Web Can Do Today for more info.


问:
Comparing two integers without any comparison
Is it possible to find the greatest of two integers without any comparison? I found some  solutions:

```<code>if(!(a/b)) // if a is less than b then division result will be zero.
{
    cout << " b is greater than a";
}
else if (!(a-b)) // we know a is greater than or equal to b now.  check whether they are equal.
{
    cout << "a and b are equal";
}
else
    cout << "a is greater than b";
</code>```

But if(c) or if(!c) is a comparison to zero. In addition it doesn't work for negative numbers. In fact I need a solution that avoids any if statement. Instead I should use switch statements and arithmetic operators. ThanX.

答:
I just cant see any good reason to do that : who would want to program without "if" ?

a possible answer is :

( ( a + b ) + abs ( a -b ) ) / 2

I guess "abs" just hides a "if" somewhere, just as the ternary operator that is just another name for "if" ...

OwnerDisplayName: kvphxga

ContentLicense: CC BY-SA 2.5

Body:
Is it possible to find the greatest of two integers without any comparison? I found some  solutions:

if(!(a/b)) // if a is less than b then division result will be zero.
{
    cout << " b is greater than a";
}
else if (!(a-b)) // we know a is greater than or equal to b now.  check whether they are equal.
{
    cout << "a and b are equal";
}
else
    cout << "a is greater than b";

But if(c) or if(!c) is a comparison to zero. In addition it doesn't work for negative numbers. In fact I need a solution that avoids any if statement. Instead I should use switch statements and arithmetic operators. ThanX.

LastEditorDisplayName: kvphxga

OwnerDisplayName: siukurnin


问:
Exporting JAR projects that use a common project
I have 4 different Java Projects created in Eclipse.

One of them contains all my Utilities and Helper methods, that the other 3 projects use.

I don't want to copy that same package 3 times into each project, since I want to be able to just edit it in one place if I should have to. So, I have referenced the myUtilities project from all other 3 projects.

I'll be exporting the 3 main projects and they will be going to different servers to run independently as  "java -jar myproject.jar"

Everytime I do an export, the myUtilities.jar is not getting compiled in the JAR. If I open the JAR, I can see it is not there.  And this is going to be a problem when I move them to the other servers.

Is there a way to add the package into the source for the JAR? Or am I going to have to copy the myUtilities.jar into the JAVA_HOME of each server?

This is my current Manifest file:

```<code>Manifest-Version: 1.0
Main-Class: com.elcool.process.alpha.RetrieverMain
</code>```

答: You may also add Classpath references in the executable jar file MANIFEST.MF or for more experienced users use maven assembly plugin which will create artefact with all its dependencies packed within a single jar.</p>

Body:
I have 4 different Java Projects created in Eclipse.

One of them contains all my Utilities and Helper methods, that the other 3 projects use.

I don't want to copy that same package 3 times into each project, since I want to be able to just edit it in one place if I should have to. So, I have referenced the myUtilities project from all other 3 projects.

I'll be exporting the 3 main projects and they will be going to different servers to run independently as  "java -jar myproject.jar"

Everytime I do an export, the myUtilities.jar is not getting compiled in the JAR. If I open the JAR, I can see it is not there.  And this is going to be a problem when I move them to the other servers.

Is there a way to add the package into the source for the JAR? Or am I going to have to copy the myUtilities.jar into the JAVA_HOME of each server?

This is my current Manifest file:

Manifest-Version: 1.0
Main-Class: com.elcool.process.alpha.RetrieverMain


问:
Update a monitor once per tick instead of continuously. Slow model
I know that monitors are updated several times per second, and that can be helpful when checking the output of a model; however, that is not the case for my model, it just weighing it down.

I am trying to plot data from a monitor. I want the monitor to only update the reporter once per tick, if possible.

My model currently functions but it is bogged down updating multiple times a second. I was hoping someone could help me minimize my model's computational effort by updating once per tick.

sample of current code:

```<code>globals [initial-patch0-health patch0-health intial-patch2-health patch2-health]
patches-own [ptype penergy max-penergy alive?]

to setup
 clear-all
 set patch-health 0
 ask-patches [
    setup-patches
    ]
 reset-ticks
end
to setup-patches
 let temp random 100
 if temp <= 50 [
  set ptype 2
  set max-penergy random-in-range 0 5
  set alive? true
 ]
 if temp > 50 and temp <= 75 [
  set ptype 0
  set max-penergy random 10
  set alive? true
 ]
 set penergy max-penergy
 set patch2-health (ptype2-health)
 set patch0-health (ptype0-health)
end

to go
 ask-patches
  update-patch-health
 tick
end

to patch-health
 if ptype = 2[
   set patch2-health (ptype2-health)
 ]
 if ptype = 0 [
  set patch0-health (ptype0-health)
 ]
end

to-report ptype2-health
  report [penergy] of patches with [ptype = 2]
end

to-report ptype0-health
  report [penergy] of patches with [ptype = 0]
end
</code>```

My monitors and plot read (same for patch2-health):

```<code>sum (initial-patch0-health)
</code>```

and

```<code>plot sum (patch0-health)
</code>```

I use sum in this situation because the reporter delivers a list.

For context, I am doing a simple "sheep-wolf predation" style model but I want to monitor the initial grass health vs grass health over time, with multiple grass types (ptype). I have turtles but did not include that code here. Let me know if you need more code from me.

This code gives me the output I desire just at the cost of speed. I figured only reporting once every tick would save some computing time. Any suggestions for cleaning and speeding it up?

答:
Your code example is not usable to me (undefined variables, patch0-health is not output from a reporter, other errors)- check the MCVE guidelines. With that in mind, I'm having trouble replicating the issue you describe- I ran a few profiler tests with a monitor present and not present, and didn't get any difference in runtime. With this setup:

```<code>extensions [ profiler ]
globals [ patch-turtle-sum profiler-results]

to setup
  ca
  ask n-of ( ( count patches ) / 2 ) patches [
    set pcolor red
  ]
  crt 1000 [
    setxy random-pxcor random-pycor
  ]
  set profiler-results []
  reset-ticks
end

to profile-check
  repeat 20 [
    profiler:start
    repeat 20 [
      go
    ]
    set profiler-results lput profiler:inclusive-time "go" profiler-results
    profiler:reset
  ]
  print profiler-results
end

to go
  ask turtles [
    fd 1
  ]
  tick
end

to-report patch-turtle-sum-report
  report sum [count turtles-here] of patches with [ pcolor = red ]
end
</code>```

I ran the profile-check procedure from the interface, once with a monitor that monitors patch-turtle-sum-report present (mean go inclusive time: 678.59 ms) and once without (mean go inclusive time: 678.56 ms)- no detectable difference. However, I'm not sure if profiler accounts for monitor, so maybe that assessment is just not useful in this case. It could also be that the number of patches you're dealing with is quite large (in my test example I was doing 100 X 100 patches) so that the calculations get bogged down.

I wonder if you could get around your issue by using a monitor that just reports a variable that you manually calculate once per tick (instead of a to-report reporter)- eg to follow my example above, monitor a variable that is updated with something like:

```<code>set patch-turtle-sum sum [count turtles-here] of patches with [ pcolor = red ]
</code>```

That way you control when the calculation is done, which may speed up the model if the calculation is what's actually slowing down your model.

Body:
I know that monitors are updated several times per second, and that can be helpful when checking the output of a model; however, that is not the case for my model, it just weighing it down.

I am trying to plot data from a monitor. I want the monitor to only update the reporter once per tick, if possible.

My model currently functions but it is bogged down updating multiple times a second. I was hoping someone could help me minimize my model's computational effort by updating once per tick.

sample of current code:

globals [initial-patch0-health patch0-health intial-patch2-health patch2-health]
patches-own [ptype penergy max-penergy alive?]

to setup
 clear-all
 set patch-health 0
 ask-patches [
    setup-patches
    ]
 reset-ticks
end
to setup-patches
 let temp random 100
 if temp <= 50 [
  set ptype 2
  set max-penergy random-in-range 0 5
  set alive? true
 ]
 if temp > 50 and temp <= 75 [
  set ptype 0
  set max-penergy random 10
  set alive? true
 ]
 set penergy max-penergy
 set patch2-health (ptype2-health)
 set patch0-health (ptype0-health)
end

to go
 ask-patches
  update-patch-health
 tick
end

to patch-health
 if ptype = 2[
   set patch2-health (ptype2-health)
 ]
 if ptype = 0 [
  set patch0-health (ptype0-health)
 ]
end

to-report ptype2-health
  report [penergy] of patches with [ptype = 2]
end

to-report ptype0-health
  report [penergy] of patches with [ptype = 0]
end

My monitors and plot read (same for patch2-health):

sum (initial-patch0-health)

and

plot sum (patch0-health)

I use sum in this situation because the reporter delivers a list.

For context, I am doing a simple "sheep-wolf predation" style model but I want to monitor the initial grass health vs grass health over time, with multiple grass types (ptype). I have turtles but did not include that code here. Let me know if you need more code from me.

This code gives me the output I desire just at the cost of speed. I figured only reporting once every tick would save some computing time. Any suggestions for cleaning and speeding it up?

Body:
Your code example is not usable to me (undefined variables, patch0-health is not output from a reporter, other errors)- check the MCVE guidelines. With that in mind, I'm having trouble replicating the issue you describe- I ran a few profiler tests with a monitor present and not present, and didn't get any difference in runtime. With this setup:

extensions [ profiler ]
globals [ patch-turtle-sum profiler-results]

to setup
  ca
  ask n-of ( ( count patches ) / 2 ) patches [
    set pcolor red
  ]
  crt 1000 [
    setxy random-pxcor random-pycor
  ]
  set profiler-results []
  reset-ticks
end

to profile-check
  repeat 20 [
    profiler:start
    repeat 20 [
      go
    ]
    set profiler-results lput profiler:inclusive-time "go" profiler-results
    profiler:reset
  ]
  print profiler-results
end

to go
  ask turtles [
    fd 1
  ]
  tick
end

to-report patch-turtle-sum-report
  report sum [count turtles-here] of patches with [ pcolor = red ]
end

I ran the profile-check procedure from the interface, once with a monitor that monitors patch-turtle-sum-report present (mean go inclusive time: 678.59 ms) and once without (mean go inclusive time: 678.56 ms)- no detectable difference. However, I'm not sure if profiler accounts for monitor, so maybe that assessment is just not useful in this case. It could also be that the number of patches you're dealing with is quite large (in my test example I was doing 100 X 100 patches) so that the calculations get bogged down.

I wonder if you could get around your issue by using a monitor that just reports a variable that you manually calculate once per tick (instead of a to-report reporter)- eg to follow my example above, monitor a variable that is updated with something like:

set patch-turtle-sum sum [count turtles-here] of patches with [ pcolor = red ]

That way you control when the calculation is done, which may speed up the model if the calculation is what's actually slowing down your model.


问:
Import and using shape files Python and matplotlib
Im having trouble implementing my shape file into my python notebook.

It doesnt seem to be referencing my file even though the path location is correct.

```<code>import shapefile as shp
sf = shp.Reader("/Shape/mygeodata/northern-ireland")

#create figure to draw map and set its size
fig, ax = plt.subplots(figsize=(10,20))

#create map with the below code
m = Basemap(resolution='h', # c, l, i, h, f or None
            projection='merc',
            lat_0=0, lon_0=0,
            llcrnrlon=-8.239, llcrnrlat=53.9911, urcrnrlon=-5.3723, urcrnrlat=55.276)

#define how map is displayed
m.drawmapboundary(fill_color='#46bcec')
m.fillcontinents(color='#f2f2f2',lake_color='#46bcec')
m.drawcoastlines()

#for loop to plot the longitude and latitude of each crime
for i, row in crimeDataNI.iterrows():
        lat = row['Latitude']
        lon  = row['Longitude']
        x,y = m(lon, lat)
        m.plot(x, y, 'o', markersize=6, color='#444444', alpha=0.8)

#try and read in Northern Ireland police force boundaries
m.readshapefile(sf, 'northern-ireland')
</code>```

And i am getting the following error:

ShapefileException: Unable to open /Shape/mygeodata/northern-ireland.dbf or /Shape/mygeodata/northern-ireland.shp.

答:
You are probably referencing the file incorrectly.  Take a look at this tutorial https://chrishavlin.wordpress.com/2016/11/16/shapefiles-tutorial/  for an example on using shapefiles with MatPlotLib.

Also you might want to search https://gis.stackexchange.com for more help and pointers.

Body:
Im having trouble implementing my shape file into my python notebook.

It doesnt seem to be referencing my file even though the path location is correct.

import shapefile as shp
sf = shp.Reader("/Shape/mygeodata/northern-ireland")

#create figure to draw map and set its size
fig, ax = plt.subplots(figsize=(10,20))

#create map with the below code
m = Basemap(resolution='h', # c, l, i, h, f or None
            projection='merc',
            lat_0=0, lon_0=0,
            llcrnrlon=-8.239, llcrnrlat=53.9911, urcrnrlon=-5.3723, urcrnrlat=55.276)

#define how map is displayed
m.drawmapboundary(fill_color='#46bcec')
m.fillcontinents(color='#f2f2f2',lake_color='#46bcec')
m.drawcoastlines()

#for loop to plot the longitude and latitude of each crime
for i, row in crimeDataNI.iterrows():
        lat = row['Latitude']
        lon  = row['Longitude']
        x,y = m(lon, lat)
        m.plot(x, y, 'o', markersize=6, color='#444444', alpha=0.8)

#try and read in Northern Ireland police force boundaries
m.readshapefile(sf, 'northern-ireland')

And i am getting the following error:

ShapefileException: Unable to open /Shape/mygeodata/northern-ireland.dbf or /Shape/mygeodata/northern-ireland.shp.


问:
Set a Property in a ViewModel from Another ViewModel
I am trying to pass a value to a view model from another view model before navigating to the page attached to that view model.
I was previously passing it to the view, then passing it to the view model. This seems like a clumsy way of doing things.
I am not using any kind of framework so that is not an option.
At the moment the property is set as static and this works but im not sure if this is good practice.
The code:

View model 1:

This command opens the new page:

```<code>public void OpenRouteDetails()
{
   RouteStopPopOverViewModel.RouteName = "TestRoute";
   App.Page.Navigation.PushAsync(new RouteStopPopOverView());
}
</code>```

View model 2: (RouteStopPopOverViewModel)

```<code>public static string RouteName { get; set; }
</code>```

This does work but I would prefer not to use static as a way to achieve this.
Is there some way to set the RouteName property without using static or passing it through view-> view model.
I have seen some answers about this but they don't seem to answer to question clearly.

答:
Share a controller class between view models.

The same instance has to be supplied to the constructor in both view models.

So you can set values, and listen for events in both view models.

The controller class becomes the intermediary.

```<code>public class SharedController : IControlSomething
{
    private string _sharedValue;

    public string SharedValue
    {
        get => _sharedValue;
        set
        {
            if (_sharedValue == value)
                return;

            _sharedValue = value;
            OnSharedValueUpdated();
        }
    }

    public event EventHandler SharedValueUpdated;

    protected virtual void OnSharedValueUpdated()
    {
        SharedValueUpdated?.Invoke(this, EventArgs.Empty);
    }
}

public class ViewModel1
{
    private readonly IControlSomething _controller;

    public ViewModel1(IControlSomething controller)
    {
        // Save to access controller values in commands
        _controller = controller;
        _controller.SharedValueUpdated += (sender, args) =>
        {
            // Handle value update event
        };
    }
}

public class ViewModel2
{
    private readonly IControlSomething _controller;

    public ViewModel2(IControlSomething controller)
    {
        // Save to access controller values in commands
        _controller = controller;
        _controller.SharedValueUpdated += (sender, args) =>
        {
            // Handle value update event
        };
    }
}
</code>```

Body:
I am trying to pass a value to a view model from another view model before navigating to the page attached to that view model.
I was previously passing it to the view, then passing it to the view model. This seems like a clumsy way of doing things.
I am not using any kind of framework so that is not an option.
At the moment the property is set as static and this works but im not sure if this is good practice.
The code:

View model 1:

This command opens the new page:

public void OpenRouteDetails()
{
   RouteStopPopOverViewModel.RouteName = "TestRoute";
   App.Page.Navigation.PushAsync(new RouteStopPopOverView());
}

View model 2: (RouteStopPopOverViewModel)

public static string RouteName { get; set; }

This does work but I would prefer not to use static as a way to achieve this.
Is there some way to set the RouteName property without using static or passing it through view-> view model.
I have seen some answers about this but they don't seem to answer to question clearly.

Body:
Share a controller class between view models.

The same instance has to be supplied to the constructor in both view models.

So you can set values, and listen for events in both view models.

The controller class becomes the intermediary.

public class SharedController : IControlSomething
{
    private string _sharedValue;

    public string SharedValue
    {
        get => _sharedValue;
        set
        {
            if (_sharedValue == value)
                return;

            _sharedValue = value;
            OnSharedValueUpdated();
        }
    }

    public event EventHandler SharedValueUpdated;

    protected virtual void OnSharedValueUpdated()
    {
        SharedValueUpdated?.Invoke(this, EventArgs.Empty);
    }
}

public class ViewModel1
{
    private readonly IControlSomething _controller;

    public ViewModel1(IControlSomething controller)
    {
        // Save to access controller values in commands
        _controller = controller;
        _controller.SharedValueUpdated += (sender, args) =>
        {
            // Handle value update event
        };
    }
}

public class ViewModel2
{
    private readonly IControlSomething _controller;

    public ViewModel2(IControlSomething controller)
    {
        // Save to access controller values in commands
        _controller = controller;
        _controller.SharedValueUpdated += (sender, args) =>
        {
            // Handle value update event
        };
    }
}


问:
Looping through nested arrays and converting to objects
I want to convert an group of nested arrays into an array of objects with the collected information from the nested arrays:

BEFORE:

```<code>var employeeData = [
  [
    ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
  ],
  [
    ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
  ]
]
</code>```

AFTER:

```<code>[
  {firstName: 'Bob', lastName: 'Lob', age: 22, role: 'salesperson'},
  {firstName: 'Mary', lastName: 'Joe', age: 32, role: 'director'}
]
</code>```

Here is the function I wrote to solve this but I can't quite see where the loop is going wrong:

    var employeeData = [
      [
        ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
      ],
      [
        ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
      ]
    ]

    function transformData(employeeData) {
      let newObject = {};
      let newArr = [];

      for (var i = 0; i < employeeData.length; i++) {
        for (var x = 0; x < employeeData[i].length; x++) {
          for (var y = 0; y < employeeData[i][y].length; y++) {
            newObject[employeeData[i][y][0]] = employeeData[i][y][1];
          }
        }
        newArr.push(newObject);
        newObject = {};
      }
      return newArr;
    }

    console.log(transformData(employeeData));```

Thanks in advance.

答:
The problmem you face can be solved using for loops, as you were trying, if you use your indexes correctly.
If you format your data as I did, you will see that there is three levels for your indexes your [i,x,y];

for example for employeeData[0] you should get:

```<code>[
    ['firstName', 'Bob'],
    ['lastName', 'Lob'],
    ['age', 22],
    ['role', 'salesperson']
  ]
</code>```

then for employeeData[0][0] you should get:

```<code> ['firstName', 'Bob']
</code>```

and for employeeData[0][0][0] you should get: 'firstName'

To access 'Bob' you would need to employeeData[0][0][1]  and since you know that there is only two elements in this inner array you don´t need to loop though it.
as @TallChuck suggested great part of your problem stems from forgetting to use your x index.

var employeeData = [
  [
    ['firstName', 'Bob'],
    ['lastName', 'Lob'],
    ['age', 22],
    ['role', 'salesperson']
  ],
  [
    ['firstName', 'Mary'],
    ['lastName', 'Joe'],
    ['age', 32],
    ['role', 'director']
  ]
]

function transformData(employeeData) {
  let newObject = {};
  let newArr = [];

  for (var i = 0; i < employeeData.length; i++) {
    for (var x = 0; x < employeeData[i].length; x++) {
      newObject[employeeData[i][x][0]] = employeeData[i][x][1];
    }
    newArr.push(newObject);
    newObject = {};
  }
  return newArr;
}

console.log(transformData(employeeData));```
</div>
</div>
</p>

<p>EDIT</p>

<hr>

<p>You could also make some more complex solutions if you pay attention to your indexes. Say you have the following data:</p>

```var employeeData = [
  [
    ['firstName', 'Bob', 'weight', '80kg'],
    ['lastName', 'Lob'],
    ['age', 22],
    ['role', 'salesperson']
  ],
  [
    ['firstName', 'Mary', 'eye color', 'green'],
    ['lastName', 'Joe'],
    ['age', 32],
    ['role', 'director']
  ]
]
```

<p>Then the solution I gave before wouldn´t work directly. But if you look closely you will see that in some of the arrays your field names are located in the positions 0, 2 of the <strong>Y</strong> index. Which means that your field names are in a pair positions and the filed values in the odd positions. So you can actually make a loop through y and just check if the Y index is divisible by 2. </p>

```if(y % 2 == 0 ..){}
```

<p>And do this only if there is an accompanying odd value thus</p>

```if(y % 2 == 0 && employeeData[i][x][y+1]){..}
```

<p>The full code is below.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var employeeData = [
  [
    ['firstName', 'Bob', 'weight', '80kg'],
    ['lastName', 'Lob'],
    ['age', 22],
    ['role', 'salesperson']
  ],
  [
    ['firstName', 'Mary', 'eye color', 'green'],
    ['lastName', 'Joe'],
    ['age', 32],
    ['role', 'director']
  ]
]

function transformData(employeeData) {
  let newObject = {};
  let newArr = [];

  for (var i = 0; i < employeeData.length; i++) {
    for (var x = 0; x < employeeData[i].length; x++) {
      for (var y = 0; y < employeeData[i][x].length; y++) {
        if(y % 2 == 0 && employeeData[i][x][y+1]){
          newObject[employeeData[i][x][y]] = employeeData[i][x][y+1];
        }
      }
    }
    newArr.push(newObject);
    newObject = {};
  }
  return newArr;
}

console.log(transformData(employeeData));</code>```

Body:
I want to convert an group of nested arrays into an array of objects with the collected information from the nested arrays:

BEFORE:

var employeeData = [
  [
    ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
  ],
  [
    ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
  ]
]

AFTER:

[
  {firstName: 'Bob', lastName: 'Lob', age: 22, role: 'salesperson'},
  {firstName: 'Mary', lastName: 'Joe', age: 32, role: 'director'}
]

Here is the function I wrote to solve this but I can't quite see where the loop is going wrong:

    var employeeData = [
      [
        ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
      ],
      [
        ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
      ]
    ]

    function transformData(employeeData) {
      let newObject = {};
      let newArr = [];

      for (var i = 0; i < employeeData.length; i++) {
        for (var x = 0; x < employeeData[i].length; x++) {
          for (var y = 0; y < employeeData[i][y].length; y++) {
            newObject[employeeData[i][y][0]] = employeeData[i][y][1];
          }
        }
        newArr.push(newObject);
        newObject = {};
      }
      return newArr;
    }

    console.log(transformData(employeeData));

Thanks in advance.

Body:
The problmem you face can be solved using for loops, as you were trying, if you use your indexes correctly.
If you format your data as I did, you will see that there is three levels for your indexes your [i,x,y];

for example for employeeData[0] you should get:

[
    ['firstName', 'Bob'],
    ['lastName', 'Lob'],
    ['age', 22],
    ['role', 'salesperson']
  ]

then for employeeData[0][0] you should get:

 ['firstName', 'Bob']

and for employeeData[0][0][0] you should get: 'firstName'

To access 'Bob' you would need to employeeData[0][0][1]  and since you know that there is only two elements in this inner array you don´t need to loop though it.
as @TallChuck suggested great part of your problem stems from forgetting to use your x index.

var employeeData = [
  [
    ['firstName', 'Bob'],
    ['lastName', 'Lob'],
    ['age', 22],
    ['role', 'salesperson']
  ],
  [
    ['firstName', 'Mary'],
    ['lastName', 'Joe'],
    ['age', 32],
    ['role', 'director']
  ]
]

function transformData(employeeData) {
  let newObject = {};
  let newArr = [];

  for (var i = 0; i < employeeData.length; i++) {
    for (var x = 0; x < employeeData[i].length; x++) {
      newObject[employeeData[i][x][0]] = employeeData[i][x][1];
    }
    newArr.push(newObject);
    newObject = {};
  }
  return newArr;
}

console.log(transformData(employeeData));

EDIT

You could also make some more complex solutions if you pay attention to your indexes. Say you have the following data:

var employeeData = [
  [
    ['firstName', 'Bob', 'weight', '80kg'],
    ['lastName', 'Lob'],
    ['age', 22],
    ['role', 'salesperson']
  ],
  [
    ['firstName', 'Mary', 'eye color', 'green'],
    ['lastName', 'Joe'],
    ['age', 32],
    ['role', 'director']
  ]
]

Then the solution I gave before wouldn´t work directly. But if you look closely you will see that in some of the arrays your field names are located in the positions 0, 2 of the Y index. Which means that your field names are in a pair positions and the filed values in the odd positions. So you can actually make a loop through y and just check if the Y index is divisible by 2.

if(y % 2 == 0 ..){}

And do this only if there is an accompanying odd value thus

if(y % 2 == 0 && employeeData[i][x][y+1]){..}

The full code is below.

var employeeData = [
  [
    ['firstName', 'Bob', 'weight', '80kg'],
    ['lastName', 'Lob'],
    ['age', 22],
    ['role', 'salesperson']
  ],
  [
    ['firstName', 'Mary', 'eye color', 'green'],
    ['lastName', 'Joe'],
    ['age', 32],
    ['role', 'director']
  ]
]

function transformData(employeeData) {
  let newObject = {};
  let newArr = [];

  for (var i = 0; i < employeeData.length; i++) {
    for (var x = 0; x < employeeData[i].length; x++) {
      for (var y = 0; y < employeeData[i][x].length; y++) {
        if(y % 2 == 0 && employeeData[i][x][y+1]){
          newObject[employeeData[i][x][y]] = employeeData[i][x][y+1];
        }
      }
    }
    newArr.push(newObject);
    newObject = {};
  }
  return newArr;
}

console.log(transformData(employeeData));


问:
How not to stop owl carousel on hover?
Currently the carousel stops when you hover it, I've added autoplayHoverPause:false but it doesn't seem to change anything.
Is there another option that I could use to stop it from stopping when it's hovered?

```<code>$('.owl-carousel').owlCarousel({
    autoplayHoverPause:false,
    loop:true,
    margin:0,
    nav:true,
    responsive:{
        0:{
            items:1
        },
        600:{
            items:2
        },
        1000:{
            items:4
        }
    }
});
</code>```

答: Just add stopOnHover:true in your script.

Title: How not to stop owl carousel on hover?

Body:
Currently the carousel stops when you hover it, I've added autoplayHoverPause:false but it doesn't seem to change anything.
Is there another option that I could use to stop it from stopping when it's hovered?

$('.owl-carousel').owlCarousel({
    autoplayHoverPause:false,
    loop:true,
    margin:0,
    nav:true,
    responsive:{
        0:{
            items:1
        },
        600:{
            items:2
        },
        1000:{
            items:4
        }
    }
});


答:
Join the address table twice. Example with your data below.</p>

```<code>CREATE TABLE #Orders (OrderID int, ShippingAddressId int, BillingAddressId int)
CREATE TABLE #Address (AddressID int, Address1 varchar(100), City varchar(100), RegionCode varchar(100))

INSERT INTO #Orders (OrderID, ShippingAddressId, BillingAddressId) VALUES
(201800194 , 21183, 21182)

INSERT INTO #Address (AddressID, Address1, City, RegionCode) VALUES
(21182, '123 Somewhere Dr', 'Hometown1', 'Florida'),
(21183, '456 Elsewhere Rd', 'Hometown2', 'Florida')

SELECT
    ORD.OrderID,
    BILL.Address1 AS 'BillingAddress1',
    BILL.City AS 'BillingCity',
    BILL.RegionCode AS 'BillingRegionCode',
    SHIP.Address1 AS 'ShippingAddress1',
    SHIP.City AS 'ShippingCity',
    SHIP.RegionCode AS 'ShippingRegionCode'
FROM
    #Orders AS ORD
    LEFT OUTER JOIN #Address AS SHIP
        ON ORD.ShippingAddressId = SHIP.AddressID
    LEFT OUTER JOIN #Address AS BILL
        ON ORD.BillingAddressId = BILL.AddressID

DROP TABLE #Orders
DROP TABLE #Address
</code>```

Title: Select multiple columns from another table depending on value of column

Body:
I'm not even sure this is possible, but I have an order table (online store).  Within this table, the shipping and billing address columns are ID's which correspond with the address table.

For E.g.

OrderID     ShippingAddressID   BillingAddressID
201800194   21183               21182

The Address table then lists the address information.

AddressID   Address1            City        RegionCode
21182       123 Somewhere Dr    Hometown1   Florida
21183       456 Elsewhere Rd    Hometown2   Florida

I'd like the resulting listing to show something similar to this:

OrderID     BillingAddress1     BillingCity BillingRegionCode   ShippingAddress1    ShippingCity    ShippingRegionCode
201800194   123 Somewhere Dr    Hometown1   Florida             456 Elsewhere Rd    Hometown2       Florida

Is this even possible?

Thanks..

Body:
Join the address table twice. Example with your data below.

CREATE TABLE #Orders (OrderID int, ShippingAddressId int, BillingAddressId int)
CREATE TABLE #Address (AddressID int, Address1 varchar(100), City varchar(100), RegionCode varchar(100))

INSERT INTO #Orders (OrderID, ShippingAddressId, BillingAddressId) VALUES
(201800194 , 21183, 21182)

INSERT INTO #Address (AddressID, Address1, City, RegionCode) VALUES
(21182, '123 Somewhere Dr', 'Hometown1', 'Florida'),
(21183, '456 Elsewhere Rd', 'Hometown2', 'Florida')

SELECT
    ORD.OrderID,
    BILL.Address1 AS 'BillingAddress1',
    BILL.City AS 'BillingCity',
    BILL.RegionCode AS 'BillingRegionCode',
    SHIP.Address1 AS 'ShippingAddress1',
    SHIP.City AS 'ShippingCity',
    SHIP.RegionCode AS 'ShippingRegionCode'
FROM
    #Orders AS ORD
    LEFT OUTER JOIN #Address AS SHIP
        ON ORD.ShippingAddressId = SHIP.AddressID
    LEFT OUTER JOIN #Address AS BILL
        ON ORD.BillingAddressId = BILL.AddressID

DROP TABLE #Orders
DROP TABLE #Address


问:
Why do I have to create a new instance template just to do a minor update to my instance group?
Say I want to update the server for a running instance group, I have to create a new image from another instance and then create an instance template from that image and then run a rolling update on the instance group. That's an a lot of steps to do minor changes to my managed instances. Is there a less tedious/slow way to do updates to running managed instance groups? </p>

答:
Please note managed instances are based on instance template so you can not skip the step of updating it.

If you need configuration changes on all instances or a limited number of instances under the managed instance group, a rolling update is the best automated solution. With the rolling update, you can choose various options like how many instances can be taken offline for the update, whether the update affects all or just a segment of instances, and so on. You can find the detailed description in this article.

Without rollout update, a new configuration must be deployed either by creating a new managed instance group with a new version, requiring additional set up each time or through a manual, user-initiated, instance-by-instance recreate. Both of these approaches require significant manual steps.
But for a minor configuration on the limited number of instances, you can still opt for manual, user-initiated configuration if that is really time-saving than the rolling update. However, if something fails in the instance it gets recreated with the original template configuration.


问:
Time issue in calendar entries in google apps
I am migrating the Calendar entries with recurrence from outlook to google apps.But  the start time and the end time of the same recurrence entry in google apps is not coming correctly.The time zone of google apps account is set as (GMT+00.00)GMT(no daylight saving).
Please help.

Regards
Sanchaita chakraborty

答:
Its not clear from your question what you are asking..
But As i checked in google documentation a time format like this is used in API 2010-03-29T13:12:38.861Z.

So u can easily convert it to C# datetime object by using DateTime.TryParse method. however it returns the date in your current culture timezone. If you want the time zone of the Actual date you can use DateTimeTime.TryParseExact and provide the CultureInfo.


问:
C# - receiving a file through network stream is blocking WPF UI
I have this method for receiving a file.

public Task Download(IProgress<int> downloadProgress)
{
    return Task.Run
    (
        async () =>
        {
            var counter = 0;

            var buffer = new byte[1024];

            while (true)
            {
                var byteCount = await _networkStream.ReadAsync(buffer, 0, buffer.Length);

                counter += byteCount;
                downloadProgress.Report(counter);

                if (byteCount != buffer.Length)
                    break;
            }
        }
    );
}
```

<p>Then in the UI I call it like this:</p>

<pre class="lang-cs prettyprint-override"><code>await Download(progress);
</code>```

where progress is simply updating a label.

When I run, the UI will be blocked (but after some time it will correctly update the label). I don't understand why, shouldn't Task.Run() create a new thread?

How do I fix this please?

答:
You are calling downloadProgress.Report on an infinite loop without any pause in execution. My educated guess is this means every time execution time is available on the UI thread, the non-UI thread is requesting an operation which will require the UI thread's time (as demanded by the synchronisation context) and therefore clogging it up with invocations.

Essentially, rather than blocking the UI thread with one long execution, you may be blocking it with an un-ending stream of tiny ones.

Try putting a Thread.Sleep(10) in your 'spinlock' while(true) { ... } loop and see if that alleviates the issue.

Body:
I have this method for receiving a file.

public Task Download(IProgress<int> downloadProgress)
{
    return Task.Run
    (
        async () =>
        {
            var counter = 0;

            var buffer = new byte[1024];

            while (true)
            {
                var byteCount = await _networkStream.ReadAsync(buffer, 0, buffer.Length);

                counter += byteCount;
                downloadProgress.Report(counter);

                if (byteCount != buffer.Length)
                    break;
            }
        }
    );
}

Then in the UI I call it like this:

await Download(progress);

where progress is simply updating a label.

When I run, the UI will be blocked (but after some time it will correctly update the label). I don't understand why, shouldn't Task.Run() create a new thread?

How do I fix this please?


问:
How to add the values from a foreach loop php
I have and foreach loop that outputs the totals I want to add when i echo the $val_tex it outputs in one number like "4911165" but if I echo it with a break tag it gives me the right values. It looks like

49

1

1

1

65

My question is how to get the sum of all the values which should equal "117"

```<code>$val_tex = array();

foreach ( $get_seller as $keys ) {

     $val_tex = $keys['total'];

}
</code>```

答:
Your for each needs another variable to add them:

```<code>foreach ( $get_seller as $keys ) {

     $val_tex = $keys['total'];
     $sum = += $val_tex
//or...
     $val_tex += $keys['total'];
//depending on how you want to us val_tex

}
</code>```

The .= adds the value to previous value instead of overwriting it.

Body:
I have and foreach loop that outputs the totals I want to add when i echo the $val_tex it outputs in one number like "4911165" but if I echo it with a break tag it gives me the right values. It looks like

49

1

1

1

65

My question is how to get the sum of all the values which should equal "117"

$val_tex = array();

foreach ( $get_seller as $keys ) {

     $val_tex = $keys['total'];

}

Body:
Your for each needs another variable to add them:

foreach ( $get_seller as $keys ) {

     $val_tex = $keys['total'];
     $sum = += $val_tex
//or...
     $val_tex += $keys['total'];
//depending on how you want to us val_tex

}

The .= adds the value to previous value instead of overwriting it.


问:
Why does my php upload not work?
TL;DR: why does reuploding the uploaded data not work?

I' trying to upload the data a user uploaded to my file to another server. This means, I want to post my post data.

I want to upload some data to upload.php, which then should get posted to test.php (which simply outputs the raw post data). And due to memory saving, I wanted it to work without generating the post whole message as string. Thus I also don't want to use curl.

test.php

```<code><?php
echo 'foo', file_get_contents('php://input'), 'bar';
</code>```

upload.php

```<code><?php
//new line variable
$NL = "\r\n";

//open the posted data as a resource
$client_upload = fopen('php://input', 'r');
//open the connection to the other server
$server_upload = fsockopen('ssl://example.com', 443);

//write the http headers to the socket
fwrite($server_upload, 'POST /test.php HTTP/1.1' . $NL);
fwrite($server_upload, 'Host: example.com' . $NL);
fwrite($server_upload, 'Connection: close' . $NL);
//header/body divider
fwrite($server_upload, $NL);

//loop until client upload reached the end
while (!feof($client_upload)) {
    fwrite($server_upload, fread($client_upload, 1024));
}
//close the client upload resource - not needed anymore
fclose($client_upload);

//intitalize response variable
$response = '';
//loop until server upload reached the end
while (!feof($server_upload)) {
    $response .= fgets($server_upload, 1024);
}
//close the server upload resource - not needed anymore
fclose($server_upload);

//output the response
echo $response;
</code>```

When I post { "test": true } (from Fiddler) to test.php file, it outputs foo{ "test": true }bar.

Now when I try to do the same for upload.php, I just get foobar (and the http headers from test.php) but not the uploaded content.

答:
Finally I managed to fix this error. Apparently the other server (and mine) depend on the http header Content-Length.

As you can see in my answer, I was not sending (neither calculating) this header. So when I finally now calculated and sent the Content-Length header everything worked. This are the missing lines:

```<code>$content_length = fstat($client_upload)['size'];
fwrite($server_upload, 'Content-Length: ' . $content_length . $NL);
</code>```

The reupload (of the uploaded data to my server) didn't work, because the other server just read the body as long as it was specified in the Content-Length header. Because I was not sending this header, it didn't work.

Title: Why does my php upload not work?

Body:
TL;DR: why does reuploding the uploaded data not work?

I' trying to upload the data a user uploaded to my file to another server. This means, I want to post my post data.

I want to upload some data to upload.php, which then should get posted to test.php (which simply outputs the raw post data). And due to memory saving, I wanted it to work without generating the post whole message as string. Thus I also don't want to use curl.

test.php

<?php
echo 'foo', file_get_contents('php://input'), 'bar';

upload.php

<?php
//new line variable
$NL = "\r\n";

//open the posted data as a resource
$client_upload = fopen('php://input', 'r');
//open the connection to the other server
$server_upload = fsockopen('ssl://example.com', 443);

//write the http headers to the socket
fwrite($server_upload, 'POST /test.php HTTP/1.1' . $NL);
fwrite($server_upload, 'Host: example.com' . $NL);
fwrite($server_upload, 'Connection: close' . $NL);
//header/body divider
fwrite($server_upload, $NL);

//loop until client upload reached the end
while (!feof($client_upload)) {
    fwrite($server_upload, fread($client_upload, 1024));
}
//close the client upload resource - not needed anymore
fclose($client_upload);

//intitalize response variable
$response = '';
//loop until server upload reached the end
while (!feof($server_upload)) {
    $response .= fgets($server_upload, 1024);
}
//close the server upload resource - not needed anymore
fclose($server_upload);

//output the response
echo $response;

When I post { "test": true } (from Fiddler) to test.php file, it outputs foo{ "test": true }bar.

Now when I try to do the same for upload.php, I just get foobar (and the http headers from test.php) but not the uploaded content.

Body:
Finally I managed to fix this error. Apparently the other server (and mine) depend on the http header Content-Length.

As you can see in my answer, I was not sending (neither calculating) this header. So when I finally now calculated and sent the Content-Length header everything worked. This are the missing lines:

$content_length = fstat($client_upload)['size'];
fwrite($server_upload, 'Content-Length: ' . $content_length . $NL);

The reupload (of the uploaded data to my server) didn't work, because the other server just read the body as long as it was specified in the Content-Length header. Because I was not sending this header, it didn't work.


问:
SendGrid: how to add a simple non-email address name for the sender
I am using SendGrid API v3 for Java. It works and does the job. However, if the sender is, say, hello@world.org, the recipient sees only that very hello@world.org. What I try to accomplish is that the recipient sees also a simple name (for example, Hello World <hello@world.org>) like this:

(Above, note that the actual address is noreply@k..., yet it is preceded with Kela Fpa.)

How can I do that programmatically?

答:
Without your code, it's hard to suggest exactly what to do, but according to their API documentation, the endpoint does in fact support an optional 'name' attribute for the sender

Taking a further glance at their Java API's source code, it looks like the example, which is this:

```<code>import com.sendgrid.*;
import java.io.IOException;

public class Example {
  public static void main(String[] args) throws IOException {
    Email from = new Email("test@example.com");
    String subject = "Sending with SendGrid is Fun";
    Email to = new Email("test@example.com");
    Content content = new Content("text/plain", "and easy to do anywhere, even with Java");
    Mail mail = new Mail(from, subject, to, content);

    SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));
    Request request = new Request();
    try {
      request.setMethod(Method.POST);
      request.setEndpoint("mail/send");
      request.setBody(mail.build());
      Response response = sg.api(request);
      System.out.println(response.getStatusCode());
      System.out.println(response.getBody());
      System.out.println(response.getHeaders());
    } catch (IOException ex) {
      throw ex;
    }
  }
}
</code>```

Using the source code, you can supply a "name" to the Email constructor, as seen here
Could be re-worked into this:

```<code>import com.sendgrid.*;
import java.io.IOException;

public class Example {
  public static void main(String[] args) throws IOException {
    Email from = new Email("test@example.com", "John Doe");
    String subject = "Sending with SendGrid is Fun";
    Email to = new Email("test@example.com", "Jane Smith");
    Content content = new Content("text/plain", "and easy to do anywhere, even with Java");
    Mail mail = new Mail(from, subject, to, content);

    SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));
    Request request = new Request();
    try {
      request.setMethod(Method.POST);
      request.setEndpoint("mail/send");
      request.setBody(mail.build());
      Response response = sg.api(request);
      System.out.println(response.getStatusCode());
      System.out.println(response.getBody());
      System.out.println(response.getHeaders());
    } catch (IOException ex) {
      throw ex;
    }
  }
}
</code>```

Note, the email constructors being changed.

If you're not using the Mail helper class for some reason, please let me know and I can re-work an example maybe.

Body:
Without your code, it's hard to suggest exactly what to do, but according to their API documentation, the endpoint does in fact support an optional 'name' attribute for the sender

Taking a further glance at their Java API's source code, it looks like the example, which is this:

import com.sendgrid.*;
import java.io.IOException;

public class Example {
  public static void main(String[] args) throws IOException {
    Email from = new Email("test@example.com");
    String subject = "Sending with SendGrid is Fun";
    Email to = new Email("test@example.com");
    Content content = new Content("text/plain", "and easy to do anywhere, even with Java");
    Mail mail = new Mail(from, subject, to, content);

    SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));
    Request request = new Request();
    try {
      request.setMethod(Method.POST);
      request.setEndpoint("mail/send");
      request.setBody(mail.build());
      Response response = sg.api(request);
      System.out.println(response.getStatusCode());
      System.out.println(response.getBody());
      System.out.println(response.getHeaders());
    } catch (IOException ex) {
      throw ex;
    }
  }
}

Using the source code, you can supply a "name" to the Email constructor, as seen here
Could be re-worked into this:

import com.sendgrid.*;
import java.io.IOException;

public class Example {
  public static void main(String[] args) throws IOException {
    Email from = new Email("test@example.com", "John Doe");
    String subject = "Sending with SendGrid is Fun";
    Email to = new Email("test@example.com", "Jane Smith");
    Content content = new Content("text/plain", "and easy to do anywhere, even with Java");
    Mail mail = new Mail(from, subject, to, content);

    SendGrid sg = new SendGrid(System.getenv("SENDGRID_API_KEY"));
    Request request = new Request();
    try {
      request.setMethod(Method.POST);
      request.setEndpoint("mail/send");
      request.setBody(mail.build());
      Response response = sg.api(request);
      System.out.println(response.getStatusCode());
      System.out.println(response.getBody());
      System.out.println(response.getHeaders());
    } catch (IOException ex) {
      throw ex;
    }
  }
}

Note, the email constructors being changed.

If you're not using the Mail helper class for some reason, please let me know and I can re-work an example maybe.