问:
Why would a character array be unchanged after a for-loop?
I have built a function with the goal of taking text that is fed from elsewhere in the program and removing all whitespace and punctuation from it. I'm able to remove whitespace and punctuation, but the changes don't stay after they are made. For instance, I put the character array/string into a for-loop to remove whitespace and verify that the whitespace is removed by printing the current string to the screen. When I send the string through a loop to remove punctuation, though, it acts as though I did not remove whitespace from earlier. This is an example of what I'm talking about:

Example of output to screen

The function that I'm using is here.

```<code>//eliminates all punctuation, capital letters, and whitespace in plaintext
char *formatPlainText(char *plainText) {
    int length = strlen(plainText);

    //turn capital letters into lower case letters
    for (int i = 0; i < length; i++)
        plainText[i] = tolower(plainText[i]);

    //remove whitespace
    for (int i = 0; i < length; i++) {
        if (plainText[i] == ' ')
            plainText[i] = plainText[i++];

        printf("%c", plainText[i]);
    }
    printf("\n\n");

    //remove punctuation from text
    for (int i = 0; i < length; i++) {
        if (ispunct(plainText[i]))
            plainText[i] = plainText[i++];

        printf("%c", plainText[i]);
    }
}
</code>```

Any help as to why the text is unchanged after if exits the loop would be appreciated.

答:
The code does convert the string to lower case, but the space and punctuation removal phases are broken: plainText[i] = plainText[i++]; has undefined behavior because you use i and modify it elsewhere in the same expression.

Furthermore, you do not return plainText from the function. Depending on how you use the function, this leads to undefined behavior if you store the return value to a pointer and later dereference it.

You can fix the problems by using 2 different index variables for reading and writing to the string when removing characters.

Note too that you should not use a length variable as the string length changes in the second and third phase. Texting for the null terminator is simpler.

Also note that tolower() and ispunct() and other functions from <ctype.h> are only defined for argument values in the range 0..UCHAR_MAX and the special negative value EOF. char arguments must be cast as (unsigned char) to avoid undefined behavior on negative char values on platforms where char is signed by default.

Here is a modified version:

#include <ctype.h>

//eliminate all punctuation, capital letters, and whitespace in plaintext
char *formatPlainText(char *plainText) {
    size_t i, j;

    //turn capital letters into lower case letters
    for (i = 0; plainText[i] != '\0'; i++) {
        plainText[i] = tolower((unsigned char)plainText[i]);
    }
    printf("lowercase: %s\n", plainText);

    //remove whitespace
    for (i = j = 0; plainText[i] != '\0'; i++) {
        if (plainText[i] != ' ')
            plainText[j++] = plainText[i];
    }
    plainText[j] = '\0';
    printf("no white space: %s\n", plainText);

    //remove punctuation from text
    for (i = j = 0; plainText[i] != '\0'; i++) {
        if (!ispunct((unsigned char)plainText[i]))
            plainText[j++] = plainText[i];
    }
    plainText[j] = '\0';
    printf("no punctuation: %s\n", plainText);
    return plainText;
}
```

Body:
I have built a function with the goal of taking text that is fed from elsewhere in the program and removing all whitespace and punctuation from it. I'm able to remove whitespace and punctuation, but the changes don't stay after they are made. For instance, I put the character array/string into a for-loop to remove whitespace and verify that the whitespace is removed by printing the current string to the screen. When I send the string through a loop to remove punctuation, though, it acts as though I did not remove whitespace from earlier. This is an example of what I'm talking about:

Example of output to screen

The function that I'm using is here.

//eliminates all punctuation, capital letters, and whitespace in plaintext
char *formatPlainText(char *plainText) {
    int length = strlen(plainText);

    //turn capital letters into lower case letters
    for (int i = 0; i < length; i++)
        plainText[i] = tolower(plainText[i]);

    //remove whitespace
    for (int i = 0; i < length; i++) {
        if (plainText[i] == ' ')
            plainText[i] = plainText[i++];

        printf("%c", plainText[i]);
    }
    printf("\n\n");

    //remove punctuation from text
    for (int i = 0; i < length; i++) {
        if (ispunct(plainText[i]))
            plainText[i] = plainText[i++];

        printf("%c", plainText[i]);
    }
}

Any help as to why the text is unchanged after if exits the loop would be appreciated.


来源: stackexchange

问:
Swift - Animating When TableView Cell Selected (didSelectRowAtIndexPath)
I've been playing around trying to animate contents of my tableviewcell when it is selected, but i'm having issues. I had read some places that you cannot run animatewithduration within didSelectRowAtIndexPath or at least it doesn't animate if you do. It seems to be the case with the code I have below, the view moves but doesn't animate.

I have tried incorporating logic into willDisplayCell to monitor for the selection but to no avail, and so I would love it if someone is able to find the right solution for me because the answer is seemingly not available, despite a lot of searching:

```<code>func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let currentCellDescriptor = getCellDescriptorForIndexPath(indexPath)
    let cell = tableView.dequeueReusableCellWithIdentifier(currentCellDescriptor["cellIdentifier"] as! String, forIndexPath: indexPath) as! CustomCell
    let indexOfTappedRow = visibleRowsPerSection[indexPath.section][indexPath.row]
    if cellDescriptors[indexPath.section][indexOfTappedRow]["isExpandable"] as! Bool == true {
        if cellDescriptors[indexPath.section][indexOfTappedRow]["isExpanded"] as! Bool == false {

            // INTERESTING BIT: Animates cell contents to Right
            if currentCellDescriptor["cellIdentifier"] as! String == "CellHeader" {
                UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 12, options: .CurveLinear, animations: {
                    cell.headerTitleLeftConstraint.priority = 999
                    cell.headerTitleRightConstraint.priority = 1
                    cell.layoutIfNeeded()
                    }, completion: nil)
            }

       } else if cellDescriptors[indexPath.section][indexOfTappedRow]["isExpanded"] as! Bool == true {
           // MARK: Animates cell contents back to left
           if currentCellDescriptor["cellIdentifier"] as! String == "CellHeader" {
                UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 12, options: .CurveLinear, animations: {
                    cell.headerTitleLeftConstraint.priority = 1
                    cell.headerTitleRightConstraint.priority = 999
                    cell.layoutIfNeeded()
                     }, completion: nil)
                    }
            }
</code>```

答:
You do not need to use UIView.animate(...). UITableView offers animated updating by default. After changing the constraints, you can achieve this by calling:

tableView.performBatchUpdates(nil, completion: nil)
```

<p>Do not forget to give your height property a lower priority than <code>.required</code> when creating it. Otherwise AutoLayout will break constraints while updating (You can observe this in your debugger). Instead of setting constraints' priorities to <code>999</code> or something like that you should use static properties of <code>UILayoutPriority</code> for more readable code.</p>

<pre class="lang-swift prettyprint-override"><code>/// Set this wherever you create your height constraint, e.g. in your custom cell's class.
heightConstraint?.priority = .defaultHigh
</code>```

The full code for didSelectRowAt would look like this:

    let expandedHeight: CGFloat = 500
    let defaultHeight: CGFloat = 85

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
      guard let cell = tableView.cellForRow(at: indexPath) as? YourCustomTableViewCell else { return }

      /// Save the status of your cell in a property of your view model.
      if viewModel[indexPath.row].isFullsize {
        cell.heightConstraint?.constant = defaultHeight
        viewModel[indexPath.row].isFullsize = false
      } else {
        cell.heightConstraint?.constant = expandedHeight
        viewModel[indexPath.row].isFullsize = true
      }

      /// Call this for an animated update (since iOS 11)
      tableView.performBatchUpdates(nil, completion: nil)

      /// For the same result you could also use
      /// tableView.beginUpdates()
      /// tableView.endUpdates()
      /// ...but the docs say that this will become deprecated soon

      /// Scrolls to your selected cell's top
      tableView.scrollToRow(at: indexPath, at: .top, animated: true)
    }
```

ContentLicense: CC BY-SA 3.0

Body:
I've been playing around trying to animate contents of my tableviewcell when it is selected, but i'm having issues. I had read some places that you cannot run animatewithduration within didSelectRowAtIndexPath or at least it doesn't animate if you do. It seems to be the case with the code I have below, the view moves but doesn't animate.

I have tried incorporating logic into willDisplayCell to monitor for the selection but to no avail, and so I would love it if someone is able to find the right solution for me because the answer is seemingly not available, despite a lot of searching:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let currentCellDescriptor = getCellDescriptorForIndexPath(indexPath)
    let cell = tableView.dequeueReusableCellWithIdentifier(currentCellDescriptor["cellIdentifier"] as! String, forIndexPath: indexPath) as! CustomCell
    let indexOfTappedRow = visibleRowsPerSection[indexPath.section][indexPath.row]
    if cellDescriptors[indexPath.section][indexOfTappedRow]["isExpandable"] as! Bool == true {
        if cellDescriptors[indexPath.section][indexOfTappedRow]["isExpanded"] as! Bool == false {

            // INTERESTING BIT: Animates cell contents to Right
            if currentCellDescriptor["cellIdentifier"] as! String == "CellHeader" {
                UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 12, options: .CurveLinear, animations: {
                    cell.headerTitleLeftConstraint.priority = 999
                    cell.headerTitleRightConstraint.priority = 1
                    cell.layoutIfNeeded()
                    }, completion: nil)
            }

       } else if cellDescriptors[indexPath.section][indexOfTappedRow]["isExpanded"] as! Bool == true {
           // MARK: Animates cell contents back to left
           if currentCellDescriptor["cellIdentifier"] as! String == "CellHeader" {
                UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 12, options: .CurveLinear, animations: {
                    cell.headerTitleLeftConstraint.priority = 1
                    cell.headerTitleRightConstraint.priority = 999
                    cell.layoutIfNeeded()
                     }, completion: nil)
                    }
            }

Body:
You do not need to use UIView.animate(...). UITableView offers animated updating by default. After changing the constraints, you can achieve this by calling:

tableView.performBatchUpdates(nil, completion: nil)

Do not forget to give your height property a lower priority than .required when creating it. Otherwise AutoLayout will break constraints while updating (You can observe this in your debugger). Instead of setting constraints' priorities to 999 or something like that you should use static properties of UILayoutPriority for more readable code.

/// Set this wherever you create your height constraint, e.g. in your custom cell's class.
heightConstraint?.priority = .defaultHigh

The full code for didSelectRowAt would look like this:

    let expandedHeight: CGFloat = 500
    let defaultHeight: CGFloat = 85

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
      guard let cell = tableView.cellForRow(at: indexPath) as? YourCustomTableViewCell else { return }

      /// Save the status of your cell in a property of your view model.
      if viewModel[indexPath.row].isFullsize {
        cell.heightConstraint?.constant = defaultHeight
        viewModel[indexPath.row].isFullsize = false
      } else {
        cell.heightConstraint?.constant = expandedHeight
        viewModel[indexPath.row].isFullsize = true
      }

      /// Call this for an animated update (since iOS 11)
      tableView.performBatchUpdates(nil, completion: nil)

      /// For the same result you could also use
      /// tableView.beginUpdates()
      /// tableView.endUpdates()
      /// ...but the docs say that this will become deprecated soon

      /// Scrolls to your selected cell's top
      tableView.scrollToRow(at: indexPath, at: .top, animated: true)
    }

ContentLicense: CC BY-SA 4.0


