问:
how to get elements from this JSON in php
How can i get the values of the field password from this json in php

```<code>[
   {
      "rid":"#145:0",
      "version":1,
      "oClass":"Login",
      "oData":{
         "Password":"hacker007",
         "role":null,
         "Name":"Nijeesh Joshy",
         "Email":"nijeesh4all@gmail.com"
      }
   }
]
</code>```

this is my code

```<code>$json = '[
   {
      "rid":"#145:0",
      "version":1,
      "oClass":"Login",
      "oData":{
         "Password":"hacker007",
         "role":null,
         "Name":"Nijeesh Joshy",
         "Email":"nijeesh4all@gmail.com"
      }
   }
]';

$json = json_decode($json,true);

echo $json[0]->oData->Name;
</code>```

I am getting this error

Notice: Trying to get property of non-object

答:
I see that after the json_decode() step, the properties are not protected anymore :

```<code>$json_data = '[
    {
        "rid":"#145:0",
        "version":1,
        "oClass":"Login",
        "oData":{
            "Password":"hacker007",
            "role":null,
            "Name":"Nijeesh Joshy",
            "Email":"nijeesh4all@gmail.com"
        }
    }
]';

$data = json_decode($json_data);
</code>```

So, you could access the data this way :

```<code>$array['name'] = $data[0]->oData->Name;
$array['password'] = $data[0]->oData->Password;

var_dump($array);
</code>```

Output :

```<code>array(2) {
    ["password"]=> string(9) "hacker007"
    ["name"]=> string(13) "Nijeesh Joshy"
}
</code>```

note :

The classes used to build the original data array must give you methods to get the data in a proper way.

Body:
How can i get the values of the field password from this json in php

[
   {
      "rid":"#145:0",
      "version":1,
      "oClass":"Login",
      "oData":{
         "Password":"hacker007",
         "role":null,
         "Name":"Nijeesh Joshy",
         "Email":"nijeesh4all@gmail.com"
      }
   }
]

this is my code

$json = '[
   {
      "rid":"#145:0",
      "version":1,
      "oClass":"Login",
      "oData":{
         "Password":"hacker007",
         "role":null,
         "Name":"Nijeesh Joshy",
         "Email":"nijeesh4all@gmail.com"
      }
   }
]';

$json = json_decode($json,true);

echo $json[0]->oData->Name;

I am getting this error

Notice: Trying to get property of non-object

Body:
I see that after the json_decode() step, the properties are not protected anymore :

$json_data = '[
    {
        "rid":"#145:0",
        "version":1,
        "oClass":"Login",
        "oData":{
            "Password":"hacker007",
            "role":null,
            "Name":"Nijeesh Joshy",
            "Email":"nijeesh4all@gmail.com"
        }
    }
]';

$data = json_decode($json_data);

So, you could access the data this way :

$array['name'] = $data[0]->oData->Name;
$array['password'] = $data[0]->oData->Password;

var_dump($array);

Output :

array(2) {
    ["password"]=> string(9) "hacker007"
    ["name"]=> string(13) "Nijeesh Joshy"
}

note :

The classes used to build the original data array must give you methods to get the data in a proper way.


来源: stackexchange

问:
Accessing Jekyll collection file from subdirectories
I'm still learning Jekyll, but I am trying to port our documentation over so that people can access our docs when we update them in our product. Ideally, I wanted to make this as seamless as possible. Our product docs are already laid out in .md format, and the tree looks like this:

```<code>├── 01_Using_The_Dashboard
│   ├── 01_Dashboard_Overview.md
│   ├── 02_Widgets_Overview.md
│   ├── 03_Pre-built_Widgets.md
│   ├── 04_Creating_your_own_widgets.md
│   ├── 05_Search_Syntax.md
│   ├── 06_Dashboard_Import_Export.md
│   ├── images
│   │   ├── add-widget@2x.png
│   │   ├── controls@2x.png
│   │   ├── creating-search-widget@2x.png
│   │   ├── dashboard-edit@2x.png
│   │   ├── dashboard-selector@2x.png
│   │   ├── edit-widget-field@2x.png
│   │   ├── edit-widget-filter@2x.png
│   │   ├── edit-widget-modal@2x.png
│   │   ├── edit-widget-other@2x.png
│   │   ├── edit-widget@2x.png
│   │   ├── event-rate-widget@2x.png
│   │   ├── lastn-widget@2x.png
│   │   ├── notifications-widget@2x.png
│   │   ├── resize-widget@2x.png
│   │   ├── save-to-dashboard@2x.png
│   │   ├── search-results-widget@2x.png
│   │   ├── system-widget@2x.png
│   │   ├── tasks-widget@2x.png
│   │   ├── time-range-selector@2x.png
│   │   ├── time-range@2x.png
│   │   └── topn-widget@2x.png
│   └── index.md
├── 02_Creating_Triggers
│   ├── 01_Trigger_Page.md
│   ├── 02_Explanation_of_Actions.md
│   ├── 03_Trigger_Scripts.md
│   ├── images
│   │   ├── add-new-trigger.png
│   │   ├── add-note@2x.png
│   │   ├── execute-script@2x.png
│   │   ├── filters@2x.png
│   │   ├── issue-notification@2x.png
│   │   ├── query-bar@2x.png
│   │   ├── search-results@2x.png
│   │   ├── send-email@2x.png
│   │   └── system-settings@2x.png
│   └── index.md
├── 03_Alerts
│   ├── 01_Alerts_Overview.md
│   ├── 02_Automations.md
│   ├── 03_Trigger_Import_Export.md
│   ├── 04_Outgoing_Webhooks.md
│   ├── images
│   │   ├── add-new-trigger.png
│   │   ├── filters-hosts.png
│   │   ├── filters-severities.png
│   │   ├── outgoing_webhooks.png
│   │   ├── slack_alert.png
│   │   └── triggers.png
│   └── index.md
├── 04_Backend_Administration
│   ├── 01_Receiving_Syslog_Events.md
│   ├── 02_Sending_Email_From_The_Server.md
│   ├── 03_Archive_and_Restore.md
│   ├── 04_Server_Licensing.md
│   ├── 05_Using_TLS_Tunnels.md
│   ├── 06_Using_HTTPS.md
│   ├── 07_Backend_Configuration_Options.md
│   ├── 08_Backend_Search_Settings.md
│   ├── 09_Migrating_LogZilla_To_A_New_Server.md
│   ├── images
│   │   └── smtp.png
│   └── index.md
├── 05_Software_Notes
│   ├── 01_Development_Lifecycle.md
│   ├── 02_Release_Notes.md
│   ├── 03_LogZilla_VMWare_Image.md
│   ├── images
│   │   └── ticketflow.png
│   └── index.md
├── 06_Performance_Tuning
│   ├── 01_UDP_Buffer_Tuning.md
│   ├── 02_CPU_Frequency_Governers.md
│   ├── 03_VMWare_Performance.md
│   ├── 04_Filesystem_Performance.md
│   ├── images
│   │   └── vmware-disk-priority.png
│   └── index.md
├── 07_Receiving_Data
│   ├── 01_Receiving_SNMP_Traps.md
│   ├── 02_Cisco_IOS_Configuration.md
│   ├── 03_Receiving_Rsyslog_Events.md
│   ├── 04_Debugging_Event_Reception.md
│   ├── 05_Incoming_Webhooks.md
│   ├── 06_Receiving_Windows_Events.md
│   ├── images
│   │   ├── snare-001.png
│   │   ├── snare-002.png
│   │   ├── snare-003.png
│   │   └── snare-004.png
│   └── index.md
├── 08_Event_Correlation
│   ├── 01_Intro_to_Event_Correlation.md
│   ├── 02_Event_Correlation_Rule_Types.md
│   ├── 03_Sample_Rules.md
│   ├── 04_Correlating_Windows_Events.md
│   ├── images
│   │   ├── cisco-ec-mne.png
│   │   ├── cisco-ec-save.png
│   │   └── cisco-ec.png
│   └── index.md
├── 09_API
│   ├── 01_Using_The_API.md
│   └── index.md
└── template.html
</code>```

I have a few hurdles:

The structure above of course

Our md files aren't using front matter, rather, we have  at the top of the markdown files. I could just do something like perl -i -pe 's/<\!-- @@@(title:)(.*?)@@@ -->/---\n$1 $2\n---\n/g' *.md but wasn't sure if there is a more elegant solution.

The image links would also have to be converted. In our files, they are done like so:![Controls](@@path/images/controls.png)

Can someone suggest a method I can use to make this an easily-repleatable process so that when we update our docs, they auto-update on the website?

答:
1) the structure above should be no problem. I would not add that to the "_posts" directory but directly to the root folder. It should then generate files like:

```<code>01_Using_The_Dashboard/01_Dashboard_Overview.html
</code>```

If you are not happy with the permalink generated, you can always overwrite this setting in the Frontmatter.

2) I am not aware on any $x2frontmatter tooling. There is something for migrating from wordpress as far as I know. I think your perl solutions is probably the most elegant way to do such a conversion. Please also think about generating addition content, like "layout: page" or similar, otherwise you would have to maintain it afterwards.

3) Instead of @@path you can use the base url. Please see Parkers post. Please also see the variables section which might contain additional nice information for you.

Regarding your fourth question, it seems you would like to know how to autdeploy changes. Just like continous deployment. There are multiple ways to do that.

Here is a blog post I wrote back then to auto deploy using rsync, crontab and shell.

Here is a more detailed blog post on how to deploying to S3 (including assets).

There is even the option to deploy to GitHub. Please see the docs for GitHub Pages.

Personally I use the CloudFront/S3 option.

ContentLicense: CC BY-SA 3.0

Body:
I'm still learning Jekyll, but I am trying to port our documentation over so that people can access our docs when we update them in our product. Ideally, I wanted to make this as seamless as possible. Our product docs are already laid out in .md format, and the tree looks like this:

├── 01_Using_The_Dashboard
│   ├── 01_Dashboard_Overview.md
│   ├── 02_Widgets_Overview.md
│   ├── 03_Pre-built_Widgets.md
│   ├── 04_Creating_your_own_widgets.md
│   ├── 05_Search_Syntax.md
│   ├── 06_Dashboard_Import_Export.md
│   ├── images
│   │   ├── add-widget@2x.png
│   │   ├── controls@2x.png
│   │   ├── creating-search-widget@2x.png
│   │   ├── dashboard-edit@2x.png
│   │   ├── dashboard-selector@2x.png
│   │   ├── edit-widget-field@2x.png
│   │   ├── edit-widget-filter@2x.png
│   │   ├── edit-widget-modal@2x.png
│   │   ├── edit-widget-other@2x.png
│   │   ├── edit-widget@2x.png
│   │   ├── event-rate-widget@2x.png
│   │   ├── lastn-widget@2x.png
│   │   ├── notifications-widget@2x.png
│   │   ├── resize-widget@2x.png
│   │   ├── save-to-dashboard@2x.png
│   │   ├── search-results-widget@2x.png
│   │   ├── system-widget@2x.png
│   │   ├── tasks-widget@2x.png
│   │   ├── time-range-selector@2x.png
│   │   ├── time-range@2x.png
│   │   └── topn-widget@2x.png
│   └── index.md
├── 02_Creating_Triggers
│   ├── 01_Trigger_Page.md
│   ├── 02_Explanation_of_Actions.md
│   ├── 03_Trigger_Scripts.md
│   ├── images
│   │   ├── add-new-trigger.png
│   │   ├── add-note@2x.png
│   │   ├── execute-script@2x.png
│   │   ├── filters@2x.png
│   │   ├── issue-notification@2x.png
│   │   ├── query-bar@2x.png
│   │   ├── search-results@2x.png
│   │   ├── send-email@2x.png
│   │   └── system-settings@2x.png
│   └── index.md
├── 03_Alerts
│   ├── 01_Alerts_Overview.md
│   ├── 02_Automations.md
│   ├── 03_Trigger_Import_Export.md
│   ├── 04_Outgoing_Webhooks.md
│   ├── images
│   │   ├── add-new-trigger.png
│   │   ├── filters-hosts.png
│   │   ├── filters-severities.png
│   │   ├── outgoing_webhooks.png
│   │   ├── slack_alert.png
│   │   └── triggers.png
│   └── index.md
├── 04_Backend_Administration
│   ├── 01_Receiving_Syslog_Events.md
│   ├── 02_Sending_Email_From_The_Server.md
│   ├── 03_Archive_and_Restore.md
│   ├── 04_Server_Licensing.md
│   ├── 05_Using_TLS_Tunnels.md
│   ├── 06_Using_HTTPS.md
│   ├── 07_Backend_Configuration_Options.md
│   ├── 08_Backend_Search_Settings.md
│   ├── 09_Migrating_LogZilla_To_A_New_Server.md
│   ├── images
│   │   └── smtp.png
│   └── index.md
├── 05_Software_Notes
│   ├── 01_Development_Lifecycle.md
│   ├── 02_Release_Notes.md
│   ├── 03_LogZilla_VMWare_Image.md
│   ├── images
│   │   └── ticketflow.png
│   └── index.md
├── 06_Performance_Tuning
│   ├── 01_UDP_Buffer_Tuning.md
│   ├── 02_CPU_Frequency_Governers.md
│   ├── 03_VMWare_Performance.md
│   ├── 04_Filesystem_Performance.md
│   ├── images
│   │   └── vmware-disk-priority.png
│   └── index.md
├── 07_Receiving_Data
│   ├── 01_Receiving_SNMP_Traps.md
│   ├── 02_Cisco_IOS_Configuration.md
│   ├── 03_Receiving_Rsyslog_Events.md
│   ├── 04_Debugging_Event_Reception.md
│   ├── 05_Incoming_Webhooks.md
│   ├── 06_Receiving_Windows_Events.md
│   ├── images
│   │   ├── snare-001.png
│   │   ├── snare-002.png
│   │   ├── snare-003.png
│   │   └── snare-004.png
│   └── index.md
├── 08_Event_Correlation
│   ├── 01_Intro_to_Event_Correlation.md
│   ├── 02_Event_Correlation_Rule_Types.md
│   ├── 03_Sample_Rules.md
│   ├── 04_Correlating_Windows_Events.md
│   ├── images
│   │   ├── cisco-ec-mne.png
│   │   ├── cisco-ec-save.png
│   │   └── cisco-ec.png
│   └── index.md
├── 09_API
│   ├── 01_Using_The_API.md
│   └── index.md
└── template.html

