问:
How to fetch outlook contacts using rest API
I'm very new to outlook plugin development .For my addon, I need to get all the contacts from the current outlook account. I tried with the following code :

```<code>Office.context.mailbox.getCallbackTokenAsync({ isRest: true }, function (result) {
                if (result.status === "succeeded") {
                    var accessToken = result.value;
                    console.log("access token", accessToken);
                    getCurrentItem(accessToken);
                } else {
                    // Handle the error.
                }
});
 function getCurrentItem(accessToken) {

        var getcontacts = Office.context.mailbox.restUrl +
            '/v2.0/me/contacts';
        console.log(getcontacts);
        $.ajax({
            url: getcontacts,
            dataType: 'json',
            headers: { 'Authorization': 'Bearer ' + accessToken }
        }).done(function (item) {
            console.log(item);
      }).fail(function (error) {
                    // Handle error.
                });
    }
</code>```

When I used this js file in my outlook addon and consoled it, ends with 403 forbidden error. How to use this? Am I leading somewhere wrong in my code?

Thanks in advance!

答:
Found the answer for the question.

The problem is , not given permission in my manifest xml file :

```<code>  <Permissions>ReadWriteMailbox</Permissions>
</code>```

Body:
I'm very new to outlook plugin development .For my addon, I need to get all the contacts from the current outlook account. I tried with the following code :

Office.context.mailbox.getCallbackTokenAsync({ isRest: true }, function (result) {
                if (result.status === "succeeded") {
                    var accessToken = result.value;
                    console.log("access token", accessToken);
                    getCurrentItem(accessToken);
                } else {
                    // Handle the error.
                }
});
 function getCurrentItem(accessToken) {

        var getcontacts = Office.context.mailbox.restUrl +
            '/v2.0/me/contacts';
        console.log(getcontacts);
        $.ajax({
            url: getcontacts,
            dataType: 'json',
            headers: { 'Authorization': 'Bearer ' + accessToken }
        }).done(function (item) {
            console.log(item);
      }).fail(function (error) {
                    // Handle error.
                });
    }

When I used this js file in my outlook addon and consoled it, ends with 403 forbidden error. How to use this? Am I leading somewhere wrong in my code?

Thanks in advance!

Body:
Found the answer for the question.

The problem is , not given permission in my manifest xml file :

  <Permissions>ReadWriteMailbox</Permissions>


来源: stackexchange

问:
Reading XML and converting it to JSON Smartly
I have code which does the formatting and convert the XML to JSON but it is vary big and lethargic. I need to pick some 50 elements out of XML and format JSON using these elements.so many part is repeating but with different elements.
Below is the code:-

private String createBrokeredMessage(String payload) {
    String message = "";
    String Ver = "";
    String ID = "";
            |
            |
    String Rec = "";
    String default1 = "[]";

    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource src = new InputSource();
        src.setCharacterStream(new StringReader(payload));

        Document doc = builder.parse(src);
        NodeList n1 = doc.getElementsByTagName("Ver");
        if (n1.getLength() > 0) {
            Ver = n1.item(0).getTextContent();
            if(Ver == "") {
                Ver = default1;
            }
            else {
                Ver = "\""+Ver+"\"";
            }
        }

        NodeList n2 = doc.getElementsByTagName("ID");
        if (n2.getLength() > 0) {
            ID = n2.item(0).getTextContent();
            if(ID == "") {
                ID = default1;
            }
            else {
                ID = "\""+ID+"\"";
            }
        }
        //|
        //|
        //|
        //|
        //|
        //|

        NodeList n49 = doc.getElementsByTagName("Rec");
        if (n49.getLength() > 0) {
            Rec = n49.item(0).getTextContent();
            if(Rec == "") {
                Rec = default1;
            }
            else {
                Rec = "\""+Rec+"\"";
            }
        }

        message = "{\"Envelope\":{\"Ver\":"+Ver+",\"ID\":"+ID+-------------------",\"Rec\":"+Rec+"}]}";
        System.out.println("Created message with ID" + message);
    } catch (Exception e){
            e.printStackTrace();
    }

    return message;
}
```

<p>Example XML:-</p>

```<?xml Version="1.0" encoding="UTF-8" standalone="no"?>
<Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Envelope>
    <Ver>1.13</Ver>
    <ID>SAO</ID>
    <Rec>men</Rec>
    <TransactionID>0987714805168</TransactionID>
  </Envelope>
  124
  <City></City>
  <CompCodes>
    <CompCode>US</CompCode>
    <Vend>13</Vend>
  </CompCodes>
  <BankData>
    123
    <BankAcctNum>231</BankAcctNum>
  </BankData>
  <BankData>
    124
    <BankAcctNum>431</BankAcctNum>
  </BankData>
</Data>
```

<p>Output JSON:-</p>

```{
   "Envelope": {
      "Ver": "1.13",
      "ID": "SAO",
      "Rec": "men",
      "TransactionID": "0987714805168"
   },
   "Code": "124",
   "City": [],
   "CompCodes": [{
      "CompCode": "US",
      "Vend": "13"
   }],
   "BankData": [
      {
         "Code": "123",
         "BankAcctNum": "231"
      },
      {
         "Code": "124",
         "BankAcctNum": "431"
      }
   ]
}
```

Any help will be appreciated!

答:
You can use JSON Jackson to convert XML to JSON quick and easy.

public static void main(String[] args) {
    String xml = "<?xml Version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"
        + "<Data xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n"
        + "  <Envelope>\n"
        + "    <Ver>1.13</Ver>\n"
        + "    <ID>SAO</ID>\n"
        + "    <Rec>men</Rec>\n"
        + "    <TransactionID>0987714805168</TransactionID>\n"
        + "  </Envelope>\n"
        + "  124\n"
        + "  <City></City>\n"
        + "  <CompCodes>\n"
        + "    <CompCode>US</CompCode>\n"
        + "    <Vend>13</Vend>\n"
        + "  </CompCodes>\n"
        + "  <BankData>\n"
        + "    123\n"
        + "    <BankAcctNum>231</BankAcctNum>\n"
        + "  </BankData>\n"
        + "  <BankData>\n"
        + "    124\n"
        + "    <BankAcctNum>431</BankAcctNum>\n"
        + "  </BankData>\n"
        + "</Data>";

    JSONObject json = XML.toJSONObject(xml);
    System.out.println(json.toString());
}
```

<p>Add the dependency:</p>

<pre class="lang-xml prettyprint-override"><code><dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20200518</version>
</dependency>
</code>```

See here: https://www.techiedelight.com/convert-xml-to-json-in-java/

ContentLicense: CC BY-SA 4.0

Body:
I have code which does the formatting and convert the XML to JSON but it is vary big and lethargic. I need to pick some 50 elements out of XML and format JSON using these elements.so many part is repeating but with different elements.
Below is the code:-

private String createBrokeredMessage(String payload) {
    String message = "";
    String Ver = "";
    String ID = "";
            |
            |
    String Rec = "";
    String default1 = "[]";

    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource src = new InputSource();
        src.setCharacterStream(new StringReader(payload));

        Document doc = builder.parse(src);
        NodeList n1 = doc.getElementsByTagName("Ver");
        if (n1.getLength() > 0) {
            Ver = n1.item(0).getTextContent();
            if(Ver == "") {
                Ver = default1;
            }
            else {
                Ver = "\""+Ver+"\"";
            }
        }

        NodeList n2 = doc.getElementsByTagName("ID");
        if (n2.getLength() > 0) {
            ID = n2.item(0).getTextContent();
            if(ID == "") {
                ID = default1;
            }
            else {
                ID = "\""+ID+"\"";
            }
        }
        //|
        //|
        //|
        //|
        //|
        //|

        NodeList n49 = doc.getElementsByTagName("Rec");
        if (n49.getLength() > 0) {
            Rec = n49.item(0).getTextContent();
            if(Rec == "") {
                Rec = default1;
            }
            else {
                Rec = "\""+Rec+"\"";
            }
        }

        message = "{\"Envelope\":{\"Ver\":"+Ver+",\"ID\":"+ID+-------------------",\"Rec\":"+Rec+"}]}";
        System.out.println("Created message with ID" + message);
    } catch (Exception e){
            e.printStackTrace();
    }

    return message;
}

Example XML:-

<?xml Version="1.0" encoding="UTF-8" standalone="no"?>
<Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Envelope>
    <Ver>1.13</Ver>
    <ID>SAO</ID>
    <Rec>men</Rec>
    <TransactionID>0987714805168</TransactionID>
  </Envelope>
  124
  <City></City>
  <CompCodes>
    <CompCode>US</CompCode>
    <Vend>13</Vend>
  </CompCodes>
  <BankData>
    123
    <BankAcctNum>231</BankAcctNum>
  </BankData>
  <BankData>
    124
    <BankAcctNum>431</BankAcctNum>
  </BankData>
</Data>

Output JSON:-

{
   "Envelope": {
      "Ver": "1.13",
      "ID": "SAO",
      "Rec": "men",
      "TransactionID": "0987714805168"
   },
   "Code": "124",
   "City": [],
   "CompCodes": [{
      "CompCode": "US",
      "Vend": "13"
   }],
   "BankData": [
      {
         "Code": "123",
         "BankAcctNum": "231"
      },
      {
         "Code": "124",
         "BankAcctNum": "431"
      }
   ]
}

Any help will be appreciated!

Body:
You can use JSON Jackson to convert XML to JSON quick and easy.

public static void main(String[] args) {
    String xml = "<?xml Version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"
        + "<Data xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n"
        + "  <Envelope>\n"
        + "    <Ver>1.13</Ver>\n"
        + "    <ID>SAO</ID>\n"
        + "    <Rec>men</Rec>\n"
        + "    <TransactionID>0987714805168</TransactionID>\n"
        + "  </Envelope>\n"
        + "  <Code>124</Code>\n"
        + "  <City></City>\n"
        + "  <CompCodes>\n"
        + "    <CompCode>US</CompCode>\n"
        + "    <Vend>13</Vend>\n"
        + "  </CompCodes>\n"
        + "  <BankData>\n"
        + "    <Code>123</Code>\n"
        + "    <BankAcctNum>231</BankAcctNum>\n"
        + "  </BankData>\n"
        + "  <BankData>\n"
        + "    <Code>124</Code>\n"
        + "    <BankAcctNum>431</BankAcctNum>\n"
        + "  </BankData>\n"
        + "</Data>";

    JSONObject json = XML.toJSONObject(xml);
    System.out.println(json.toString());
}

Add the dependency:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20200518</version>
</dependency>

See here: https://www.techiedelight.com/convert-xml-to-json-in-java/


问:
Parallel Processing in python to fill a dictionary with the value as a dictionary(nested)
I have multiple links(URL's) in a CSV file and I would like to use these URL's to extract/scrape data and store it in a dictionary format.

To facilitate this, I have developed a function that takes in the URL as the input and returns a dictionary as an output.

Ex:

```<code>def site_details(URL):

    site_dict = {}
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')
    site_dict['Date_created'] = soup.find('div', attrs={"class":"date" })
    site_dict['visits'] = soup.find('div', attrs={"class":"visits" })
    return(site_dict)