问:
Unable to click an element within iframe in IE
I want to click on an element as follows:

```<code>//select[@name='instructionSelection']
</code>```

But its not clicking with Selenium on IE 11.

HTML:

答:
As the the desired element is within an  so to invoke click() on the element you have to:

Induce WebDriverWait for the desired frame to be available and switch to it.

Induce WebDriverWait for the desired element to be clickable.

You can use the following  Locator Strategies::

Using CSS_SELECTOR:

```<code>WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[name='invoiceDeatils'][src*='invoiceDeatils']")))
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "select[name='instructionSelection']"))).click()
</code>```

Using XPATH:

```<code>WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@name='invoiceDeatils' and contains(@src, 'invoiceDeatils')]")))
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//select[@name='instructionSelection']"))).click()
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Reference

You can find a relevant discussion in:

Ways to deal with #document under iframe

Body:
I want to click on an element as follows:

//select[@name='instructionSelection']

But its not clicking with Selenium on IE 11.

HTML:

Body:
As the the desired element is within an <iframe> so to invoke click() on the element you have to:

Induce WebDriverWait for the desired frame to be available and switch to it.

Induce WebDriverWait for the desired element to be clickable.

You can use the following  Locator Strategies::

Using CSS_SELECTOR:

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[name='invoiceDeatils'][src*='invoiceDeatils']")))
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "select[name='instructionSelection']"))).click()

Using XPATH:

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@name='invoiceDeatils' and contains(@src, 'invoiceDeatils')]")))
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//select[@name='instructionSelection']"))).click()

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Reference

You can find a relevant discussion in:

Ways to deal with #document under iframe


问:
Oracle SQL select query compare 2 columns
I have a table with these two columns:

```<code>USERNAME    EMAIL_ADDRESS
------------------------------
username1   username1@abc.com
username2   username2@abc.com
username3   username3@abc.com
</code>```

The first column is the username and the second column is <username> with email domain along with it.

How can I compare the two columns using Oracle SQL to find if there are any rows where the email_address column doesn't have the correct corresponding username in the email address format?

答:
Given the data you've presented you can use a regular expression to parse out your email address and then compare the USER_NAME to the user name in the email:

```<code>WITH cteData(USER_NAME, EMAIL_ADDRESS) AS
       (SELECT 'username1', 'username1@abc.com' FROM DUAL UNION ALL
        SELECT 'username2', 'username2@abc.com' FROM DUAL UNION ALL
        SELECT 'usernameX', 'username3@xyz.com' FROM DUAL UNION ALL
        SELECT 'username4', 'username4@abc.com' FROM DUAL),
     cteEmails AS
       (SELECT um.USER_NAME,
               REGEXP_SUBSTR(um.EMAIL_ADDRESS, '[^@.]+', 1, 1) AS EMAIL_USER_NAME,
               REGEXP_SUBSTR(um.EMAIL_ADDRESS, '[^@.]+', 1, 2) AS EMAIL_COMPANY,
               REGEXP_SUBSTR(um.EMAIL_ADDRESS, '[^@.]+', 1, 3) AS EMAIL_DOMAIN
          FROM cteData um)
SELECT *
  FROM cteEmails
  WHERE USER_NAME <> EMAIL_USER_NAME
</code>```

which returns

```<code>USER_NAME   EMAIL_USER_NAME EMAIL_COMPANY   EMAIL_DOMAIN
usernameX   username3       xyz             com
</code>```

when run.

db<>fiddle here

Body:
I have a table with these two columns:

USERNAME    EMAIL_ADDRESS
------------------------------
username1   username1@abc.com
username2   username2@abc.com
username3   username3@abc.com

The first column is the username and the second column is <username> with email domain along with it.

How can I compare the two columns using Oracle SQL to find if there are any rows where the email_address column doesn't have the correct corresponding username in the email address format?

Body:
Given the data you've presented you can use a regular expression to parse out your email address and then compare the USER_NAME to the user name in the email:

WITH cteData(USER_NAME, EMAIL_ADDRESS) AS
       (SELECT 'username1', 'username1@abc.com' FROM DUAL UNION ALL
        SELECT 'username2', 'username2@abc.com' FROM DUAL UNION ALL
        SELECT 'usernameX', 'username3@xyz.com' FROM DUAL UNION ALL
        SELECT 'username4', 'username4@abc.com' FROM DUAL),
     cteEmails AS
       (SELECT um.USER_NAME,
               REGEXP_SUBSTR(um.EMAIL_ADDRESS, '[^@.]+', 1, 1) AS EMAIL_USER_NAME,
               REGEXP_SUBSTR(um.EMAIL_ADDRESS, '[^@.]+', 1, 2) AS EMAIL_COMPANY,
               REGEXP_SUBSTR(um.EMAIL_ADDRESS, '[^@.]+', 1, 3) AS EMAIL_DOMAIN
          FROM cteData um)
SELECT *
  FROM cteEmails
  WHERE USER_NAME <> EMAIL_USER_NAME

which returns

USER_NAME   EMAIL_USER_NAME EMAIL_COMPANY   EMAIL_DOMAIN
usernameX   username3       xyz             com

when run.

db<>fiddle here


问:
How to make this "Reverse number function work", python 3?
Reverse a inputted number...

Please help me turn this input number into a defined function that spits out a
that number in reverse order?  I am trying to make it exist inside a function(N1) with a request for input being inside "def". While the leg work is being done inside the "while" loop and being iterated through until all there is no remainder, and all that is left is the input number to be printed in reverse.

```<code>def n1(n):
    rev = 0

    n = int(input("Enter number: "))

    while(n>0):

        dig=n%10

        rev=rev*10+dig

        n=n//10

        return print("reverse of the number: ", rev)

n2 = n1

print(n2(n))
</code>```

答:
You can leverage the fact, that str is a sequence in python, and hence you can treat it as a list of single characters (and hence reverse its order similarly to any list in python):

def revNum(n):
    x=str(abs(n))[::-1]
    res=int(x)*10**(len(x)-len(str(int(x))))
    if(n<0): return -res
    return res
```

Body:
Reverse a inputted number...

Please help me turn this input number into a defined function that spits out a
that number in reverse order?  I am trying to make it exist inside a function(N1) with a request for input being inside "def". While the leg work is being done inside the "while" loop and being iterated through until all there is no remainder, and all that is left is the input number to be printed in reverse.

def n1(n):
    rev = 0

    n = int(input("Enter number: "))

    while(n>0):

        dig=n%10

        rev=rev*10+dig

        n=n//10

        return print("reverse of the number: ", rev)

n2 = n1

print(n2(n))


问:
Reload My Location button when permission is granted

Background

I am using the google_maps_flutter package to show a map with markers corresponding to houses. To avoid overloading devices, I only load houses near the location the user is looking at. To make this easier, I request the user's location and provide that to Google Maps in order to show a My Location button.

The Problem

If location access has already been granted, it works as intended. Whoever if the map is already loaded, the My Location button does not show up.

Currently, if location permission is granted while the map is on-screen, I simply move the camera over to their location. This is an OK workaround, but I'd rather let the user decide where to look.

How can I load in the button when permission is granted while the map is already loaded?

Tried

I have tried just setting state.

Manually marking the map as dirty.

Forcing the map to reload options using a test method.

I've checked every available method I had access to, so at this point I doubt there is any other option. If this is the case I will report it as a bug.

My Code

  @override
  Widget build(BuildContext context) {
    // Load markers when permission is granted.
    location.hasPermission().then((currPerm) async {
      if (!currPerm) {
        bool newPerm = await location.requestPermission();
        if (newPerm) {
          LocationData data = await location.getLocation();
          (await mapController.future).moveCamera(CameraUpdate.newLatLng(LatLng(data.latitude, data.longitude)));
        }
      }
    });

    GoogleMap map = GoogleMap(
      initialCameraPosition: CameraPosition(
        target: INIT_POS,
        zoom: 11.5,
      ),
      myLocationEnabled: true,
      myLocationButtonEnabled: true,
      trafficEnabled: true,
      markers: markers,
      onMapCreated: (newController) => mapController.complete(newController),
      onCameraIdle: () async {
        // Load markers when the camera stops moving.
        LatLngBounds bounds = await (await mapController.future).getVisibleRegion();
        loadMarkers(
          LatLng(
            (bounds.northeast.latitude + bounds.southwest.latitude)/2,
            (bounds.northeast.longitude + bounds.southwest.longitude)/2
          ),
        );
      },
    );
    return map;
  }
```

答:
As of google_maps_flutter: ^0.5.23+1, I solved it by assigning a variable to myLocationEnabled, and changing its value once I got the location permission. If you hardcode true, it just won't work.

GoogleMap map = GoogleMap(
      myLocationEnabled: _isLocationGranted,
      ...
```

So, _isLocationGranted is initially false. When I get location permission, I set it to true and rebuild the widget (by calling setState(), triggering BlocBuilder(), or whatever method you use).

The other related parameter, myLocationButtonEnabled: true, doesn't seem to need this handling.

Body:
As of google_maps_flutter: ^0.5.23+1, I solved it by assigning a variable to myLocationEnabled, and changing its value once I got the location permission. If you hardcode true, it just won't work.