I have a few hurdles:

The structure above of course

Our md files aren't using front matter, rather, we have  at the top of the markdown files. I could just do something like perl -i -pe 's/<\!-- @@@(title:)(.*?)@@@ -->/---\n$1 $2\n---\n/g' *.md but wasn't sure if there is a more elegant solution.

The image links would also have to be converted. In our files, they are done like so:![Controls](@@path/images/controls.png)

Can someone suggest a method I can use to make this an easily-repleatable process so that when we update our docs, they auto-update on the website?

Body:
1) the structure above should be no problem. I would not add that to the "_posts" directory but directly to the root folder. It should then generate files like:

01_Using_The_Dashboard/01_Dashboard_Overview.html

If you are not happy with the permalink generated, you can always overwrite this setting in the Frontmatter.

2) I am not aware on any $x2frontmatter tooling. There is something for migrating from wordpress as far as I know. I think your perl solutions is probably the most elegant way to do such a conversion. Please also think about generating addition content, like "layout: page" or similar, otherwise you would have to maintain it afterwards.

3) Instead of @@path you can use the base url. Please see Parkers post. Please also see the variables section which might contain additional nice information for you.

Regarding your fourth question, it seems you would like to know how to autdeploy changes. Just like continous deployment. There are multiple ways to do that.

Here is a blog post I wrote back then to auto deploy using rsync, crontab and shell.

Here is a more detailed blog post on how to deploying to S3 (including assets).

There is even the option to deploy to GitHub. Please see the docs for GitHub Pages.

Personally I use the CloudFront/S3 option.


问:
function prototype variable scope C++
Are variables in function prototype declaration in C++ considered global in scope?

E.g. In the script below, we declare a function prototype of readArray that takes an array integerArray and integer maxNumElements as input and returns the number of elements the user has provided. Of course, the readArray function is called from main. My question is if displayArray can print the array edited in readArray by being provided the maximum number of elements the user has inserted. In short, are integerArray and numElements global?

```<code>/* prototype declaration*/
int readArray (int integerArray [], int maxNumElements);
void displayArray(int integerArray[], int numElements);

int main()
{
    int inputValues[128]; /*the array to be read*/
    int numberOfValues = readArray(inputValues, 128);
    displayArray(inputValues, numberOfValues);
    return 0;
}

int readArray(int integerArray[], int maxNumElements)
{
    int numberOfValues;
    for (numberOfValues = 0; numberOfValues < maxNumElements; numberOfValues++)
    { /*take integers as input from user and insert into array */
       /*return the number of elements the user as provided*/
    }
    return numberOfValues;
}

void displayArray(int integerArray[], int numElements)
{ /*print the array*/
    for (int = 0; i < numElements; i++)
    {
        cout << i << ":" << integerArray[i] << endl;
    }
    cout << endl;
}
</code>```

答:
Scope is about where names are visible. Names in global scope, for example, are visible from their point of declaration to the end of the translation unit in which they are declared; names in local scope are visible from their point of declaration to the end of the block in which they are declared (i.e., up to the closing }). The names of arguments in a function prototype are visible only in the prototype. The names of arguments that are passed to a function are visible throughout that function.

So, from your code:

```<code>int readArray(int integerArray[], int maxNumElements);
</code>```

The names integerArray and maxNumElements are not visible outside this prototype.

```<code>int readArray(int integerArray[], int maxNumElements) {
    // ...
}
</code>```

The names integerArray and maxNumElements are visible thoughout the function definition, but not outside it.

```<code>int displayArray(int intgerArray[], int numElements) {
    // ...
}
</code>```

The names integerArray and numElements are visible thoughout the function definition, but not outside it.

The three uses of the name integerArray have no connection to each other; it's as if each of them was a completely different name.

Title: function prototype variable scope C++

Body:
Are variables in function prototype declaration in C++ considered global in scope?

E.g. In the script below, we declare a function prototype of readArray that takes an array integerArray and integer maxNumElements as input and returns the number of elements the user has provided. Of course, the readArray function is called from main. My question is if displayArray can print the array edited in readArray by being provided the maximum number of elements the user has inserted. In short, are integerArray and numElements global?

/* prototype declaration*/
int readArray (int integerArray [], int maxNumElements);
void displayArray(int integerArray[], int numElements);

int main()
{
    int inputValues[128]; /*the array to be read*/
    int numberOfValues = readArray(inputValues, 128);
    displayArray(inputValues, numberOfValues);
    return 0;
}

int readArray(int integerArray[], int maxNumElements)
{
    int numberOfValues;
    for (numberOfValues = 0; numberOfValues < maxNumElements; numberOfValues++)
    { /*take integers as input from user and insert into array */
       /*return the number of elements the user as provided*/
    }
    return numberOfValues;
}

void displayArray(int integerArray[], int numElements)
{ /*print the array*/
    for (int = 0; i < numElements; i++)
    {
        cout << i << ":" << integerArray[i] << endl;
    }
    cout << endl;
}

Body:
Scope is about where names are visible. Names in global scope, for example, are visible from their point of declaration to the end of the translation unit in which they are declared; names in local scope are visible from their point of declaration to the end of the block in which they are declared (i.e., up to the closing }). The names of arguments in a function prototype are visible only in the prototype. The names of arguments that are passed to a function are visible throughout that function.

So, from your code:

int readArray(int integerArray[], int maxNumElements);

The names integerArray and maxNumElements are not visible outside this prototype.

int readArray(int integerArray[], int maxNumElements) {
    // ...
}

The names integerArray and maxNumElements are visible thoughout the function definition, but not outside it.

int displayArray(int intgerArray[], int numElements) {
    // ...
}

The names integerArray and numElements are visible thoughout the function definition, but not outside it.

The three uses of the name integerArray have no connection to each other; it's as if each of them was a completely different name.


问:
Getting values in double array from index. Swift
I have a collection view made up of 4 sections.

Each section is an array of strings, like this:

```<code>var picList: [String] = ["Bird", "Cat", "Cow", "Dog", "Duck", "Elephant", "Fish", "Giraffe", "Lion", "Mouse", "Sheep", "Snake" ]

var vehiclesList: [String] = ["Airplane", "Ambulance", "Boat", "Bus", "Car", "Fire_Engine", "Helicopter", "Motorcycle", "Tank", "Tractor", "Train", "Truck" ]

var fruitsList: [String] = ["Apple", "Banana", "Grapes", "Mango", "Orange", "Peach", "Pineapple", "Strawberry", "Watermelon" ]

var bodyPartsList: [String] = ["Arm", "Ear", "Eye", "Face", "Feet", "Hand", "Hair", "Legs", "Mouth", "Nose" ]
</code>```

I created a UITapGestureRecognizer for the cell, that when I click on the cell, I get the index.

Here is the tapMethod

```<code>func handleTap(sender: UITapGestureRecognizer) {
        print("tap")

        if let indexPath = self.collectionView?.indexPathForItem(at: sender.location(in: self.collectionView)) {

            let cell = collectionView?.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PicViewCell

            print("index path: + \(indexPath)")

        } else {
            print("")
        }

    }
</code>```

Now the index prints like this [0,0] (if I press on the first item, ie bird). [2,4] if I press on the 4th item in the 2nd secion (ie mango). But I don't know how to translate the index, to get the corresponding string value. I mean something like this:

var itemName: String = [2,4] (and itemName would be mango)

I'm new to swift, so any help would be great.

Thanks so much.

答: You can create a two dimensional array, and add there your lists, indexpath.section will be the index of list and indexpath.item will be the index in thst list</p>

Body:
I have a collection view made up of 4 sections.

Each section is an array of strings, like this:

var picList: [String] = ["Bird", "Cat", "Cow", "Dog", "Duck", "Elephant", "Fish", "Giraffe", "Lion", "Mouse", "Sheep", "Snake" ]

var vehiclesList: [String] = ["Airplane", "Ambulance", "Boat", "Bus", "Car", "Fire_Engine", "Helicopter", "Motorcycle", "Tank", "Tractor", "Train", "Truck" ]

var fruitsList: [String] = ["Apple", "Banana", "Grapes", "Mango", "Orange", "Peach", "Pineapple", "Strawberry", "Watermelon" ]

var bodyPartsList: [String] = ["Arm", "Ear", "Eye", "Face", "Feet", "Hand", "Hair", "Legs", "Mouth", "Nose" ]

I created a UITapGestureRecognizer for the cell, that when I click on the cell, I get the index.

Here is the tapMethod

func handleTap(sender: UITapGestureRecognizer) {
        print("tap")

        if let indexPath = self.collectionView?.indexPathForItem(at: sender.location(in: self.collectionView)) {

            let cell = collectionView?.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PicViewCell

            print("index path: + \(indexPath)")

        } else {
            print("")
        }

    }

Now the index prints like this [0,0] (if I press on the first item, ie bird). [2,4] if I press on the 4th item in the 2nd secion (ie mango). But I don't know how to translate the index, to get the corresponding string value. I mean something like this:

var itemName: String = [2,4] (and itemName would be mango)

I'm new to swift, so any help would be great.

Thanks so much.


问:
Seaborn barplot with regression line
Is there a way to add a regression line to a barplot in seaborn where the x axis contains pandas.Timestamps?

For example, overlay a trendline in this bar plot below. Am looking for the most efficient way to do this:

```<code>seaborn.set(style="white", context="talk")
a = pandas.DataFrame.from_dict({'Attendees': {pandas.Timestamp('2016-12-01'): 10,
  pandas.Timestamp('2017-01-01'): 12,
  pandas.Timestamp('2017-02-01'): 15,
  pandas.Timestamp('2017-03-01'): 16,
  pandas.Timestamp('2017-04-01'): 20}})
ax = seaborn.barplot(data=a, x=a.index, y=a.Attendees, color='lightblue', )
seaborn.despine(offset=10, trim=False)
ax.set_ylabel("")
ax.set_xticklabels(['Dec', 'Jan','Feb','Mar','Apr'])
plt.show()
</code>```

答:
Seaborn barplots are categorical plots. Categorical plots cannot directly be used for regression, because the numeric values would not fit. The usual matplotlib bar plots however use numeric data.

An option is to plot a matplotlib barplot and seaborn regplot in the same graph.