</code>```

Now I would like to process parallel all the URL's and store them in another dictionary which can later be converted in a CSV file.

So far I have tried the following:

```<code>from multiprocess import Process, Manager
def f(d, x):
    d[x] = site_details(df["Subject_link"][x])
    return d

manager = Manager()
d = manager.dict()
job = [Process(target=f, args=(d, i)) for i in range(5)]

_ = [p.start() for p in job]
_ = [p.join() for p in job]
print(d)
</code>```

The issue is that I am getting an empty list as a result

I would like an output like this:

```<code>d = {
      1:{date_created : '22/1/2014',visits:490}
      2:{date_created : '23/1/2014',visits:480}
      3:{date_created : '24/1/2014',visits:470}
    }

</code>```

Thanks for the help!!

答:
This code, using multiprocessing module works as expected.

This code, using multiprocess from Mike McKearns should either.

Not working?

a) Check the presence of the dill module, it is a pre-requisite for multiprocess to work.

b) Re-run the code below.

c) Adapt this working template as you wish, yet do resist not to return any value(s), but rather store it/them into instance variable(s) managed by a Manager-instance, best using the Manager as a context-manager using with Manager as myNewContextManagerForThisLimitedScopeOfUse: clause

```<code>from multiprocessing import Process, Manager                            # https://stackoverflow.com/questions/62130801/parallel-processing-in-python-to-fill-a-dictionary-with-the-value-as-a-dictionar
import os

def f( d, l, i ):
    d[0]    = '1'
    d['2']  =  2
    d[0.25] = None
    d[1] = { "date_created": '22/1/2014', "visits": 490, "os.getpid()": os.getpid() }
    d[2] = { "date_created": '23/1/2014', "visits": 480, "os.getpid()": os.getpid() }
    d[3] = { "date_created": '24/1/2014', "visits": 470, "os.getpid()": os.getpid() }
    d[99 + 100 * ( i + 1 )] = os.getpid()
    l.reverse()

if __name__ == '__main__':
    print( "The __main__ in PID::", os.getpid() )
    with Manager() as myDemoMANAGER:
        d = myDemoMANAGER.dict()
        l = myDemoMANAGER.list( range( 10 ) )

        # p = Process( target = f, args = ( d, l ) )
        #
        # p.start()
        # p.join()

        jobs = [ Process( target = f, args = ( d, l, i ) ) for i in range( 5 ) ]
        _    = [ p.start() for p in jobs ]
        _    = [ p.join()  for p in jobs ]

        print( "The dict instance is: ", d )
        print( "The list instance is: ", l )
        print( "\nQ.E.D." )

'''
(py3) Tue Jun 02 13:49:27 $ python StackOverflow_py3_Multiprocess.py

The __main__ in PID:: 19595
The dict instance is:  { 0: '1',
                         0.25: None,
                         1: { 'date_created': '22/1/2014', 'visits': 490, 'os.getpid()': 19610 },
                         2: { 'date_created': '23/1/2014', 'visits': 480, 'os.getpid()': 19607 },
                         3: { 'date_created': '24/1/2014', 'visits': 470, 'os.getpid()': 19607 },
                         199: 19604,
                         299: 19605,
                         399: 19607,
                         499: 19609,
                         599: 19610,
                        '2': 2
                         }
The list instance is:  [ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 ]

Q.E.D.

'''
</code>```

A minor remark on modifying managed objects internal details:

Documentation explicitly warns about modifying v/s assigning v/s re-assigning managed referents:

If standard (non-proxy) list or dict objects are contained in a referent, modifications to those mutable values will not be propagated through the manager because the proxy has no way of knowing when the values contained within are modified. However, storing a value in a container proxy (which triggers a __setitem__ on the proxy object) does propagate through the manager and so to effectively modify such an item, one could re-assign the modified value to the container proxy

Body:
I have multiple links(URL's) in a CSV file and I would like to use these URL's to extract/scrape data and store it in a dictionary format.

To facilitate this, I have developed a function that takes in the URL as the input and returns a dictionary as an output.

Ex:

def site_details(URL):

    site_dict = {}
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')
    site_dict['Date_created'] = soup.find('div', attrs={"class":"date" })
    site_dict['visits'] = soup.find('div', attrs={"class":"visits" })
    return(site_dict)

Now I would like to process parallel all the URL's and store them in another dictionary which can later be converted in a CSV file.

So far I have tried the following:

from multiprocess import Process, Manager
def f(d, x):
    d[x] = site_details(df["Subject_link"][x])
    return d

manager = Manager()
d = manager.dict()
job = [Process(target=f, args=(d, i)) for i in range(5)]

_ = [p.start() for p in job]
_ = [p.join() for p in job]
print(d)

The issue is that I am getting an empty list as a result

I would like an output like this:

d = {
      1:{date_created : '22/1/2014',visits:490}
      2:{date_created : '23/1/2014',visits:480}
      3:{date_created : '24/1/2014',visits:470}
    }

Thanks for the help!!

Body:
This code, using multiprocessing module works as expected.

This code, using multiprocess from Mike McKearns should either.

Not working?

a) Check the presence of the dill module, it is a pre-requisite for multiprocess to work.

b) Re-run the code below.

c) Adapt this working template as you wish, yet do resist not to return any value(s), but rather store it/them into instance variable(s) managed by a Manager-instance, best using the Manager as a context-manager using with Manager as myNewContextManagerForThisLimitedScopeOfUse: clause

from multiprocessing import Process, Manager                            # https://stackoverflow.com/questions/62130801/parallel-processing-in-python-to-fill-a-dictionary-with-the-value-as-a-dictionar
import os

def f( d, l, i ):
    d[0]    = '1'
    d['2']  =  2
    d[0.25] = None
    d[1] = { "date_created": '22/1/2014', "visits": 490, "os.getpid()": os.getpid() }
    d[2] = { "date_created": '23/1/2014', "visits": 480, "os.getpid()": os.getpid() }
    d[3] = { "date_created": '24/1/2014', "visits": 470, "os.getpid()": os.getpid() }
    d[99 + 100 * ( i + 1 )] = os.getpid()
    l.reverse()

if __name__ == '__main__':
    print( "The __main__ in PID::", os.getpid() )
    with Manager() as myDemoMANAGER:
        d = myDemoMANAGER.dict()
        l = myDemoMANAGER.list( range( 10 ) )

        # p = Process( target = f, args = ( d, l ) )
        #
        # p.start()
        # p.join()

        jobs = [ Process( target = f, args = ( d, l, i ) ) for i in range( 5 ) ]
        _    = [ p.start() for p in jobs ]
        _    = [ p.join()  for p in jobs ]

        print( "The dict instance is: ", d )
        print( "The list instance is: ", l )
        print( "\nQ.E.D." )

'''
(py3) Tue Jun 02 13:49:27 $ python StackOverflow_py3_Multiprocess.py

The __main__ in PID:: 19595
The dict instance is:  { 0: '1',
                         0.25: None,
                         1: { 'date_created': '22/1/2014', 'visits': 490, 'os.getpid()': 19610 },
                         2: { 'date_created': '23/1/2014', 'visits': 480, 'os.getpid()': 19607 },
                         3: { 'date_created': '24/1/2014', 'visits': 470, 'os.getpid()': 19607 },
                         199: 19604,
                         299: 19605,
                         399: 19607,
                         499: 19609,
                         599: 19610,
                        '2': 2
                         }
The list instance is:  [ 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 ]

Q.E.D.

'''

A minor remark on modifying managed objects internal details:

Documentation explicitly warns about modifying v/s assigning v/s re-assigning managed referents:

If standard (non-proxy) list or dict objects are contained in a referent, modifications to those mutable values will not be propagated through the manager because the proxy has no way of knowing when the values contained within are modified. However, storing a value in a container proxy (which triggers a __setitem__ on the proxy object) does propagate through the manager and so to effectively modify such an item, one could re-assign the modified value to the container proxy


问:
json format from rails to sproutcore
For those of you using Rails as a backend to their Sproutcore clients,
which one is the best way to format the data into json?

From the Sproutcore guides there was this approach:

```<code> def as_json(options = {})
   event_hash = {
     "guid" => self.id,
     "id" => self.id,
     "designation" => self.designation,
     "category" => self.category,
     "scheduled_for" => self.scheduled_for,
     "location" => self.location,
     "groups" => self.groups,
     "resources" => self.resources
   }

   event_hash
 end
</code>```

But it fails, send an "Illegal statement error". Then, I changed to this other method:

```<code> def as_json(options = {})
   # event_hash = options.merge(:include => [:groups, :resources], :methods => :guid)
   event_hash = options.merge(:methods => :guid)
   super(event_hash)
 end
</code>```

which seems to be working as far as the formatting is concerned, although I am suspecting it to causing some trouble regarding the representation in the dataHash of the store. Anyway, ha anyone been having similar issues with the first version of as_json? If not, is there anything I am doing wrong?

Appreciate any help

答:
On the first method you need to call super:

```<code>def as_json(options = {})
  event_hash = {
    "guid" => self.id,
    "id" => self.id,
    "designation" => self.designation,
    "category" => self.category,
    "scheduled_for" => self.scheduled_for,
    "location" => self.location,
    "groups" => self.groups,
    "resources" => self.resources
  }

  super(event_hash)
end
</code>```

However you should get the options param and process to do this apropiately.

ContentLicense: CC BY-SA 3.0

Title: json format from rails to sproutcore

Body:
For those of you using Rails as a backend to their Sproutcore clients,
which one is the best way to format the data into json?

From the Sproutcore guides there was this approach:

 def as_json(options = {})
   event_hash = {
     "guid" => self.id,
     "id" => self.id,
     "designation" => self.designation,
     "category" => self.category,
     "scheduled_for" => self.scheduled_for,
     "location" => self.location,
     "groups" => self.groups,
     "resources" => self.resources
   }

   event_hash
 end

But it fails, send an "Illegal statement error". Then, I changed to this other method:

 def as_json(options = {})
   # event_hash = options.merge(:include => [:groups, :resources], :methods => :guid)
   event_hash = options.merge(:methods => :guid)
   super(event_hash)
 end

which seems to be working as far as the formatting is concerned, although I am suspecting it to causing some trouble regarding the representation in the dataHash of the store. Anyway, ha anyone been having similar issues with the first version of as_json? If not, is there anything I am doing wrong?

Appreciate any help

Body:
On the first method you need to call super:

def as_json(options = {})
  event_hash = {
    "guid" => self.id,
    "id" => self.id,
    "designation" => self.designation,
    "category" => self.category,
    "scheduled_for" => self.scheduled_for,
    "location" => self.location,
    "groups" => self.groups,
    "resources" => self.resources
  }

  super(event_hash)
end

However you should get the options param and process to do this apropiately.


问:
can't perform a react state update on an unmounted component. this is a no-op but it indicates a memory leak
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.</p>

```<code>componentDidMount() {
    this.RetrieveSellerNo();
    this.requestLocationPermission();
    this.requestData();
    this.Watch();

    this._interval = setInterval(() => {

        if (this.state.SellerNo !== null) {
            this.uploadPosition();
        }
        this.requestData();
    }, 60000);
    setTimeout(() => {
        this.requestData();
        this.StoreiposLat();
        this.StoreiposLong();
    }, 5000);
}