GoogleMap map = GoogleMap(
      myLocationEnabled: _isLocationGranted,
      ...

So, _isLocationGranted is initially false. When I get location permission, I set it to true and rebuild the widget (by calling setState(), triggering BlocBuilder(), or whatever method you use).

The other related parameter, myLocationButtonEnabled: true, doesn't seem to need this handling.


问:
Why do I get an error when I try to model autocorrelation, even when exactly following this example in Pinheiro and Bates (2009)?
Here is an excerpt from Mixed Effects Models in S and S-Plus page 238:

this is the code that I have used to recreate this example:

```<code>library(nlme)
spatDat <- data.frame(x = c(0,0.25,0.5,0.75,1), y = c(0,0.25,0.5,0.50,0.75))
cs1Exp <- corExp(1, form = ~x+y)
cs1Exp <- initialize(cs1Exp, spatDat)
</code>```

but when I do so, I get this error:

```<code>Error in getClass(Class) :
  c("\"corExp\" is not a defined class", "\"corSpatial\" is not a defined class", "\"corStruct\" is not a defined class")
In addition: Warning message:
In if (!is.na(match(Class, .BasicClasses))) return(newBasic(Class,  :
  the condition has length > 1 and only the first element will be used
</code>```

Why do I get this error?

Appendix

```<code>R version 2.13.0 (2011-04-13)
Platform: x86_64-pc-linux-gnu (64-bit)
attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] nlme_3.1-101

loaded via a namespace (and not attached):
[1] grid_2.13.0     lattice_0.19-26
</code>```

Body:
Here is an excerpt from Mixed Effects Models in S and S-Plus page 238:

this is the code that I have used to recreate this example:

library(nlme)
spatDat <- data.frame(x = c(0,0.25,0.5,0.75,1), y = c(0,0.25,0.5,0.50,0.75))
cs1Exp <- corExp(1, form = ~x+y)
cs1Exp <- initialize(cs1Exp, spatDat)

but when I do so, I get this error:

Error in getClass(Class) :
  c("\"corExp\" is not a defined class", "\"corSpatial\" is not a defined class", "\"corStruct\" is not a defined class")
In addition: Warning message:
In if (!is.na(match(Class, .BasicClasses))) return(newBasic(Class,  :
  the condition has length > 1 and only the first element will be used

Why do I get this error?

Appendix

R version 2.13.0 (2011-04-13)
Platform: x86_64-pc-linux-gnu (64-bit)
attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] nlme_3.1-101

loaded via a namespace (and not attached):
[1] grid_2.13.0     lattice_0.19-26

Body:
The reason is that Initialize takes a capital I in nlme so it is not confused with initialize in base. And then there is Vivi's comment on spatdat$y

This works:

> library(nlme)
> spatDat <- data.frame(x = c(0,0.25,0.5,0.75,1), y = c(0,0.25,0.50,0.75,1.0))
> cs1Exp <- corExp( 1, form = ~x+y )
> cs1Exp <- Initialize( cs1Exp, spatDat )
> corMatrix( cs1Exp )
          [,1]      [,2]      [,3]      [,4]      [,5]
[1,] 1.0000000 0.7021885 0.4930687 0.3462272 0.2431167
[2,] 0.7021885 1.0000000 0.7021885 0.4930687 0.3462272
[3,] 0.4930687 0.7021885 1.0000000 0.7021885 0.4930687
[4,] 0.3462272 0.4930687 0.7021885 1.0000000 0.7021885
[5,] 0.2431167 0.3462272 0.4930687 0.7021885 1.0000000


问:
Can Arduino Uno send data to Cloud Firestore?
I need information on how to connect and send data to firestore from an Arduino Board  and an ESP2866 module. I've only found tutorials using Firebase realtime, the ones I found using Firestore are using the NodeMCU board.

I have a Vue.js application reading some fields from a Firestore db, which should recieve information from the arduino with some attached sensors. From what I've seen my options are changing to firebase realtime or changing to NodeMCU( not possible ). I some direction to follow, on how to use firestore with arduino or just change the db.

答: I had quick success using firebase-arduino for the real-time database rather than Firestore. Since Arduino projects are generally hobby, this should probably work well enough.</p>


问:
Indexing into a Dask Series gives back the Dask Series
I have a Dask series of Dask dataframes.

I'd like to index into this series to acquire the dask dataframes for subsequent work.

However using loc[0] results in another dask series. Using to_frame also doesn't work because the result is then a "Dask dataframe of a Dask series of Dask dataframes".

Here is a minimal example that uses a Dask Series of Pandas dataframes (not exactly the same but illustrates the problem):

```<code>import pandas as pd
import dask.dataframe as dd

pdf1 = pd.DataFrame({'a': [1,2,3,4], 'b': [4,3,2,1]})
pdf2 = pd.DataFrame({'a': [4,3,2,1], 'b': [1,2,3,4]})

ps = pd.Series([pdf1, pdf2])
ds = dd.from_pandas(ps, npartitions=1)

print(type(ds.loc[0])) # still dask series
print(type(ds.loc[1])) # still dask series

print(ds.compute().loc[0]) # this is a pandas dataframe
print(ds.loc[0].compute()) # this is a pandas series
print(ds.loc[0].compute().loc[0]) # need to index into the singleton series to get back the dataframe
</code>```

It appears that once the object becomes a dask series, all subsequent combinators keeps it as a dask series until compute, which returns a "singleton" pandas series.

Is there anyway to tell dask to treat the indexed object the type that I expect it to be?

答:
I suspect that the reason for this is that Dask does not know that there is only one index value with the value 0.  In principle there could be many rows with the index value 0, and so the general output type for .loc is a series.

This goes against our intuition when we have uniquely valued indices, which can cause the kind of frustration that you seem to have encountered.

Body:
I have a Dask series of Dask dataframes.

I'd like to index into this series to acquire the dask dataframes for subsequent work.

However using loc[0] results in another dask series. Using to_frame also doesn't work because the result is then a "Dask dataframe of a Dask series of Dask dataframes".

Here is a minimal example that uses a Dask Series of Pandas dataframes (not exactly the same but illustrates the problem):

import pandas as pd
import dask.dataframe as dd

pdf1 = pd.DataFrame({'a': [1,2,3,4], 'b': [4,3,2,1]})
pdf2 = pd.DataFrame({'a': [4,3,2,1], 'b': [1,2,3,4]})

ps = pd.Series([pdf1, pdf2])
ds = dd.from_pandas(ps, npartitions=1)

print(type(ds.loc[0])) # still dask series
print(type(ds.loc[1])) # still dask series

print(ds.compute().loc[0]) # this is a pandas dataframe
print(ds.loc[0].compute()) # this is a pandas series
print(ds.loc[0].compute().loc[0]) # need to index into the singleton series to get back the dataframe

It appears that once the object becomes a dask series, all subsequent combinators keeps it as a dask series until compute, which returns a "singleton" pandas series.

Is there anyway to tell dask to treat the indexed object the type that I expect it to be?


问:
Architectural Patterns for a Game
So I've got a solution that contains a few big projects, which I'm trying to break down into smaller projects with more isolated responsibilities. This is a game, but I'm mainly a LOB developer and I think the principles are probably universal, and I think I could learn something here.

The dependencies in some of the objects are a bit too tightly intertwined, and I'm hoping for some help on how to untangle them. Or maybe some sort of pattern or abstraction that might make them more manageable.

Ares.Core.World has classes in it like Creatures, Items, etc. All of them inherit from Entity, which is aware of what cell on the map it exist at. It accomplishes this by holding a reference to a  Ares.Core.UI.MapControls.MapCell... And you can see that the wires are already getting crossed.

Ares.Core.UI.MapControls contains Map and MapCell, each of which contain Lists of creatures and items that they contain. MapCell also inherits from Ares.Core.World.Entity since that solved a few early problems very elegantly -- for instance, all Entities have inventory.

I would like to find a way to split UI and World out into seperate projects (Ares.World and Ares.UI) since UI and the overarching world should probably be seperate concerns. But as you can see, the way it is now the two projects would need to reference each other, and circular references are not allowed.

I'm wondering if there are any architectural patterns out there that might help in this situation. Thanks!

答:
There's nothing wrong with having classes in different namespaces interacting at a fine grained level. Separation of concerns can be done at the accessor protection level (public, protected, private, etc). You can break down your project into subprojects either logically or structurally, applying whatever extra organizational constraints you think are relevant.

Some strategies might be:

Structurally separating logic, where each silo happens to reside in their own established namespaces, and interacting only through high level interfaces.

Logical separation, where an assembly (or set of asms) become a logical project that may span multiple namespaces. Interaction could be done through interfaces, but also through thorough consideration of member access.

To untangle them, try to see the project from different perspectives. What can look like an utter mess from one POV can actually look elegant from another POV. If you find there actually is a reasonable logic behind their class structure, perhaps all that is needed is to start separating bits and pieces into different assemblies, with only minor tweaks to namespaces. If you find it truly is chaos, well, your work is cut out for you :-D

Title: Architectural Patterns for a Game


问:
Creating a counter for C++ with a button
I am trying to put together a button press counter with my argon device. I have a couple sounds I want to alternate between but can not get a counter to work for me to change songs A and B.  I wanted to set song A as counter evens and song B on counter odds. I currently have very little and do not know where to go from where I am at. Not sure how to upload what I have currently. </p>

```<code>int button = A0;

int buzzer = A2;

// Defining Sound
int sound1[] = {1700,2500,2800,2000,2500,1500,2000,1800};

int sound2[] = {3800,3600,3400,3200,2400,2600,2800,3000};

//Defining Duration Of Notes

int Duration1[] = {4,2,4,2,4,2,4,2};

int Duration2[] = {2,4,2,4,2,2,4,2};

//Setting Button Count
int bcount = 0;
#define MAX 2

//Creates The Setup Of Code
void setup()
{
    //Creates The Input Of Button Being Pressed
    pinMode (button, INPUT);
    //Creates The Output Of The Buzzer
    pinMode (buzzer, OUTPUT);
}

void loop() {
    //When Button Is Pressed
    if (digitalRead(button) == 1) {
        bcount = bcount + 1;
        }
        else if
                (bcount = 0);
        for (int i = 0; i < bcount; i++) {
            digitalWrite(buzzer, 1);

    if (bcount == MAX) {
        bcount = 0;
        break;
    }
        //Reads Notes
        for (int Note = 0; Note < 8; Note++){
            //Note Duration
            int Duration = 1000/Duration1[Note];
            //Sends Notes To Speaker
            tone(buzzer, sound1[Note], Duration);
            //Sets Delay Between Notes
            int pauseBetweenNotes = Duration * 1.50;
            //Delay Itself
            delay(pauseBetweenNotes);
            //Stop To The Sound
            noTone(buzzer);
        }
    }
        //When Button Is Pressed 2nd Time
      if(digitalRead(button) == 2) {
        //Reads Notes
        for (int Note = 0; Note < 8; Note++){
            //Note Duration
            int Duration = 1000/Duration2[Note];
            //Sends Notes To Speaker
            tone(buzzer, sound2[Note], Duration);
            //Sets Delay Between Notes
            int pauseBetweenNotes = Duration * 1.50;
            //Delay Itself
            delay(pauseBetweenNotes);
            //Stop To The Sound
            noTone(buzzer);
}
}
}
</code>```

答:
Thanks to the help of @DeducibleSteak the code works now to swap between the two sounds.</p>

```<code>int button = A0;

int buzzer = A2;

// Defining Sound
int sound1[] = {1700,2500,2800,2000,2500,1500,2000,1800};

int sound2[] = {3800,3600,3400,3200,2400,2600,2800,3000};

//Defining Duration Of Notes

int Duration1[] = {4,2,4,2,4,2,4,2};

int Duration2[] = {2,4,2,4,2,2,4,2};

//Setting Button Count
int bcount = 0;
#define MAX 2

//Creates The Setup Of Code
void setup()
{
    //Creates The Input Of Button Being Pressed
    pinMode (button, INPUT);
    //Creates The Output Of The Buzzer
   pinMode (buzzer, OUTPUT);
}
//Counter Setup
int counter = 0;

void loop() {
    if (digitalRead(button) == HIGH) {
        ++counter;

        if (counter % 2 == 1)
        {
            for (int Note = 0; Note < 8; Note++){
            //Note Duration
            int Duration = 1000/Duration1[Note];
            //Sends Notes To Speaker
            tone(buzzer, sound1[Note], Duration);
            //Sets Delay Between Notes
            int pauseBetweenNotes = Duration * 1.50;
            //Delay Itself
            delay(pauseBetweenNotes);
            //Stop To The Sound
            noTone(buzzer);
        }
            }
        else {
                for (int Note = 0; Note < 8; Note++){
                //Note Duration
                int Duration = 1000/Duration2[Note];
                //Sends Notes To Speaker
                tone(buzzer, sound2[Note], Duration);
                //Sets Delay Between Notes
                int pauseBetweenNotes = Duration * 1.50;
                //Delay Itself
                delay(pauseBetweenNotes);
                //Stop To The Sound
                noTone(buzzer);
            }
        }
    }
}
</code>```

Body:
I am trying to put together a button press counter with my argon device. I have a couple sounds I want to alternate between but can not get a counter to work for me to change songs A and B.  I wanted to set song A as counter evens and song B on counter odds. I currently have very little and do not know where to go from where I am at. Not sure how to upload what I have currently.

int button = A0;

int buzzer = A2;

// Defining Sound
int sound1[] = {1700,2500,2800,2000,2500,1500,2000,1800};

int sound2[] = {3800,3600,3400,3200,2400,2600,2800,3000};

//Defining Duration Of Notes

int Duration1[] = {4,2,4,2,4,2,4,2};

int Duration2[] = {2,4,2,4,2,2,4,2};

//Setting Button Count
int bcount = 0;
#define MAX 2

//Creates The Setup Of Code
void setup()
{
    //Creates The Input Of Button Being Pressed
    pinMode (button, INPUT);
    //Creates The Output Of The Buzzer
    pinMode (buzzer, OUTPUT);
}

void loop() {
    //When Button Is Pressed
    if (digitalRead(button) == 1) {
        bcount = bcount + 1;
        }
        else if
                (bcount = 0);
        for (int i = 0; i < bcount; i++) {
            digitalWrite(buzzer, 1);

    if (bcount == MAX) {
        bcount = 0;
        break;
    }
        //Reads Notes
        for (int Note = 0; Note < 8; Note++){
            //Note Duration
            int Duration = 1000/Duration1[Note];
            //Sends Notes To Speaker
            tone(buzzer, sound1[Note], Duration);
            //Sets Delay Between Notes
            int pauseBetweenNotes = Duration * 1.50;
            //Delay Itself
            delay(pauseBetweenNotes);
            //Stop To The Sound
            noTone(buzzer);
        }
    }
        //When Button Is Pressed 2nd Time
      if(digitalRead(button) == 2) {
        //Reads Notes
        for (int Note = 0; Note < 8; Note++){
            //Note Duration
            int Duration = 1000/Duration2[Note];
            //Sends Notes To Speaker
            tone(buzzer, sound2[Note], Duration);
            //Sets Delay Between Notes
            int pauseBetweenNotes = Duration * 1.50;
            //Delay Itself
            delay(pauseBetweenNotes);
            //Stop To The Sound
            noTone(buzzer);
}
}
}

Body:
Thanks to the help of @DeducibleSteak the code works now to swap between the two sounds.

int button = A0;

int buzzer = A2;

// Defining Sound
int sound1[] = {1700,2500,2800,2000,2500,1500,2000,1800};

int sound2[] = {3800,3600,3400,3200,2400,2600,2800,3000};

//Defining Duration Of Notes

int Duration1[] = {4,2,4,2,4,2,4,2};

int Duration2[] = {2,4,2,4,2,2,4,2};

//Setting Button Count
int bcount = 0;
#define MAX 2

//Creates The Setup Of Code
void setup()
{
    //Creates The Input Of Button Being Pressed
    pinMode (button, INPUT);
    //Creates The Output Of The Buzzer
   pinMode (buzzer, OUTPUT);
}
//Counter Setup
int counter = 0;

void loop() {
    if (digitalRead(button) == HIGH) {
        ++counter;

        if (counter % 2 == 1)
        {
            for (int Note = 0; Note < 8; Note++){
            //Note Duration
            int Duration = 1000/Duration1[Note];
            //Sends Notes To Speaker
            tone(buzzer, sound1[Note], Duration);
            //Sets Delay Between Notes
            int pauseBetweenNotes = Duration * 1.50;
            //Delay Itself
            delay(pauseBetweenNotes);
            //Stop To The Sound
            noTone(buzzer);
        }
            }
        else {
                for (int Note = 0; Note < 8; Note++){
                //Note Duration
                int Duration = 1000/Duration2[Note];
                //Sends Notes To Speaker
                tone(buzzer, sound2[Note], Duration);
                //Sets Delay Between Notes
                int pauseBetweenNotes = Duration * 1.50;
                //Delay Itself
                delay(pauseBetweenNotes);
                //Stop To The Sound
                noTone(buzzer);
            }
        }
    }
}


问:
How to get code completion for Tensorflow in PyCharm?
I have installed the tensorflow module and it works in PyCharm. However, I want it to have code completion. Currently I do this:

```<code>import tensorflow as tf
hello = tf.constant("Hello, Tensorflow!")
</code>```

However, PyCharm doesn't suggest or autocomplete functions when I type 'tf'

Is this possible to be done automatically or am I missing something?

I am using Windows 10. Tensorflow is installed natively.

答: Watch out whether you are not at the bottom of editor when working on 2 or more monitors. Popups (including autocompletion ones) vanish there. See this https://youtrack.jetbrains.com/issue/IDEA-85749 JetBranins bug - old, still open (and vote it up).</p>

Body:
I have installed the tensorflow module and it works in PyCharm. However, I want it to have code completion. Currently I do this:

import tensorflow as tf
hello = tf.constant("Hello, Tensorflow!")

However, PyCharm doesn't suggest or autocomplete functions when I type 'tf'

Is this possible to be done automatically or am I missing something?

I am using Windows 10. Tensorflow is installed natively.


问:
How to make 'self' in parent class refer to extended class in PHP?
I'm working with Wordpress and need to instantiate a new class similar to this oversimplified example (for an add_action() hook which receives some arguments):

```<code>class A {
        public function __construct() {
        }

        public static function init() {
                $instance = new self();
                $instance->doStuff();
        }

        protected function doStuff() {
                echo get_class($this);
        }
}

class B extends A {
}

B::init(); //returns 'A'
</code>```

How can I get self in init() to refer to extended classes when called from them? I'm aware of the late static bindings page in the PHP docs, but I'm not clear on how to apply it in the above context. Thanks!

答:
public static function init() {
    $instance = new static();
    $instance->doStuff();
}
```

<p>You can see this working on 3v4l, which is a great place to sandbox some PHP.</p>

<p>Why <code>static</code>? You were right to look at the PHP manual for late static bindings, and it's a shame the page doesn't explicitly mention this specific use of the static keyword (though, there's a comment that does).</p>

<p>In the context of late static bindings, you can replace <code>self</code> with <code>static</code>, and it will use the instantiated class, whereas <code>self</code> would use the class the code lives in. For example:</p>

<pre class="lang-php prettyprint-override"><code><?php
class A {

}

class B extends A {
    public function test() {
        echo parent::class;
        echo self::class;
        echo static::class;
    }
}
class C extends B {

}

$c = new C();
$c->test();
</code>```

This even works in a static context (unfortunately, the static keyword is used in two different contexts: static calls, and late static binding), as per my example above.

Body:
I'm working with Wordpress and need to instantiate a new class similar to this oversimplified example (for an add_action() hook which receives some arguments):

class A {
        public function __construct() {
        }

        public static function init() {
                $instance = new self();
                $instance->doStuff();
        }

        protected function doStuff() {
                echo get_class($this);
        }
}

class B extends A {
}

B::init(); //returns 'A'

How can I get self in init() to refer to extended classes when called from them? I'm aware of the late static bindings page in the PHP docs, but I'm not clear on how to apply it in the above context. Thanks!

Body:
public static function init() {
    $instance = new static();
    $instance->doStuff();
}

You can see this working on 3v4l, which is a great place to sandbox some PHP.

Why static? You were right to look at the PHP manual for late static bindings, and it's a shame the page doesn't explicitly mention this specific use of the static keyword (though, there's a comment that does).

In the context of late static bindings, you can replace self with static, and it will use the instantiated class, whereas self would use the class the code lives in. For example:

<?php
class A {

}

class B extends A {
    public function test() {
        echo parent::class;
        echo self::class;
        echo static::class;
    }
}
class C extends B {

}

$c = new C();
$c->test();

This even works in a static context (unfortunately, the static keyword is used in two different contexts: static calls, and late static binding), as per my example above.


Title: Why do I get an error when I try to model autocorrelation, even when exactly following this example in Pinheiro and Bates (2009)?

Body:
There are a couple of problems with your code.    Here's the corrected version:

library(nlme)
spatDat <- data.frame(x = c(0, 0.25, 0.5, 0.75, 1), y = c(0, 0.25, 0.5, 0.75, 1.0))
cs1Exp <- corExp(1, form = ~x+y)
cs1Exp <- Initialize(cs1Exp, spatDat)
corMatrix(cs1Exp)

          [,1]      [,2]      [,3]      [,4]      [,5]
[1,] 1.0000000 0.7021885 0.4930687 0.3462272 0.2431167
[2,] 0.7021885 1.0000000 0.7021885 0.4930687 0.3462272
[3,] 0.4930687 0.7021885 1.0000000 0.7021885 0.4930687
[4,] 0.3462272 0.4930687 0.7021885 1.0000000 0.7021885
[5,] 0.2431167 0.3462272 0.4930687 0.7021885 1.0000000


问:
I wrote a function for a math formula, may I ask you please check my code?
For my research, I needed to calculate some formula. I create a function for it. This is the very first time for me to write a function and also the first time to write a math formula in Matlab language. May I please ask you to check if where I do wrong?

Here is formula

And here is the function I wrote (P is x and P^ is y):

```<code>function biass = BIASS(x,y)
%This function calculates biass error
%   Detailed explanation goes here
H = sum(y-x)/sum(y)
biass = H * 100
end
</code>```

I'm not sure about results because I believe they are not reasonable.

答: If y is P^, then you should write H = sum(y-x)/sum(x), not H = sum(y-x)/sum(y).

Body:
For my research, I needed to calculate some formula. I create a function for it. This is the very first time for me to write a function and also the first time to write a math formula in Matlab language. May I please ask you to check if where I do wrong?

Here is formula

And here is the function I wrote (P is x and P^ is y):

function biass = BIASS(x,y)
%This function calculates biass error
%   Detailed explanation goes here
H = sum(y-x)/sum(y)
biass = H * 100
end

I'm not sure about results because I believe they are not reasonable.


问:
Trivial change but different results (ForAll and Exists)
I have a set of inequalities that I want to find a (trivial) solution.

When I use the Exists operator, everything works great, as you can see in this Z3 script and in its Z3Py version.

```<code>#!/bin/python

from z3 import *

# we have that
s = Solver()
## mu0_px is the initial marking for place px;
mu_p1, mu_p2, mu_p3 = 0, 0, 1

## pi_tj is the pre-condition from place pi to transition tj
p1_t1, p1_t2, p1_t3 = 1, 0, 0
p2_t1, p2_t2, p2_t3 = 0, 1, 0
p3_t1, p3_t2, p3_t3 = 0, 0, 1

## tj_pi is the post-condition from transition tj to place pi
t1_p1, t2_p1, t3_p1 = 0, 1, 0
t1_p2, t2_p2, t3_p2 = 1, 0, 0
t1_p3, t2_p3, t3_p3 = 0, 0, 0

## find the values for the faulty transitions
f_p1, p1_f = Ints('f_p1 p1_f')
f_p2, p2_f = Ints('f_p2 p2_f')
f_p3, p3_f = Ints('f_p3 p3_f')

# where they should be
s.add( f_p1 == 1, f_p2 == 0, f_p3 == 0 )
s.add( p1_f == 0, p2_f == 0, p3_f == 1 )

## l \in Naturals ;
l11 = Int('l11')

# Sequence 11: t1,t2,t3
s11_t1, s11_t2, s11_t3 = 1, 1, 0

# It does works! :o
s.add( l11 == 1 )
s.add(
   Exists([l11],
      Or(
         mu_p1 + (t1_p1-p1_t1)*s11_t1 + (t2_p1-p1_t2)*s11_t2 + (t3_p1-p1_t3)*s11_t3 + l11 * (f_p1 - p1_f) < p1_t3,
         mu_p2 + (t1_p2-p2_t1)*s11_t1 + (t2_p2-p2_t2)*s11_t2 + (t3_p2-p2_t3)*s11_t3 + l11 * (f_p2 - p2_f) < p2_t3,
         mu_p3 + (t1_p3-p3_t1)*s11_t1 + (t2_p3-p3_t2)*s11_t2 + (t3_p3-p3_t3)*s11_t3 + l11 * (f_p3 - p3_f) < p3_t3,
      )
   )
)

print(s)
print(s.check())
print(s.model())
</code>```

However, when I replace the existential quantifier by Forall as in this link, and in the Python code below, there is no solution when I believe that it should still be sat.

```<code>#!/bin/python

from z3 import *

# we have that
s = Solver()
## mu0_px is the initial marking for place px;
mu_p1, mu_p2, mu_p3 = 0, 0, 1

## pi_tj is the pre-condition from place pi to transition tj
p1_t1, p1_t2, p1_t3 = 1, 0, 0
p2_t1, p2_t2, p2_t3 = 0, 1, 0
p3_t1, p3_t2, p3_t3 = 0, 0, 1

## tj_pi is the post-condition from transition tj to place pi
t1_p1, t2_p1, t3_p1 = 0, 1, 0
t1_p2, t2_p2, t3_p2 = 1, 0, 0
t1_p3, t2_p3, t3_p3 = 0, 0, 0

## find the values for the faulty transitions
f_p1, p1_f = Ints('f_p1 p1_f')
f_p2, p2_f = Ints('f_p2 p2_f')
f_p3, p3_f = Ints('f_p3 p3_f')

# where they should be
s.add( f_p1 == 1, f_p2 == 0, f_p3 == 0 )
s.add( p1_f == 0, p2_f == 0, p3_f == 1 )

## l \in Naturals ;
l11 = Int('l11')

# Sequence 11: t1,t2,t3
s11_t1, s11_t2, s11_t3 = 1, 1, 0

# It does not work! :(
s.add( l11 == 1 )
s.add(
   ForAll([l11],
      Or(
         mu_p1 + (t1_p1-p1_t1)*s11_t1 + (t2_p1-p1_t2)*s11_t2 + (t3_p1-p1_t3)*s11_t3 + l11 * (f_p1 - p1_f) < p1_t3,
         mu_p2 + (t1_p2-p2_t1)*s11_t1 + (t2_p2-p2_t2)*s11_t2 + (t3_p2-p2_t3)*s11_t3 + l11 * (f_p2 - p2_f) < p2_t3,
         mu_p3 + (t1_p3-p3_t1)*s11_t1 + (t2_p3-p3_t2)*s11_t2 + (t3_p3-p3_t3)*s11_t3 + l11 * (f_p3 - p3_f) < p3_t3,
      )
   )
)

print(s)
print(s.check())
print(s.model())
</code>```

Did anyone ever have a problem like this before?

答:
The variable l11 as you declared and the one that gets used in the quantification are totally different: In particular, you stating it equals 1 have no bearing in the quantified formula. So you get sat with existential but unsat with universal since the formula is clearly not true for all values of l11.

This might be confusing, but it is the intended behaviour. To see the effect, simply print the smtlib equivalent and you’ll see how the variables are assigned.

Body:
I have a set of inequalities that I want to find a (trivial) solution.

When I use the Exists operator, everything works great, as you can see in this Z3 script and in its Z3Py version.

#!/bin/python

from z3 import *

# we have that
s = Solver()
## mu0_px is the initial marking for place px;
mu_p1, mu_p2, mu_p3 = 0, 0, 1

## pi_tj is the pre-condition from place pi to transition tj
p1_t1, p1_t2, p1_t3 = 1, 0, 0
p2_t1, p2_t2, p2_t3 = 0, 1, 0
p3_t1, p3_t2, p3_t3 = 0, 0, 1

## tj_pi is the post-condition from transition tj to place pi
t1_p1, t2_p1, t3_p1 = 0, 1, 0
t1_p2, t2_p2, t3_p2 = 1, 0, 0
t1_p3, t2_p3, t3_p3 = 0, 0, 0

## find the values for the faulty transitions
f_p1, p1_f = Ints('f_p1 p1_f')
f_p2, p2_f = Ints('f_p2 p2_f')
f_p3, p3_f = Ints('f_p3 p3_f')

# where they should be
s.add( f_p1 == 1, f_p2 == 0, f_p3 == 0 )
s.add( p1_f == 0, p2_f == 0, p3_f == 1 )

## l \in Naturals ;
l11 = Int('l11')

# Sequence 11: t1,t2,t3
s11_t1, s11_t2, s11_t3 = 1, 1, 0

# It does works! :o
s.add( l11 == 1 )
s.add(
   Exists([l11],
      Or(
         mu_p1 + (t1_p1-p1_t1)*s11_t1 + (t2_p1-p1_t2)*s11_t2 + (t3_p1-p1_t3)*s11_t3 + l11 * (f_p1 - p1_f) < p1_t3,
         mu_p2 + (t1_p2-p2_t1)*s11_t1 + (t2_p2-p2_t2)*s11_t2 + (t3_p2-p2_t3)*s11_t3 + l11 * (f_p2 - p2_f) < p2_t3,
         mu_p3 + (t1_p3-p3_t1)*s11_t1 + (t2_p3-p3_t2)*s11_t2 + (t3_p3-p3_t3)*s11_t3 + l11 * (f_p3 - p3_f) < p3_t3,
      )
   )
)

print(s)
print(s.check())
print(s.model())

However, when I replace the existential quantifier by Forall as in this link, and in the Python code below, there is no solution when I believe that it should still be sat.

#!/bin/python

from z3 import *

# we have that
s = Solver()
## mu0_px is the initial marking for place px;
mu_p1, mu_p2, mu_p3 = 0, 0, 1

## pi_tj is the pre-condition from place pi to transition tj
p1_t1, p1_t2, p1_t3 = 1, 0, 0
p2_t1, p2_t2, p2_t3 = 0, 1, 0
p3_t1, p3_t2, p3_t3 = 0, 0, 1

## tj_pi is the post-condition from transition tj to place pi
t1_p1, t2_p1, t3_p1 = 0, 1, 0
t1_p2, t2_p2, t3_p2 = 1, 0, 0
t1_p3, t2_p3, t3_p3 = 0, 0, 0

## find the values for the faulty transitions
f_p1, p1_f = Ints('f_p1 p1_f')
f_p2, p2_f = Ints('f_p2 p2_f')
f_p3, p3_f = Ints('f_p3 p3_f')

# where they should be
s.add( f_p1 == 1, f_p2 == 0, f_p3 == 0 )
s.add( p1_f == 0, p2_f == 0, p3_f == 1 )

## l \in Naturals ;
l11 = Int('l11')

# Sequence 11: t1,t2,t3
s11_t1, s11_t2, s11_t3 = 1, 1, 0

# It does not work! :(
s.add( l11 == 1 )
s.add(
   ForAll([l11],
      Or(
         mu_p1 + (t1_p1-p1_t1)*s11_t1 + (t2_p1-p1_t2)*s11_t2 + (t3_p1-p1_t3)*s11_t3 + l11 * (f_p1 - p1_f) < p1_t3,
         mu_p2 + (t1_p2-p2_t1)*s11_t1 + (t2_p2-p2_t2)*s11_t2 + (t3_p2-p2_t3)*s11_t3 + l11 * (f_p2 - p2_f) < p2_t3,
         mu_p3 + (t1_p3-p3_t1)*s11_t1 + (t2_p3-p3_t2)*s11_t2 + (t3_p3-p3_t3)*s11_t3 + l11 * (f_p3 - p3_f) < p3_t3,
      )
   )
)

print(s)
print(s.check())
print(s.model())

Did anyone ever have a problem like this before?


问:
The best way to do localization in Unity
I am building an android game with unity and I would like to add 1 or more language. I tried the smart localization asset in the asset store. I was searching for an asset that would allow me to edit language directly from the text component (in the editor) but I couldn't find so I tried this:
Find all the text Components on the scene and change the text according to the user preferred language. For example I don't put the real text in the buttons but the unique key of the text and the scripts will do the change in his start method. But I wonder if this is the better to do localization.</p>

答:
Since it is third result on "Unity Localization" search I would like to share my 5 cents on this topic.

First of all, I definitely agree with Damien Yoccoz opinion regarding having the text in the code directly or in Unity Text components - simply don't do this if you want to translate your game.
Let me propose a solution I used in one of my recent games:

Create property files with languages you want to support. Those files will have key-value structure, (e.g. greetings=Hello!)

Create a script - let's call it LangResolver - that will read those files on a game startup (e.g. in a Splash screen). This script will hold key-value pairs, so Dictionary<> will be a data structure of choice.

Mark all Text components available for translation. I wouldn't go for searching all Text components, since some of them might not be needed (e.g. numbers only fields). So, another script - let's call it LangText - to bind keys from properties to Text components should be created. This script will have a public String field to identify a key from properties.

Last step, LangResolver should have a method to collect all LangText on a scene, get their identifiers and set the actual text as per current system language or a language selector. This method then will be called from some other UIHandler component on a scene.

Those steps should be a good start for anyone trying to build a simple localization support, if you are searching for nice tutorial with pictures\video, here it is.


问:
Load content from file as argument in ant
Assume I have a file test.key and the file contains a string let call “123456789”.
How can I pass this file as an argument to a program in ant build?
I wonder if Something like this is possible?
ant -Darg=‘cat test.key’

Where cat test.key is a command on Linux terminal.

答:
You can use the LoadFile ant task, which reads the content of a file into a property:
https://ant.apache.org/manual/Tasks/loadfile.html

```<code><loadfile property="arg.value"
      srcFile="test.key"
      failonerror="false"/>
</code>```

You can then use this property in an exec task with this property:
https://ant.apache.org/manual/Tasks/exec.html

```<code><exec executable="myprogram">
  <arg value="${arg.value}"/>
</exec>
</code>```

To add some more flexibility, you can pass the file name as a property:

```<code>ant -Dfile.name=test.key
</code>```

So the LoadFile task the becomes:

```<code>    <loadfile property="arg.value"
      srcFile="${file.name}"
      failonerror="false"/>
</code>```

Body:
You can use the LoadFile ant task, which reads the content of a file into a property:
https://ant.apache.org/manual/Tasks/loadfile.html

<loadfile property="arg.value"
      srcFile="test.key"
      failonerror="false"/>

You can then use this property in an exec task with this property:
https://ant.apache.org/manual/Tasks/exec.html

<exec executable="myprogram">
  <arg value="${arg.value}"/>
</exec>

To add some more flexibility, you can pass the file name as a property:

ant -Dfile.name=test.key

So the LoadFile task the becomes:

    <loadfile property="arg.value"
      srcFile="${file.name}"
      failonerror="false"/>


问:
java - live view on collection contained within a collection contained within ... etc
I have a class A which can contain many instances of class B which may in turn contain many instances of Class C, which can contain many instances of class D

Now, in class A I have a method getAllD. Currently every time this is called there is a lot of iterating that takes place, and a rather large list is freshly created and returned. This cannot be very efficient.

I was wondering how I could do this better. This question Combine multiple Collections into a single logical Collection? seems to touch upon a similar topic, but I'm not really sure how I could apply it to my situation.

All comments are much appreciated!

答:
The answer to your question is going to depend on the specifics of your situation. Are these collections static or dynamic? How big is your collection of B's in A? Are you only going to access the Ds from A, or will you sometimes want to be farther down in the tree or returning Bs or Cs? How frequently are you going to want to access the same set of Ds from a particular A? Can a D (or C or B) be associated with more than 1 A?

If everything is dynamic, then the best chance of improving performance is to have parent references from the Cs to A, and then updating the parent whenever C's list of Ds changes. This way, you can keep a collection of Ds in your A object and update A whenever one of the Cs gets a new one or has one deleted.

If everything is static and there is some reuse of the D collections from each A, then caching may be a good choice, particularly if there are a lot of Bs. A would have a map with a key of B and a value of a collection of Ds. The getAllDs() method would first check to see if the map had a key for B and if so return its collection of Ds. If not, then it would generate the collection, store it into the cache map, and return the collection.

You could also use a tree to store the objects, particularly if they were fairly simple. For example, you could create an XML DOM object and use XPath expressions to pull out the subset of Ds that you wanted. This would allow far more dynamic access to the sets of objects you were interested in.

Each of these solutions has different tradeoffs in terms of cost to setup, cost to maintain, timeliness of results, flexibility of use, and cost to fetch results. Which you should choose is going to depend on your context.


问:
Multiple Categorical Variables in a Column & The Prep
I have a survey data, with text answers, categorical variables, and numeric.

Converted into a dataframe in pandas, but the problem is multiple-choice columns, sometimes have more than 1 categorical variables, because the survey was designed as "choose all applies".

For example:

```<code>ID  Category    Num1 Num2 Num3
1   A, B, C     1    1    1
2   B, C, D     1    0    1
3   A, C        1    1    1
4   A           0    1    1
5   A, C, D     0    1    1
</code>```

I am trying to correlate these categories to the numerical variables.

Let's say the presence of A to value of Num1.

But when I use the dataframe, as it is, Python (and R) considers, for example [A, B, C] as another category, recognizes the whole cell as the category.

I think I need a method of parsing (exploding?) the value (in a hidden way), before feeding into a statistical analysis command.

How can I solve this problem?

答:
We could use cSplit_e from splitstackshape in R

```<code>library(splitstackshape)
cSplit_e(df1, "Category", type =  "character", fill = 0, sep=",\\s*", fixed = FALSE)
#   ID Category Num1 Num2 Num3 Category_A Category_B Category_C Category_D
#1  1  A, B, C    1    1    1          1          1          1          0
#2  2  B, C, D    1    0    1          0          1          1          1
#3  3     A, C    1    1    1          1          0          1          0
#4  4        A    0    1    1          1          0          0          0
#5  5  A, C, D    0    1    1          1          0          1          1
</code>```

In base R, we can split the 'Category' column at , and then use table

```<code>cbind(df1, as.data.frame.matrix(table(stack(setNames(strsplit(df1$Category,
             ",\\s+"), df1$ID))[2:1])))
#   ID Category Num1 Num2 Num3 A B C D
#1  1  A, B, C    1    1    1 1 1 1 0
#2  2  B, C, D    1    0    1 0 1 1 1
#3  3     A, C    1    1    1 1 0 1 0
#4  4        A    0    1    1 1 0 0 0
#5  5  A, C, D    0    1    1 1 0 1 1
</code>```

It can be made further compact with

```<code>library(qdapTools)
cbind(df1, mtabulate(strsplit(df1$Category, ",\\s+")))
#  ID Category Num1 Num2 Num3 A B C D
#1  1  A, B, C    1    1    1 1 1 1 0
#2  2  B, C, D    1    0    1 0 1 1 1
#3  3     A, C    1    1    1 1 0 1 0
#4  4        A    0    1    1 1 0 0 0
#5  5  A, C, D    0    1    1 1 0 1 1
</code>```

data

```<code>df1 <- structure(list(ID = 1:5, Category = c("A, B, C", "B, C, D", "A, C",
"A", "A, C, D"), Num1 = c(1L, 1L, 1L, 0L, 0L), Num2 = c(1L, 0L,
1L, 1L, 1L), Num3 = c(1L, 1L, 1L, 1L, 1L)), class = "data.frame", row.names = c(NA,
-5L))
</code>```

Body:
I have a survey data, with text answers, categorical variables, and numeric.

Converted into a dataframe in pandas, but the problem is multiple-choice columns, sometimes have more than 1 categorical variables, because the survey was designed as "choose all applies".

For example:

ID  Category    Num1 Num2 Num3
1   A, B, C     1    1    1
2   B, C, D     1    0    1
3   A, C        1    1    1
4   A           0    1    1
5   A, C, D     0    1    1

I am trying to correlate these categories to the numerical variables.

Let's say the presence of A to value of Num1.

But when I use the dataframe, as it is, Python (and R) considers, for example [A, B, C] as another category, recognizes the whole cell as the category.

I think I need a method of parsing (exploding?) the value (in a hidden way), before feeding into a statistical analysis command.

How can I solve this problem?

Body:
We could use cSplit_e from splitstackshape in R

library(splitstackshape)
cSplit_e(df1, "Category", type =  "character", fill = 0, sep=",\\s*", fixed = FALSE)
#   ID Category Num1 Num2 Num3 Category_A Category_B Category_C Category_D
#1  1  A, B, C    1    1    1          1          1          1          0
#2  2  B, C, D    1    0    1          0          1          1          1
#3  3     A, C    1    1    1          1          0          1          0
#4  4        A    0    1    1          1          0          0          0
#5  5  A, C, D    0    1    1          1          0          1          1

In base R, we can split the 'Category' column at , and then use table

cbind(df1, as.data.frame.matrix(table(stack(setNames(strsplit(df1$Category,
             ",\\s+"), df1$ID))[2:1])))
#   ID Category Num1 Num2 Num3 A B C D
#1  1  A, B, C    1    1    1 1 1 1 0
#2  2  B, C, D    1    0    1 0 1 1 1
#3  3     A, C    1    1    1 1 0 1 0
#4  4        A    0    1    1 1 0 0 0
#5  5  A, C, D    0    1    1 1 0 1 1

It can be made further compact with

library(qdapTools)
cbind(df1, mtabulate(strsplit(df1$Category, ",\\s+")))
#  ID Category Num1 Num2 Num3 A B C D
#1  1  A, B, C    1    1    1 1 1 1 0
#2  2  B, C, D    1    0    1 0 1 1 1
#3  3     A, C    1    1    1 1 0 1 0
#4  4        A    0    1    1 1 0 0 0
#5  5  A, C, D    0    1    1 1 0 1 1

data

df1 <- structure(list(ID = 1:5, Category = c("A, B, C", "B, C, D", "A, C",
"A", "A, C, D"), Num1 = c(1L, 1L, 1L, 0L, 0L), Num2 = c(1L, 0L,
1L, 1L, 1L), Num3 = c(1L, 1L, 1L, 1L, 1L)), class = "data.frame", row.names = c(NA,
-5L))


问:
Number of elements in Char array
How can I get the size of char array if I define the size but put less elements

```<code>#define N 100

char a[N];
cin >> a;
</code>```

supoose I enter 126,
then what do i do to get the number of elemens (3 in this case) in this array now

答:
Since the question is tagged with C++, I would first suggest using std::string instead of char array. Furthermore, use std::getline in order to fill out declared std::string with user's input. Then the code would look like the following:

#include <iostream>
#include <string>

int main() {
    std::string a;
    std::getline(std::cin, a);
    std::cout << std::endl;
    std::cout << "Length: " << a.size() << std::endl;
    return 0;
}
```

Title: Number of elements in Char array

Body:
How can I get the size of char array if I define the size but put less elements

#define N 100

char a[N];
cin >> a;

supoose I enter 126,
then what do i do to get the number of elemens (3 in this case) in this array now


问:
Passing anonymous functions as parameters for later use
I'm having issues with a script that I made for use in HTML5.
Here is the function

```<code>function loadImage(loc,after,para){
        var img = new Image();
        img.src = loc;
        if(typeof(after) != "undefined" && typeof(para) != "undefined"){
            img.onloadeddata  = after(img,para);
        }else if(typeof(after) != "undefined"){
            img.onloadeddata  = after(img);
        }
        return img;
}
</code>```

and here is what is calling it

```<code>window.globalFriends[i][2]=loadImage('http://graph.facebook.com/'+window.globalFriends[i][0]+'/picture', function (a){
    updateLoaders();
    loadingDrawPerson(a);});
</code>```

What I'm trying to do is send a function as a parameter for it then to be called.
It kinda of works but it a weird way. For example; All the images do get loaded but the onloadeddata either fires the function way to early or the function is getting executed before it gets to the loadImage function.

What are your ideas on my malfunctioning script?

Thank-you for reading
Paul

答:
It's img.onload And it needs a function.

Try

```<code>img.onload = function() {
    after(img, para);
}
</code>```

I think your missing the para parameter

```<code>window.globalFriends[i][2]=loadImage('http://graph.facebook.com/'+window.globalFriends[i][0]+'/picture', function (a){
    updateLoaders();
    loadingDrawPerson(a);}/*, para */); // <- where is para?
</code>```

Body:
I'm having issues with a script that I made for use in HTML5.
Here is the function

function loadImage(loc,after,para){
        var img = new Image();
        img.src = loc;
        if(typeof(after) != "undefined" && typeof(para) != "undefined"){
            img.onloadeddata  = after(img,para);
        }else if(typeof(after) != "undefined"){
            img.onloadeddata  = after(img);
        }
        return img;
}

and here is what is calling it

window.globalFriends[i][2]=loadImage('http://graph.facebook.com/'+window.globalFriends[i][0]+'/picture', function (a){
    updateLoaders();
    loadingDrawPerson(a);});

What I'm trying to do is send a function as a parameter for it then to be called.
It kinda of works but it a weird way. For example; All the images do get loaded but the onloadeddata either fires the function way to early or the function is getting executed before it gets to the loadImage function.

What are your ideas on my malfunctioning script?

Thank-you for reading
Paul

Body:
It's img.onload And it needs a function.

Try

img.onload = function() {
    after(img, para);
}

I think your missing the para parameter

window.globalFriends[i][2]=loadImage('http://graph.facebook.com/'+window.globalFriends[i][0]+'/picture', function (a){
    updateLoaders();
    loadingDrawPerson(a);}/*, para */); // <- where is para?


问:
Hello world flask app stops working when customizing host to "0.0.0.0"
If you initialize the default PyCharm Flask starter project, or just follow the first section that starts up "hello world" or just this:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()

```

<p>you'll have the same code as me. And it works fine, until I change the <code>host</code> argument to <code>0.0.0.0</code>, and then the application starts up like this:</p>

<pre class="lang-sh prettyprint-override"><code>$ python app.py
 * Serving Flask app "app" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
</code>```

And then when I go to that link, I get an invalid address error:

I need to use 0.0.0.0 instead of 127.0.0.1 because that's the IP address AWS uses for open connections.

How can I even start to get the 0.0.0.0 address to work locally?

I'm working on Windows.

答:
My guess on the question here is a firewall denying the connections or some kind of Windows policy in place and not an IP address problem. Maybe a proxy configured to allow 127.0.0.0/8 but not 0.0.0.0.

0.0.0.0 is a perfectly valid IP address even for a client. When you bind to it, it simply means listen on all IP addresses configured on the host.

If you are running the browser on the same machine as you are running the Flask app, you can even simply point it to http://0:5000 and it will show the content.

If you are running the application on AWS and are trying to access from a remote machine, than you need to specify the public IP address of your AWS instance instead, since 0.0.0.0 is a non-routable IP address (as any of the reserved private space IP addresses like 10.0.0.0/8, 127.0.0.0/8, 192.168.0.0/16, and 172.16.0.0/12).

Body:
If you initialize the default PyCharm Flask starter project, or just follow the first section that starts up "hello world" or just this:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()

you'll have the same code as me. And it works fine, until I change the host argument to 0.0.0.0, and then the application starts up like this:

$ python app.py
 * Serving Flask app "app" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)

And then when I go to that link, I get an invalid address error:

I need to use 0.0.0.0 instead of 127.0.0.1 because that's the IP address AWS uses for open connections.

How can I even start to get the 0.0.0.0 address to work locally?

I'm working on Windows.


问:
imagemagick convert RGB PNG to CMYK PDF
I am trying to create a PDF file using Latex. However, Latex does not handle TIFF or any other image format capable of both transparency and CMYK. The only solution I think I can use is to convert the PNG image to PDF and embed those in the file.

I am somewhat familiar with imagemagick, however, I am having trouble figuring out how to convert a PNG (probably in the RGB/SRGB colour space) to a PDF in the CMYK colour space.

How do I go about doing this conversion so that the colours are correct and the transparency remains?

答:
In Imagemagick, you should use a CMYK type profile to do the conversion:

```<code>convert input.png -profile USWebCoatedSWOP.icc output.pdf
</code>```

Note, however, that Imagemagick will simply put the raster image into a vector PDF shell. It will not vectorize the image.

Title: imagemagick convert RGB PNG to CMYK PDF

Body:
In Imagemagick, you should use a CMYK type profile to do the conversion:

convert input.png -profile USWebCoatedSWOP.icc output.pdf

Note, however, that Imagemagick will simply put the raster image into a vector PDF shell. It will not vectorize the image.


问:
How to iterate through a range of given keys in a nested dictionary
I am iterating through a nested dictionary of stock prices that has the key: dates.

I am having trouble in being able to only get the prices of stocks at start date and end date.

This is a link to the nested dictionary.
https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=TSLA&apikey=IMS80WN3J6S2ILKW

I've been trying a lot of different ways but not able to solve it for past 2 hrs:

```<code>starting_date  = '2020-02-13'
ending_date = '2020-02-11'

#data = the nested dictionary

opening_prices = []
series = data['Time Series (Daily)'] #Now were given the nested dictionary of the keys being dates and value being a dictionary of info: price.
for date in series:
    if date == starting_date:
        for data, price in date.items()
            opening_prices.append(float(price['1. open']))
#we are retrieving the opening prices of the nested dict.
#For this attempt, I get the error of date being str type.
#I still don't know how to stop at the end_date as I tried a while loop, but it failed.
</code>```

答:
If your goal is to get just the values for 2 dates you could do:

```<code>>>> res = [float(series[k]['1. open']) for k in (starting_date, ending_date)]
>>> res
[741.84, 768.79]
</code>```

For a range of dates, it can be changed to

```<code>>>> starting_date  = '2020-02-11'
>>> ending_date = '2020-02-13'
>>> res = [float(series[k]['1. open']) for k in series if starting_date <= k <= ending_date]
>>> res
[741.84, 777.87, 768.79]
</code>```

Body:
I am iterating through a nested dictionary of stock prices that has the key: dates.

I am having trouble in being able to only get the prices of stocks at start date and end date.

This is a link to the nested dictionary.
https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=TSLA&apikey=IMS80WN3J6S2ILKW

I've been trying a lot of different ways but not able to solve it for past 2 hrs:

starting_date  = '2020-02-13'
ending_date = '2020-02-11'

#data = the nested dictionary

opening_prices = []
series = data['Time Series (Daily)'] #Now were given the nested dictionary of the keys being dates and value being a dictionary of info: price.
for date in series:
    if date == starting_date:
        for data, price in date.items()
            opening_prices.append(float(price['1. open']))
#we are retrieving the opening prices of the nested dict.
#For this attempt, I get the error of date being str type.
#I still don't know how to stop at the end_date as I tried a while loop, but it failed.

Body:
If your goal is to get just the values for 2 dates you could do:

>>> res = [float(series[k]['1. open']) for k in (starting_date, ending_date)]
>>> res
[741.84, 768.79]

For a range of dates, it can be changed to

>>> starting_date  = '2020-02-11'
>>> ending_date = '2020-02-13'
>>> res = [float(series[k]['1. open']) for k in series if starting_date <= k <= ending_date]
>>> res
[741.84, 777.87, 768.79]


问:
Given a class type, infer typeof other parameters in Typescript
I'm trying to make a function that has 2 parameters, where the type of the 2nd parameter is based on the type of the 1st. I can see several threads that this question might be a duplicate of but the typing syntax can get so complex that I've been fiddling with this for a while now and can't get it right.

```<code>class Mammal { }
class Bird { }

function stuff(classType: typeof Mammal | typeof Bird, arg: number or string depends on first param) {
    if (classType extends Mammal) {
        console.log(arg * 5);
    } else {
        console.log(arg.split(" "))
    }
}

stuff(Mammal, 5);  // want this to be valid

stuff(Bird, "Hello world"); // want this to be valid

stuff(Bird, 5); // want this to be invalid
</code>```

Playground link

答:
```<code>class Mammal {
    static type = 'mammal' as const
 }
class Bird {
    static type = 'bird' as const
}

function stuff<
M extends typeof Mammal | typeof Bird,
A extends (M extends (typeof Mammal) ? number : string)>
(classType: M, arg: A) {
    if (classType.type === 'mammal') {
        console.log((arg as number) * 5);
    } else {
        console.log((arg as string).split(" "))
    }
}

stuff(Mammal, 5); // ok
stuff(Mammal, 'a'); // error

stuff(Bird, "Hello world"); // ok
stuff(Bird, 1); // error
</code>```

TS is structural typed language, that means that if you have two classes which have the same definition, they are just the same for TS, as there is no structural difference between them. Below proove of this statement:

```<code>class Mammal {}
class Bird {}
type MammalIsBird
  = Mammal extends Bird
  ? Bird extends Mammal
  ? true
  : false
  : false // evaluates to true, Mammal and Bird are equal
</code>```

That is the reason why in order to distinguish both Mammal and Bird we need to create some static property to have the difference.

Another thing is that when we ask about this property in for example Mammal there will be none, as Mammal has all non-static properties, we need to use typeof Mammal in order to have the interface with static ones. That is why in the implementation I am using typeof M and not M.

Few important informations:

M extends typeof Mammal | typeof Bird means we allow or class Mammal or class Bird, if I would say just Mammal | Bird it would mean I want to get instances of the class not a class itself

A extends (M extends (typeof Mammal) ? number : string) - conditional type, if we get Mammal type as M we have second argument number if not it is string

classType.type === 'mammal' thanks of having static property we can use it in condition

(arg as number) type assertion needs to be done, as discriminant for first property doesn't work for the second one.

You can avoid type assertion by working with one object/array type of arguments. But I don't recommend this approach, nevertheless here you go:

```<code>type MammalArgs = [typeof Mammal, number]
type BirdsArgs = [typeof Bird, string];

const isMammalClass = (x: MammalArgs | BirdsArgs): x is MammalArgs => x[0].type === 'mammal'
const isBirdArgs = (x: MammalArgs | BirdsArgs): x is BirdsArgs => x[0].type === 'bird'
function stuff<
M extends typeof Mammal | typeof Bird,
A extends (M extends (typeof Mammal) ? MammalArgs : BirdsArgs)>
(...args: A) {
    if (isMammalClass(args)) {
        console.log(args[1] * 5); // no type assertion
    }
    if (isBirdArgs(args)) {
        console.log(args[1].split(" ")); // no type assertion
    }
}
</code>```

What I have done above is joining our arguments into one type [typeof Mammal, number] | [typeof Bird, string] in order to achieve relation between discriminant in first argument with the second. Having both in one type allows on such relation. The issue is that I needed to create two type guards, and also needed to use array directly, as any destructuring would broke our type narrowing. I would choose the first approach with type assertion.

Body:
I'm trying to make a function that has 2 parameters, where the type of the 2nd parameter is based on the type of the 1st. I can see several threads that this question might be a duplicate of but the typing syntax can get so complex that I've been fiddling with this for a while now and can't get it right.

class Mammal { }
class Bird { }

function stuff(classType: typeof Mammal | typeof Bird, arg: number or string depends on first param) {
    if (classType extends Mammal) {
        console.log(arg * 5);
    } else {
        console.log(arg.split(" "))
    }
}

stuff(Mammal, 5);  // want this to be valid

stuff(Bird, "Hello world"); // want this to be valid

stuff(Bird, 5); // want this to be invalid

Playground link

Body:
class Mammal {
    static type = 'mammal' as const
 }
class Bird {
    static type = 'bird' as const
}

function stuff<
M extends typeof Mammal | typeof Bird,
A extends (M extends (typeof Mammal) ? number : string)>
(classType: M, arg: A) {
    if (classType.type === 'mammal') {
        console.log((arg as number) * 5);
    } else {
        console.log((arg as string).split(" "))
    }
}

stuff(Mammal, 5); // ok
stuff(Mammal, 'a'); // error

stuff(Bird, "Hello world"); // ok
stuff(Bird, 1); // error

TS is structural typed language, that means that if you have two classes which have the same definition, they are just the same for TS, as there is no structural difference between them. Below proove of this statement:

class Mammal {}
class Bird {}
type MammalIsBird
  = Mammal extends Bird
  ? Bird extends Mammal
  ? true
  : false
  : false // evaluates to true, Mammal and Bird are equal

That is the reason why in order to distinguish both Mammal and Bird we need to create some static property to have the difference.

Another thing is that when we ask about this property in for example Mammal there will be none, as Mammal has all non-static properties, we need to use typeof Mammal in order to have the interface with static ones. That is why in the implementation I am using typeof M and not M.

Few important informations:

M extends typeof Mammal | typeof Bird means we allow or class Mammal or class Bird, if I would say just Mammal | Bird it would mean I want to get instances of the class not a class itself

A extends (M extends (typeof Mammal) ? number : string) - conditional type, if we get Mammal type as M we have second argument number if not it is string

classType.type === 'mammal' thanks of having static property we can use it in condition

(arg as number) type assertion needs to be done, as discriminant for first property doesn't work for the second one.

You can avoid type assertion by working with one object/array type of arguments. But I don't recommend this approach, nevertheless here you go:

type MammalArgs = [typeof Mammal, number]
type BirdsArgs = [typeof Bird, string];

const isMammalClass = (x: MammalArgs | BirdsArgs): x is MammalArgs => x[0].type === 'mammal'
const isBirdArgs = (x: MammalArgs | BirdsArgs): x is BirdsArgs => x[0].type === 'bird'
function stuff<
M extends typeof Mammal | typeof Bird,
A extends (M extends (typeof Mammal) ? MammalArgs : BirdsArgs)>
(...args: A) {
    if (isMammalClass(args)) {
        console.log(args[1] * 5); // no type assertion
    }
    if (isBirdArgs(args)) {
        console.log(args[1].split(" ")); // no type assertion
    }
}

What I have done above is joining our arguments into one type [typeof Mammal, number] | [typeof Bird, string] in order to achieve relation between discriminant in first argument with the second. Having both in one type allows on such relation. The issue is that I needed to create two type guards, and also needed to use array directly, as any destructuring would broke our type narrowing. I would choose the first approach with type assertion.


问:
Public __construct , retrieve user information class
I am looking to create a class and retrieve the account information in private and then make a public Getters
do you have any advice to improve this code?

```<code>    private $db;
    private $get;

    public function __construct($db = null)
    {
        $this->db = new Database();
    }

    private function get($information = 0, $userid = null)
    {
        if ($userid === null)
        {
            //if ($this->isOnline()) {
                $token = $_COOKIE['session'];

                $req = $this->db->query('SELECT user_id FROM cms_sessions WHERE token = :token',
                array(
                "token" => $token
                ));

                $userid = $req[0]['user_id'];
            //}
        }

        $req = $this->db->query('SELECT '. $information .' FROM users INNER JOIN users_info ON users.id = users_info.user_id WHERE users.id = :userid',
        array(
        "userid" => $userid
        ));

        return (count($req) > 0) ? htmlspecialchars($req[0][$information]) : "Erreur";
    }

    public function getId()
    {
        $req = $this->db->query('SELECT user_id FROM cms_sessions WHERE token = :token',
        array(
        "token" => @$_COOKIE['session']
        ));

        return (count($req) > 0) ? intval($req[0]['user_id']) : "0";
    }

    public function getIP()
    {
        return $this->get('last_ip');
    }

    public function getGender()
    {
        return $this->get('gender');
    }
</code>```

}

but this gives me '0' once I try to retrieve user information
Thank you for your response! cordially

答:
If you want to follow SOLID design principles to have decoupled code, then here is another way of achieving the required results

Lets define a contract which is responsible for returning a user

```<code> interface Extractable
 {
    public function user($db=null, $userId=null);
 }
</code>```

Lets define a User extractor class to get the user from database or session and will return the user to us

```<code> class UserExtractor implements Extractable
    {

      public function user($db=null, $userId=null)
      {
         return $this->retrieve($db,$userId);
      }
      protected function retrieve($db, $userId)
      {

        $db = $db ?? new Database();

        // This logic can further be extracted to its own method to get rid of
        // ugly conditional
         if($userid ) {

           $user = $db->query('SELECT * FROM users INNER JOIN users_info ON users.id = users_info.user_id WHERE users.id = :userid',
              array(
                    "userid" => $userid
               ));

            } else {

                // I believe you have this method defined so you can
                // bring it in this class

                if($this->existValue('session')) {
                    $user = $this->getValue('session');
                }
            }

           return $user;

      }

    }
</code>```

Now we can define the User class which will depend on contract and will give us the required info

```<code>    class Users extends Session
    {

        protected $extractable;

        // Ok lets work with interface and not the concrete class
        public function __construct(Extractable $extractable)
        {
          $this->extractable = $extractable

        }

        public function getId()
        {
            return (int) $this->extractable->user['id'];
        }

        public function getTokenTimes()
        {
          return (int) $this->extractable->user['token_times'];
        }
    }
</code>```

You can now use them as follow;

```<code> $extractedUser = new UserExtractor($db, 5); // whatever the params are

    $user = new Users($extractedUser);

    $user->getId();
    $user->getTokenTimes();
</code>```

Body:
I am looking to create a class and retrieve the account information in private and then make a public Getters
do you have any advice to improve this code?

    private $db;
    private $get;

    public function __construct($db = null)
    {
        $this->db = new Database();
    }

    private function get($information = 0, $userid = null)
    {
        if ($userid === null)
        {
            //if ($this->isOnline()) {
                $token = $_COOKIE['session'];

                $req = $this->db->query('SELECT user_id FROM cms_sessions WHERE token = :token',
                array(
                "token" => $token
                ));

                $userid = $req[0]['user_id'];
            //}
        }

        $req = $this->db->query('SELECT '. $information .' FROM users INNER JOIN users_info ON users.id = users_info.user_id WHERE users.id = :userid',
        array(
        "userid" => $userid
        ));

        return (count($req) > 0) ? htmlspecialchars($req[0][$information]) : "Erreur";
    }

    public function getId()
    {
        $req = $this->db->query('SELECT user_id FROM cms_sessions WHERE token = :token',
        array(
        "token" => @$_COOKIE['session']
        ));

        return (count($req) > 0) ? intval($req[0]['user_id']) : "0";
    }

    public function getIP()
    {
        return $this->get('last_ip');
    }

    public function getGender()
    {
        return $this->get('gender');
    }

}

but this gives me '0' once I try to retrieve user information
Thank you for your response! cordially

Body:
If you want to follow SOLID design principles to have decoupled code, then here is another way of achieving the required results

Lets define a contract which is responsible for returning a user

 interface Extractable
 {
    public function user($db=null, $userId=null);
 }

Lets define a User extractor class to get the user from database or session and will return the user to us

 class UserExtractor implements Extractable
    {

      public function user($db=null, $userId=null)
      {
         return $this->retrieve($db,$userId);
      }
      protected function retrieve($db, $userId)
      {

        $db = $db ?? new Database();

        // This logic can further be extracted to its own method to get rid of
        // ugly conditional
         if($userid ) {

           $user = $db->query('SELECT * FROM users INNER JOIN users_info ON users.id = users_info.user_id WHERE users.id = :userid',
              array(
                    "userid" => $userid
               ));

            } else {

                // I believe you have this method defined so you can
                // bring it in this class

                if($this->existValue('session')) {
                    $user = $this->getValue('session');
                }
            }

           return $user;

      }

    }

Now we can define the User class which will depend on contract and will give us the required info

    class Users extends Session
    {

        protected $extractable;

        // Ok lets work with interface and not the concrete class
        public function __construct(Extractable $extractable)
        {
          $this->extractable = $extractable

        }

        public function getId()
        {
            return (int) $this->extractable->user['id'];
        }

        public function getTokenTimes()
        {
          return (int) $this->extractable->user['token_times'];
        }
    }

You can now use them as follow;

 $extractedUser = new UserExtractor($db, 5); // whatever the params are

    $user = new Users($extractedUser);

    $user->getId();
    $user->getTokenTimes();


问:
Replace special characters from clipboard before pasting
I use a little js function which permits to paste the content of the clipboard in a textarea. see below.
the datas I paste are from excel, and are delimited with special characters \r\n
My need is to replace this special characters with a comma "," directly before the paste
Is there an easy way to do it ? thanks per advance

 function Coller() {
  navigator.clipboard.readText().then(clipText =>
  document.getElementById("textarea").innerText = clipText);
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="Coller()">Coller</button>

<textarea id="textarea" rows="10" cols="40"></textarea></code>```

答:
Replace the special characters with regex:

```<code>document.getElementById("textarea").innerText = clipText.replace(/\r\n/g, ',');
</code>```

Sample example:

let text = "Cherry\r\nOrange\r\nApple"

console.log(text.replace(/\r\n/g, ','))```

Body:
I use a little js function which permits to paste the content of the clipboard in a textarea. see below.
the datas I paste are from excel, and are delimited with special characters \r\n
My need is to replace this special characters with a comma "," directly before the paste
Is there an easy way to do it ? thanks per advance

 function Coller() {
  navigator.clipboard.readText().then(clipText =>
  document.getElementById("textarea").innerText = clipText);
 }

<button onclick="Coller()">Coller</button>

<textarea id="textarea" rows="10" cols="40"></textarea>

Body:
Replace the special characters with regex:

document.getElementById("textarea").innerText = clipText.replace(/\r\n/g, ',');

Sample example:

let text = "Cherry\r\nOrange\r\nApple"

console.log(text.replace(/\r\n/g, ','))


问:
angular appBootstrap method
I'm having some hard time finding why I need to call this method.
This line to be more specific: if ((window as any).appBootstrap) (window as any).appBootstrap();

```<code>platformBrowserDynamic()
    .bootstrapModule(AppModule)
    .then(value => {
        if ((window as any).appBootstrap) (window as any).appBootstrap();
    })
    .catch(err => console.error(err));
</code>```

When I create a new angular project it doesnt have that and works fine.
Does any one have any idea where should I be looking at?

答: Indeed, that line is not necessary to be called in order to run an normal angular app, however, if it is needed to bootstrap your app correctly you have to look for a third library or some module that required that object.</p>

Title: angular appBootstrap method

Body:
I'm having some hard time finding why I need to call this method.
This line to be more specific: if ((window as any).appBootstrap) (window as any).appBootstrap();

platformBrowserDynamic()
    .bootstrapModule(AppModule)
    .then(value => {
        if ((window as any).appBootstrap) (window as any).appBootstrap();
    })
    .catch(err => console.error(err));

When I create a new angular project it doesnt have that and works fine.
Does any one have any idea where should I be looking at?


问:
Group Data using two columns and merge the third column into a single row
I have the data in this form

I want this as Ouput using R

答:
We can do this in dplyr.  After grouping by 'subject', 'center', we paste the 'rollno' by collapseing with | in summarise and replace the duplicated 'subject' with blank ('')

```<code>library(dplyr)
df1 %>%
  group_by(subject, center) %>%
  summarise(rollno = paste(rollno, collapse="|")) %>%
  ungroup %>%
  mutate(subject = replace(subject, duplicated(subject), ""))
# A tibble: 6 x 3
#  subject center rollno
#  <chr>    <dbl> <chr>
#1 "100"     2500 700|701|702
#2 ""        2501 703
#3 "101"     2500 701
#4 ""        2501 705
#5 "102"     2500 707
#6 ""        2502 701|700
</code>```

Or in base R with aggregate/replace/transform

```<code>transform(aggregate(rollno ~ ., df1, paste, collapse='|'),
       subject = replace(subject, duplicated(subject), ""))
</code>```

data

```<code>df1 <- structure(list(subject = c(100, 100, 100, 100, 101, 101, 102,
102, 102), center = c(2500, 2500, 2500, 2501, 2500, 2501, 2502,
2500, 2502), rollno = c(700, 701, 702, 703, 701, 705, 701, 707,
700)), class = "data.frame", row.names = c(NA, -9L))
</code>```

Body:
We can do this in dplyr.  After grouping by 'subject', 'center', we paste the 'rollno' by collapseing with | in summarise and replace the duplicated 'subject' with blank ('')

library(dplyr)
df1 %>%
  group_by(subject, center) %>%
  summarise(rollno = paste(rollno, collapse="|")) %>%
  ungroup %>%
  mutate(subject = replace(subject, duplicated(subject), ""))
# A tibble: 6 x 3
#  subject center rollno
#  <chr>    <dbl> <chr>
#1 "100"     2500 700|701|702
#2 ""        2501 703
#3 "101"     2500 701
#4 ""        2501 705
#5 "102"     2500 707
#6 ""        2502 701|700

Or in base R with aggregate/replace/transform

transform(aggregate(rollno ~ ., df1, paste, collapse='|'),
       subject = replace(subject, duplicated(subject), ""))

data

df1 <- structure(list(subject = c(100, 100, 100, 100, 101, 101, 102,
102, 102), center = c(2500, 2500, 2500, 2501, 2500, 2501, 2502,
2500, 2502), rollno = c(700, 701, 702, 703, 701, 705, 701, 707,
700)), class = "data.frame", row.names = c(NA, -9L))