```<code>import numpy as np; np.random.seed(1)
import seaborn.apionly as sns
import matplotlib.pyplot as plt

x = np.linspace(5,9,13)
y = np.cumsum(np.random.rand(len(x)))

fig, ax = plt.subplots()

ax.bar(x,y, width=0.1, color="lightblue", zorder=0)
sns.regplot(x=x, y=y, ax=ax)
ax.set_ylim(0, None)
plt.show()
</code>```

Since seaborn's barplot uses the integers from 0 to number of bars as indizes, one can also use those indizes for a regression plot on top of seaborn bar plot.

```<code>import numpy as np
import seaborn.apionly as sns
import matplotlib.pyplot as plt
import pandas

sns.set(style="white", context="talk")
a = pandas.DataFrame.from_dict({'Attendees': {pandas.Timestamp('2016-12-01'): 10,
  pandas.Timestamp('2017-01-01'): 12,
  pandas.Timestamp('2017-02-01'): 15,
  pandas.Timestamp('2017-03-01'): 16,
  pandas.Timestamp('2017-04-01'): 20}})
ax = sns.barplot(data=a, x=a.index, y=a.Attendees, color='lightblue' )
# put bars in background:
for c in ax.patches:
    c.set_zorder(0)
# plot regplot with numbers 0,..,len(a) as x value
sns.regplot(x=np.arange(0,len(a)), y=a.Attendees, ax=ax)
sns.despine(offset=10, trim=False)
ax.set_ylabel("")
ax.set_xticklabels(['Dec', 'Jan','Feb','Mar','Apr'])
plt.show()
</code>```

Title: Seaborn barplot with regression line

Body:
Is there a way to add a regression line to a barplot in seaborn where the x axis contains pandas.Timestamps?

For example, overlay a trendline in this bar plot below. Am looking for the most efficient way to do this:

seaborn.set(style="white", context="talk")
a = pandas.DataFrame.from_dict({'Attendees': {pandas.Timestamp('2016-12-01'): 10,
  pandas.Timestamp('2017-01-01'): 12,
  pandas.Timestamp('2017-02-01'): 15,
  pandas.Timestamp('2017-03-01'): 16,
  pandas.Timestamp('2017-04-01'): 20}})
ax = seaborn.barplot(data=a, x=a.index, y=a.Attendees, color='lightblue', )
seaborn.despine(offset=10, trim=False)
ax.set_ylabel("")
ax.set_xticklabels(['Dec', 'Jan','Feb','Mar','Apr'])
plt.show()

Body:
Seaborn barplots are categorical plots. Categorical plots cannot directly be used for regression, because the numeric values would not fit. The usual matplotlib bar plots however use numeric data.

An option is to plot a matplotlib barplot and seaborn regplot in the same graph.

import numpy as np; np.random.seed(1)
import seaborn.apionly as sns
import matplotlib.pyplot as plt

x = np.linspace(5,9,13)
y = np.cumsum(np.random.rand(len(x)))

fig, ax = plt.subplots()

ax.bar(x,y, width=0.1, color="lightblue", zorder=0)
sns.regplot(x=x, y=y, ax=ax)
ax.set_ylim(0, None)
plt.show()

Since seaborn's barplot uses the integers from 0 to number of bars as indizes, one can also use those indizes for a regression plot on top of seaborn bar plot.

import numpy as np
import seaborn.apionly as sns
import matplotlib.pyplot as plt
import pandas

sns.set(style="white", context="talk")
a = pandas.DataFrame.from_dict({'Attendees': {pandas.Timestamp('2016-12-01'): 10,
  pandas.Timestamp('2017-01-01'): 12,
  pandas.Timestamp('2017-02-01'): 15,
  pandas.Timestamp('2017-03-01'): 16,
  pandas.Timestamp('2017-04-01'): 20}})
ax = sns.barplot(data=a, x=a.index, y=a.Attendees, color='lightblue' )
# put bars in background:
for c in ax.patches:
    c.set_zorder(0)
# plot regplot with numbers 0,..,len(a) as x value
sns.regplot(x=np.arange(0,len(a)), y=a.Attendees, ax=ax)
sns.despine(offset=10, trim=False)
ax.set_ylabel("")
ax.set_xticklabels(['Dec', 'Jan','Feb','Mar','Apr'])
plt.show()


问:
How to make a program shut itself down
How do I make a program shut itself down after user says y in case 3. I want when they press y in case 3 that program exits it self like it would when compiling is done. I'm trying to make a menu where you can browse trough the options its not complete yet I need to make play, graphics, sounds case. Here is the code:</p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>

int main()
{
     int op1;

     printf("1.Play\n");
     printf("2.Options\n");
     printf("3.Exit\n");

     scanf(" %d", &op1);

     char ans;

     switch(op1)
     {
           case 1 : printf("Press 5 to start a new game");
                 break;
           case 2 : printf("1.Graphics\n"); printf("2.Sound\n");
                 break;
           case 3 :  printf("Are you sure (y/n)");
                 scanf(" %c", &ans);
                 if(ans =='y')
                 {

                 }
                 else
                 {
                     printf("1.Play\n");
                     printf("2.Options\n");
                     printf("3.Exit\n");
                 }
            default : printf("Wrong choice.");
     }
     return 0;
}
</code>```

答:
First of all, y is not a variable, you have to compare with the character code:

```<code>if (ans == 'y') {...}
</code>```

To terminate your program, use:

```<code>exit(0);
</code>```

Title: How to make a program shut itself down

Body:
How do I make a program shut itself down after user says y in case 3. I want when they press y in case 3 that program exits it self like it would when compiling is done. I'm trying to make a menu where you can browse trough the options its not complete yet I need to make play, graphics, sounds case. Here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>

int main()
{
     int op1;

     printf("1.Play\n");
     printf("2.Options\n");
     printf("3.Exit\n");

     scanf(" %d", &op1);

     char ans;

     switch(op1)
     {
           case 1 : printf("Press 5 to start a new game");
                 break;
           case 2 : printf("1.Graphics\n"); printf("2.Sound\n");
                 break;
           case 3 :  printf("Are you sure (y/n)");
                 scanf(" %c", &ans);
                 if(ans =='y')
                 {

                 }
                 else
                 {
                     printf("1.Play\n");
                     printf("2.Options\n");
                     printf("3.Exit\n");
                 }
            default : printf("Wrong choice.");
     }
     return 0;
}

Body:
First of all, y is not a variable, you have to compare with the character code:

if (ans == 'y') {...}

To terminate your program, use:

exit(0);


问:
Remote process communication
How can I do inter-process communication between two remote process on unix C/C++? Currently,  popen works for  two process on same host? Product need to be capability to call remote process and send /receive the data.</p>

答:
As you mentioned popen you may not realize this already allows you to use ssh to remotely execute a process and treat exactly the same as a locally spawned one.

```<code>popen ("ssh user@remotehost /usr/bin/cal", "r")
</code>```

And a pre-emptive link for further questions on ssh:

https://serverfault.com/questions/117007/ssh-key-questions

ContentLicense: CC BY-SA 2.5

Title: Remote process communication

Body:
As you mentioned popen you may not realize this already allows you to use ssh to remotely execute a process and treat exactly the same as a locally spawned one.

popen ("ssh user@remotehost /usr/bin/cal", "r")

And a pre-emptive link for further questions on ssh:

https://serverfault.com/questions/117007/ssh-key-questions


问:
Racket: get same random element from list in 2 different functions
I want to pick a random element from list1, remove it from list1, and add it to  list2.

(define list1 '(1 2 3 4 5 6 7 8)
 (define list2 '(9 10)

Now my problem is, that i use 2 functions to update the lists.

list1 will get a random element removed and list2 will get a random element appended but its not always the same element.

How can I make it that list2 gets the element added, that list1 got removed and then repeat these steps until list1 is empty?

Thanks a lot in advance

#lang racket
(define list1 '(1 2 3 4 5 6 7 8))
(define list2 '(9 10))

(define (select_random list)
  (car (shuffle list)))

(define (update_list list)
  (remove (select_random list) list))

(define (addToList list1 target_list)
  (append (list (select_random list1)) target_list))
```

答:
The way to select one element at random to be used several places is to do it outside of the functions:

(define (select-random lst)
  (car (shuffle lst)))
```

<p>Now you need to use the element to do your stuff:</p>

<pre class="lang-scm prettyprint-override"><code>(define (remove-element element lst)
  (remove element lst))

(define (add-element element lst)
  (cons element lst))
</code>```

So in your loop you can do something like this:

(let loop ((list1 '(1 2 3 4 5 6 7 8 9 10))
           (list2 '()))
  (if (null? list1)
      list2
      (let ((element (select-random list1)))
        (loop (remove-element element list1)
              (add-element element list2)))))

; ==> (2 1 5 4 10 7 6 8 9 3)
```

<p>Notice that <code>remove-element</code> and <code>add-element</code> are really just synonyms for <code>remove</code> and <code>cons</code>. They don't add any value but change the name. Thus you can just omit them:</p>

<pre class="lang-scm prettyprint-override"><code>(let loop ((list1 '(1 2 3 4 5 6 7 8 9 10))
           (list2 '()))
  (if (null? list1)
      list2
      (let ((element (select-random list1)))
        (loop (remove element list1)
              (cons element list2)))))
</code>```

In reality this is just a very complicated way to do (shuffle '(1 2 3 4 5 6 7 8 9 10)).

Body:
The way to select one element at random to be used several places is to do it outside of the functions:

(define (select-random lst)
  (car (shuffle lst)))

Now you need to use the element to do your stuff:

(define (remove-element element lst)
  (remove element lst))

(define (add-element element lst)
  (cons element lst))

So in your loop you can do something like this:

(let loop ((list1 '(1 2 3 4 5 6 7 8 9 10))
           (list2 '()))
  (if (null? list1)
      list2
      (let ((element (select-random list1)))
        (loop (remove-element element list1)
              (add-element element list2)))))

; ==> (2 1 5 4 10 7 6 8 9 3)

Notice that remove-element and add-element are really just synonyms for remove and cons. They don't add any value but change the name. Thus you can just omit them:

(let loop ((list1 '(1 2 3 4 5 6 7 8 9 10))
           (list2 '()))
  (if (null? list1)
      list2
      (let ((element (select-random list1)))
        (loop (remove element list1)
              (cons element list2)))))

In reality this is just a very complicated way to do (shuffle '(1 2 3 4 5 6 7 8 9 10)).


问:
Tensorflow tf.constant_initializer is very slow
Trying to use pre trained word2vec embeddings of 100 dim for training a LSTM

```<code>@staticmethod
def load_embeddings(pre_trained_embeddings_path, word_embed_size):
    embd = []
    import time
    start_time = time.time()
    cnt = 4
    with codecs.open(pre_trained_embeddings_path, mode="r", encoding='utf-8') as f:
        for line in f.readlines():
            values = line.strip().split(' ')
            embd.append(values[1:])
            cnt += 1
            if cnt % 100000 == 0:
                print("word-vectors loaded: %d" % cnt)

    embedding, vocab_size, embed_dim = embd, len(embd), len(embd[0])

    load_end_time = time.time()
    print("word vectors loaded from and start initialising, cnt: %d, time taken: %d secs " % (vocab_size, load_end_time - start_time))

    embedding_init = tf.constant_initializer(embedding, dtype=tf.float16)
    src_word_embedding = tf.get_variable(shape=[vocab_size, embed_dim], initializer=embedding_init, trainable=False, name='word_embedding', dtype=tf.float16)

    print("word-vectors loaded and initialised, cnt: %d, time taken: %d secs" % (vocab_size, time.time() - load_end_time))

    return src_word_embedding
</code>```

And the output of this when running this method is like :

```<code>word vectors loaded from and start initialising, cnt: 2419080, time taken: 74 secs
word-vectors loaded and initialised, cnt: 2419080, time taken: 1647 secs
</code>```

system info: tensorflow 1.1.0, tcmalloc, python 3.6, ubuntu 14.04

HALF an hour to initialize seems to be very slow or is it a normal behavior ? Any idea what could be the issue or is there one ?

UPDATE: using @sirfz method of supplying the embeddings made it really fast to load the embeddings Initialization Done in 85 secs

答:
Loading large constants into a graph is not only slower, it also leaks lots of memory. I had a similar issue which I reported not long ago and the best workaround for me was:</p>

```<code># placeholder for loading your saved embeddings
embedding_init = tf.placeholder(tf.float16, shape=[vocab_size, embed_dim])
src_word_embedding = tf.get_variable(initializer=embedding_init, trainable=False, name='word_embedding', dtype=tf.float16)

# run initialization with the value of embeddings placeholder
session.run(tf.global_variables_initializer(), feed_dict={embedding_init: embedding})
</code>```

Body:
Trying to use pre trained word2vec embeddings of 100 dim for training a LSTM

@staticmethod
def load_embeddings(pre_trained_embeddings_path, word_embed_size):
    embd = []
    import time
    start_time = time.time()
    cnt = 4
    with codecs.open(pre_trained_embeddings_path, mode="r", encoding='utf-8') as f:
        for line in f.readlines():
            values = line.strip().split(' ')
            embd.append(values[1:])
            cnt += 1
            if cnt % 100000 == 0:
                print("word-vectors loaded: %d" % cnt)

    embedding, vocab_size, embed_dim = embd, len(embd), len(embd[0])

    load_end_time = time.time()
    print("word vectors loaded from and start initialising, cnt: %d, time taken: %d secs " % (vocab_size, load_end_time - start_time))

    embedding_init = tf.constant_initializer(embedding, dtype=tf.float16)
    src_word_embedding = tf.get_variable(shape=[vocab_size, embed_dim], initializer=embedding_init, trainable=False, name='word_embedding', dtype=tf.float16)

    print("word-vectors loaded and initialised, cnt: %d, time taken: %d secs" % (vocab_size, time.time() - load_end_time))

    return src_word_embedding

And the output of this when running this method is like :

word vectors loaded from and start initialising, cnt: 2419080, time taken: 74 secs
word-vectors loaded and initialised, cnt: 2419080, time taken: 1647 secs

system info: tensorflow 1.1.0, tcmalloc, python 3.6, ubuntu 14.04

HALF an hour to initialize seems to be very slow or is it a normal behavior ? Any idea what could be the issue or is there one ?

UPDATE: using @sirfz method of supplying the embeddings made it really fast to load the embeddings Initialization Done in 85 secs

Body:
Loading large constants into a graph is not only slower, it also leaks lots of memory. I had a similar issue which I reported not long ago and the best workaround for me was:

# placeholder for loading your saved embeddings
embedding_init = tf.placeholder(tf.float16, shape=[vocab_size, embed_dim])
src_word_embedding = tf.get_variable(initializer=embedding_init, trainable=False, name='word_embedding', dtype=tf.float16)

# run initialization with the value of embeddings placeholder
session.run(tf.global_variables_initializer(), feed_dict={embedding_init: embedding})


问:
Set input's 'value' attribute from data?
I have a string coming in from the server named 'email'. In my pug template I'd like to set the initial value of an input field, but it renders literally as '#{email}' instead of the actual email address. If I remove the quotation marks, the pug file throws an error.

```<code>input(type='text' id='eMailAddress' value='#{email}')
</code>```

On the server-side:

```<code>res.render('personal-details', {email:req.session.email})
</code>```

How can I set the value dynamically?

答:
If you're using pug version 2+, you can do the following…</p>

```<code>input#eMailAddress(type='text' value=email)
</code>```

Body:
I have a string coming in from the server named 'email'. In my pug template I'd like to set the initial value of an input field, but it renders literally as '#{email}' instead of the actual email address. If I remove the quotation marks, the pug file throws an error.

input(type='text' id='eMailAddress' value='#{email}')

On the server-side:

res.render('personal-details', {email:req.session.email})

How can I set the value dynamically?

Body:
If you're using pug version 2+, you can do the following…

input#eMailAddress(type='text' value=email)


问:
Separating Windows Forms and Classes C#
I am looking for a way to design a C# application. I understand 3-tier model, but idk how to apply this in a good C# design.

I have looked some asp.net mvc tutorials, but I am looking for a windows-form based tutorial.

is there any book or website to learn a way to implement this?

答:
I believe that traditional MVC is overkill for WinForms. The form is the view, and there's seldom a need for a separate controller. The model is just a class (usually implementing INotifyPropertyChanged). You can use data binding to notify the view that the model has changed.

The important point is to minimize code under buttons. If it's form code, it should either (a) be UI-specific or (b) be delegating calls to the model. Any business logic should be in the model or in classes on which the model depends.

Avoid making the model a God Object. It can delegate internally to other classes.

EDIT: You may want to consider moving the bound data out into a separate object owned by the model. I'd call this Presentation Model, but I don't want to put words in Fowler's mouth.

EDIT2: Important - the model must have NO KNOWLEDGE of the view and NO UI code (such as dialogs).

Title: Separating Windows Forms and Classes C#


问:
simulate background-size:cover on <video> or
How can I simulate the functionality of background-size:cover on an html element like <video> or ?

I'd like it to work like

```<code>background-size: cover;
background-position: center center;
</code>```

答:
object-fit: cover is the best answer with this IE, Safari polyfill.

https://github.com/constancecchen/object-fit-polyfill

It is supporting img, video and picture elements.

Title: simulate background-size:cover on <video> or <img>

Body:
How can I simulate the functionality of background-size:cover on an html element like <video> or ?

I'd like it to work like

background-size: cover;
background-position: center center;


问:
Java executor model that allows running tasks only on instantiating thread
I am writing a multithreaded application where I've got the situation that I have certain library-related methods that can only be run on the main-thread. Currently I am running a simple, self-written, solution that listens on a queue for tasks and then executes them serially as they come in.

This works so far although it gets ugly when I need return values etc. (Which I am currently solving the c-way by passing along datastructures with the tasks and then have a busy-loop checking if the structure has been written to on the site of the method that queues a task.

This is not really the cleanest solution, and while it works, I was hoping to find a better way of doing this..

Q: Is there anything in the JDK or in a single specialized library that does what I need? Or is there any programming pattern that addresses my needs in  a clean and structured way?

答:
Let your main thread plays role of an Executor:

```<code>static ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(10);
public static void main(String... args) {
    // initialization...
    for (;;) {
        queue.take().run();
    }
}
</code>```

Whenever you need to execute a task on the main thread, put it to the queue:

```<code> queue.add(()->methodCall(1,2,3));
</code>```

Body:
Let your main thread plays role of an Executor:

static ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(10);
public static void main(String... args) {
    // initialization...
    for (;;) {
        queue.take().run();
    }
}

Whenever you need to execute a task on the main thread, put it to the queue:

 queue.add(()->methodCall(1,2,3));


答:
If this is to be restricted to the main() method, then just return out.

```<code> if(ans == 'y') {
     return 0;
 }
</code>```

It is a good practice to avoid hard exits unless you really need them.

But if you really need to hard exit out, you may try _exit(0); here. exit(0); as well, which has already been mentioned.

Title: How to make a program shut itself down

Body:
If this is to be restricted to the main() method, then just return out.

 if(ans == 'y') {
     return 0;
 }

It is a good practice to avoid hard exits unless you really need them.

But if you really need to hard exit out, you may try _exit(0); here. exit(0); as well, which has already been mentioned.


问:
Powering off multiple monitors programmatically
I'm looking for a way to programmatically power off multiple monitors.

Note: This doesn't mean power off ALL monitors.

The languages I'm currently able to compile in with my current enviorment is python/C/C++. I am aware of the easy C++ way of.

```<code>SendMessage(GetConsoleWindow(), WM_SYSCOMMAND, SC_MONITORPOWER, 2);
</code>```

However this powers off all the monitors the system has on, which isn't the result I'm after.

Let's say I have a Window with the name "Application Window", now I want to power off all of the monitors that does not have this app window open.

Note: Ideally it'd be implemented with python, however not needed.

Edit:
Found this, however I'm unable to recreate it and have the desired functionality.

Cpp how to turn off specific monitor?

答:
Using ctypes you can access the winapi functions you mentioned:

```<code>import ctypes

WM_SYSCOMMAND = 0x0112
SC_MONITORPOWER = 0xF170

window = ctypes.windll.kernel32.GetConsoleWindow()

ctypes.windll.user32.SendMessageA(window, WM_SYSCOMMAND, SC_MONITORPOWER, 2);
</code>```

The msdn documentation:

SendMessage

GetConsoleWindow

WM_SYSCOMMAND

You should use GetDesktopWindow:

```<code>window = ctypes.windll.kernel32.GetDesktopWindow()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm looking for a way to programmatically power off multiple monitors.

Note: This doesn't mean power off ALL monitors.

The languages I'm currently able to compile in with my current enviorment is python/C/C++. I am aware of the easy C++ way of.

SendMessage(GetConsoleWindow(), WM_SYSCOMMAND, SC_MONITORPOWER, 2);

However this powers off all the monitors the system has on, which isn't the result I'm after.

Let's say I have a Window with the name "Application Window", now I want to power off all of the monitors that does not have this app window open.

Note: Ideally it'd be implemented with python, however not needed.

Edit:
Found this, however I'm unable to recreate it and have the desired functionality.

Cpp how to turn off specific monitor?

Body:
Using ctypes you can access the winapi functions you mentioned:

import ctypes

WM_SYSCOMMAND = 0x0112
SC_MONITORPOWER = 0xF170

window = ctypes.windll.kernel32.GetConsoleWindow()

ctypes.windll.user32.SendMessageA(window, WM_SYSCOMMAND, SC_MONITORPOWER, 2);

The msdn documentation:

SendMessage

GetConsoleWindow

WM_SYSCOMMAND

You should use GetDesktopWindow:

window = ctypes.windll.kernel32.GetDesktopWindow()


问:
php session id value to multiple pages
I'm trying to pass the value of a session id to a different page, but only the last product id is passed to the second page no matter if a product with a different id is selected. Ideally what ever product is clicked that id should pass to the second page

```<code><body>
<?php
session_start();
$_SESSION['favcolor'] = 'green';
?>

<!--Some other html code -->

  <?php

      $servername = "localhost";
      $username = "user";
      $password = "pass";
      $dbname = "dbname";

      // Create connection
      $conn = new mysqli($servername, $username, $password, $dbname);
      // Check connection
      if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
      }

      $sql2 = "SELECT * FROM tablename WHERE 1 ORDER BY ProductName ASC";
      $myresult = $conn->query($sql2);

       $x = 1;
       while ($row = $myresult->fetch_assoc()) {
$_SESSION['id'] = $row['ProductID'];
       ?>

       <div class="col-sm-4">
                           <div class="product-image-wrapper">
                               <div class="single-products">
                                   <div class="productinfo text-center">

                                      <a href="page2.php"> <img src="../../images/myImages/<?php echo $row['ProductImage1'];?>_0001_1.jpg" alt="../../images/myImages/<?php echo $row['ProductImage1'];?>_0001_1.jpg" /></a>
                                       <h2><?php echo $row['ProductPrice'];?></h2>

 <!-- when i echo $_SESSION['id'] i get correct values for each product -->
                                       <p><?php echo $_SESSION['id'];?></p>
                                       <p><?php echo $row['ProductName']; ?></p>

 <!-- Other HTML Code -->
</code>```

Second Page after clicking a product and expecting the correct product id to be passed.

```<code><body>
<?php

 session_start();
 echo $_SESSION['favcolor'];
 echo $_SESSION['id'];

?>
</code>```

This results in the last Product ID being passed to the second page no matter what product is clicked

答: When you print the Id's of the products you're retrieving from the table and iterate them in the while loop so they're gonna be right. To set the id product in the session when this is clicked you must either set the value in the second page or set it with an AJAX Request, in this case is necessary use Javascript.

Title: php session id value to multiple pages

Body:
I'm trying to pass the value of a session id to a different page, but only the last product id is passed to the second page no matter if a product with a different id is selected. Ideally what ever product is clicked that id should pass to the second page

<?php
session_start();
$_SESSION['favcolor'] = 'green';
?>

  <?php

      $servername = "localhost";
      $username = "user";
      $password = "pass";
      $dbname = "dbname";

      // Create connection
      $conn = new mysqli($servername, $username, $password, $dbname);
      // Check connection
      if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
      }

      $sql2 = "SELECT * FROM tablename WHERE 1 ORDER BY ProductName ASC";
      $myresult = $conn->query($sql2);

       $x = 1;
       while ($row = $myresult->fetch_assoc()) {
$_SESSION['id'] = $row['ProductID'];
       ?>

                                       <img src="../../images/myImages/<?php echo $row['ProductImage1'];?>_0001_1.jpg" alt="../../images/myImages/<?php echo $row['ProductImage1'];?>_0001_1.jpg" />

<?php echo $row['ProductPrice'];?>

<?php echo $_SESSION['id'];?>

<?php echo $row['ProductName']; ?>

Second Page after clicking a product and expecting the correct product id to be passed.

<?php

 session_start();
 echo $_SESSION['favcolor'];
 echo $_SESSION['id'];

?>

This results in the last Product ID being passed to the second page no matter what product is clicked


问:
Add function to event runtime
```<code>procedure TFormOrderAdd.DBEdit1DblClick(Sender: TObject);
var
  FormSelectEmp: TForm;
  SelectEmpDBGrid: TDBGrid;

begin
  FormSelectEmp := TForm.Create(Self);
  SelectEmpDBGrid :=  TDBGrid.Create(Self);
  SelectEmpDBGrid.Parent := FormSelectEmp;
  SelectEmpDBGrid.Align := alClient;
  SelectEmpDBGrid.DataSource := DMl.DataSourceViewEmpList;
  FormSelectEmp.ShowModal;
  SelectEmpDBGrid.OnDblClick := AddSelectedEmp;
  FormSelectEmp.Close;
end;

procedure TFormOrderAdd.AddSelectedEmp;
begin
  DBEdit1.Text := Dml.ADOQueryViewEmpList.FieldByName('ID').Text;
end;
</code>```

How i can add my procedure to OnDblClick Event?
I tryed just assign, but compiller says: [dcc32 Error] OrderAdd.pas(66): E2010 Incompatible types: 'TNotifyEvent' and 'procedure, untyped pointer or untyped parameter'

答:
You must create a matching event method prototype in a class that you then assign to the event handler (for the TDBGrid control's OnDblClick event it is the TNotifyEvent), so you can write for example:

```<code>type
  TForm1 = class(TForm)
    DBEdit1: TDBEdit;
    DBGrid1: TDBGrid;
  private
    procedure Form1Create(Sender: TObject);
    procedure MyGridDblClick(Sender: TObject);
  end;

implementation

procedure TForm1.Form1Create(Sender: TObject);
begin
  { it doesn't matter if you create the component at runtime,
    this is a common principle of assigning event methods at
    runtime - they just have to match the method prototypes }
  DBGrid1.OnDblClick := MyGridDblClick;
end;

procedure TForm1.MyGridDblClick(Sender: TObject);
begin
  { to access the grid instance in case more than one grid
    uses this handler you can use TDBGrid(Sender) or safer
    cast (Sender as TDBGrid) }
  DBEdit1.Text := TDBGrid(Sender).DataSource.Dataset.FieldByName('ID').Text;
end;
</code>```

Title: Add function to event runtime

Body:
procedure TFormOrderAdd.DBEdit1DblClick(Sender: TObject);
var
  FormSelectEmp: TForm;
  SelectEmpDBGrid: TDBGrid;

begin
  FormSelectEmp := TForm.Create(Self);
  SelectEmpDBGrid :=  TDBGrid.Create(Self);
  SelectEmpDBGrid.Parent := FormSelectEmp;
  SelectEmpDBGrid.Align := alClient;
  SelectEmpDBGrid.DataSource := DMl.DataSourceViewEmpList;
  FormSelectEmp.ShowModal;
  SelectEmpDBGrid.OnDblClick := AddSelectedEmp;
  FormSelectEmp.Close;
end;

procedure TFormOrderAdd.AddSelectedEmp;
begin
  DBEdit1.Text := Dml.ADOQueryViewEmpList.FieldByName('ID').Text;
end;

How i can add my procedure to OnDblClick Event?
I tryed just assign, but compiller says: [dcc32 Error] OrderAdd.pas(66): E2010 Incompatible types: 'TNotifyEvent' and 'procedure, untyped pointer or untyped parameter'

Body:
You must create a matching event method prototype in a class that you then assign to the event handler (for the TDBGrid control's OnDblClick event it is the TNotifyEvent), so you can write for example:

type
  TForm1 = class(TForm)
    DBEdit1: TDBEdit;
    DBGrid1: TDBGrid;
  private
    procedure Form1Create(Sender: TObject);
    procedure MyGridDblClick(Sender: TObject);
  end;

implementation

procedure TForm1.Form1Create(Sender: TObject);
begin
  { it doesn't matter if you create the component at runtime,
    this is a common principle of assigning event methods at
    runtime - they just have to match the method prototypes }
  DBGrid1.OnDblClick := MyGridDblClick;
end;

procedure TForm1.MyGridDblClick(Sender: TObject);
begin
  { to access the grid instance in case more than one grid
    uses this handler you can use TDBGrid(Sender) or safer
    cast (Sender as TDBGrid) }
  DBEdit1.Text := TDBGrid(Sender).DataSource.Dataset.FieldByName('ID').Text;
end;


问:
Why is PHP mailer printing mimeheader to screen after send?
Here is the problem, I have just implemented PHPMailer and it is printing the Mime Header to the screen after the email is sent.  I am using the latest PHPMailer code listed on GITHUB, and I have gone through virtually everything but cant find any reason why this is printing to the screen.  Let me know if you need anymore information.  I cant seem to think of anything else.  See below:

```<code>2013-09-30 20:37:14 CLIENT -> SERVER: AUTH LOGIN
2013-09-30 20:37:14 CLIENT -> SERVER: ZGFwaWVjaG9jxXlAZ21haWwuY29t
2013-09-30 20:37:14 CLIENT -> SERVER: ZHBpZT5HNzE=
2013-09-30 20:37:15 CLIENT -> SERVER: MAIL FROM:<xxxxx@xxxxxx.com>
2013-09-30 20:37:15 CLIENT -> SERVER: RCPT TO:<yyyyy@yyyyyyy.com>
2013-09-30 20:37:15 CLIENT -> SERVER: DATA
2013-09-30 20:37:15 CLIENT -> SERVER: Date: Mon, 30 Sep 2013 16:37:14 -0400
2013-09-30 20:37:15 CLIENT -> SERVER: Return-Path: <xxxxx@xxxxxxx.com>
2013-09-30 20:37:15 CLIENT -> SERVER: To: Someone <yyyyyy@yyyyyyyy.com>
2013-09-30 20:37:15 CLIENT -> SERVER: From: xxxxxxx xxxxx <xxxxx@xxxxxxx.com>
2013-09-30 20:37:15 CLIENT -> SERVER: Subject: xxxxxxx.com Confirmation
2013-09-30 20:37:15 CLIENT -> SERVER: Message-ID: <c22a17772edd75gh89td324ac0fe67ae@localhost>
2013-09-30 20:37:15 CLIENT -> SERVER: X-Priority: 3
2013-09-30 20:37:15 CLIENT -> SERVER: X-Mailer: PHPMailer 5.2.7 (https://github.com/PHPMailer/PHPMailer/)
2013-09-30 20:37:15 CLIENT -> SERVER: MIME-Version: 1.0
2013-09-30 20:37:15 CLIENT -> SERVER: Content-Type: multipart/alternative;
2013-09-30 20:37:15 CLIENT -> SERVER:   boundary="b1_c22a17772edd75gh89td324ac0fe67ae"
2013-09-30 20:37:15 CLIENT -> SERVER: Content-Transfer-Encoding: 8bit
2013-09-30 20:37:15 CLIENT -> SERVER:
2013-09-30 20:37:15 CLIENT -> SERVER: --b1_c22a17772edd75gh89td324ac0fe67ae
2013-09-30 20:37:15 CLIENT -> SERVER: Content-Type: text/plain; charset=iso-8859-1
2013-09-30 20:37:15 CLIENT -> SERVER: Content-Transfer-Encoding: 8bit
2013-09-30 20:37:15 CLIENT -> SERVER:
2013-09-30 20:37:15 CLIENT -> SERVER: This is the text body of the message, it is
2013-09-30 20:37:15 CLIENT -> SERVER: printed here.  blah blah blah
2013-09-30 20:37:15 CLIENT -> SERVER:
2013-09-30 20:37:15 CLIENT -> SERVER:
2013-09-30 20:37:15 CLIENT -> SERVER: --b1_c22a17772edd75gh89td324ac0fe67ae
2013-09-30 20:37:15 CLIENT -> SERVER: Content-Type: text/html; charset=iso-8859-1
2013-09-30 20:37:15 CLIENT -> SERVER: Content-Transfer-Encoding: 8bit
2013-09-30 20:37:15 CLIENT -> SERVER:
2013-09-30 20:37:15 CLIENT -> SERVER: This is the alternate text body for non-html email that may or may no be reading this.
2013-09-30 20:37:15 CLIENT -> SERVER: This is also the text body
2013-09-30 20:37:15 CLIENT -> SERVER:
2013-09-30 20:37:15 CLIENT -> SERVER:
2013-09-30 20:37:15 CLIENT -> SERVER:
2013-09-30 20:37:15 CLIENT -> SERVER: --b1_c22a17772edd79e8f6fd324ac0fe67ae--
2013-09-30 20:37:15 CLIENT -> SERVER:
2013-09-30 20:37:15 CLIENT -> SERVER: .
2013-09-30 20:37:16 CLIENT -> SERVER: QUIT
</code>```

Here is the implementing code:

```<code>require("class.phpmailer.php");

$mail = new PHPMailer;

$mail->From = 'xxxxx@xxxxxxx.com';
$mail->FromName = 'xxxxxxx xxxxx';
$mail->addAddress($email, $fname);
$mail->addReplyTo('', '');
$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = "smtpout.secureserver.net ";
$mail->Port = 465;
$mail->Username = "xxxxx@xxxxxxx.com";
$mail->Password = "password";
$mail->WordWrap = 50;
$mail->isHTML(true);

$mail->Subject = 'xxxxxxx.com Confirmation';
$mail->Body    = "This is the text body of the message, it is printed here.  blah blah blah";
$mail->AltBody = "This is the alternate text body for non-html email that may or may no be reading this.<br />This is also the text body";

if(!$mail->send()) {
   echo 'Message could not be sent.';
   echo 'Mailer Error: ' . $mail->ErrorInfo;
   exit;
}
</code>```

答:
Personally, I expected SMTPDebug to write to the error_log rather than echo to the screen.

Add this to your PHPMailer configuration to enable this behavior:

```<code>$mail->Debugoutput = 'error_log';
</code>```

Thankfully this is supported, just not the default.

Body:
Here is the problem, I have just implemented PHPMailer and it is printing the Mime Header to the screen after the email is sent.  I am using the latest PHPMailer code listed on GITHUB, and I have gone through virtually everything but cant find any reason why this is printing to the screen.  Let me know if you need anymore information.  I cant seem to think of anything else.  See below:

2013-09-30 20:37:14 CLIENT -> SERVER: AUTH LOGIN
2013-09-30 20:37:14 CLIENT -> SERVER: ZGFwaWVjaG9jxXlAZ21haWwuY29t
2013-09-30 20:37:14 CLIENT -> SERVER: ZHBpZT5HNzE=
2013-09-30 20:37:15 CLIENT -> SERVER: MAIL FROM:<xxxxx@xxxxxx.com>
2013-09-30 20:37:15 CLIENT -> SERVER: RCPT TO:<yyyyy@yyyyyyy.com>
2013-09-30 20:37:15 CLIENT -> SERVER: DATA
2013-09-30 20:37:15 CLIENT -> SERVER: Date: Mon, 30 Sep 2013 16:37:14 -0400
2013-09-30 20:37:15 CLIENT -> SERVER: Return-Path: <xxxxx@xxxxxxx.com>
2013-09-30 20:37:15 CLIENT -> SERVER: To: Someone <yyyyyy@yyyyyyyy.com>
2013-09-30 20:37:15 CLIENT -> SERVER: From: xxxxxxx xxxxx <xxxxx@xxxxxxx.com>
2013-09-30 20:37:15 CLIENT -> SERVER: Subject: xxxxxxx.com Confirmation
2013-09-30 20:37:15 CLIENT -> SERVER: Message-ID: <c22a17772edd75gh89td324ac0fe67ae@localhost>
2013-09-30 20:37:15 CLIENT -> SERVER: X-Priority: 3
2013-09-30 20:37:15 CLIENT -> SERVER: X-Mailer: PHPMailer 5.2.7 (https://github.com/PHPMailer/PHPMailer/)
2013-09-30 20:37:15 CLIENT -> SERVER: MIME-Version: 1.0
2013-09-30 20:37:15 CLIENT -> SERVER: Content-Type: multipart/alternative;
2013-09-30 20:37:15 CLIENT -> SERVER:   boundary="b1_c22a17772edd75gh89td324ac0fe67ae"
2013-09-30 20:37:15 CLIENT -> SERVER: Content-Transfer-Encoding: 8bit
2013-09-30 20:37:15 CLIENT -> SERVER:
2013-09-30 20:37:15 CLIENT -> SERVER: --b1_c22a17772edd75gh89td324ac0fe67ae
2013-09-30 20:37:15 CLIENT -> SERVER: Content-Type: text/plain; charset=iso-8859-1
2013-09-30 20:37:15 CLIENT -> SERVER: Content-Transfer-Encoding: 8bit
2013-09-30 20:37:15 CLIENT -> SERVER:
2013-09-30 20:37:15 CLIENT -> SERVER: This is the text body of the message, it is
2013-09-30 20:37:15 CLIENT -> SERVER: printed here.  blah blah blah
2013-09-30 20:37:15 CLIENT -> SERVER:
2013-09-30 20:37:15 CLIENT -> SERVER:
2013-09-30 20:37:15 CLIENT -> SERVER: --b1_c22a17772edd75gh89td324ac0fe67ae
2013-09-30 20:37:15 CLIENT -> SERVER: Content-Type: text/html; charset=iso-8859-1
2013-09-30 20:37:15 CLIENT -> SERVER: Content-Transfer-Encoding: 8bit
2013-09-30 20:37:15 CLIENT -> SERVER:
2013-09-30 20:37:15 CLIENT -> SERVER: This is the alternate text body for non-html email that may or may no be reading this.
2013-09-30 20:37:15 CLIENT -> SERVER: This is also the text body
2013-09-30 20:37:15 CLIENT -> SERVER:
2013-09-30 20:37:15 CLIENT -> SERVER:
2013-09-30 20:37:15 CLIENT -> SERVER:
2013-09-30 20:37:15 CLIENT -> SERVER: --b1_c22a17772edd79e8f6fd324ac0fe67ae--
2013-09-30 20:37:15 CLIENT -> SERVER:
2013-09-30 20:37:15 CLIENT -> SERVER: .
2013-09-30 20:37:16 CLIENT -> SERVER: QUIT

Here is the implementing code:

require("class.phpmailer.php");

$mail = new PHPMailer;

$mail->From = 'xxxxx@xxxxxxx.com';
$mail->FromName = 'xxxxxxx xxxxx';
$mail->addAddress($email, $fname);
$mail->addReplyTo('', '');
$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = "smtpout.secureserver.net ";
$mail->Port = 465;
$mail->Username = "xxxxx@xxxxxxx.com";
$mail->Password = "password";
$mail->WordWrap = 50;
$mail->isHTML(true);

$mail->Subject = 'xxxxxxx.com Confirmation';
$mail->Body    = "This is the text body of the message, it is printed here.  blah blah blah";
$mail->AltBody = "This is the alternate text body for non-html email that may or may no be reading this.
This is also the text body";

if(!$mail->send()) {
   echo 'Message could not be sent.';
   echo 'Mailer Error: ' . $mail->ErrorInfo;
   exit;
}

Body:
Personally, I expected SMTPDebug to write to the error_log rather than echo to the screen.

Add this to your PHPMailer configuration to enable this behavior:

$mail->Debugoutput = 'error_log';

Thankfully this is supported, just not the default.


问:
Modifying a structure passed as pointer in C
I'm a noob student trying to write a program that uses binary search tree to organize the workers of a company. My teacher told me if I want to be able to create a new instance of the Worker structure, i can use malloc with the structure, which will return pointer to a new struct every time it's used, then i can edit the details of that new struct from another function. But how can i do it? No matter what i do it gets so complicated and i can't do it. Here's the code i've been able to write this part of the code, just to test if i can create and edit a new structure.
The main thing i ask is, how can i edit the newly created structure?</p>

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

struct btnode
{
    int value = 5;
    struct btnode *l;
    struct btnode *r;
};

int test(int *p)
{

    printf("%d", &p->value);
}

int main()
{
    int *asdf = (int *)malloc(sizeof(struct btnode));

    test(asdf);
}
</code>```

答:
First of all there are some mistakes in the code.

1) You can not assign values in the structure.

2) When you are making a pointer for the structure you need pointer of the structure not of the int (does not matter what you want from the inside of the structure)

This is the modified code which runs perfactly

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

struct btnode
{
    int value;
    struct btnode *l;
    struct btnode *r;
};

int test(struct btnode *p)
{

    printf("%d", p->value);
}

int main()
{
    struct btnode *asdf = (struct btnode*)malloc(sizeof(struct btnode));
    asdf->value = 5;
    test(asdf);
}
</code>```

Body:
I'm a noob student trying to write a program that uses binary search tree to organize the workers of a company. My teacher told me if I want to be able to create a new instance of the Worker structure, i can use malloc with the structure, which will return pointer to a new struct every time it's used, then i can edit the details of that new struct from another function. But how can i do it? No matter what i do it gets so complicated and i can't do it. Here's the code i've been able to write this part of the code, just to test if i can create and edit a new structure.
The main thing i ask is, how can i edit the newly created structure?

#include<stdlib.h>
#include<stdio.h>

struct btnode
{
    int value = 5;
    struct btnode *l;
    struct btnode *r;
};

int test(int *p)
{

    printf("%d", &p->value);
}

int main()
{
    int *asdf = (int *)malloc(sizeof(struct btnode));

    test(asdf);
}

Body:
First of all there are some mistakes in the code.

1) You can not assign values in the structure.

2) When you are making a pointer for the structure you need pointer of the structure not of the int (does not matter what you want from the inside of the structure)

This is the modified code which runs perfactly

#include<stdio.h>

struct btnode
{
    int value;
    struct btnode *l;
    struct btnode *r;
};

int test(struct btnode *p)
{

    printf("%d", p->value);
}

int main()
{
    struct btnode *asdf = (struct btnode*)malloc(sizeof(struct btnode));
    asdf->value = 5;
    test(asdf);
}


答:
Here is a mod of your program which allocates memory for one struct, fills in values for its members, and calls test() to print one member.

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

struct btnode
{
    int value;
    struct btnode *l;
    struct btnode *r;
};

void test(struct btnode *p)
{
    printf("%d", p->value);
}

int main(void)
{
    struct btnode *asdf = malloc(sizeof *asdf);
    if(asdf != NULL) {
        asdf->value = 5;
        asdf->l = NULL;
        asdf->r = NULL;
        test(asdf);
        free(asdf);
    }
    return 0;
}
</code>```

There are a number of small changes to detail too, I leave you to spot the differences.

Title: Modifying a structure passed as pointer in C

Body:
Here is a mod of your program which allocates memory for one struct, fills in values for its members, and calls test() to print one member.

#include <stdlib.h>
#include <stdio.h>

struct btnode
{
    int value;
    struct btnode *l;
    struct btnode *r;
};

void test(struct btnode *p)
{
    printf("%d", p->value);
}

int main(void)
{
    struct btnode *asdf = malloc(sizeof *asdf);
    if(asdf != NULL) {
        asdf->value = 5;
        asdf->l = NULL;
        asdf->r = NULL;
        test(asdf);
        free(asdf);
    }
    return 0;
}

There are a number of small changes to detail too, I leave you to spot the differences.


问:
Dynamically put and remove a item from numpy array at a constant rate
I want to put and delete a certain item in a numpy array dynamically, that is, with timing.

This is my current code:

```<code>import time
import numpy as np

gen_array = np.array([[0, 0, 0, 0],
                      [0, 0, 0, 0],
                      [0, 0, 0, 0],
                      [0, 0, 0, 0],
                      [0, 0, 0, 0],
                      [0, 0, 0, 0]])

insert_candidate = np.array([1])
counter = 0
while 1:
    time.sleep(1)
    for i in range(1):
        np.put(gen_array[i + counter], range(1, 2), insert_candidate)
    print(gen_array)
    print('\n')
    counter += 1
</code>```

Albeit it's adding an item to the next row every second, it's keeping the old one.

Is there any function that deals with this or possible solution?

答:
I don't understand very well what you want but ...

May be you want something like :

```<code>import time
import numpy as np

gen_array = np.array([[0, 0, 0, 0],
                      [0, 0, 0, 0],
                      [0, 0, 0, 0],
                      [0, 0, 0, 0],
                      [0, 0, 0, 0],
                      [0, 0, 0, 0]])

insert_candidate = np.array([1])
counter = 0
while 1:
    time.sleep(1)
    gen_array[counter][1]=1
    gen_array[counter-1][1]=0
    print(gen_array)
    print('\n')
    counter += 1
</code>```

Body:
I want to put and delete a certain item in a numpy array dynamically, that is, with timing.

This is my current code:

import time
import numpy as np

gen_array = np.array([[0, 0, 0, 0],
                      [0, 0, 0, 0],
                      [0, 0, 0, 0],
                      [0, 0, 0, 0],
                      [0, 0, 0, 0],
                      [0, 0, 0, 0]])

insert_candidate = np.array([1])
counter = 0
while 1:
    time.sleep(1)
    for i in range(1):
        np.put(gen_array[i + counter], range(1, 2), insert_candidate)
    print(gen_array)
    print('\n')
    counter += 1

Albeit it's adding an item to the next row every second, it's keeping the old one.

Is there any function that deals with this or possible solution?

Body:
I don't understand very well what you want but ...

May be you want something like :

import time
import numpy as np

gen_array = np.array([[0, 0, 0, 0],
                      [0, 0, 0, 0],
                      [0, 0, 0, 0],
                      [0, 0, 0, 0],
                      [0, 0, 0, 0],
                      [0, 0, 0, 0]])

insert_candidate = np.array([1])
counter = 0
while 1:
    time.sleep(1)
    gen_array[counter][1]=1
    gen_array[counter-1][1]=0
    print(gen_array)
    print('\n')
    counter += 1


问:
openCV mac OSX suggested webcam
Does anyone have a recommendation for a web cam to be used on a mac with opencv?

Thank you!

答: The internal webcam that comes with their laptop works quite well (rather high  quality). You can also get Logitech Orbit (I personally have rather good experience with those). </p>

Title: openCV mac OSX suggested webcam


问:
How to convert UInt16 to UInt8 in Swift 3?
I want to convert UInt16 to UInt8 array, but am getting the following error message:

'init' is unavailable: use 'withMemoryRebound(to:capacity:_)' to
  temporarily view memory as another layout-compatible type.

The code:

```<code>    let statusByte: UInt8 = UInt8(status)
    let lenghtByte: UInt16 = UInt16(passwordBytes.count)

    var bigEndian = lenghtByte.bigEndian

    let bytePtr = withUnsafePointer(to: &bigEndian) {
        UnsafeBufferPointer<UInt8>(start: UnsafePointer($0), count: MemoryLayout.size(ofValue: bigEndian))
    }
</code>```

答:
As the error message indicates, you have to use withMemoryRebound()
to reinterpret the pointer to UInt16 as a pointer to UInt8:

```<code>let bytes = withUnsafePointer(to: &bigEndian) {
    $0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout.size(ofValue: bigEndian)) {
        Array(UnsafeBufferPointer(start: $0, count: MemoryLayout.size(ofValue: bigEndian)))
    }
}
</code>```

The closures are invoked with pointers ($0) which are only valid
for the lifetime of the closure and must not be passed to the outside
for later use. That's why an Array is created and used as return value.

There is a simpler solution however:

```<code>let bytes = withUnsafeBytes(of: &bigEndian) { Array($0) }
</code>```

Explanation: withUnsafeBytes invokes the closure with a UnsafeRawBufferPointer to the storage of the bigEndian variable.
Since UnsafeRawBufferPointer is a Sequence of UInt8, an array
can be created from that with Array($0).

Body:
I want to convert UInt16 to UInt8 array, but am getting the following error message:

'init' is unavailable: use 'withMemoryRebound(to:capacity:_)' to
  temporarily view memory as another layout-compatible type.

The code:

    let statusByte: UInt8 = UInt8(status)
    let lenghtByte: UInt16 = UInt16(passwordBytes.count)

    var bigEndian = lenghtByte.bigEndian

    let bytePtr = withUnsafePointer(to: &bigEndian) {
        UnsafeBufferPointer<UInt8>(start: UnsafePointer($0), count: MemoryLayout.size(ofValue: bigEndian))
    }

Body:
As the error message indicates, you have to use withMemoryRebound()
to reinterpret the pointer to UInt16 as a pointer to UInt8:

let bytes = withUnsafePointer(to: &bigEndian) {
    $0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout.size(ofValue: bigEndian)) {
        Array(UnsafeBufferPointer(start: $0, count: MemoryLayout.size(ofValue: bigEndian)))
    }
}

The closures are invoked with pointers ($0) which are only valid
for the lifetime of the closure and must not be passed to the outside
for later use. That's why an Array is created and used as return value.

There is a simpler solution however:

let bytes = withUnsafeBytes(of: &bigEndian) { Array($0) }

Explanation: withUnsafeBytes invokes the closure with a UnsafeRawBufferPointer to the storage of the bigEndian variable.
Since UnsafeRawBufferPointer is a Sequence of UInt8, an array
can be created from that with Array($0).


问:
passing input values to javascript under laravel
I have an HTML form with input fields. I am trying to get the data from the input fields to be passed to a javascript function for processing. I am trying to get the value of "tenantid" but the only thing I get, when displaying the value in the popup:

first objectHMTLFormElement

How can I get values entered in the form to the Javascript code?

TIA

I have:
testing.blade.php

```<code>    <script type="text/javascript" src="{{ URL::asset('js/test.js') }}">
    </script>

    [.. snip ..]

    <form id="oogie" class="form-horizontal" role="form" method="POST" action="{{ url('') }}/dashboard">
                {{ csrf_field() }}

            <div class="form-group{{ $errors->has('tenantid') ? ' has-error' : '' }}">
                    <label for="tenantid" class="col-md-4 control-label"> Tenant ID </label>

                    <div class="col-md-6">
                        <input id="tenantid" type="integer" class="form-control" name="tenantid" value="{{ old('tenantid') }}" required autofocus>

                        @if ($errors->has('tenantid'))
                            <span class="help-block">
                                <strong>{{ $errors->first('tenantid') }}</strong>
                            </span>
                        @endif
                    </div>
                </div>
      </form>

      [... snip ...]

      <button class="ClickMe" onclick="testme();">Click me</button>
</code>```

test.js

```<code>function testme()
{
alert("got in");
var parameters = document.getElementById("oogie");

alert("first " + parameters );

}
</code>```

答:
That's because your script isn't trying to access the value of the field, but the field itself.

You should use document.getElementById(ID).value. This will fix your issue.

Body:
I have an HTML form with input fields. I am trying to get the data from the input fields to be passed to a javascript function for processing. I am trying to get the value of "tenantid" but the only thing I get, when displaying the value in the popup:

first objectHMTLFormElement

How can I get values entered in the form to the Javascript code?

TIA

I have:
testing.blade.php

    [.. snip ..]

    <form id="oogie" class="form-horizontal" role="form" method="POST" action="{{ url('') }}/dashboard">
                {{ csrf_field() }}

has('tenantid') ? ' has-error' : '' }}">
                     Tenant ID

                        <input id="tenantid" type="integer" class="form-control" name="tenantid" value="{{ old('tenantid') }}" required autofocus>

                        @if ($errors->has('tenantid'))

                                {{ $errors->first('tenantid') }}

                        @endif

      </form>

      [... snip ...]

      <button class="ClickMe" onclick="testme();">Click me</button>

test.js

function testme()
{
alert("got in");
var parameters = document.getElementById("oogie");

alert("first " + parameters );

}


问:
What is the best way to run background script in firefox Addon script?
I have to make a small modification on a legacy addon built in Addon SDK that's why I am not using webextension. I am trying to make a background script that should be running in the background as long as the addon is installed. I have an HTML panel and there is a script that is attached to it. But the panel's script runs only when the button is clicked. I tried to make another panel and attach the background script to it simply as:

```<code>var panels = require("sdk/panel");
var backgroundPanel = panels.Panel({
    contentScriptFile: "./background.js"
});
</code>```

But the background.js never runs. How to run a script on the background automatically as long as the addon is installed without the need to be triggered?

答: The code you have already shown, commonly placed in a file called index.js, is already executed when the add-on is added to Firefox (i.e. upon add-on installation and when Firefox loads the add-on each time Firefox starts up) and will be executing until Firefox closes. It is already your background script.

Body:
I have to make a small modification on a legacy addon built in Addon SDK that's why I am not using webextension. I am trying to make a background script that should be running in the background as long as the addon is installed. I have an HTML panel and there is a script that is attached to it. But the panel's script runs only when the button is clicked. I tried to make another panel and attach the background script to it simply as:

var panels = require("sdk/panel");
var backgroundPanel = panels.Panel({
    contentScriptFile: "./background.js"
});

But the background.js never runs. How to run a script on the background automatically as long as the addon is installed without the need to be triggered?


问:
Listener to detect whether a view is at the front?
I have RecyclerView and, in some cases, I show another view on top of it - ProgressDialog, AlertDialog or DialogFragment.

Is there some way to notify me about cases when my RecyclerView is at front or another view is above it now?

I tried to add onFocusChangeListener() to my RecyclerView, but no luck.

PS. Definitely, I can in my RecyclerView create some method isOnFront(boolean onFront) and in all my other views call it, but maybe there is some more elegance way?

答:
ProgressDialog, AlertDialog and DialogFragment would lay their content on the Window, not to your activity's/fragment's view hierarchy. Which means, that as soon as either of them is shown, the focus of Window is changed. Hence, you can make use of ViewTreeObserver#addOnWindowFocusChangeListener() API:

```
<code>
    contentView.getViewTreeObserver().addOnWindowFocusChangeListener(
        new ViewTreeObserver.OnWindowFocusChangeListener() {
          @Override public void onWindowFocusChanged(boolean hasFocus) {
            // Remove observer when no longer needed
            // contentView.getViewTreeObserver().removeOnWindowFocusChangeListener(this);

            if (hasFocus) {
              // Your view hierarchy is in the front
            } else {
              // There is some other view on top of your view hierarchy,
              // which resulted in losing the focus of window
            }
          }
        });
</code>
```

Body:
ProgressDialog, AlertDialog and DialogFragment would lay their content on the Window, not to your activity's/fragment's view hierarchy. Which means, that as soon as either of them is shown, the focus of Window is changed. Hence, you can make use of ViewTreeObserver#addOnWindowFocusChangeListener() API:

    contentView.getViewTreeObserver().addOnWindowFocusChangeListener(
        new ViewTreeObserver.OnWindowFocusChangeListener() {
          @Override public void onWindowFocusChanged(boolean hasFocus) {
            // Remove observer when no longer needed
            // contentView.getViewTreeObserver().removeOnWindowFocusChangeListener(this);

            if (hasFocus) {
              // Your view hierarchy is in the front
            } else {
              // There is some other view on top of your view hierarchy,
              // which resulted in losing the focus of window
            }
          }
        });


问:
ASP.Net Response.Redirect not working in Application_Error?
I don't know why the Response.Redirect not working properly when I deploy my code to IIS7? The white/yellow error page always get displayed instead of my Errors.aspx. But when debug running using Visual Studio on my computer, it runs just fine?</p>

```<code>protected void Application_Error(object sender, EventArgs e)
        {
            ILog log = LogManager.GetLogger(typeof(Global).Name);
            Exception objErr = Server.GetLastError().GetBaseException();
            log.Error(objErr);
            string err = "Error Caught in Application_Error event\n" +
                    "\nError Message:" + objErr.Message.ToString() +
                    "\nStack Trace:" + objErr.StackTrace.ToString();
            EventLog.WriteEntry("Kiosk", err, EventLogEntryType.Error);
            Server.ClearError();
            Response.Redirect("~/Error.aspx", false);
        }
</code>```

答: Try to turn off the CustomError in web.config. It will give you more specific about the error details. Maybe it doesn't the error from Response.Redirect. </p>

Body:
I don't know why the Response.Redirect not working properly when I deploy my code to IIS7? The white/yellow error page always get displayed instead of my Errors.aspx. But when debug running using Visual Studio on my computer, it runs just fine?

protected void Application_Error(object sender, EventArgs e)
        {
            ILog log = LogManager.GetLogger(typeof(Global).Name);
            Exception objErr = Server.GetLastError().GetBaseException();
            log.Error(objErr);
            string err = "Error Caught in Application_Error event\n" +
                    "\nError Message:" + objErr.Message.ToString() +
                    "\nStack Trace:" + objErr.StackTrace.ToString();
            EventLog.WriteEntry("Kiosk", err, EventLogEntryType.Error);
            Server.ClearError();
            Response.Redirect("~/Error.aspx", false);
        }


问:
Unable to use ADC on atmega328
I am trying to make a proximity sensor using ATmega328P. I am using the onboard ADC to convert the voltage value and if it is higher than the ambient, an LED is lit.

The voltage that is being sensed is according to this circuit:

In the circuit, the VOUT is going to ADC channel 3 and should be sensed (think of the led on the right as the IR Sensor).

When the program starts, it senses 30 readings and takes their average to be used as the ambient setting. If any subsequent measurement is higher than this value, the LED should be lit.

But the LED does not light even if I place my hand above the sensor.

I have tested with just the LED to see if the IR sensor is ok. It is ok by the way.

The code for the microcontroller is as follows:

/*
 * Proximity Sensor IR.c
 *
 * Created: 6/3/2017 2:35:33 PM
 * Author : Rishav
 */

#include <avr/io.h>
#include <stdio.h>

#define F_CPU 16000000UL
#include <util/delay.h>

int calibration()
{
    unsigned int sum = 0;

    for (int i=0; i<30; i++)
        {
            ADCSRA |= (1<<ADSC);
            while(!(ADCSRA & (1<<ADIF)));

            ADCSRA |= (1<<ADIF);

            sum += (ADCH<<8)|ADCL;
        }

    return (sum/30);
}

int main(void)
{
    unsigned int val = 0;

    ADMUX |= (0<<REFS1)|(1<<REFS0)|(0<<MUX3)|(0<<MUX2)|(1<<MUX1)|(1<<MUX0);     //setting the multiplexer to ADC3
    ADCSRA |= (1<<ADEN)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);

    DDRB = 0b00000010;

    DDRD |= (1<<PCINT22);
    PORTD |= (1<<PCINT22);

    int calib_value = calibration();

    while (1)
    {
        ADCSRA |= (1<<ADSC);
        while(!(ADCSRA & (1<<ADIF)));

        val = (ADCH<<8)|ADCL;

        ADCSRA |= (1<<ADIF);

        if (val > calib_value)
            PORTB = 0b00000010;
    }
}
```

I think there is some problem in the code. Please help.

答:
You have to enable the ADC first and select channel and reference voltage afterwards. It is easy to skip this fact in the datasheet.

The ADC is enabled by setting the ADC Enable bit, ADEN in ADCSRA.
  Voltage reference and input channel selections will not go into effect
  until ADEN is set. Datasheet page 238.

I did not check all of your settings but I am pretty sure that this must be your issue.

Example order:

void init_adc()
{
    ADCSRA |= (1<<ADEN);                            // enable ADC
    ADMUX |= (1<<MUX1) | (1<<MUX0);                 // channel selection ADC3 - PB3
    ADMUX &= ~(1<<REFS0);                           // VCC as reference
    ADCSRA |= (1<<ADPS2) | (1<<ADPS1) | (1<<ADPS0); // setting prescaler to 128
}
```

<p>As mentioned a you should read ADCL first to:</p>

<blockquote>
  <p>ADCL must be read first, then ADCH, to ensure that the content of the
  Data Registers belongs to the same conversion</p>
</blockquote>

<p>I suggest to move this part into a separate function like:</p>

<pre class="lang-c prettyprint-override"><code>uint16_t read_adc()
{
    ADCSRA |= (1<<ADSC);

    while(!(ADCSRA & (1<<ADIF)));

    uint8_t adcl = ADCL;
    uint8_t adch = ADCH;

    ADCSRA |= (1<<ADIF);

    return (adch<<8) | adcl;
}
</code>```

Title: Unable to use ADC on atmega328

Body:
I am trying to make a proximity sensor using ATmega328P. I am using the onboard ADC to convert the voltage value and if it is higher than the ambient, an LED is lit.

The voltage that is being sensed is according to this circuit:

In the circuit, the VOUT is going to ADC channel 3 and should be sensed (think of the led on the right as the IR Sensor).

When the program starts, it senses 30 readings and takes their average to be used as the ambient setting. If any subsequent measurement is higher than this value, the LED should be lit.

But the LED does not light even if I place my hand above the sensor.

I have tested with just the LED to see if the IR sensor is ok. It is ok by the way.

The code for the microcontroller is as follows:

/*
 * Proximity Sensor IR.c
 *
 * Created: 6/3/2017 2:35:33 PM
 * Author : Rishav
 */

#include <avr/io.h>
#include <stdio.h>

#define F_CPU 16000000UL
#include <util/delay.h>

int calibration()
{
    unsigned int sum = 0;

    for (int i=0; i<30; i++)
        {
            ADCSRA |= (1<<ADSC);
            while(!(ADCSRA & (1<<ADIF)));

            ADCSRA |= (1<<ADIF);

            sum += (ADCH<<8)|ADCL;
        }

    return (sum/30);
}

int main(void)
{
    unsigned int val = 0;

    ADMUX |= (0<<REFS1)|(1<<REFS0)|(0<<MUX3)|(0<<MUX2)|(1<<MUX1)|(1<<MUX0);     //setting the multiplexer to ADC3
    ADCSRA |= (1<<ADEN)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);

    DDRB = 0b00000010;

    DDRD |= (1<<PCINT22);
    PORTD |= (1<<PCINT22);

    int calib_value = calibration();

    while (1)
    {
        ADCSRA |= (1<<ADSC);
        while(!(ADCSRA & (1<<ADIF)));

        val = (ADCH<<8)|ADCL;

        ADCSRA |= (1<<ADIF);

        if (val > calib_value)
            PORTB = 0b00000010;
    }
}

I think there is some problem in the code. Please help.

Body:
You have to enable the ADC first and select channel and reference voltage afterwards. It is easy to skip this fact in the datasheet.

The ADC is enabled by setting the ADC Enable bit, ADEN in ADCSRA.
  Voltage reference and input channel selections will not go into effect
  until ADEN is set. Datasheet page 238.

I did not check all of your settings but I am pretty sure that this must be your issue.

Example order:

void init_adc()
{
    ADCSRA |= (1<<ADEN);                            // enable ADC
    ADMUX |= (1<<MUX1) | (1<<MUX0);                 // channel selection ADC3 - PB3
    ADMUX &= ~(1<<REFS0);                           // VCC as reference
    ADCSRA |= (1<<ADPS2) | (1<<ADPS1) | (1<<ADPS0); // setting prescaler to 128
}

As mentioned a you should read ADCL first to:

ADCL must be read first, then ADCH, to ensure that the content of the
  Data Registers belongs to the same conversion

I suggest to move this part into a separate function like:

uint16_t read_adc()
{
    ADCSRA |= (1<<ADSC);

    while(!(ADCSRA & (1<<ADIF)));

    uint8_t adcl = ADCL;
    uint8_t adch = ADCH;

    ADCSRA |= (1<<ADIF);

    return (adch<<8) | adcl;
}


问:
How to save SMS to inbox in android?
I have written the below code for sending SMS messages.

```<code>SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(destAddr, null, mMessageText, il, null);
</code>```

But this is not updating in my Inbox, I need to save the same message in Inbox,
Or is there any way to invoke a native SMS application to send SMS ?

答:
```<code>ContentValues values = new ContentValues();
values.put("address", phoneNumber);
values.put("body", multimessage);
values.put("read", 1); //"0" for have not read sms and "1" for have read sms
Uri uri = Telephony.Sms.Sent.CONTENT_URI;
Activity ctx = this.cordova.getActivity();
ctx.getContentResolver().insert(uri, values);
</code>```

OwnerDisplayName: Senthil

LastEditorDisplayName: Ólafur Waage

Title: How to save SMS to inbox in android?

Body:
I have written the below code for sending SMS messages.

SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(destAddr, null, mMessageText, il, null);

But this is not updating in my Inbox, I need to save the same message in Inbox,
Or is there any way to invoke a native SMS application to send SMS ?


问:
How to center a subclass of QGLWidget in PyQt5
I have an example program in PyQt5

I have a class:

```<code>class QGLControllerWidget(QtOpenGL.QGLWidget):
    ...
</code>```

And a main program:

```<code>app = QtWidgets.QApplication([])
window = QGLControllerWidget()    # this is my class
window.show()                     # I want to center the window on the screen
app.exec_()
</code>```

Currently the window's location is somewhere between the center and the bottom right corner, please see the image:

How to center the window/widget on the screen in PyQt5?

03_alpha_blending.py

```<code>import struct

from PyQt5 import QtCore, QtOpenGL, QtWidgets

import ModernGL

class QGLControllerWidget(QtOpenGL.QGLWidget):
    def __init__(self):
        fmt = QtOpenGL.QGLFormat()
        fmt.setVersion(3, 3)
        fmt.setProfile(QtOpenGL.QGLFormat.CoreProfile)
        fmt.setSampleBuffers(True)
        self.timer = QtCore.QElapsedTimer()
        super(QGLControllerWidget, self).__init__(fmt, None)

    def initializeGL(self):
        self.ctx = ModernGL.create_context()

        prog = self.ctx.program([
            self.ctx.vertex_shader('''
                #version 330

                in vec2 vert;

                in vec4 vert_color;
                out vec4 frag_color;

                uniform vec2 scale;
                uniform float rotation;

                void main() {
                    frag_color = vert_color;
                    float r = rotation * (0.5 + gl_InstanceID * 0.05);
                    mat2 rot = mat2(cos(r), sin(r), -sin(r), cos(r));
                    gl_Position = vec4((rot * vert) * scale, 0.0, 1.0);
                }
            '''),
            self.ctx.fragment_shader('''
                #version 330

                in vec4 frag_color;
                out vec4 color;

                void main() {
                    color = vec4(frag_color);
                }
            '''),
        ])

        self.scale = prog.uniforms['scale']
        self.rotation = prog.uniforms['rotation']

        vbo = self.ctx.buffer(struct.pack(
            '18f',
            1.0, 0.0, 1.0, 0.0, 0.0, 0.5,
            -0.5, 0.86, 0.0, 1.0, 0.0, 0.5,
            -0.5, -0.86, 0.0, 0.0, 1.0, 0.5,
        ))

        self.vao = self.ctx.simple_vertex_array(prog, vbo, ['vert', 'vert_color'])

        self.timer.restart()

    def paintGL(self):
        self.ctx.viewport = (0, 0, self.width(), self.height())
        self.ctx.clear(0.9, 0.9, 0.9)
        self.scale.value = (self.height() / self.width() * 0.75, 0.75)
        self.rotation.value = self.timer.elapsed() / 1000
        self.ctx.enable(ModernGL.BLEND)
        self.vao.render(instances=10)
        self.ctx.finish()
        self.update()

app = QtWidgets.QApplication([])
window = QGLControllerWidget()
window.show()
app.exec_()
</code>```

答:
You have to move the widget to the center of the screen, to know the size of the screen you must use QDesktopWidget, like the following:

```<code>app = QtWidgets.QApplication([])
window = QGLControllerWidget()
pos = QtWidgets.QDesktopWidget().rect().center() -window.rect().center()
window.move(pos)
window.show()
app.exec_()
</code>```

Body:
I have an example program in PyQt5

I have a class:

class QGLControllerWidget(QtOpenGL.QGLWidget):
    ...

And a main program:

app = QtWidgets.QApplication([])
window = QGLControllerWidget()    # this is my class
window.show()                     # I want to center the window on the screen
app.exec_()

Currently the window's location is somewhere between the center and the bottom right corner, please see the image:

How to center the window/widget on the screen in PyQt5?

03_alpha_blending.py

import struct

from PyQt5 import QtCore, QtOpenGL, QtWidgets

import ModernGL

class QGLControllerWidget(QtOpenGL.QGLWidget):
    def __init__(self):
        fmt = QtOpenGL.QGLFormat()
        fmt.setVersion(3, 3)
        fmt.setProfile(QtOpenGL.QGLFormat.CoreProfile)
        fmt.setSampleBuffers(True)
        self.timer = QtCore.QElapsedTimer()
        super(QGLControllerWidget, self).__init__(fmt, None)

    def initializeGL(self):
        self.ctx = ModernGL.create_context()

        prog = self.ctx.program([
            self.ctx.vertex_shader('''
                #version 330

                in vec2 vert;

                in vec4 vert_color;
                out vec4 frag_color;

                uniform vec2 scale;
                uniform float rotation;

                void main() {
                    frag_color = vert_color;
                    float r = rotation * (0.5 + gl_InstanceID * 0.05);
                    mat2 rot = mat2(cos(r), sin(r), -sin(r), cos(r));
                    gl_Position = vec4((rot * vert) * scale, 0.0, 1.0);
                }
            '''),
            self.ctx.fragment_shader('''
                #version 330

                in vec4 frag_color;
                out vec4 color;

                void main() {
                    color = vec4(frag_color);
                }
            '''),
        ])

        self.scale = prog.uniforms['scale']
        self.rotation = prog.uniforms['rotation']

        vbo = self.ctx.buffer(struct.pack(
            '18f',
            1.0, 0.0, 1.0, 0.0, 0.0, 0.5,
            -0.5, 0.86, 0.0, 1.0, 0.0, 0.5,
            -0.5, -0.86, 0.0, 0.0, 1.0, 0.5,
        ))

        self.vao = self.ctx.simple_vertex_array(prog, vbo, ['vert', 'vert_color'])

        self.timer.restart()

    def paintGL(self):
        self.ctx.viewport = (0, 0, self.width(), self.height())
        self.ctx.clear(0.9, 0.9, 0.9)
        self.scale.value = (self.height() / self.width() * 0.75, 0.75)
        self.rotation.value = self.timer.elapsed() / 1000
        self.ctx.enable(ModernGL.BLEND)
        self.vao.render(instances=10)
        self.ctx.finish()
        self.update()

app = QtWidgets.QApplication([])
window = QGLControllerWidget()
window.show()
app.exec_()

Body:
You have to move the widget to the center of the screen, to know the size of the screen you must use QDesktopWidget, like the following:

app = QtWidgets.QApplication([])
window = QGLControllerWidget()
pos = QtWidgets.QDesktopWidget().rect().center() -window.rect().center()
window.move(pos)
window.show()
app.exec_()


问:
Firebase Android: Retrieve post from current user's friends only
I'm using FirebaseRecyclerAdapter to show posts. But I don't want to show all the posts. I just want to show posts which are posted by current user's friends.
Current User's friends in Realtime Database is stored in this way:

And Every post is stored with the uid of User who posted it, in following way:

So, what will be the efficient way to retrieve posts from only current user's friends.

答:
Solution for this issue is use FirebaseIndexRecyclerAdapter instead of FirebaseRecyclerAdapter.
Link: https://github.com/firebase/FirebaseUI-Android/blob/master/database/README.md#using-firebaseui-with-indexed-data

Step  by Step:

First-> maintain post of every user in a node let say "My_Challenges":

So whenever a user post anything, copy that post id under user uid inside this node too.

Second-> Maintain another node for posts which you can see(in my case i want to see only my friends posts) let say "timelineIndex":

Let say User 1(1014382358695053) and User 2(10207254337991322) are friend. So copy all post id from My_Challenges of User 1 to timelineIndex of User 2 and vice versa also. (NOTE : You have to do this every time a new post id comes under your uid copy it to your friend uid under timelineIndex)

Finally-> Use FirebaseIndexRecyclerAdapter :
As in above given link, use

keyRef = databaseReference.child("timelineIndex").child(mUserId);

dataRef = databaseReference.child("Blogs");

That's it. I hope it helps.


问:
print python emoji as unicode string
I've been trying to output '' as '\U0001f604' instead of the smiley, but it doesn't seem to work.

I tried using repr() but it gives me this '\xf0\x9f\x98\x84'. Currently it outputs the smiley which is not what I wanted. encode('unicode_escape') gives me a UnicodeDecodeError.

The smiley was passed as a string to a class method in python. i.e. "I am happy "

答:
Just add </p>

```<code># -*- coding: UTF-8 -*-
</code>```

<p>into your code and you will be able to print Unicode characters </p>

Title: print python emoji as unicode string

Body:
Just add

# -*- coding: UTF-8 -*-

into your code and you will be able to print Unicode characters