componentWillUnmount = () => {
    Geolocation.clearWatch(this.watchId);

}

Watch = () => {
    this.watchId = Geolocation.watchPosition(
        (position) => {
            this.setState({
                watch: {
                    lat: position.coords.latitude,
                    long: position.coords.longitude
                }
            });
        },
        (error) => {
            // console.log(error.message)
        },
        { enableHighAccuracy: false, timeout: 20000, maximumAge: 1000, } //distanceFilter:1
    );
}
</code>```

答:
I did it . But there is still an error.
I used pureComponent and clearing all timeout and interval.

I have to say that this happens when I go from this page to the login page and come back to the this page.

Each time the amount of RAM is increased and added to the previous value.

Body:
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

componentDidMount() {
    this.RetrieveSellerNo();
    this.requestLocationPermission();
    this.requestData();
    this.Watch();

    this._interval = setInterval(() => {

        if (this.state.SellerNo !== null) {
            this.uploadPosition();
        }
        this.requestData();
    }, 60000);
    setTimeout(() => {
        this.requestData();
        this.StoreiposLat();
        this.StoreiposLong();
    }, 5000);
}

componentWillUnmount = () => {
    Geolocation.clearWatch(this.watchId);

}

Watch = () => {
    this.watchId = Geolocation.watchPosition(
        (position) => {
            this.setState({
                watch: {
                    lat: position.coords.latitude,
                    long: position.coords.longitude
                }
            });
        },
        (error) => {
            // console.log(error.message)
        },
        { enableHighAccuracy: false, timeout: 20000, maximumAge: 1000, } //distanceFilter:1
    );
}


问:
What is the smallest subset of C that modern compilers can optimise as well as C?
I want to generate some C and verify that it will compile and so I want to use a subset of C to make the verification easier.
However I don’t want to limit what can be written so I want a subset of C such that given any C program you can write a program that will compile to the same machine code in a modern compiler.

For example I believe the following constructs to be unnecessary:

x++, ++x, x—-, —-x

(Edit: These are not, thanks to @dmuir and @StoryTeller-UnslanderMonica) +=, -=, *=, /=, %=, <<=, >>=, &=, ^=, |=

a[i]

Array types outside of declarations

p->m

Are there any more and are any of mine necessary for certain optimisations?

答:
Things you could exclude from the "subset of C" without requiring a difference in the compiler's output include:

pre-increment and post-increment (x++, ++x).  This includes unusual situations where side-effects would have to be emulated explicitly.

assignment operators (x =+ .., etc). This includes unusual situations where side-effects would have to be emulated explicitly.

either array accesses (but not definition of arrays) or * as pointer dereference (e.g. x = *pointer; replaced by x = pointer[0];).

almost all whitespace (e.g. everything except the newline character), including comments and line continuation (\ at end of line)

trigraphs (replaceable by their normal character equivalents)

do, while and for (all replaceable with if and goto); but not switch (I expect that modern compilers use the switch keyword as a "consider conversion into jump table" hint)

break; (can be replaced by goto)

the inline keyword (its typically ignored anyway)

brackets in expressions. These can be eliminated by re-arranging expressions and/or using temporary variables (e.g. x = (y + z) * 3; replaced by temp = y + z; x = temp * 3;).

half of the relational operators (e.g. x = a != b can be replaced by x = !(a == b);, x = a <= b can be replaced by x = !(a > b);, etc)

hexadecimal and octal for numerical constants (can replace with decimal constants)

negation. Can be replaced with subtraction (e.g. x = -y; replaced with x = 0 - y;)

either & or |. Replaced by their equivalent using DeMorgan's laws (e.g. x = a & b; replaced with x = ~(~a | ~b);).

either && or ||. Replaced by their equivalent using DeMorgan's laws (e.g. if( (a == b) && (c == d) ) replaced with if( !(a != b) || (c != d) )).

comma used as statement separator. Code using comma as a statement separator can always be refactored into code that doesn't (e.g. for(i = 0, j = 0; i < k; i++, j++) { foo(); } replaced with j = 0; for(i = 0; i < k; i++) { foo(); j++; } or maybe i = 0; j = 0; if(i < k) goto done; next: ; foo(); i = i + 1; j = j + 1; if( !(i < k)) goto next; done: ; }.

enum. Can be replaced by a set of #define ...

Note 1: "without requiring a difference in the compiler's output" (in my first sentence) means that there may be a difference in the compiler's output that wasn't required.

Note 2: I would "very much dislike" reading source code that did these things. For source code readability (e.g. debugging the output of your "Idris to C" converter to see if your converter has bugs) I would avoid doing any of the things in this list.


问:
Get Distinct Value in a List/Cell in PostgreSQL
it happens that I am having this type of data structure and trying to eliminate the duplicated values under Type in Postgres.

Initial Table

```<code>Index   Type
1       A, B
2       A, A
3       B, B
</code>```

Expected Table

```<code>Index   Type
1       A, B
2       A
3       B
</code>```

Thanks for the help!

答:
Here is an alternative approach that doesn't use aggregation over the entire table:

```<code>SELECT Index,
       (SELECT STRING_AGG(DISTINCT t, ', ')
        FROM UNNEST(STRING_TO_ARRAY(Type, ', ')) AS t
       ) as types
FROM Data;
</code>```

Here is a db<>fiddle.

Although I would expect Avoiding the outer aggregation would be a win on performance on larger data sets, it doesn't appear to be so.

Body:
it happens that I am having this type of data structure and trying to eliminate the duplicated values under Type in Postgres.

Initial Table

Index   Type
1       A, B
2       A, A
3       B, B

Expected Table

Index   Type
1       A, B
2       A
3       B

Thanks for the help!

Body:
Here is an alternative approach that doesn't use aggregation over the entire table:

SELECT Index,
       (SELECT STRING_AGG(DISTINCT t, ', ')
        FROM UNNEST(STRING_TO_ARRAY(Type, ', ')) AS t
       ) as types
FROM Data;

Here is a db<>fiddle.

Although I would expect Avoiding the outer aggregation would be a win on performance on larger data sets, it doesn't appear to be so.


问:
How to parse json with unknown keys in android
Hi I am using retrofit to send and receive data from server.How to parse if the keys are different.

Can any one help me how to parse json with below keys.

```<code>{"users": {"19x1": "Admin","19x5": "Manager"}}
</code>```

答:
The json you gave is not correct.It should be like this:

```<code>{"users": {"19x1": "Admin","19x5": "Manager"}}
</code>```

You can check the accuracy of json object in here: https://www.bejson.com/

Body:
Hi I am using retrofit to send and receive data from server.How to parse if the keys are different.

Can any one help me how to parse json with below keys.

{"users": {"19x1": "Admin","19x5": "Manager"}}

Body:
The json you gave is not correct.It should be like this:

{"users": {"19x1": "Admin","19x5": "Manager"}}

You can check the accuracy of json object in here: https://www.bejson.com/


问:
Handle French Characters in Java
I Have a Page where I search for a term and it is displaying perfect. Whatever character type it is.

Now when I have few checkboxes in JSP and I check it and submit. In these checkboxes I have one box name like ABC Farmacéutica Corporation.

When I click on submit button, I am calling a function and will set all parameters to a form and will submit that form. (I tested putting alert for the special character display before submit and it is displaying good).

Now, coming to the Java end, I use Springs Frame work. When I print the term in controller, then it is displayed like ABC FarmacÃ©utica Corporation.

Please help...
Thanks in advance.

EDIT :

Please try this sample Example

```<code>import java.net.*;
class sample{
    public static void main(String[] args){
        try{
            String aaa = "ABC Farmacéutica Corporation";
            String bbb = "ABC FarmacÃ©utica Corporation";

            aaa = URLEncoder.encode(aaa, "UTF-8");
            bbb = URLDecoder.decode(bbb, "UTF-8");

            System.out.println("aaa   "+aaa);
            System.out.println("bbb   "+bbb);

        }catch(Exception e){
            System.out.println(e);
        }
    }
}
</code>```

I am getting output as,

```<code>aaa   PiSA+Farmac%C3%A9utica+Mexicana+Corporativo
bbb   PiSA Farmac├⌐utica Mexicana Corporativo
</code>```

Try to print the string aaa as it is.

答:
You get "ABC FarmacÃ©utica Corporation" because the string you receive from the client is ISO-8859-1, you need to convert it into UTF-8 before you URL decode it. Like this :

```<code>bbb = URLDecoder.decode(new String(bbb.getBytes("ISO-8859-1"), "UTF-8"), "UTF-8");
</code>```

NOTE : some encodings cannot be converted from and to different encodings without risking data loss. For example, you cannot convert Thaï characters (TIS-620) to another encoding, not even UTF-8. For this reason, avoid converting from one encoding to another, unless ultimately necessary (ie. the data comes from an external, third perty, or proprietary source, etc.) This is only a solution on how to convert from one source to another, knowing the source encoding.

Title: Handle French Characters in Java

Body:
I Have a Page where I search for a term and it is displaying perfect. Whatever character type it is.

Now when I have few checkboxes in JSP and I check it and submit. In these checkboxes I have one box name like ABC Farmacéutica Corporation.

When I click on submit button, I am calling a function and will set all parameters to a form and will submit that form. (I tested putting alert for the special character display before submit and it is displaying good).

Now, coming to the Java end, I use Springs Frame work. When I print the term in controller, then it is displayed like ABC FarmacÃ©utica Corporation.

Please help...
Thanks in advance.

EDIT :

Please try this sample Example

import java.net.*;
class sample{
    public static void main(String[] args){
        try{
            String aaa = "ABC Farmacéutica Corporation";
            String bbb = "ABC FarmacÃ©utica Corporation";

            aaa = URLEncoder.encode(aaa, "UTF-8");
            bbb = URLDecoder.decode(bbb, "UTF-8");

            System.out.println("aaa   "+aaa);
            System.out.println("bbb   "+bbb);

        }catch(Exception e){
            System.out.println(e);
        }
    }
}

I am getting output as,

aaa   PiSA+Farmac%C3%A9utica+Mexicana+Corporativo
bbb   PiSA Farmac├⌐utica Mexicana Corporativo

Try to print the string aaa as it is.

Body:
You get "ABC FarmacÃ©utica Corporation" because the string you receive from the client is ISO-8859-1, you need to convert it into UTF-8 before you URL decode it. Like this :

bbb = URLDecoder.decode(new String(bbb.getBytes("ISO-8859-1"), "UTF-8"), "UTF-8");

NOTE : some encodings cannot be converted from and to different encodings without risking data loss. For example, you cannot convert Thaï characters (TIS-620) to another encoding, not even UTF-8. For this reason, avoid converting from one encoding to another, unless ultimately necessary (ie. the data comes from an external, third perty, or proprietary source, etc.) This is only a solution on how to convert from one source to another, knowing the source encoding.


问:
Electronics Shop
I have been working on this question, and after submitting my code 7 cases passed, however, 9 cases failed. The question link is here of HackerRank : Electronic Shop

Problem Statement

A girl wants to buy a keyboard, and a USB drive, she want to spend as much as possible but within budget (combining both the items). And if the price of both the items exceeds her budget, return -1 or she can't buy. What is mandatory is that She wants to buy both the items, not a single one.

Example

A range of keyboards is given in the form of an array [40, 50, 60], and USB drives is given as [5,8,12]. Her max budget is 60. Now if we sum up both the things we get two max value of combination :

40 + 12 = 52

50 + 8 = 58

Since 58 one is greater, hence she will get the items worth of 50 and 8.

Input format

The first line contains three space-separated integers b, n, and m, her budget, the number of keyboard models and the number of USB drive models.

The second line contains  space-separated integers , the prices of each keyboard model.

The third line contains  space-separated integers , the prices of the USB drives.

Output Format

Print a single integer denoting the amount of money Monica will spend. If she doesn't have enough money to buy one keyboard and one USB drive, print -1 instead.

My Algo

```<code>1. Take answer variable as 0, and max value initialize it with first element of keyboard + first element of usb drives

2. loop through keyboard, make an inner loop for usb

3. Compare keyboard[i] + drives[j], if greater than b, then return -1.

4. Else find the max value and assign it to answer

5. return answer
</code>```

My logic is as simple as the requirements, but somehow fails for the cases which has a very large number of elements in the array.

Code

```<code>static int getMoneySpent(int[] keyboards, int[] drives, int b) {
    int answer = 0, maxAmount = keyboards[0] + drives[0];

    //This will compare the value of i+j throughout the loop and returns the max one
    for(int i: keyboards){
      for(int j: drives){
        // Ofcourse if all i+j values will be greater than the max budget then -1
        if((i+j) > b)
          answer = -1;
        else if((i+j) == b){
           answer = i+j;
        }else{
           /*If the value is smaller than the max budget, the finding the max value we get after adding them and comparing with the maxAmount variable */
          if((i+j) > maxAmount){
            maxAmount = i+j;
            answer = maxAmount;
        }
      }
    }
  }

  return answer;
}
</code>```

I'm having two cases which failed,, here they are :

Failed Test Case 1

Input =>

```<code>539855 818 628
380710 674456 878173 532602 868253 721585 806107 141310 790209 212031
304748 818920 80938 322601 403071 22899 173564 153826 695108 223665
346178 957539 975830 573171 641117 932941 822666 575293 132555 479463
862209 313799 922966 606508 487172 139230 606390 898464 764983 829520
174879 317603 502680 953013 398753 825387 146407 666457 367618 121790
68188 478342 25818 506222 135197 232604 963333 79984 549654 776899
966040 122063 432596 594425 311887 936661 506256 876303 439611 277816
105689 851641 640971 333 216087 17692 619728 602689 650348 364881
152060 386548 61364 564569 780938 191826 459905 211804 58177 484711
995091 754424 57794 619638 695192 297423 983901 430435 239234 170704
142282 74647 121413 782873 303344 265448 101069 177807 692318 691774
62306 618191 509537 633333 996922 228947 814154 232698 615359 220853
306323 173792 624037 655872 527161 848207 426180 724481 130740 792273
886804 404890 449886 654224 194667 354317 367843 525624 414224 481744
827725 176927 733780 387166 769479 964040 1{-truncated-}
</code>```

Expected Output

```<code>539854
</code>```

For full input data here is the link : Input Array Data Full

Failed Test Case 2

Input =>

```<code>374625 797 951
183477 732159 779867 598794 596985 156054 445934 156030 99998 58097
459353 866372 333784 601251 142899 708233 651036 20590 56425 970129
722162 832631 938765 212387 779 181866 992436 183446 617621 304311
611791 524875 7068 432043 23068 291295 524893 611991 399952 139526
46677 292211 973975 366445 232824 456173 90627 785353 618526 199719
382549 514351 983453 592549 466869 46461 860135 607682 680461 170563
450601 65067 13268 949100 942415 965850 563416 808580 385504 304683
15970 97695 230946 684388 241080 440252 683418 122066 610135 495289
833383 34397 173404 909526 391149 258839 182278 662672 755532 311782
425252 520186 207989 546834 567829 184897 31321 969804 842475 775308
449856 939711 395240 895029 926868 598035 727436 922082 326615 88513
570573 196028 520952 45238 961389 325404 844725 388765 747489 271411
539814 828925 586884 356834 965473 280998 607171 542819 276062 140956
296341 802378 165305 74568 15640 987110 423497 772419 394971 198761
293555 5524 14083 815646 198888 707017 711503 729172{-truncated-}
</code>```

Expected Output

```<code>374625
</code>```

For full input array data for this one follow this link : Failed Test Case 2 Full Input

I'm there almost but somehow I'm confused why my code is not working for long input array elements. Any help would be appreciated, as it will make me learn new thing in my future endeavor.

答:
```<code>int getMoneySpent(int keyboards_count, int* keyboards, int drives_count, int* drives, int b) {

     int price=-1;

         for(int i=0;i<drives_count;i++)
         {
             for(int j=0;j<keyboards_count;j++)
             {
                 if((drives[i]+keyboards[j]>price) && (drives[i]+keyboards[j]<=b))
                 {
                     price=drives[i]+keyboards[j];
                 }
             }
         }
         return price;
}
</code>```

Title: Electronics Shop

Body:
I have been working on this question, and after submitting my code 7 cases passed, however, 9 cases failed. The question link is here of HackerRank : Electronic Shop

Problem Statement

A girl wants to buy a keyboard, and a USB drive, she want to spend as much as possible but within budget (combining both the items). And if the price of both the items exceeds her budget, return -1 or she can't buy. What is mandatory is that She wants to buy both the items, not a single one.

Example

A range of keyboards is given in the form of an array [40, 50, 60], and USB drives is given as [5,8,12]. Her max budget is 60. Now if we sum up both the things we get two max value of combination :

40 + 12 = 52

50 + 8 = 58

Since 58 one is greater, hence she will get the items worth of 50 and 8.

Input format

The first line contains three space-separated integers b, n, and m, her budget, the number of keyboard models and the number of USB drive models.

The second line contains  space-separated integers , the prices of each keyboard model.

The third line contains  space-separated integers , the prices of the USB drives.

Output Format

Print a single integer denoting the amount of money Monica will spend. If she doesn't have enough money to buy one keyboard and one USB drive, print -1 instead.

My Algo

1. Take answer variable as 0, and max value initialize it with first element of keyboard + first element of usb drives

2. loop through keyboard, make an inner loop for usb

3. Compare keyboard[i] + drives[j], if greater than b, then return -1.

4. Else find the max value and assign it to answer

5. return answer

My logic is as simple as the requirements, but somehow fails for the cases which has a very large number of elements in the array.

Code

static int getMoneySpent(int[] keyboards, int[] drives, int b) {
    int answer = 0, maxAmount = keyboards[0] + drives[0];

    //This will compare the value of i+j throughout the loop and returns the max one
    for(int i: keyboards){
      for(int j: drives){
        // Ofcourse if all i+j values will be greater than the max budget then -1
        if((i+j) > b)
          answer = -1;
        else if((i+j) == b){
           answer = i+j;
        }else{
           /*If the value is smaller than the max budget, the finding the max value we get after adding them and comparing with the maxAmount variable */
          if((i+j) > maxAmount){
            maxAmount = i+j;
            answer = maxAmount;
        }
      }
    }
  }

  return answer;
}

I'm having two cases which failed,, here they are :

Failed Test Case 1

Input =>

539855 818 628
380710 674456 878173 532602 868253 721585 806107 141310 790209 212031
304748 818920 80938 322601 403071 22899 173564 153826 695108 223665
346178 957539 975830 573171 641117 932941 822666 575293 132555 479463
862209 313799 922966 606508 487172 139230 606390 898464 764983 829520
174879 317603 502680 953013 398753 825387 146407 666457 367618 121790
68188 478342 25818 506222 135197 232604 963333 79984 549654 776899
966040 122063 432596 594425 311887 936661 506256 876303 439611 277816
105689 851641 640971 333 216087 17692 619728 602689 650348 364881
152060 386548 61364 564569 780938 191826 459905 211804 58177 484711
995091 754424 57794 619638 695192 297423 983901 430435 239234 170704
142282 74647 121413 782873 303344 265448 101069 177807 692318 691774
62306 618191 509537 633333 996922 228947 814154 232698 615359 220853
306323 173792 624037 655872 527161 848207 426180 724481 130740 792273
886804 404890 449886 654224 194667 354317 367843 525624 414224 481744
827725 176927 733780 387166 769479 964040 1{-truncated-}

Expected Output

539854

For full input data here is the link : Input Array Data Full

Failed Test Case 2

Input =>

374625 797 951
183477 732159 779867 598794 596985 156054 445934 156030 99998 58097
459353 866372 333784 601251 142899 708233 651036 20590 56425 970129
722162 832631 938765 212387 779 181866 992436 183446 617621 304311
611791 524875 7068 432043 23068 291295 524893 611991 399952 139526
46677 292211 973975 366445 232824 456173 90627 785353 618526 199719
382549 514351 983453 592549 466869 46461 860135 607682 680461 170563
450601 65067 13268 949100 942415 965850 563416 808580 385504 304683
15970 97695 230946 684388 241080 440252 683418 122066 610135 495289
833383 34397 173404 909526 391149 258839 182278 662672 755532 311782
425252 520186 207989 546834 567829 184897 31321 969804 842475 775308
449856 939711 395240 895029 926868 598035 727436 922082 326615 88513
570573 196028 520952 45238 961389 325404 844725 388765 747489 271411
539814 828925 586884 356834 965473 280998 607171 542819 276062 140956
296341 802378 165305 74568 15640 987110 423497 772419 394971 198761
293555 5524 14083 815646 198888 707017 711503 729172{-truncated-}

Expected Output

374625

For full input array data for this one follow this link : Failed Test Case 2 Full Input

I'm there almost but somehow I'm confused why my code is not working for long input array elements. Any help would be appreciated, as it will make me learn new thing in my future endeavor.


问:
how to pip install fancyimpute?
in my case, I also have python 3.7.7 but couldn't install fancyimpute as well
I tried cp36 , and cp37 version. and I already installed visual studio C++ 2015

here's my error log.

error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/

ERROR: Failed building wheel for scs
Running setup.py clean for scs
Failed to build cvxpy scs
ERROR: Could not build wheels for cvxpy which use PEP 517 and cannot be installed directly

答:
I am not sure if your problem still persists. I installed the vs and reinstalled cvxpy, then got the error resolved.
Unable to install 'fancyimpute' in Anaconda
and
https://www.cvxpy.org/install/index.html#conda
may give you more info on this problem.</p>

Title: how to pip install fancyimpute?


问:
How do I set the framerate/FPS in an FFmpeg code (C)?
I try to encode single pictures to a .avi video. The goal is to have every picture displayed for a set amount of seconds to create a slide show. I tried my script with 10 pictures and a delay of 1/5 of a second but the output file was not even half a second long (but displayed every picture). For setting the framerate I use the time_base option of the AVCodeContext:

ctx->time_base = (AVRational) {1, 5};

When I use the command ffmpeg -framerate 1/3 -i img%03d.png -codec png output.avi everything works fine and I get the file I want. I use the png codec because it was the only one i tried that is playable with Windows Media Player.

Am I missing anything here? Is there another option that has impact on the framerate?

This is my code so far:

Note: I use a couple of self made data structures and methodes from other classes. They are the ones written in Caps Lock. They basicly do what the name suggests but are necessary for my project. The Input Array contains the pictures that i want to encode.

```<code>include <libavutil/opt.h>
include <libavutil/imgutils.h>
include <libavutil/error.h>

void PixmapsToAVI (ARRAY* arr, String outfile, double secs)
{
     if (arr!=nil && outfile!="" && secs!=0) {
         AVCodec* codec = avcodec_find_encoder(AV_CODEC_ID_PNG);
         if (codec) {
             int width  = -1;
             int height = -1;
             int ret = 0;

             AVCodecContext* ctx = NULL;
             ctx = avcodec_alloc_context3(codec);
             AVFrame* frame = av_frame_alloc();
             AVPacket* pkt  = av_packet_alloc();

             FILE* file = fopen(outfile, "wb");

             ARRAYELEMENT* e;
             int count = 0;
             forall (e, *arr) {
                 BITMAP bitmap (e->value, false);
                 if (width < 0) {
                     width  = bitmap.Width();
                     height = bitmap.Height();

                     ctx->width = width;
                     ctx->height = height;
                     ctx->time_base = (AVRational){1, 5};
                     ctx->framerate = (AVRational){5, 1};
                     ctx->pix_fmt = AV_PIX_FMT_RGB24;
                     ret = avcodec_open2(ctx, codec, NULL);

                     frame->width  = width;
                     frame->height = height;
                     frame->format = ctx->pix_fmt;
                     av_opt_set(ctx->priv_data, "preset", "slow", 1);

                 }
                 ret  = av_frame_get_buffer(frame, 1);
                 frame->linesize[0] = width*3;

                 bitmap.Convert32();
                 byte* pixels = bitmap.PixelsRGB();

//The two methodes above convert the Pixmap into the RGB structure we need
//They are not needed to get an output file but are needed to get one that makes sense

                     fflush(stdout);
                     int writeable = av_frame_make_writable(frame);
                     if (writeable>=0) {
                         for(int i=0; i<(height*width*3); i++){
                             frame->data[0][i] = pixels[i];
                         }
                     }
                     ret = avcodec_send_frame(ctx, frame);
                     for(int i=0; i<secs; i++){
                         fflush(stdout);
                         avcodec_send_frame(ctx, frame);
                     }
                     while (ret >= 0) {
                       ret = avcodec_receive_packet(ctx, pkt);
                     }
                     count++;
                 avcodec_receive_packet(ctx, pkt);
                 fwrite(pkt->data, 1, pkt->size, file);
                 fflush(stdout);
                 av_packet_unref(pkt);
             }
             fclose(file);
             avcodec_free_context(&ctx);
             av_frame_free(&frame);
             av_packet_free(&pkt);

         }
     }
}

</code>```

答:
png codec because it was the only one i tried that is playable with Windows Media Player.

try to install k-lite codec pack for media player, it can help to display other format
https://codecguide.com/download_k-lite_codec_pack_basic.htm

I tried my script with 10 pictures and a delay of 1/5 of a second but the output file was not even half a second long (but displayed every picture).

ctx->time_base = (AVRational) {1, 5};

```<code>/* frames per second */
c->time_base = (AVRational){1, 25};
c->framerate = (AVRational){25, 1};
</code>```

please take a look at below reference may help you
https://libav.org/documentation/doxygen/master/encode_video_8c-example.html#a25

Body:
I try to encode single pictures to a .avi video. The goal is to have every picture displayed for a set amount of seconds to create a slide show. I tried my script with 10 pictures and a delay of 1/5 of a second but the output file was not even half a second long (but displayed every picture). For setting the framerate I use the time_base option of the AVCodeContext:

ctx->time_base = (AVRational) {1, 5};

When I use the command ffmpeg -framerate 1/3 -i img%03d.png -codec png output.avi everything works fine and I get the file I want. I use the png codec because it was the only one i tried that is playable with Windows Media Player.

Am I missing anything here? Is there another option that has impact on the framerate?

This is my code so far:

Note: I use a couple of self made data structures and methodes from other classes. They are the ones written in Caps Lock. They basicly do what the name suggests but are necessary for my project. The Input Array contains the pictures that i want to encode.

include <libavutil/opt.h>
include <libavutil/imgutils.h>
include <libavutil/error.h>

void PixmapsToAVI (ARRAY* arr, String outfile, double secs)
{
     if (arr!=nil && outfile!="" && secs!=0) {
         AVCodec* codec = avcodec_find_encoder(AV_CODEC_ID_PNG);
         if (codec) {
             int width  = -1;
             int height = -1;
             int ret = 0;

             AVCodecContext* ctx = NULL;
             ctx = avcodec_alloc_context3(codec);
             AVFrame* frame = av_frame_alloc();
             AVPacket* pkt  = av_packet_alloc();

             FILE* file = fopen(outfile, "wb");

             ARRAYELEMENT* e;
             int count = 0;
             forall (e, *arr) {
                 BITMAP bitmap (e->value, false);
                 if (width < 0) {
                     width  = bitmap.Width();
                     height = bitmap.Height();

                     ctx->width = width;
                     ctx->height = height;
                     ctx->time_base = (AVRational){1, 5};
                     ctx->framerate = (AVRational){5, 1};
                     ctx->pix_fmt = AV_PIX_FMT_RGB24;
                     ret = avcodec_open2(ctx, codec, NULL);

                     frame->width  = width;
                     frame->height = height;
                     frame->format = ctx->pix_fmt;
                     av_opt_set(ctx->priv_data, "preset", "slow", 1);

                 }
                 ret  = av_frame_get_buffer(frame, 1);
                 frame->linesize[0] = width*3;

                 bitmap.Convert32();
                 byte* pixels = bitmap.PixelsRGB();

//The two methodes above convert the Pixmap into the RGB structure we need
//They are not needed to get an output file but are needed to get one that makes sense

                     fflush(stdout);
                     int writeable = av_frame_make_writable(frame);
                     if (writeable>=0) {
                         for(int i=0; i<(height*width*3); i++){
                             frame->data[0][i] = pixels[i];
                         }
                     }
                     ret = avcodec_send_frame(ctx, frame);
                     for(int i=0; i<secs; i++){
                         fflush(stdout);
                         avcodec_send_frame(ctx, frame);
                     }
                     while (ret >= 0) {
                       ret = avcodec_receive_packet(ctx, pkt);
                     }
                     count++;
                 avcodec_receive_packet(ctx, pkt);
                 fwrite(pkt->data, 1, pkt->size, file);
                 fflush(stdout);
                 av_packet_unref(pkt);
             }
             fclose(file);
             avcodec_free_context(&ctx);
             av_frame_free(&frame);
             av_packet_free(&pkt);

         }
     }
}

Body:
png codec because it was the only one i tried that is playable with Windows Media Player.

try to install k-lite codec pack for media player, it can help to display other format
https://codecguide.com/download_k-lite_codec_pack_basic.htm

I tried my script with 10 pictures and a delay of 1/5 of a second but the output file was not even half a second long (but displayed every picture).

ctx->time_base = (AVRational) {1, 5};

/* frames per second */
c->time_base = (AVRational){1, 25};
c->framerate = (AVRational){25, 1};

please take a look at below reference may help you
https://libav.org/documentation/doxygen/master/encode_video_8c-example.html#a25


问:
How can i get make a table model work efficiently?
So,i am making an app for making timetables. and i have  run into a problem.
I have two models . Timetable and Content.

```<code>class Timetable(models.Model):

title=models.CharField(max_length=50)
start_time=models.TimeField(default="8:0")
end_time=models.TimeField(default="4:0")
entries=models.IntegerField(default=3)
theme=models.ForeignKey(Theme,on_delete=models.CASCADE,null=True)
def __str__(self):
    return self.title

def get_absoulte_url(self):
    return reverse('timetable-detail',args=[str(self.id)])

class CellEntry(models.Model):

parent_table=models.ForeignKey(Timetable,on_delete=models.CASCADE)
content=models.CharField(max_length=30)

def __str__(self):
    return self.content
</code>```

How can i make a form such that i can get the two models to behave like a table in excel? How can i set the value of multiple cellentry's parent_table attribute to be the same value in a view?

答: So, what you want here is the form with cellEntry to be the parent with multiple child timetable.</p>

Body:
So,i am making an app for making timetables. and i have  run into a problem.
I have two models . Timetable and Content.

class Timetable(models.Model):

title=models.CharField(max_length=50)
start_time=models.TimeField(default="8:0")
end_time=models.TimeField(default="4:0")
entries=models.IntegerField(default=3)
theme=models.ForeignKey(Theme,on_delete=models.CASCADE,null=True)
def __str__(self):
    return self.title

def get_absoulte_url(self):
    return reverse('timetable-detail',args=[str(self.id)])

class CellEntry(models.Model):

parent_table=models.ForeignKey(Timetable,on_delete=models.CASCADE)
content=models.CharField(max_length=30)

def __str__(self):
    return self.content

How can i make a form such that i can get the two models to behave like a table in excel? How can i set the value of multiple cellentry's parent_table attribute to be the same value in a view?


问:
Trusted SSL certificate showing as self signed
I have a trusted TLS certificate deliverd by DigiCert that I'm trying to use in a java/spring application exposing rest apis.

I created a .p12 file with openssl doing the following :
openssl pkcs12 -export -in mycertificate.cer -certfile mycertificate_INTERMEDIATE.cer -inkey myprivate_key.key -out myCert.p12

I am able to use this file in my application to access the app through https with the following configuration (application.properties) :

```<code>server.port:8443
server.ssl.key-store-type=PKCS12
server.ssl.key-store=classpath:myCert.p12
server.ssl.key-store-password=mypass
</code>```

However when accessing my app (through postman for example on https://localhost:8443/api/auth) I have an error indicating that I am using a self signed certificate.

My understanding is that since I am using a trusted certificate I shouldn't have this error message.

Am I missing something when creating the .p12 file that I am using in my app or am I wrong in my assumption ?

答:
You should not access URL using localhost (definitely you have not provided CN as localhost).

Please access using the same hostname what you have provided as CN parameter when you were generating the certificate.

Body:
I have a trusted TLS certificate deliverd by DigiCert that I'm trying to use in a java/spring application exposing rest apis.

I created a .p12 file with openssl doing the following :
openssl pkcs12 -export -in mycertificate.cer -certfile mycertificate_INTERMEDIATE.cer -inkey myprivate_key.key -out myCert.p12

I am able to use this file in my application to access the app through https with the following configuration (application.properties) :

server.port:8443
server.ssl.key-store-type=PKCS12
server.ssl.key-store=classpath:myCert.p12
server.ssl.key-store-password=mypass

However when accessing my app (through postman for example on https://localhost:8443/api/auth) I have an error indicating that I am using a self signed certificate.

My understanding is that since I am using a trusted certificate I shouldn't have this error message.

Am I missing something when creating the .p12 file that I am using in my app or am I wrong in my assumption ?


问:
Sharepoint. Use CAML query to search items
I need to search items inside one list. Can i use CAML query? Case need to be ignored and it should find word inside text... Or CAML not for that purposes? </p>

答:
You can use this CAML query:

```<code><Where>
  <Contains>
    <FieldRef Name='FilterField' />
    <Value Type='Text'>FilterValue</Value>
  </Contains>
<Where>
</code>```

The contains operator matches items with "FilterValue" in the given field.

Body:
You can use this CAML query:

<Where>
  <Contains>
    <FieldRef Name='FilterField' />
    <Value Type='Text'>FilterValue</Value>
  </Contains>
<Where>

The contains operator matches items with "FilterValue" in the given field.


问:
special character "Â" is not work in Linux, converted into "?"
I consuming an api which is returning String with special characters, so I replace them with blank or some other user readable char.

My code:

```<code>String text = response;
        if (text != null) {
            text = text.replace("Â", "");
            //same for other special char
        }
</code>```

The above code works fine for windows machine but in Linux "Â" converted into "?", even other all special char converted into "?".
I am using Java, UTF-8 in my HTML.
Please let me know any platform independent solution. Thanks

答:
I am consuming the REST api, so while getting the output I have to maintain UTF-8 encoding.

```<code>BufferedReader br = new BufferedReader(new InputStreamReader((inputStream), standardCharsets.UTF_8));
</code>```

I have added standardCharsets.UTF_8

Body:
I consuming an api which is returning String with special characters, so I replace them with blank or some other user readable char.

My code:

String text = response;
        if (text != null) {
            text = text.replace("Â", "");
            //same for other special char
        }

The above code works fine for windows machine but in Linux "Â" converted into "?", even other all special char converted into "?".
I am using Java, UTF-8 in my HTML.
Please let me know any platform independent solution. Thanks

Body:
I am consuming the REST api, so while getting the output I have to maintain UTF-8 encoding.

BufferedReader br = new BufferedReader(new InputStreamReader((inputStream), standardCharsets.UTF_8));

I have added standardCharsets.UTF_8


问:
TypeScript + React <- passing props
I am trying to pass value to component props.

This is what I do:

I create interface:

```<code>interface CheckoutItem {
    id: string,
    name: string,
    img: string,
    unitPrice: number,
    amount: number,
}
</code>```

I create display component:

```<code>const CheckoutDisplay = (items: CheckoutItem[] ) => {
    return (
        <div>
            {items.map(item => (
                <p>
                    {item.name}
                </p>
            ))}
        </div>
    )
}
</code>```

I create container component:

```<code>const Checkout = (items: CheckoutItem[], setAmount: any) => {
  return <CheckoutDisplay items={items} setAmount={setAmount} />;
  // error here:
  // Type '{ items: CheckoutItem[]; setAmount: any; }' is not assignable to type
  // 'IntrinsicAttributes & CheckoutItem[]'.
  //  Property 'items' does not exist on type 'IntrinsicAttributes & CheckoutItem[]'.
};

const mapStateToProps = (state: any) => {
  return {
    items: state.items,
  };
};

const mapDispatchToProps = (dispatch: AppDispatch) => {
    return {
        setAmount: (id: number, amount: number) => dispatch(setItemAmount(id, amount)),
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Checkout);
</code>```

What is wrong with my code?

Thank you!

答:
Props are passed as an object to CheckoutDisplay, so you need to destructure them.

```<code>interface CheckoutDisplayProps {
  items: CheckoutItem[],
  setItemAmount: any,
}

const CheckoutDisplay: React.FunctionComponent<CheckoutDisplayProps> = ({ items, setItemAmount }) => {
    return (
        <div>
            {items.map(item => (
                <p>
                    {item.name}
                </p>
            ))}
        </div>
    )
}
</code>```

Title: TypeScript + React <- passing props

Body:
I am trying to pass value to component props.

This is what I do:

I create interface:

interface CheckoutItem {
    id: string,
    name: string,
    img: string,
    unitPrice: number,
    amount: number,
}

I create display component:

const CheckoutDisplay = (items: CheckoutItem[] ) => {
    return (

            {items.map(item => (

                    {item.name}

            ))}

    )
}

I create container component:

const Checkout = (items: CheckoutItem[], setAmount: any) => {
  return <CheckoutDisplay items={items} setAmount={setAmount} />;
  // error here:
  // Type '{ items: CheckoutItem[]; setAmount: any; }' is not assignable to type
  // 'IntrinsicAttributes & CheckoutItem[]'.
  //  Property 'items' does not exist on type 'IntrinsicAttributes & CheckoutItem[]'.
};

const mapStateToProps = (state: any) => {
  return {
    items: state.items,
  };
};

const mapDispatchToProps = (dispatch: AppDispatch) => {
    return {
        setAmount: (id: number, amount: number) => dispatch(setItemAmount(id, amount)),
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Checkout);

What is wrong with my code?

Thank you!

Body:
Props are passed as an object to CheckoutDisplay, so you need to destructure them.

interface CheckoutDisplayProps {
  items: CheckoutItem[],
  setItemAmount: any,
}

const CheckoutDisplay: React.FunctionComponent<CheckoutDisplayProps> = ({ items, setItemAmount }) => {
    return (
        <div>
            {items.map(item => (
                <p>
                    {item.name}
                </p>
            ))}
        </div>
    )
}


问:
Is there something wrong with this SQL query
I am new to SQL queries and trying to understand it a little better.
Is this SQL query valid regarding the picture below
The question I was given was:

"For each book authored (or co-authored) by "Stephen King", retrieve the title and the number of copies owned by the librarybranch whose name is "Central"

```<code>SELECT Title
FROM BOOK
WHERE BookID =
(
 SELECT BookID
 FROM BOOK_AUTHORS
 WHERE AuthorName = 'Stephen King'
)
AND
BookID =
(
 SELECT BookID, No_Of_Copies
 FROM BOOK_COPIES
 WHERE BranchID =
 (
  SELECT BranchID
  FROM LIBRARY_BRANCH
  WHERE BranchName = 'Central'
 )
)
</code>```

答:
For this requirement you can use joins to get the results:</p>

```<code>SELECT b.Title, bc.No_Of_Copies
FROM BOOK b
INNER JOIN BOOK_AUTHORS ba ON ba.BookId = b.BookId
INNER JOIN BOOK_COPIES bc ON bc.BookId = b.BookId
INNER JOIN LIBRARY_BRANCH lb ON lb.BranchId = bc.BranchId
WHERE ba.AuthorName = 'Stephen King' AND lb.BranchName = 'Central'
</code>```

Body:
I am new to SQL queries and trying to understand it a little better.
Is this SQL query valid regarding the picture below
The question I was given was:

"For each book authored (or co-authored) by "Stephen King", retrieve the title and the number of copies owned by the librarybranch whose name is "Central"

SELECT Title
FROM BOOK
WHERE BookID =
(
 SELECT BookID
 FROM BOOK_AUTHORS
 WHERE AuthorName = 'Stephen King'
)
AND
BookID =
(
 SELECT BookID, No_Of_Copies
 FROM BOOK_COPIES
 WHERE BranchID =
 (
  SELECT BranchID
  FROM LIBRARY_BRANCH
  WHERE BranchName = 'Central'
 )
)

Body:
For this requirement you can use joins to get the results:

SELECT b.Title, bc.No_Of_Copies
FROM BOOK b
INNER JOIN BOOK_AUTHORS ba ON ba.BookId = b.BookId
INNER JOIN BOOK_COPIES bc ON bc.BookId = b.BookId
INNER JOIN LIBRARY_BRANCH lb ON lb.BranchId = bc.BranchId
WHERE ba.AuthorName = 'Stephen King' AND lb.BranchName = 'Central'


问:
Bluez connection on STM32MP1
I have a VisionSOM-STM32MP1 with installed OpenSTLinux and bluez version 5.50.

I am able to find nearby devices. Using bluetoothctl I can pair with the android device.
Unfortunately when I am try to establish connection from android device it fails.

```<code>[CHG] Device 00:00:00:00:00:00 Connected: yes
[CHG] Device 00:00:00:00:00:00 Connected: no
</code>```

Then I try to establish connection to android device, I get:

```<code>[bluetooth]# connect 00:00:00:00:00:00
Attempting to connect to 00:00:00:00:00:00
[CHG] Device 00:00:00:00:00:00 Connected: yes
Failed to connect: org.bluez.Error.Failed
[CHG] Device 00:00:00:00:00:00 Connected: no
</code>```

I also tried to do this in c program, like it is here and as a result I get errno 93(Protocol not supported) after creating socket.

```<code>s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
if(s == -1) {
   printf("errno %d\n", errno);
   return -1;
}
</code>```

Thank you for any advice.

答:
There are several things you can try to get more information about your issue.

I suggest that you enable debug logging in the Bluetooth daemon. I think that you need to run the Bluez daemon with "-d" for this to work. Debug logs will be in syslog.

Then you could record a HCI log using hcidump. This will tell you what HCI commands were sent to the Controller by Bluez.

Title: Bluez connection on STM32MP1

Body:
I have a VisionSOM-STM32MP1 with installed OpenSTLinux and bluez version 5.50.

I am able to find nearby devices. Using bluetoothctl I can pair with the android device.
Unfortunately when I am try to establish connection from android device it fails.

[CHG] Device 00:00:00:00:00:00 Connected: yes
[CHG] Device 00:00:00:00:00:00 Connected: no

Then I try to establish connection to android device, I get:

[bluetooth]# connect 00:00:00:00:00:00
Attempting to connect to 00:00:00:00:00:00
[CHG] Device 00:00:00:00:00:00 Connected: yes
Failed to connect: org.bluez.Error.Failed
[CHG] Device 00:00:00:00:00:00 Connected: no

I also tried to do this in c program, like it is here and as a result I get errno 93(Protocol not supported) after creating socket.

s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
if(s == -1) {
   printf("errno %d\n", errno);
   return -1;
}

Thank you for any advice.


问:
perl module installation shared host
My shared hosting is missing two Perl modules required by Amazon SES Scripts. They are:

Digest::SHA and XML::LibXML

I downloaded Digest::SHA from here and XML::LibXML from here

Extracted, and uploaded LibXML.pm and SHA.pm to my custome directory (my_perl_lib).

I have added:

```<code>use lib "/var/chroot/home/content/09/6758009/html/my_perl_lib";
</code>```

to the second line to the perl script.

I get this:

```<code>Can't locate XML/LibXML.pm in @INC (@INC contains: /var/chroot/home/content/09/6758009
/html/my_perl_lib /usr/lib/perl5/site_perl/5.8.8/i386-linux-thread-multi /usr/lib/perl5
/site_perl/5.8.8 /usr/lib/perl5/site_perl /usr/lib/perl5/vendor_perl/5.8.8/i386-linux-
 thread-multi /usr/lib/perl5/vendor_perl/5.8.8 /usr/lib/perl5/vendor_perl /usr/lib/perl5/5.8.8
/i386-linux-thread-multi /usr/lib/perl5/5.8.8 .) at ./ses-get-stats.pl line 24.
BEGIN failed--compilation aborted at ./ses-get-stats.pl line 24.
</code>```

Please advise.

Updated:

thanks, i created the directory, the error gone, but i faced another one:

```<code>Can't locate loadable object for module XML::LibXML in @INC (@INC contains: /var/chroot
/home/content/09/6758009/html/my_perl_lib .......) at /var/chroot/home/content/09/6758009
/html/my_perl_lib/XML/LibXML.pm line 153 BEGIN failed--compilation aborted at /var/chroot
/home/content/09/6758009/html/my_perl_lib/XML/LibXML.pm line 153. Compilation failed in require
 at ./ses-get-stats.pl line 24. BEGIN failed--compilation aborted at ./ses-get-stats.pl line 24.
</code>```

Updated:

thanks again for your reply.

here are the results:

```<code>-bash-3.2$ perl Makefile.PL INSTALL_BASE=/var/chroot/home/content/09/6758009/html/my_perl_lib
enable native perl UTF8
running xml2-config...ok (2.6.26)
looking for -lxml2... no
looking for -llibxml2... no
libxml2 not found
Try setting LIBS and INC values on the command line
Or get libxml2 from
http://xmlsoft.org/
If you install via RPMs, make sure you also install the -devel
RPMs, as this is where the headers (.h files) are.

Also, you may try to run perl Makefile.PL with the DEBUG=1 parameter
to see the exact reason why the detection of libxml2 installation
failed or why Makefile.PL was not able to compile a test program.
-bash-3.2$
</code>```

答:
It needs to be inside an "XML" directory...  IE, make sure that LibXML.pm is actually in /var/chroot/home/content/09/6758009/html/my_perl_lib/XML/LibXML.pm.

Updated:

You probably need to do a full local install of the perl module, and the shared object that accompanies it.  You can do this by using:

```<code># extract sources
# cd source-directory
# perl Makefile.PL INSTALL_BASE=/var/chroot/home/content/09/6758009/html/my_perl_lib
# make
# make install
</code>```

This will install everything needed into that directory.  Then in the script, reference both of these paths:

```<code>use lib '/var/chroot/home/content/09/6758009/html/my_perl_lib/lib/perl5';
use lib '/var/chroot/home/content/09/6758009/html/my_perl_lib/lib/perl5/i386-linux-thread-multi/auto';
</code>```

Note that you'll likely need to change the architecture of the i386-linux-thread-multi part of that line.  That's where the .so file is installed.

Title: perl module installation shared host

Body:
My shared hosting is missing two Perl modules required by Amazon SES Scripts. They are:

Digest::SHA and XML::LibXML

I downloaded Digest::SHA from here and XML::LibXML from here

Extracted, and uploaded LibXML.pm and SHA.pm to my custome directory (my_perl_lib).

I have added:

use lib "/var/chroot/home/content/09/6758009/html/my_perl_lib";

to the second line to the perl script.

I get this:

Can't locate XML/LibXML.pm in @INC (@INC contains: /var/chroot/home/content/09/6758009
/html/my_perl_lib /usr/lib/perl5/site_perl/5.8.8/i386-linux-thread-multi /usr/lib/perl5
/site_perl/5.8.8 /usr/lib/perl5/site_perl /usr/lib/perl5/vendor_perl/5.8.8/i386-linux-
 thread-multi /usr/lib/perl5/vendor_perl/5.8.8 /usr/lib/perl5/vendor_perl /usr/lib/perl5/5.8.8
/i386-linux-thread-multi /usr/lib/perl5/5.8.8 .) at ./ses-get-stats.pl line 24.
BEGIN failed--compilation aborted at ./ses-get-stats.pl line 24.

Please advise.

Updated:

thanks, i created the directory, the error gone, but i faced another one:

Can't locate loadable object for module XML::LibXML in @INC (@INC contains: /var/chroot
/home/content/09/6758009/html/my_perl_lib .......) at /var/chroot/home/content/09/6758009
/html/my_perl_lib/XML/LibXML.pm line 153 BEGIN failed--compilation aborted at /var/chroot
/home/content/09/6758009/html/my_perl_lib/XML/LibXML.pm line 153. Compilation failed in require
 at ./ses-get-stats.pl line 24. BEGIN failed--compilation aborted at ./ses-get-stats.pl line 24.

Updated:

thanks again for your reply.

here are the results:

-bash-3.2$ perl Makefile.PL INSTALL_BASE=/var/chroot/home/content/09/6758009/html/my_perl_lib
enable native perl UTF8
running xml2-config...ok (2.6.26)
looking for -lxml2... no
looking for -llibxml2... no
libxml2 not found
Try setting LIBS and INC values on the command line
Or get libxml2 from
http://xmlsoft.org/
If you install via RPMs, make sure you also install the -devel
RPMs, as this is where the headers (.h files) are.

Also, you may try to run perl Makefile.PL with the DEBUG=1 parameter
to see the exact reason why the detection of libxml2 installation
failed or why Makefile.PL was not able to compile a test program.
-bash-3.2$

Body:
It needs to be inside an "XML" directory...  IE, make sure that LibXML.pm is actually in /var/chroot/home/content/09/6758009/html/my_perl_lib/XML/LibXML.pm.

Updated:

You probably need to do a full local install of the perl module, and the shared object that accompanies it.  You can do this by using:

# extract sources
# cd source-directory
# perl Makefile.PL INSTALL_BASE=/var/chroot/home/content/09/6758009/html/my_perl_lib
# make
# make install

This will install everything needed into that directory.  Then in the script, reference both of these paths:

use lib '/var/chroot/home/content/09/6758009/html/my_perl_lib/lib/perl5';
use lib '/var/chroot/home/content/09/6758009/html/my_perl_lib/lib/perl5/i386-linux-thread-multi/auto';

Note that you'll likely need to change the architecture of the i386-linux-thread-multi part of that line.  That's where the .so file is installed.


问:
How to get percentage of categorical variables and overall percent of a single choice
Basically I have a new data as below and I want the percentage of yes in each province likewise percentage of no each province and I want overall percentage of Yes and No.

```<code>new_data <-data.frame(province=c("a","b"),food=c("yes","no","no","yes","yes","no"),shelter_type=c("unfinished","permanent","transitional"))
</code>```

and I want output as below

```<code>out_put <- data.frame (province=c("a","b","overall_perc"),food_yes_per=c(66.6,36.4,50),food_No_per=c(36.4,66.6,50),shelter_type_unfinished=c(50,50,33.3),shelter_type_permanent=c(50,50,33.3),shelter_type_transitional=c(50,50,33.3))
</code>```

can anyone help please

答:
Updated answer

The tricky part of this problem is the difference between row percentages and column percentages that are represented in the data. Since all rows but the total row are column percentages, we will need to process the data twice, first for the the province * variable level of aggregation, and then variable aggregated over province.

```<code>new_data <-data.frame(province=c("a","b"),
                      food=c("yes","no","no","yes","yes","no"),
                      shelter_type=c("unfinished","permanent","transitional"))
library(dplyr)
library(tidyr)
</code>```

First we'll generate what ultimately becomes column percentages within a wide format data frame. We use pivot_longer() to create a narrow format tidy data set, create counts, summarise() the counts, and then group_by() variable & value to generate column percentages.

```<code>new_data  %>% group_by(province) %>%
     pivot_longer(.,c(food,shelter_type),names_to = "variable",
                  values_to = "value") %>% ungroup() %>%
     group_by(province,variable,value) %>%
     mutate(count = 1) %>% summarise(.,count = sum(count)) %>% ungroup() %>%
     group_by(variable,value) %>%
     mutate(pct = count / sum(count)) -> prov_var
</code>```

Next, we reaggregate the data to create what will become the Total province. We take the original data, convert to narrow format tidy data, and this time group_by() variable & value to calculate the percentages across province.

```<code>new_data  %>% group_by(province) %>%
     pivot_longer(.,c(food,shelter_type),names_to = "variable",
                  values_to = "value") %>% ungroup() %>%
     group_by(variable,value) %>%
     mutate(count = 1) %>% summarise(., count = sum(count)) %>%
     mutate(province = "Total",
            pct = count / sum(count)) -> tot_var
</code>```

Finally, we rbind() the data and use tidyr::pivot_wider() to create the wide format data frame as illustrated in the original question.

```<code># now add rows & pivot_wider()
rbind(prov_var,tot_var) %>%
     mutate(concat_var = paste(variable,value,sep="_")) %>%
     select(-variable,-value,-count) %>%
     pivot_wider(id_cols = province,names_from=concat_var,
                 values_from = pct)
</code>```

...and the output:

```<code># A tibble: 3 x 6
  province food_no food_yes shelter_type_perm… shelter_type_tra… shelter_type_unf…
  <chr>      <dbl>    <dbl>              <dbl>             <dbl>             <dbl>
1 a          0.333    0.667              0.5               0.5               0.5
2 b          0.667    0.333              0.5               0.5               0.5
3 Total      0.5      0.5                0.333             0.333             0.333
</code>```

Partial solutions with tables::tabular()

Another way to attempt to answer the question is with the tables package. We can generate the column percentages by province as follows.

```<code>library(tables)

# replicate column percentages, where "All" is 100

tabular((Factor(province,"Province") + 1) ~
                (Factor(food) + Factor(shelter_type)) *
                (Percent("col")),data = new_data )
</code>```

Unfortunately, the row for totals isn't what was requested.

```<code>          food            shelter_type
          no      yes     permanent    transitional unfinished
 Province Percent Percent Percent      Percent      Percent
 a         33.33   66.67   50           50           50
 b         66.67   33.33   50           50           50
 All      100.00  100.00  100          100          100
</code>```

We can fix the All row by configuring the table with row percentages, but then the data by province doesn't match what was requested.

```<code># replicate row percentages in All row
tabular((Factor(province,"Province") + 1) ~
                (Factor(food) + Factor(shelter_type)) *
                (Percent("row")),data = new_data )

          food            shelter_type
          no      yes     permanent    transitional unfinished
 Province Percent Percent Percent      Percent      Percent
 a        33.33   66.67   33.33        33.33        33.33
 b        66.67   33.33   33.33        33.33        33.33
 All      50.00   50.00   33.33        33.33        33.33
</code>```

Correct solution with tabular()

However, if we control the percentages by specifying them on the row dimension of the table instead of the column dimension, we can achieve the desired output.

```<code>tabular((Factor(province,"Province")*( colPct = Percent("col")) + 1*(rowPct = Percent("row")))  ~
                (Factor(food) + Factor(shelter_type)),data = new_data )
</code>```

...and the output:

```<code>                 food        shelter_type
 Province        no    yes   permanent    transitional unfinished
 a        colPct 33.33 66.67 50.00        50.00        50.00
 b        colPct 66.67 33.33 50.00        50.00        50.00
 All      rowPct 50.00 50.00 33.33        33.33        33.33
</code>```

Original answer

We'll use the dplyr package to summarise the data by province & food, calculate percentages, and then ungroup() to calculate percentage of total responses.

```<code>new_data <-data.frame(province=c("a","b"),
                      food=c("yes","no","no","yes","yes","no"),
                      shelter_type=c("unfinished","permanent","transitional"))

library(dplyr)

new_data %>% group_by(province,food) %>%
     summarise(count_food = n()) %>% group_by(province) %>%
     mutate(pct_food = count_food / sum(count_food)) %>%
     ungroup(.) %>%
     mutate(pct_total = count_food / sum(count_food))
</code>```

...and the output:

```<code># A tibble: 4 x 5
  province food  count_food pct_food pct_total
  <chr>    <chr>      <int>    <dbl>     <dbl>
1 a        no             1    0.333     0.167
2 a        yes            2    0.667     0.333
3 b        no             2    0.667     0.333
4 b        yes            1    0.333     0.167
>
</code>```

Body:
Basically I have a new data as below and I want the percentage of yes in each province likewise percentage of no each province and I want overall percentage of Yes and No.

new_data <-data.frame(province=c("a","b"),food=c("yes","no","no","yes","yes","no"),shelter_type=c("unfinished","permanent","transitional"))

and I want output as below

out_put <- data.frame (province=c("a","b","overall_perc"),food_yes_per=c(66.6,36.4,50),food_No_per=c(36.4,66.6,50),shelter_type_unfinished=c(50,50,33.3),shelter_type_permanent=c(50,50,33.3),shelter_type_transitional=c(50,50,33.3))

can anyone help please

Body:
Updated answer

The tricky part of this problem is the difference between row percentages and column percentages that are represented in the data. Since all rows but the total row are column percentages, we will need to process the data twice, first for the the province * variable level of aggregation, and then variable aggregated over province.

new_data <-data.frame(province=c("a","b"),
                      food=c("yes","no","no","yes","yes","no"),
                      shelter_type=c("unfinished","permanent","transitional"))
library(dplyr)
library(tidyr)

First we'll generate what ultimately becomes column percentages within a wide format data frame. We use pivot_longer() to create a narrow format tidy data set, create counts, summarise() the counts, and then group_by() variable & value to generate column percentages.

new_data  %>% group_by(province) %>%
     pivot_longer(.,c(food,shelter_type),names_to = "variable",
                  values_to = "value") %>% ungroup() %>%
     group_by(province,variable,value) %>%
     mutate(count = 1) %>% summarise(.,count = sum(count)) %>% ungroup() %>%
     group_by(variable,value) %>%
     mutate(pct = count / sum(count)) -> prov_var

Next, we reaggregate the data to create what will become the Total province. We take the original data, convert to narrow format tidy data, and this time group_by() variable & value to calculate the percentages across province.

new_data  %>% group_by(province) %>%
     pivot_longer(.,c(food,shelter_type),names_to = "variable",
                  values_to = "value") %>% ungroup() %>%
     group_by(variable,value) %>%
     mutate(count = 1) %>% summarise(., count = sum(count)) %>%
     mutate(province = "Total",
            pct = count / sum(count)) -> tot_var

Finally, we rbind() the data and use tidyr::pivot_wider() to create the wide format data frame as illustrated in the original question.

# now add rows & pivot_wider()
rbind(prov_var,tot_var) %>%
     mutate(concat_var = paste(variable,value,sep="_")) %>%
     select(-variable,-value,-count) %>%
     pivot_wider(id_cols = province,names_from=concat_var,
                 values_from = pct)

...and the output:

# A tibble: 3 x 6
  province food_no food_yes shelter_type_perm… shelter_type_tra… shelter_type_unf…
  <chr>      <dbl>    <dbl>              <dbl>             <dbl>             <dbl>
1 a          0.333    0.667              0.5               0.5               0.5
2 b          0.667    0.333              0.5               0.5               0.5
3 Total      0.5      0.5                0.333             0.333             0.333

Partial solutions with tables::tabular()

Another way to attempt to answer the question is with the tables package. We can generate the column percentages by province as follows.

library(tables)

# replicate column percentages, where "All" is 100

tabular((Factor(province,"Province") + 1) ~
                (Factor(food) + Factor(shelter_type)) *
                (Percent("col")),data = new_data )

Unfortunately, the row for totals isn't what was requested.

          food            shelter_type
          no      yes     permanent    transitional unfinished
 Province Percent Percent Percent      Percent      Percent
 a         33.33   66.67   50           50           50
 b         66.67   33.33   50           50           50
 All      100.00  100.00  100          100          100

We can fix the All row by configuring the table with row percentages, but then the data by province doesn't match what was requested.

# replicate row percentages in All row
tabular((Factor(province,"Province") + 1) ~
                (Factor(food) + Factor(shelter_type)) *
                (Percent("row")),data = new_data )

          food            shelter_type
          no      yes     permanent    transitional unfinished
 Province Percent Percent Percent      Percent      Percent
 a        33.33   66.67   33.33        33.33        33.33
 b        66.67   33.33   33.33        33.33        33.33
 All      50.00   50.00   33.33        33.33        33.33

Correct solution with tabular()

However, if we control the percentages by specifying them on the row dimension of the table instead of the column dimension, we can achieve the desired output.

tabular((Factor(province,"Province")*( colPct = Percent("col")) + 1*(rowPct = Percent("row")))  ~
                (Factor(food) + Factor(shelter_type)),data = new_data )

...and the output:

                 food        shelter_type
 Province        no    yes   permanent    transitional unfinished
 a        colPct 33.33 66.67 50.00        50.00        50.00
 b        colPct 66.67 33.33 50.00        50.00        50.00
 All      rowPct 50.00 50.00 33.33        33.33        33.33

Original answer

We'll use the dplyr package to summarise the data by province & food, calculate percentages, and then ungroup() to calculate percentage of total responses.

new_data <-data.frame(province=c("a","b"),
                      food=c("yes","no","no","yes","yes","no"),
                      shelter_type=c("unfinished","permanent","transitional"))

library(dplyr)

new_data %>% group_by(province,food) %>%
     summarise(count_food = n()) %>% group_by(province) %>%
     mutate(pct_food = count_food / sum(count_food)) %>%
     ungroup(.) %>%
     mutate(pct_total = count_food / sum(count_food))

...and the output:

# A tibble: 4 x 5
  province food  count_food pct_food pct_total
  <chr>    <chr>      <int>    <dbl>     <dbl>
1 a        no             1    0.333     0.167
2 a        yes            2    0.667     0.333
3 b        no             2    0.667     0.333
4 b        yes            1    0.333     0.167
>


问:
Error calculating time difference in Python
Quick question. Does someone know why I'am getting an 'Invalid Syntax' error usign this code? Thank you all.</p>

```<code>def get_time_difference(date, time_string):
    time_difference = datetime.now() - datetime.strptime(f"{date} {time_string}", "%d-%m-%Y %H:%M")
    return f"{time_difference.hour}:{time_difference.minute}"

get_time_difference(1-1-2020 1:50)
</code>```

答:
You should call get_time_difference("1-1-2020", "1:50").

However, you will get another error:

```<code>AttributeError: 'datetime.timedelta' object has no attribute 'hour'
</code>```

You can adapt get_time_difference as follows:

def get_time_difference(date, time_string):
    time_difference = datetime.now() - datetime.strptime(
        f"{date} {time_string}", "%d-%m-%Y %H:%M"
    )
    hours = time_difference.seconds // 3600
    minutes = time_difference.seconds // 60 % 60
    return f"{hours}:{minutes}"
```

Body:
Quick question. Does someone know why I'am getting an 'Invalid Syntax' error usign this code? Thank you all.

def get_time_difference(date, time_string):
    time_difference = datetime.now() - datetime.strptime(f"{date} {time_string}", "%d-%m-%Y %H:%M")
    return f"{time_difference.hour}:{time_difference.minute}"

get_time_difference(1-1-2020 1:50)

Body:
You should call get_time_difference("1-1-2020", "1:50").

However, you will get another error:

AttributeError: 'datetime.timedelta' object has no attribute 'hour'

You can adapt get_time_difference as follows:

def get_time_difference(date, time_string):
    time_difference = datetime.now() - datetime.strptime(
        f"{date} {time_string}", "%d-%m-%Y %H:%M"
    )
    hours = time_difference.seconds // 3600
    minutes = time_difference.seconds // 60 % 60
    return f"{hours}:{minutes}"