问:
Is there an API to list all Azure Regions?
I would like to list all Azure locations via some API (I need to generate some config files for every region, and use the exact naming that Azure does to avoid typos). I found this question, but it only lists regions a particular subscription is authorized to use.

I want to list all regions that exist whether my subscription has access or not.

答:
az account list-locations -o table

will give you a table like:

```<code>DisplayName               Name                 RegionalDisplayName
------------------------  -------------------  -------------------------------------
East US                   eastus               (US) East US
East US 2                 eastus2              (US) East US 2
South Central US          southcentralus       (US) South Central US
West US 2                 westus2              (US) West US 2
Australia East            australiaeast        (Asia Pacific) Australia East
Southeast Asia            southeastasia        (Asia Pacific) Southeast Asia
North Europe              northeurope          (Europe) North Europe
UK South                  uksouth              (Europe) UK South
West Europe               westeurope           (Europe) West Europe
Central US                centralus            (US) Central US
North Central US          northcentralus       (US) North Central US
West US                   westus               (US) West US
South Africa North        southafricanorth     (Africa) South Africa North
Central India             centralindia         (Asia Pacific) Central India
East Asia                 eastasia             (Asia Pacific) East Asia
Japan East                japaneast            (Asia Pacific) Japan East
JIO India West            jioindiawest         (Asia Pacific) JIO India West
Korea Central             koreacentral         (Asia Pacific) Korea Central
Canada Central            canadacentral        (Canada) Canada Central
France Central            francecentral        (Europe) France Central
Germany West Central      germanywestcentral   (Europe) Germany West Central
Norway East               norwayeast           (Europe) Norway East
Switzerland North         switzerlandnorth     (Europe) Switzerland North
UAE North                 uaenorth             (Middle East) UAE North
Brazil South              brazilsouth          (South America) Brazil South
Central US (Stage)        centralusstage       (US) Central US (Stage)
East US (Stage)           eastusstage          (US) East US (Stage)
East US 2 (Stage)         eastus2stage         (US) East US 2 (Stage)
North Central US (Stage)  northcentralusstage  (US) North Central US (Stage)
South Central US (Stage)  southcentralusstage  (US) South Central US (Stage)
West US (Stage)           westusstage          (US) West US (Stage)
West US 2 (Stage)         westus2stage         (US) West US 2 (Stage)
Asia                      asia                 Asia
Asia Pacific              asiapacific          Asia Pacific
Australia                 australia            Australia
Brazil                    brazil               Brazil
Canada                    canada               Canada
Europe                    europe               Europe
Global                    global               Global
India                     india                India
Japan                     japan                Japan
United Kingdom            uk                   United Kingdom
United States             unitedstates         United States
East Asia (Stage)         eastasiastage        (Asia Pacific) East Asia (Stage)
Southeast Asia (Stage)    southeastasiastage   (Asia Pacific) Southeast Asia (Stage)
Central US EUAP           centraluseuap        (US) Central US EUAP
East US 2 EUAP            eastus2euap          (US) East US 2 EUAP
West Central US           westcentralus        (US) West Central US
West US 3                 westus3              (US) West US 3
South Africa West         southafricawest      (Africa) South Africa West
Australia Central         australiacentral     (Asia Pacific) Australia Central
Australia Central 2       australiacentral2    (Asia Pacific) Australia Central 2
Australia Southeast       australiasoutheast   (Asia Pacific) Australia Southeast
Japan West                japanwest            (Asia Pacific) Japan West
Korea South               koreasouth           (Asia Pacific) Korea South
South India               southindia           (Asia Pacific) South India
West India                westindia            (Asia Pacific) West India
Canada East               canadaeast           (Canada) Canada East
France South              francesouth          (Europe) France South
Germany North             germanynorth         (Europe) Germany North
Norway West               norwaywest           (Europe) Norway West
Switzerland West          switzerlandwest      (Europe) Switzerland West
UK West                   ukwest               (Europe) UK West
UAE Central               uaecentral           (Middle East) UAE Central
Brazil Southeast          brazilsoutheast      (South America) Brazil Southeast
</code>```

Body:
az account list-locations -o table

will give you a table like:

DisplayName               Name                 RegionalDisplayName
------------------------  -------------------  -------------------------------------
East US                   eastus               (US) East US
East US 2                 eastus2              (US) East US 2
South Central US          southcentralus       (US) South Central US
West US 2                 westus2              (US) West US 2
Australia East            australiaeast        (Asia Pacific) Australia East
Southeast Asia            southeastasia        (Asia Pacific) Southeast Asia
North Europe              northeurope          (Europe) North Europe
UK South                  uksouth              (Europe) UK South
West Europe               westeurope           (Europe) West Europe
Central US                centralus            (US) Central US
North Central US          northcentralus       (US) North Central US
West US                   westus               (US) West US
South Africa North        southafricanorth     (Africa) South Africa North
Central India             centralindia         (Asia Pacific) Central India
East Asia                 eastasia             (Asia Pacific) East Asia
Japan East                japaneast            (Asia Pacific) Japan East
JIO India West            jioindiawest         (Asia Pacific) JIO India West
Korea Central             koreacentral         (Asia Pacific) Korea Central
Canada Central            canadacentral        (Canada) Canada Central
France Central            francecentral        (Europe) France Central
Germany West Central      germanywestcentral   (Europe) Germany West Central
Norway East               norwayeast           (Europe) Norway East
Switzerland North         switzerlandnorth     (Europe) Switzerland North
UAE North                 uaenorth             (Middle East) UAE North
Brazil South              brazilsouth          (South America) Brazil South
Central US (Stage)        centralusstage       (US) Central US (Stage)
East US (Stage)           eastusstage          (US) East US (Stage)
East US 2 (Stage)         eastus2stage         (US) East US 2 (Stage)
North Central US (Stage)  northcentralusstage  (US) North Central US (Stage)
South Central US (Stage)  southcentralusstage  (US) South Central US (Stage)
West US (Stage)           westusstage          (US) West US (Stage)
West US 2 (Stage)         westus2stage         (US) West US 2 (Stage)
Asia                      asia                 Asia
Asia Pacific              asiapacific          Asia Pacific
Australia                 australia            Australia
Brazil                    brazil               Brazil
Canada                    canada               Canada
Europe                    europe               Europe
Global                    global               Global
India                     india                India
Japan                     japan                Japan
United Kingdom            uk                   United Kingdom
United States             unitedstates         United States
East Asia (Stage)         eastasiastage        (Asia Pacific) East Asia (Stage)
Southeast Asia (Stage)    southeastasiastage   (Asia Pacific) Southeast Asia (Stage)
Central US EUAP           centraluseuap        (US) Central US EUAP
East US 2 EUAP            eastus2euap          (US) East US 2 EUAP
West Central US           westcentralus        (US) West Central US
West US 3                 westus3              (US) West US 3
South Africa West         southafricawest      (Africa) South Africa West
Australia Central         australiacentral     (Asia Pacific) Australia Central
Australia Central 2       australiacentral2    (Asia Pacific) Australia Central 2
Australia Southeast       australiasoutheast   (Asia Pacific) Australia Southeast
Japan West                japanwest            (Asia Pacific) Japan West
Korea South               koreasouth           (Asia Pacific) Korea South
South India               southindia           (Asia Pacific) South India
West India                westindia            (Asia Pacific) West India
Canada East               canadaeast           (Canada) Canada East
France South              francesouth          (Europe) France South
Germany North             germanynorth         (Europe) Germany North
Norway West               norwaywest           (Europe) Norway West
Switzerland West          switzerlandwest      (Europe) Switzerland West
UK West                   ukwest               (Europe) UK West
UAE Central               uaecentral           (Middle East) UAE Central
Brazil Southeast          brazilsoutheast      (South America) Brazil Southeast


来源: stackexchange

问:
Microsoft Edge: Get Window URL and Title
Previously I was using ShellWindows() API for IE to get the window Title and URL for my application
Now with new development, Microsoft Edge is new and has many features under development.

I want to know how I can get the URL and Title of all the pages opened in MS-Edge.
As none of the shell APIs are working with MS-Edge.
I tried also with UI Automation but it does not return all the UI elements

I am using MS Visual Studio 2010 for development. Do I need new version of Visual Studio?
Can anybody help me about how to access the Title and URL?
Or Does MS-Edge not allow such an access due to security?
thanks

答:
Dim tmp1 As String = ""
        Dim strME As String = "Microsoft Edge"</p>

```<code>    Try
        Dim conditions As Condition = Condition.TrueCondition
        Dim BaseElement As AutomationElement = AutomationElement.RootElement
        Dim elementCollection As AutomationElementCollection = BaseElement.FindAll(TreeScope.Children, conditions)
        Dim AE As AutomationElement

        For Each AE In elementCollection
            If AE IsNot Nothing Then
                tmp1 = AE.GetCurrentPropertyValue(AutomationElement.NameProperty).ToString
                If StrComp(Strings.Right(tmp1, strME.Length), strME, vbTextCompare) = 0 Then
                    Dim elmUrlBar0 As AutomationElement
                    elmUrlBar0 = AE.FindFirst(TreeScope.Subtree, New PropertyCondition(AutomationElement.AutomationIdProperty, "addressEditBox"))
                    If elmUrlBar0 IsNot Nothing Then
                        Dim patterns0 As AutomationPattern() = elmUrlBar0.GetSupportedPatterns()
                        If patterns0.Length > 0 Then
                            Dim val As ValuePattern = DirectCast(elmUrlBar0.GetCurrentPattern(patterns0(0)), ValuePattern)
                            If Not elmUrlBar0.GetCurrentPropertyValue(AutomationElement.HasKeyboardFocusProperty) Then
                                Dim pvgc As String = LCase(val.Current.Value).Trim
                                If pvgc.ToString <> "" Then
                                    urls = pvgc.ToString
                                    MsgBox(urls)
                                End If
                            End If
                        End If
                    End If
                End If
            End If
        Next

    Catch ex As Exception
        MsgBox("Function AutomationElementData system error." + vbCr + vbCr + ex.ToString, vbExclamation)
    End Try
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Dim tmp1 As String = ""
        Dim strME As String = "Microsoft Edge"

    Try
        Dim conditions As Condition = Condition.TrueCondition
        Dim BaseElement As AutomationElement = AutomationElement.RootElement
        Dim elementCollection As AutomationElementCollection = BaseElement.FindAll(TreeScope.Children, conditions)
        Dim AE As AutomationElement

        For Each AE In elementCollection
            If AE IsNot Nothing Then
                tmp1 = AE.GetCurrentPropertyValue(AutomationElement.NameProperty).ToString
                If StrComp(Strings.Right(tmp1, strME.Length), strME, vbTextCompare) = 0 Then
                    Dim elmUrlBar0 As AutomationElement
                    elmUrlBar0 = AE.FindFirst(TreeScope.Subtree, New PropertyCondition(AutomationElement.AutomationIdProperty, "addressEditBox"))
                    If elmUrlBar0 IsNot Nothing Then
                        Dim patterns0 As AutomationPattern() = elmUrlBar0.GetSupportedPatterns()
                        If patterns0.Length > 0 Then
                            Dim val As ValuePattern = DirectCast(elmUrlBar0.GetCurrentPattern(patterns0(0)), ValuePattern)
                            If Not elmUrlBar0.GetCurrentPropertyValue(AutomationElement.HasKeyboardFocusProperty) Then
                                Dim pvgc As String = LCase(val.Current.Value).Trim
                                If pvgc.ToString <> "" Then
                                    urls = pvgc.ToString
                                    MsgBox(urls)
                                End If
                            End If
                        End If
                    End If
                End If
            End If
        Next

    Catch ex As Exception
        MsgBox("Function AutomationElementData system error." + vbCr + vbCr + ex.ToString, vbExclamation)
    End Try

ContentLicense: CC BY-SA 4.0


问:
Is there a way to increase the upload size of my zip file?
Zip files over 65mb won't upload to my database and file folder. The server allows 500MB and php allows 128MB

I have up the size of the file to determine how large the file can be before it stops working.

This is the form

           Enter Your Account Email:

          Upload File:

          upload

And this is the code to add the files. It works but stops at a certain size.

```<code> if (!in_array($extension, ['mp3', 'wma', 'wav', 'zip'])) {
    echo "Your file extension must be .mov, .wmv, .mp4 or .zip";
} elseif ($_FILES['myfile']['size'] > 100000000) { // file shouldn't be larger than 1Gigabyte
    echo "File too large!";
</code>```

To upload zip files at least 125MB

答:
first create .htaccess file and copy paste it in .htaccess file in your root directory.

When you make change on php configration through .htaccess you should put configrations in  IfModule tag,.

```<code><IfModule mod_php5.c>
   php_value upload_max_filesize 100M
   php_value post_max_size 100M
</IfModule>
</code>```

Body:
Zip files over 65mb won't upload to my database and file folder. The server allows 500MB and php allows 128MB

I have up the size of the file to determine how large the file can be before it stops working.

This is the form

           Enter Your Account Email:

          Upload File:

          upload

And this is the code to add the files. It works but stops at a certain size.

 if (!in_array($extension, ['mp3', 'wma', 'wav', 'zip'])) {
    echo "Your file extension must be .mov, .wmv, .mp4 or .zip";
} elseif ($_FILES['myfile']['size'] > 100000000) { // file shouldn't be larger than 1Gigabyte
    echo "File too large!";

To upload zip files at least 125MB

Body:
first create .htaccess file and copy paste it in .htaccess file in your root directory.

When you make change on php configration through .htaccess you should put configrations in  IfModule tag,.

<IfModule mod_php5.c>
   php_value upload_max_filesize 100M
   php_value post_max_size 100M
</IfModule>


问:
Trying to sum a joined subquery
For my sql class I am trying to write a query that sums a column in a sub query. The Sub query has a calculated value in it and I am trying to total that calculated value for particular zipcodes.
the query runs without errors but the output is null in the sum column

Tried running the sub query on its own and the value is calculated for the column properly

```<code>select c.CustomerState
,c.CustomerZip
,sum (b.TotalSales)as Sales
from [DBM460LearningTeam].[dbo].[TBLcustomer]as c
Left Join (select v.CustomerNumber
    ,sum (v.QuantitySold * i.ItemPrice) as TotalSales
    from TBLinvoice as v
    inner join TBLitem as i
    on v.ItemNumber = right(i.ItemNumber,3)
    group by v.CustomerNumber) as b
on c.CustomerNumber = b.CustomerNumber
group by c.CustomerZip , c.CustomerState;
</code>```

I want to sum the total sales by zipcode so i expect to see column for zipcode and column for state and column for sales  and thats what I get but the sales column is Null all the way down.

答: Your CustomerNumbers aren't lining up on your join on. I would verify that that part if you say you have a value for TotalSales when you just run the subquery. I bet if you changed that left join to an inner join you would get nothing. So you are getting all values from TBLCustomer but nothing matches on customernumber when you do the left join. </p>

Title: Trying to sum a joined subquery

Body:
For my sql class I am trying to write a query that sums a column in a sub query. The Sub query has a calculated value in it and I am trying to total that calculated value for particular zipcodes.
the query runs without errors but the output is null in the sum column

Tried running the sub query on its own and the value is calculated for the column properly

select c.CustomerState
,c.CustomerZip
,sum (b.TotalSales)as Sales
from [DBM460LearningTeam].[dbo].[TBLcustomer]as c
Left Join (select v.CustomerNumber
    ,sum (v.QuantitySold * i.ItemPrice) as TotalSales
    from TBLinvoice as v
    inner join TBLitem as i
    on v.ItemNumber = right(i.ItemNumber,3)
    group by v.CustomerNumber) as b
on c.CustomerNumber = b.CustomerNumber
group by c.CustomerZip , c.CustomerState;

I want to sum the total sales by zipcode so i expect to see column for zipcode and column for state and column for sales  and thats what I get but the sales column is Null all the way down.


问:
How to create an admin page to add/remove elements to a drop-down list?
I have a form in my website that's used to insert documents (has different privileges -Admin/User- ).

This form includes a drop-down list, the problem is that it needs to be edited by the admin to make more or less items in the drop down list.

This edit shouldn't be a code edit (which is absolutely easy)
but a form that allows the admin to add elements to drop-down list
I searched around and I didn't find an answer , I wish you could help me with this !

<?php
require_once("identification.php");
require_once('connexionDB.php');
$nom            = isset($_POST['nom']) ? $_POST['nom'] : "";
$pole           = isset($_POST['pole']) ? $_POST['pole'] : "";
$valideur       = isset($_POST['valideur']) ? $_POST['valideur'] : "";
$perimetre      = isset($_POST['perimetre']) ? $_POST['perimetre'] : "";
$direction      = isset($_POST['direction']) ? $_POST['direction'] : "";
$activite       = isset($_POST['activite']) ? $_POST['activite'] : "";
$version        = isset($_POST['version']) ? $_POST['version'] : "";
$type_doc       = isset($_POST['type_doc']) ? $_POST['type_doc'] : "";
$description    = isset($_POST['description']) ? $_POST['description'] : "";
$zone           = isset($_POST['zone']) ? $_POST['zone'] : "";
$langue         = isset($_POST['langue']) ? $_POST['langue'] : "";
$date           = isset($_POST['date']) ? $_POST['date'] : "";
$comm_sur_modif = isset($_POST['comm_sur_modif']) ? $_POST['comm_sur_modif'] : "";
$commentaire    = isset($_POST['commentaire']) ? $_POST['commentaire'] : "";
$auteur         = $_SESSION["fati"];

if (isset($_FILES['document']) and !empty($_FILES['document']['name'])) {
    $taillemax        = 4221225472;
    $extensionvalides = ['pdf', 'docx'];
    if ($_FILES['document']['size'] <= $taillemax) {
        $extensionUpload = strtolower(substr(strrchr($_FILES['document']['name'], '.'), 1));
        if (in_array($extensionUpload, $extensionvalides)) {
            $chemain = "doc/" . $nom . "." . $extensionUpload;

            $resultat = move_uploaded_file($_FILES['document']['tmp_name'], $chemain);

            if ($resultat) {
                $requete  = "insert into document(nom,direction,pole,activite,version,type_doc,description,zone,perimetre,langue,chemin,auteur,date,comm_sur_modif,commentaire) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                $params   = [
                    $nom,
                    $direction,
                    $pole,
                    $activite,
                    $version,
                    $type_doc,
                    $description,
                    $zone,
                    $perimetre,
                    $langue,
                    "doc/" . $nom . "." . $extensionUpload,
                    $auteur,
                    $date,
                    $comm_sur_modif,
                    $commentaire,
                ];
                $resultat = $pdo->prepare($requete);
                $resultat->execute($params);
                header("location:documents.php");
            }
        }
    }
}```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="form-group">
    <label for="type_doc">type de document  </label>
    </br>
    <select name="type_doc" id="type_doc">
        <option value="NA">N/A</option>
        <option  value="guide_de_conception">guide de conception</option>
        <option  value="standard_rt">standard et RT</option>
        <option  value="methodologies">methodologies</option>
        <option  value="processus">processus</option>
        <option  value="retex_capitalisation">retex et  capitalisation</option>
        <option  value="normes_reglementations">normes reglementations</option>
        <option  value="cdc">CDC</option>
        <option  value="essais_plans_validation">essais et plans de validation</option>
    </select>
</div></code>```

答:
Overview:

You need to store the list of desired fields somewhere. You cannot store them in LocalStorage or in cookies - those would be stored locally on the admin's computer (so how would a user see those changes?). You need a central location: the webserver. This gives you two choices: (a) a file on the webserver, or in a MySQL (now called MariaDB) database table. I suggest (b).

In order to read/write to a file on the webserver -- or to add/delete/read from a database on the webserver -- you need to write some server-side code. MOST webservers have PHP available as a back-end language, but Microsoft servers use ASP .Net. There is now also the choice to install/use node.js (if you want to use javascript as your back-end server language). As mentioned, PHP is hugely popular and there are somewhere around a gazillion blog and YouTube tutorials showing how to do this.

Using PHP as the example, you will rename your index.html to index.php - just do that. Nothing that currently exists will be affected - but now you can embed sections of PHP code and the server will run that code before rendering/displaying the HTML. (Note that nothing else changes when you rename the file extension. Provided you are on an apache web server - and most are - you need never use the .html extension ever again. Try it.)

Your index.php will now begin with a snippet of PHP code that tells it to (a) login to the database, (b) read that value from the table, (c) store the value in a variable. It is now patently easy to schlep that data into the HTML as the page is being rendered.

You will need a page that only the admin can access. Again, using a back-end language will allow your admin page (HTML) to request a username and password, and then run some back-end code to check the info stored on the webserver (again, either in a file or in a database table), to see if the username/password is correct.

Your admin page, after logging in, will:

As in step (4) above, read the database table to get the current settings for user-level choices for the drop-down, then display those choices on the screen. You will also need a method of adding new options for the drop down, and a button to signify that the changes are done. Once pressed, the page will send that data back to the webserver to store back in the table, over-writing what was there before.

There are two ways to send data from an HTML page to the webserver: (a) <form></form> and (b) AJAX. By all means, use AJAX - forms are more restricted, way less elegant, and require that the page is refreshed or changed. Forms are 1999, AJAX is 2019.

AJAX, written in javascript/jQuery, lets you (a) detect a button click; (b) collect the data from the input fields; (c) send that data to a PHP file on the webserver; (d) receive a message (from the webserver, after it has finished adding the data to the table) back on the HTML side; (e) update the page smoothly and without refreshing anything. With AJAX, you (as the developer) retain complete control from beginning to end, comme il faut.

There are gazillions of YouTube and blog tutorials on how to do all of this in PHP and jQuery. Enjoy!

Here's are a couple:

https://www.youtube.com/watch?v=aujNp92p0Uc

https://www.youtube.com/watch?v=gvGb5Z0yMFY

Body:
I have a form in my website that's used to insert documents (has different privileges -Admin/User- ).

This form includes a drop-down list, the problem is that it needs to be edited by the admin to make more or less items in the drop down list.

This edit shouldn't be a code edit (which is absolutely easy)
but a form that allows the admin to add elements to drop-down list
I searched around and I didn't find an answer , I wish you could help me with this !

<?php
require_once("identification.php");
require_once('connexionDB.php');
$nom            = isset($_POST['nom']) ? $_POST['nom'] : "";
$pole           = isset($_POST['pole']) ? $_POST['pole'] : "";
$valideur       = isset($_POST['valideur']) ? $_POST['valideur'] : "";
$perimetre      = isset($_POST['perimetre']) ? $_POST['perimetre'] : "";
$direction      = isset($_POST['direction']) ? $_POST['direction'] : "";
$activite       = isset($_POST['activite']) ? $_POST['activite'] : "";
$version        = isset($_POST['version']) ? $_POST['version'] : "";
$type_doc       = isset($_POST['type_doc']) ? $_POST['type_doc'] : "";
$description    = isset($_POST['description']) ? $_POST['description'] : "";
$zone           = isset($_POST['zone']) ? $_POST['zone'] : "";
$langue         = isset($_POST['langue']) ? $_POST['langue'] : "";
$date           = isset($_POST['date']) ? $_POST['date'] : "";
$comm_sur_modif = isset($_POST['comm_sur_modif']) ? $_POST['comm_sur_modif'] : "";
$commentaire    = isset($_POST['commentaire']) ? $_POST['commentaire'] : "";
$auteur         = $_SESSION["fati"];

if (isset($_FILES['document']) and !empty($_FILES['document']['name'])) {
    $taillemax        = 4221225472;
    $extensionvalides = ['pdf', 'docx'];
    if ($_FILES['document']['size'] <= $taillemax) {
        $extensionUpload = strtolower(substr(strrchr($_FILES['document']['name'], '.'), 1));
        if (in_array($extensionUpload, $extensionvalides)) {
            $chemain = "doc/" . $nom . "." . $extensionUpload;

            $resultat = move_uploaded_file($_FILES['document']['tmp_name'], $chemain);

            if ($resultat) {
                $requete  = "insert into document(nom,direction,pole,activite,version,type_doc,description,zone,perimetre,langue,chemin,auteur,date,comm_sur_modif,commentaire) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                $params   = [
                    $nom,
                    $direction,
                    $pole,
                    $activite,
                    $version,
                    $type_doc,
                    $description,
                    $zone,
                    $perimetre,
                    $langue,
                    "doc/" . $nom . "." . $extensionUpload,
                    $auteur,
                    $date,
                    $comm_sur_modif,
                    $commentaire,
                ];
                $resultat = $pdo->prepare($requete);
                $resultat->execute($params);
                header("location:documents.php");
            }
        }
    }
}

    type de document

    <select name="type_doc" id="type_doc">
        <option value="NA">N/A</option>
        <option  value="guide_de_conception">guide de conception</option>
        <option  value="standard_rt">standard et RT</option>
        <option  value="methodologies">methodologies</option>
        <option  value="processus">processus</option>
        <option  value="retex_capitalisation">retex et  capitalisation</option>
        <option  value="normes_reglementations">normes reglementations</option>
        <option  value="cdc">CDC</option>
        <option  value="essais_plans_validation">essais et plans de validation</option>
    </select>


问:
split a list to several nested lists based on "2 consecutive" entries
My question is semi-answered in
Python split for lists page. However, I need to split based on TWO consecutive components (not one component). And the code is in Python.
For example:

```<code>list = ["id","title","data","more data","id","title","data 2","more data 2","danger","id","title","date3","lll"]
</code>```

and I want the following outcome:

```<code>new_list = [["id","title","data","more data"],["id","title","data 2","more data 2","danger"],["id","title","date3","lll"]]
</code>```

Please help.

答:
you could do this in segments. First off, find all the indexes of 'id' where the following item is 'title'

lst = ["id","title","data","more data","id","title","data 2","more data 2","danger","id","title","date3","lll"]
lst_len = len(lst)
indexes = [i for i, v in enumerate(lst) if v=='id' and i+1 < lst_len and lst[i+1]=='title']
```

<p>Then iterate over them as pairs and split appropriately.</p>

<pre class="lang-py prettyprint-override"><code>import itertools

# from itertools recipes
def pairwise(iterable, fillvalue=None):
    a, b = iter(iterable), iter(iterable)
    next(b, None)
    return itertools.zip_longest(a, b, fillvalue=fillvalue)

result = [lst[i:j] for i,j in pairwise(indexes)]
</code>```

>>> result
[['id', 'title', 'data', 'more data'], ['id', 'title', 'data 2', 'more data 2', 'danger'], ['id', 'title', 'date3', 'lll']]
```

<hr>

<p>You could use that pairwise iterator to more quickly find the indexes, too.</p>

<pre class="lang-py prettyprint-override"><code>indexes = [i for i, (a, b) in enumerate(pairwise(lst)) if a=='id' and b=='title']
</code>```

Body:
My question is semi-answered in
Python split for lists page. However, I need to split based on TWO consecutive components (not one component). And the code is in Python.
For example:

list = ["id","title","data","more data","id","title","data 2","more data 2","danger","id","title","date3","lll"]

and I want the following outcome:

new_list = [["id","title","data","more data"],["id","title","data 2","more data 2","danger"],["id","title","date3","lll"]]

Please help.

Body:
you could do this in segments. First off, find all the indexes of 'id' where the following item is 'title'

lst = ["id","title","data","more data","id","title","data 2","more data 2","danger","id","title","date3","lll"]
lst_len = len(lst)
indexes = [i for i, v in enumerate(lst) if v=='id' and i+1 < lst_len and lst[i+1]=='title']

Then iterate over them as pairs and split appropriately.

import itertools

# from itertools recipes
def pairwise(iterable, fillvalue=None):
    a, b = iter(iterable), iter(iterable)
    next(b, None)
    return itertools.zip_longest(a, b, fillvalue=fillvalue)

result = [lst[i:j] for i,j in pairwise(indexes)]

>>> result
[['id', 'title', 'data', 'more data'], ['id', 'title', 'data 2', 'more data 2', 'danger'], ['id', 'title', 'date3', 'lll']]

You could use that pairwise iterator to more quickly find the indexes, too.

indexes = [i for i, (a, b) in enumerate(pairwise(lst)) if a=='id' and b=='title']


问:
Table Component is not re-rendered after state update
i'm having a table component for displaying some data. After dispatching an action the table data in the state are channging. However my table component is not updated. It is updated only when i click on another radio button in another row of my table. I want my component to rerender when the data are changed. Here is my code:

```<code>const mapStateToProps = state => ({
  evaluationData: evaluationResultsSelector(state)
});

const mapDispatchToProps = dispatch => ({
  setSelectedEvaluationRecord: record =>
    dispatch(setSelectedEvaluationRecord(record))
});

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

and my component is this:

```<code>import React from 'react';
import Table from 'antd/lib/table';
import 'antd/lib/table/style/css';
import "antd/dist/antd.css";
import { columnEvaluation } from './evaluationDataStructure';

class EvaluationDataTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedRowKeys: [0], // Check here to configure the default column
    };
  }
  // shouldComponentUpdate(prevProps, prevState) {
  //   return (prevProps.results !== this.props.results || prevState.selectedRowKeys !== this.state.selectedRowKeys);
  // }
  onRowChange = selectedRowKeys => {
    if (selectedRowKeys.length > 1) {
      const lastSelectedRowIndex = [...selectedRowKeys].pop();
      this.setState({ selectedRowKeys: lastSelectedRowIndex });
    }
    this.setState({ selectedRowKeys });
  };

  onRowSelect = (record) => {
    this.props.setSelectedEvaluationRecord(record)
  };

  render() {
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      type: 'radio',
      selectedRowKeys,
      onChange: this.onRowChange,
      onSelect: this.onRowSelect
    };
    return (
      <React.Fragment>
        <div style={{ marginBottom: 16 }} />
        <Table
          rowSelection={rowSelection}
          columns={columnEvaluation}
          dataSource={this.props.evaluationData}
        />
      </React.Fragment>
    );
  }
}

export default EvaluationDataTable;
</code>```

When i click in another row the table is rerendered as my setState is triggered but when the data are channged the table is not rerendered. Only when i click in another row. How to deal with it? Thanks a lot

Also my reducer which mutates the table is this:

```<code>case ACTION_TYPES.EDIT_EVALUATION_RESULTS: {
      const evaluationResults = state.evaluationResults;
      const editedRecord = action.payload.editedEvaluationData;
      evaluationResults.forEach((item, i)  => {
        if (item.id === editedRecord.id) {
          evaluationResults[i] = editedRecord;
        }
      });
      return {
        ...state,
        evaluationResults
      };
    }
</code>```

答:
Problem was here as OP has already deduced.

```<code> const evaluationResults = state.evaluationResults;
</code>```

This was causing a state-mutation which goes against Redux principles. Although the state values were being updated in OP's proceeding code, the changes were being made to the same, initial object in reference. Redux does not register it as a new-state so it found no need to re-render our component. To get your connected-component to re-render we need a completely new redux-state.

To achieve this, we need to create a brand-new copy of evaluationResults like so and then the OP's feature will work as expected:

```<code>const evaluationResults = [...state.evaluationResults];
</code>```

Body:
i'm having a table component for displaying some data. After dispatching an action the table data in the state are channging. However my table component is not updated. It is updated only when i click on another radio button in another row of my table. I want my component to rerender when the data are changed. Here is my code:

const mapStateToProps = state => ({
  evaluationData: evaluationResultsSelector(state)
});

const mapDispatchToProps = dispatch => ({
  setSelectedEvaluationRecord: record =>
    dispatch(setSelectedEvaluationRecord(record))
});

export default connect(mapStateToProps,
  mapDispatchToProps
  EvaluationDataTable,
);

and my component is this:

import React from 'react';
import Table from 'antd/lib/table';
import 'antd/lib/table/style/css';
import "antd/dist/antd.css";
import { columnEvaluation } from './evaluationDataStructure';

class EvaluationDataTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedRowKeys: [0], // Check here to configure the default column
    };
  }
  // shouldComponentUpdate(prevProps, prevState) {
  //   return (prevProps.results !== this.props.results || prevState.selectedRowKeys !== this.state.selectedRowKeys);
  // }
  onRowChange = selectedRowKeys => {
    if (selectedRowKeys.length > 1) {
      const lastSelectedRowIndex = [...selectedRowKeys].pop();
      this.setState({ selectedRowKeys: lastSelectedRowIndex });
    }
    this.setState({ selectedRowKeys });
  };

  onRowSelect = (record) => {
    this.props.setSelectedEvaluationRecord(record)
  };

  render() {
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      type: 'radio',
      selectedRowKeys,
      onChange: this.onRowChange,
      onSelect: this.onRowSelect
    };
    return (
      <React.Fragment>

      </React.Fragment>
    );
  }
}

export default EvaluationDataTable;

When i click in another row the table is rerendered as my setState is triggered but when the data are channged the table is not rerendered. Only when i click in another row. How to deal with it? Thanks a lot

Also my reducer which mutates the table is this:

case ACTION_TYPES.EDIT_EVALUATION_RESULTS: {
      const evaluationResults = state.evaluationResults;
      const editedRecord = action.payload.editedEvaluationData;
      evaluationResults.forEach((item, i)  => {
        if (item.id === editedRecord.id) {
          evaluationResults[i] = editedRecord;
        }
      });
      return {
        ...state,
        evaluationResults
      };
    }

Body:
Problem was here as OP has already deduced.

 const evaluationResults = state.evaluationResults;

This was causing a state-mutation which goes against Redux principles. Although the state values were being updated in OP's proceeding code, the changes were being made to the same, initial object in reference. Redux does not register it as a new-state so it found no need to re-render our component. To get your connected-component to re-render we need a completely new redux-state.

To achieve this, we need to create a brand-new copy of evaluationResults like so and then the OP's feature will work as expected:

const evaluationResults = [...state.evaluationResults];


问:
Select last element without a class
I'm dynamically adding and removing classes to and from elements on specific JS events. What I would like to do is select the last child element that has none these classes with CSS.

Example #1

```<code><container-element>
  <h2></h2>
  <div class='some-class'></div>
  <div></div>
  <div></div> <!-- select this div -->
</container-element>
</code>```

Example #2

```<code><container-element>
  <h2></h2>
  <div></div>
  <div></div> <!-- select this div -->
  <div class='some-class'></div>
</container-element>
</code>```

Is it possible to write a CSS selector to do this?

Something like container-element > div:not(.select):last-of-type?

答:
You're saying: select the last sibling that doesn't contain a class attribute.

I don't believe it's possible with currently available CSS.

You're asking a waterfall (the cascade) to run upward. The browser needs to check the last element, then check the ones that came before it. This is not how CSS works.

div:not(.some-class):last-of-type won't work because the browser doesn't move up automatically to the next sibling.

Title: Select last element without a class

Body:
I'm dynamically adding and removing classes to and from elements on specific JS events. What I would like to do is select the last child element that has none these classes with CSS.

Example #1

<container-element>

</container-element>

Example #2

<container-element>

</container-element>

Is it possible to write a CSS selector to do this?

Something like container-element > div:not(.select):last-of-type?


问:
How to return Console.Write output as a string in unit test?
I have the following code that returns an output of "AAlAleAlex" with the following code:

```<code>string s = "Alex";

        for (int i = 0; i < s.Length; i++)
        {
            for (int j = 0; j <= i; j++)
            {
                char start = s[j];

                Console.Write("{0}", start);
            }
        }
</code>```

However, I want to get the output of the Console.Write into a string and return it, but the only thing that I could come up with is this, but it only returns the first letter for some reason. How could I return a valid string?

Unit:

```<code>public string FunnyName(string firstName)
    {
        for (int i = 0; i < firstName.Length; i++)
        {
            for (int j = 0; j <= i; )
            {
                char start = firstName[j];

                //Console.Write("{0}", start);
                firstName = String.Format("{0}", start);
                return firstName;
            }
        }
        return firstName;
    }
</code>```

UnitTest:

```<code>[TestCase("Alex", "AAlAleAlex")]
    public void FunnyName(string firstName, string expected)
    {
        var actual = warmups.FunnyName(firstName);
        Assert.AreEqual(expected, actual);
    }
</code>```

答:
A little hard to follow your question, but I think you want this maybe??</p>

```<code>public string FunnyName(string firstName)
{
    var s = new System.Text.StringBuilder();

    for (int i = 0; i < firstName.Length; i++)
        for (int j = 0; j <= i; j++)
            s.Append(firstName[j]);

    return s.ToString();
}
</code>```

Body:
I have the following code that returns an output of "AAlAleAlex" with the following code:

string s = "Alex";

        for (int i = 0; i < s.Length; i++)
        {
            for (int j = 0; j <= i; j++)
            {
                char start = s[j];

                Console.Write("{0}", start);
            }
        }

However, I want to get the output of the Console.Write into a string and return it, but the only thing that I could come up with is this, but it only returns the first letter for some reason. How could I return a valid string?

Unit:

public string FunnyName(string firstName)
    {
        for (int i = 0; i < firstName.Length; i++)
        {
            for (int j = 0; j <= i; )
            {
                char start = firstName[j];

                //Console.Write("{0}", start);
                firstName = String.Format("{0}", start);
                return firstName;
            }
        }
        return firstName;
    }

UnitTest:

[TestCase("Alex", "AAlAleAlex")]
    public void FunnyName(string firstName, string expected)
    {
        var actual = warmups.FunnyName(firstName);
        Assert.AreEqual(expected, actual);
    }

Body:
A little hard to follow your question, but I think you want this maybe??

public string FunnyName(string firstName)
{
    var s = new System.Text.StringBuilder();

    for (int i = 0; i < firstName.Length; i++)
        for (int j = 0; j <= i; j++)
            s.Append(firstName[j]);

    return s.ToString();
}


问:
extending Function
I've been seeing the syntax:

```<code>var module = {

    func: function(value) {

        some code;

    }.func2("value");

}
</code>```

cropping up in various places, as am wondering how this is done. I remember seeing an article about it a while back, but can't find it now. Whatever I try .func2("value") just trows syntax errors.

For example, take a look at SproutCore's intro to their TemplateView.

```<code>Todos.StatsView = SC.TemplateView.extend({
  remainingBinding: 'Todos.todoListController.remaining',

  displayRemaining: function() {
    var remaining = this.get('remaining');
    return remaining + (remaining === 1 ? " item" : " items");
  }.property('remaining').cacheable()
});
</code>```

Seems like it would be a useful tool to give users when writing factories.

Thanks.

答:
that's kind'a weird.Maby is was something like :

```<code>var module = {
    func : (function(){
        return {func2 : function(v){alert(v);}};
    }).func2('alert me');
}
</code>```

you cannot chain function definitions (function func (){}.func1()),only function calls (if configured properly) that would look like : func1().func2().func3().....

Title: extending Function

Body:
I've been seeing the syntax:

var module = {

    func: function(value) {

        some code;

    }.func2("value");

}

cropping up in various places, as am wondering how this is done. I remember seeing an article about it a while back, but can't find it now. Whatever I try .func2("value") just trows syntax errors.

For example, take a look at SproutCore's intro to their TemplateView.

Todos.StatsView = SC.TemplateView.extend({
  remainingBinding: 'Todos.todoListController.remaining',

  displayRemaining: function() {
    var remaining = this.get('remaining');
    return remaining + (remaining === 1 ? " item" : " items");
  }.property('remaining').cacheable()
});

Seems like it would be a useful tool to give users when writing factories.

Thanks.

Body:
that's kind'a weird.Maby is was something like :

var module = {
    func : (function(){
        return {func2 : function(v){alert(v);}};
    }).func2('alert me');
}

you cannot chain function definitions (function func (){}.func1()),only function calls (if configured properly) that would look like : func1().func2().func3().....


问:
Eclipse: full rebuild triggered
I'd like to get some information to debug a problem I am having, being that Eclipse rebuilds everything in my open Java-only project instead of just recompiling incrementally. Not restarting Eclipse or anything, just saving a file or whatever.

What exact conditions in Eclipse triggers a full rebuild? Seems to be sometimes when you rename or move compilation units, and sometimes this persists even after the first full rebuild after the move/rename.

Is there any way to get Eclipse to show the reason it is rebuilding? Maybe there is some logging that could provide useful information?

Sometimes the problem goes away on its own after a few bouts, sometimes after some indeterminate combination of: closing the project, cleaning the project, quitting the Eclipse app, touching the .classpath file.

Automatic rebuild is not turned on.

Similar questions below.

Why does Eclipse sometimes rebuild the whole workspace?

Note: 'After I start Eclipse ...'

Prevent full project clean / rebuild in Eclipse

No answers.

Eclipse: can I keep progress dialog from blocking UI somehow?

Me earlier, trying to mitigate some of the impact.

答:
Update 2: well it's been beach-balling again a few times. But this seems to work, (ie has worked twice in a row for me now), and seems to make sense:

Start build, but cancel somewhere in the middle. Then start build again.

The idea being that if a build starts in the bad state, there's a good chance that it ends in the bad state again, for whatever reasons. But cancelling in the middle might stop it from ending in the bad state. So we can restart the build in a better state.

Original: I think I figured it out. There is an error message with a stack trace,
containing a DirectoryNotEmptyException. I suspect that under some conditions, a ".DSStore" file (a Finder/OSX/macOS hack) may stop the build process from deleting a directory in the target tree. This doesn't explain why it sometimes resolves itself, but maybe it's a timing issue. I think I one could make a script to find and delete all ".DSStore" files when this happens.

Update: the issue resurfaced, badly. Clean, close project, restart Eclipse, no avail. However, deleting target/classes worked in the end. (Weird, doesn't 'clean' do that? Deleting was slow as _, maybe that's why? I'll do a 'mv target/classes trash/' or something next time instead, see if that's ok with Eclipse). This note be useful to some fellow Eclipse user. Or myself, sadly :).

Title: Eclipse: full rebuild triggered


问:
Mapping over an array and returning API result
Trying a simple code to map over an array and, for each result, search an API for that result and spit out data retrieved from the API.

import React from 'react';

const App = () => {

  let artistData = require('./mass-artists.json')

  artistData.map(
    (theArtist) => {
        fetch(`[url]https://api.scryfall.com/cards/search?q=a:[/url]"${theArtist}"`)
            .then((response) => {
              return response.json();
            })
            .then((myJson) => {
              console.log(JSON.stringify(myJson)); //returns the JSON data, so I know it's working
              console.log(myJson.data[0].name); //returns the first card name
            })
    }
  )

  return(This is here so React doesn't yell at me about no return statement.)
}

export default App;
```

The JSON file is just a list of names of Magic artists. The map maps over the list of artists and searches on the API for them. I want to do the usual thing I do with the map, i.e. display something on the front-end. But I'm having trouble getting anything to work. I can log things to the console or do any Javascript function such as setting something's innerHTML, but where/how would I put a return statement to show the result in, say, a span tag? Even such as "Hello!".

Thanks as always!

答:
I recommend looking into either the new hooks api or old Class components in react if you need more help with state. The following code will search for the data and then set state so that the component will know to update.
You also probably don't want to run that map directly in render because that will rerun your fetches each time the component updates. </p>

```<code>import React, { useState, useEffect } from "react";

const App = () => {
  const [artistsInfo, setArtistsInfo] = useState([]);

  useEffect(async () => {
    let artistData = require("./mass-artists.json");

    const promises = artistData.map(theArtist => {
      return fetch(
        `[url]https://api.scryfall.com/cards/search?q=a:[/url]"${theArtist}"`
      )
        .then(response => {
          return response.json();
        })
        .then(myJson => {
          return myJson.data;
        });
    });
    const results = await Promise.all(promises);
    // results is an array of arrays because that is what your data seemed to be
    // you could use lodash flatten if you want to get a single array

    setArtistsInfo(results);
  }, []); // empty array so it only runs once

  // you could have a second useState to add a loader if you want

  return artistsInfo.map(infoArray => {
    return infoArray.map(singleInfo => {
      return <span key={singleInfo.id}>{singleInfo.name}</span>;
    });
  });
};

export default App;
</code>```

Body:
Trying a simple code to map over an array and, for each result, search an API for that result and spit out data retrieved from the API.

import React from 'react';

const App = () => {

  let artistData = require('./mass-artists.json')

  artistData.map(
    (theArtist) => {
        fetch(`[url]https://api.scryfall.com/cards/search?q=a:[/url]"${theArtist}"`)
            .then((response) => {
              return response.json();
            })
            .then((myJson) => {
              console.log(JSON.stringify(myJson)); //returns the JSON data, so I know it's working
              console.log(myJson.data[0].name); //returns the first card name
            })
    }
  )

  return(This is here so React doesn't yell at me about no return statement.)
}

export default App;

The JSON file is just a list of names of Magic artists. The map maps over the list of artists and searches on the API for them. I want to do the usual thing I do with the map, i.e. display something on the front-end. But I'm having trouble getting anything to work. I can log things to the console or do any Javascript function such as setting something's innerHTML, but where/how would I put a return statement to show the result in, say, a span tag? Even such as "Hello!".

Thanks as always!

Body:
I recommend looking into either the new hooks api or old Class components in react if you need more help with state. The following code will search for the data and then set state so that the component will know to update.
You also probably don't want to run that map directly in render because that will rerun your fetches each time the component updates.

import React, { useState, useEffect } from "react";

const App = () => {
  const [artistsInfo, setArtistsInfo] = useState([]);

  useEffect(async () => {
    let artistData = require("./mass-artists.json");

    const promises = artistData.map(theArtist => {
      return fetch(
        `[url]https://api.scryfall.com/cards/search?q=a:[/url]"${theArtist}"`
      )
        .then(response => {
          return response.json();
        })
        .then(myJson => {
          return myJson.data;
        });
    });
    const results = await Promise.all(promises);
    // results is an array of arrays because that is what your data seemed to be
    // you could use lodash flatten if you want to get a single array

    setArtistsInfo(results);
  }, []); // empty array so it only runs once

  // you could have a second useState to add a loader if you want

  return artistsInfo.map(infoArray => {
    return infoArray.map(singleInfo => {
      return <span key={singleInfo.id}>{singleInfo.name}</span>;
    });
  });
};

export default App;


问:
count function mechanism in laravel
suppose we have this code

result of count() function is about each query or after queries
executes then count function return result ?

```<code>$model=Model::query()

foreach ($Entities as $entity) {
               $model->orWhereBetween("id",$entity->first_id,$entity->last_id])
         }
$model->count()
</code>```

答:
```<code>$model=Model::query()

    foreach ($Entities as $entity) {
        $model->orWhereBetween("id",$entity->first_id,$entity->last_id])
    }

//$model - object of query builder
$model->count();
</code>```

It will generate one query and calculate on the db side: SELECT COUNT(*) FROM table WHERE id BETWEEN ? AND ? OR id BETWEEN ? AND ? OR id BETWEEN ? AND ?

Title: count function mechanism in laravel

Body:
suppose we have this code

result of count() function is about each query or after queries
executes then count function return result ?

$model=Model::query()

foreach ($Entities as $entity) {
               $model->orWhereBetween("id",$entity->first_id,$entity->last_id])
         }
$model->count()

Body:
$model=Model::query()

    foreach ($Entities as $entity) {
        $model->orWhereBetween("id",$entity->first_id,$entity->last_id])
    }

//$model - object of query builder
$model->count();

It will generate one query and calculate on the db side: SELECT COUNT(*) FROM table WHERE id BETWEEN ? AND ? OR id BETWEEN ? AND ? OR id BETWEEN ? AND ?


问:
Socket fix error TypeError: an integer is required
I have to
 Connect to alien server ('localhost', 10000),
Then send USER followed by aliensignal

But I get an error message that's mean that the format of my .send is incorrecte.
Do you know what's the good way to send two differents string in one .send?

import socket
clientsocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
clientsocket.connect (('localhost', 10000))
clientsocket.send('USER:','aliensignal')

Traceback (most recent call last):
File "/tmp/usercode.py", line 15, in <module>
clientsocket.send('USER:','aliensignal')
TypeError: an integer is required
```

答:
send only takes a string and option integer flags that normally aren't used.  TCP is just a byte stream and there are no message boundaries.  The protocol for what makes a complete message must be defined.  Your alien server needs to be a bit more specific.

You can do:

```<code>clientsocket.send(b'USER:aliensignal')
</code>```

but you can also do variations of the following.  The bytes are just entered into the transmit buffer in the same order.

```<code>clientsocket.send(b'USE')
clientsocket.send(b'R:a')
clientsocket.send(b'liens')
clientsocket.send(b'ignal')
</code>```

So how does alien server know you've sent a complete message?  Here are some possible ways:

Close the client connection.  The server can keep reading bytes until it recv returns 0, which means the client closed the connection.

Use a delimiter.  Send a newline \n character at the end of the message.  The server can read until it finds a newline and know that it has the complete message.  If it reads beyond the newline, it can save the excess as part of the next incoming message.

Send the length in bytes of the message, then the message.  send(b'\x16User:aliensignal') for example.  For longer messages, the protocol can agree on the length and endianness of the message, e.g. 32-bit (4-byte) big-endian length.

Body:
send only takes a string and option integer flags that normally aren't used.  TCP is just a byte stream and there are no message boundaries.  The protocol for what makes a complete message must be defined.  Your alien server needs to be a bit more specific.

You can do:

clientsocket.send(b'USER:aliensignal')

but you can also do variations of the following.  The bytes are just entered into the transmit buffer in the same order.

clientsocket.send(b'USE')
clientsocket.send(b'R:a')
clientsocket.send(b'liens')
clientsocket.send(b'ignal')

So how does alien server know you've sent a complete message?  Here are some possible ways:

Close the client connection.  The server can keep reading bytes until it recv returns 0, which means the client closed the connection.

Use a delimiter.  Send a newline \n character at the end of the message.  The server can read until it finds a newline and know that it has the complete message.  If it reads beyond the newline, it can save the excess as part of the next incoming message.

Send the length in bytes of the message, then the message.  send(b'\x16User:aliensignal') for example.  For longer messages, the protocol can agree on the length and endianness of the message, e.g. 32-bit (4-byte) big-endian length.


问:
Warning messages keep appearing in RStudio notebooks in chunks unrelated to the warnings
I am starting to use RStudio notebooks, and I am still trying to understand how some of the things work.
I do not understand why some produced warning messages are kept and appear when executing code that is completely unrelated to the message. For instance, I have a document with several chunks, where the last of them produces the warning

```<code>> warnings()
Warning messages:
1: Unknown or uninitialised column: 'perc.goal.met.period'.
2: Unknown or uninitialised column: 'perc.goal.met.period'.
3: Unknown or uninitialised column: 'perc.goal.met.period'.
4: Unknown or uninitialised column: 'perc.goal.met.period'.
5: Unknown or uninitialised column: 'perc.goal.met.period'.
6: Unknown or uninitialised column: 'perc.goal.met.period'.
7: Unknown or uninitialised column: 'perc.goal.met.period'.
8: Unknown or uninitialised column: 'perc.goal.met.period'.
9: Unknown or uninitialised column: 'perc.goal.met.period'.
10: Unknown or uninitialised column: 'perc.goal.met.period'.
11: Unknown or uninitialised column: 'perc.goal.met.period'.
12: Unknown or uninitialised column: 'perc.goal.met.period'.
13: Unknown or uninitialised column: 'perc.goal.met.period'.
14: Unknown or uninitialised column: 'perc.goal.met.period'.
15: Unknown or uninitialised column: 'perc.goal.met.period'.
16: Unknown or uninitialised column: 'perc.goal.met.period'.
17: Unknown or uninitialised column: 'perc.goal.met.period'.
18: Unknown or uninitialised column: 'perc.goal.met.period'.
19: Unknown or uninitialised column: 'perc.goal.met.period'.
20: Unknown or uninitialised column: 'perc.goal.met.period'.
21: Unknown or uninitialised column: 'perc.goal.met.period'.
22: Unknown or uninitialised column: 'perc.goal.met.period'.
23: Unknown or uninitialised column: 'perc.goal.met.period'.
24: Unknown or uninitialised column: 'perc.goal.met.period'.
25: Unknown or uninitialised column: 'perc.goal.met.period'.
26: Unknown or uninitialised column: 'perc.goal.met.period'.
27: Unknown or uninitialised column: 'perc.goal.met.period'.
28: Unknown or uninitialised column: 'perc.goal.met.period'.
29: Unknown or uninitialised column: 'perc.goal.met.period'.
30: Unknown or uninitialised column: 'perc.goal.met.period'.
There were 30 warnings (use warnings() to see them)
</code>```

I am ok with that warning. But later, I thought I would load one additional library to the first of the chunks (where I load them). After running that chunk, I get:

```<code>```{r echo=F, message=F, warnings=F, include=F}
# Load libraries
library(rgdal)
library(raster)
library(openxlsx)
library(tidyverse)
library(dplyr)
library(magrittr)
library(ggplot2)
library(rasterVis)
```
There were 30 warnings (use warnings() to see them)
</code>```

If I see the warnings, they are those I printed before.
Why am I seeing them here? I am seeing this also in other chunks also unrelated to the variable perc.goal.met.period. If I see the warnings, they will stop appearing for a while, but at a moment that I am still not able to anticipate, they will eventually reappear at some point.

Is there a logical explanation for this behaviour? Thanks a lot for your help!

答: My experience is that this occurs in RStudio while my code still has the error, even if this is not run (for example, when I leave some wrong code to be revised later). When I delete, change or convert into comments the relevant lines, this behavior ends. I guess that this is caused by the RStudio interpreter. It would be interesting to know if people using base R have the same problem. </p>

Body:
I am starting to use RStudio notebooks, and I am still trying to understand how some of the things work.
I do not understand why some produced warning messages are kept and appear when executing code that is completely unrelated to the message. For instance, I have a document with several chunks, where the last of them produces the warning

> warnings()
Warning messages:
1: Unknown or uninitialised column: 'perc.goal.met.period'.
2: Unknown or uninitialised column: 'perc.goal.met.period'.
3: Unknown or uninitialised column: 'perc.goal.met.period'.
4: Unknown or uninitialised column: 'perc.goal.met.period'.
5: Unknown or uninitialised column: 'perc.goal.met.period'.
6: Unknown or uninitialised column: 'perc.goal.met.period'.
7: Unknown or uninitialised column: 'perc.goal.met.period'.
8: Unknown or uninitialised column: 'perc.goal.met.period'.
9: Unknown or uninitialised column: 'perc.goal.met.period'.
10: Unknown or uninitialised column: 'perc.goal.met.period'.
11: Unknown or uninitialised column: 'perc.goal.met.period'.
12: Unknown or uninitialised column: 'perc.goal.met.period'.
13: Unknown or uninitialised column: 'perc.goal.met.period'.
14: Unknown or uninitialised column: 'perc.goal.met.period'.
15: Unknown or uninitialised column: 'perc.goal.met.period'.
16: Unknown or uninitialised column: 'perc.goal.met.period'.
17: Unknown or uninitialised column: 'perc.goal.met.period'.
18: Unknown or uninitialised column: 'perc.goal.met.period'.
19: Unknown or uninitialised column: 'perc.goal.met.period'.
20: Unknown or uninitialised column: 'perc.goal.met.period'.
21: Unknown or uninitialised column: 'perc.goal.met.period'.
22: Unknown or uninitialised column: 'perc.goal.met.period'.
23: Unknown or uninitialised column: 'perc.goal.met.period'.
24: Unknown or uninitialised column: 'perc.goal.met.period'.
25: Unknown or uninitialised column: 'perc.goal.met.period'.
26: Unknown or uninitialised column: 'perc.goal.met.period'.
27: Unknown or uninitialised column: 'perc.goal.met.period'.
28: Unknown or uninitialised column: 'perc.goal.met.period'.
29: Unknown or uninitialised column: 'perc.goal.met.period'.
30: Unknown or uninitialised column: 'perc.goal.met.period'.
There were 30 warnings (use warnings() to see them)

I am ok with that warning. But later, I thought I would load one additional library to the first of the chunks (where I load them). After running that chunk, I get:

```{r echo=F, message=F, warnings=F, include=F}
# Load libraries
library(rgdal)
library(raster)
library(openxlsx)
library(tidyverse)
library(dplyr)
library(magrittr)
library(ggplot2)
library(rasterVis)
```
There were 30 warnings (use warnings() to see them)

If I see the warnings, they are those I printed before.
Why am I seeing them here? I am seeing this also in other chunks also unrelated to the variable perc.goal.met.period. If I see the warnings, they will stop appearing for a while, but at a moment that I am still not able to anticipate, they will eventually reappear at some point.

Is there a logical explanation for this behaviour? Thanks a lot for your help!


问:
Regex for extracting part of a file path
I am using regex function in Impala to find the folder name in file path but it doesn't seem to give me correct result

I want to parse out "one" from this file path:

```<code>/this/one/path/to/hdfs
</code>```

This is the regex which I used:

```<code>regexp_extract(filepath,'[/]+',0)
</code>```

答:
If here we wish to capture the /, then we might just want to try ([\/]+). There should be other expressions to extract one also, such as:

```<code>(?:\/[a-z]+\/)(.+?)(?:\/.+)
</code>```

and our code might look like:

```<code>regexp_extract(filepath, '(?:\/[a-z]+\/)(.+?)(?:\/.+)', 2)
</code>```

or

```<code>regexp_extract(filepath, '(?:\/.+?\/)(.+?)(?:\/.+)', 2)
</code>```

Compartments

In this case, we are not capturing what is behind one using a non-capturing group:

```<code>(?:\/[a-z]+\/)
</code>```

then we capture one using:

```<code>(.+?)
</code>```

and finally we add a right boundary after one in another non-capturing group:

```<code>(?:\/.+)
</code>```

RegEx Circuit

jex.im visualizes regular expressions:

DEMO

Depending on which slash, one might be located, we can modify our expression. For example, in this case, this expression also might be working:

```<code>(?:\/.+?\/)(.+?)(?:\/.+)
</code>```

DEMO

Body:
I am using regex function in Impala to find the folder name in file path but it doesn't seem to give me correct result

I want to parse out "one" from this file path:

/this/one/path/to/hdfs

This is the regex which I used:

regexp_extract(filepath,'[/]+',0)

Body:
If here we wish to capture the /, then we might just want to try ([\/]+). There should be other expressions to extract one also, such as:

(?:\/[a-z]+\/)(.+?)(?:\/.+)

and our code might look like:

regexp_extract(filepath, '(?:\/[a-z]+\/)(.+?)(?:\/.+)', 2)

or

regexp_extract(filepath, '(?:\/.+?\/)(.+?)(?:\/.+)', 2)

Compartments

In this case, we are not capturing what is behind one using a non-capturing group:

(?:\/[a-z]+\/)

then we capture one using:

(.+?)

and finally we add a right boundary after one in another non-capturing group:

(?:\/.+)

RegEx Circuit

jex.im visualizes regular expressions:

DEMO

Depending on which slash, one might be located, we can modify our expression. For example, in this case, this expression also might be working:

(?:\/.+?\/)(.+?)(?:\/.+)

DEMO


问:
Make table automatically update row
I have a database with the following columns:

```<code>CurrentCredits, CreditsPerDate, RefillDate, RefillFrequency, RefillDayMonth
</code>```

I'd like to make it automatically update the CreditsPerDate and RefillDate depending on the frequency selected.

For example,

```<code>if RefillFrequency = 5 and RefillDayMonth = "day" and CreditsPerMonth = 2
</code>```

I want it to update CurrentCredits and RefillDate every 5 days such that

```<code>CurrentCredits = CurrentCredits + CreditsPerMonth and
RefillDate = RefillDate + the frequency date (here add 5 days)
</code>```

答: You can't get a table to do that by itself. I would say go with Patricio's idea and schedule a job to run. Write a stored proc and have that run daily to run calculations. You will need additional columns probably to help facilitate this as you will need to know when a row was last updated and use that date (ie, UpdateDt) to determine if some values will need to be recalculated. </p>

Title: Make table automatically update row

Body:
I have a database with the following columns:

CurrentCredits, CreditsPerDate, RefillDate, RefillFrequency, RefillDayMonth

I'd like to make it automatically update the CreditsPerDate and RefillDate depending on the frequency selected.

For example,

if RefillFrequency = 5 and RefillDayMonth = "day" and CreditsPerMonth = 2

I want it to update CurrentCredits and RefillDate every 5 days such that

CurrentCredits = CurrentCredits + CreditsPerMonth and
RefillDate = RefillDate + the frequency date (here add 5 days)


问:
Updating indexed documents of Zend Search Lucene indexes
I have already read this question
Creating and updating Zend_Search_Lucene indexes.

But it has failed to answer to my problem. This article from zend, tells that updating the document is not possible. To update effectively, every document have to be deleted and re indexed.

```<code>$removePath = ...;
$hits = $index->find('path:' . $removePath);
foreach ($hits as $hit) {
    $index->delete($hit->id);
}
</code>```

Now, this does not work for me. I gave the index Path in the $removePath and tried the code. It didn't work. If I use something relative to my particular index such as $index->find("title:test"); it throws

```<code>Fatal error:  Exception thrown without a stack frame in Unknown on line 0
</code>```

I also tried using

```<code>  $query = new Zend_Search_Lucene_Search_Query_Term(new Zend_Search_Lucene_Index_Term('test', 'title'));
  $hits = $this -> index->find($query);
</code>```

But it gave same result.

I do not even know how to debug that type of error. And even it gets debugged, I will only get the searched items rather than all the documents. So, all documents are not deleted.

Can anyone, tell me what am i doing wrong. How to update your search indexes?

答:
Fatal error:  Exception thrown without
  a stack frame in Unknown on line 0

Means that you have thrown an exception where an exception cannot be thrown. Usually this occurs when you try to throw an exception in a php destructur or an php exception handler (destructors and exception handlers do not have a stack frame)

This error message is kind of cryptic because it gives you no hint where the error might be.

However this is a know issue: Using the index as static property

So you should call commit() on your index. It will prevent lucene from throwing the exception:

```<code>$this->index->commit();
</code>```

To delete documents you have to interate through the index and delete each document.

```<code>$index = Zend_Search_Lucene::open('data/index');

$hits = $index->find('id:'.$id);

  foreach ($hits as $hit) {
     $index->delete($hit->id);
  }
}
</code>```

So with id or path you identify the field that shoud match with the parameter from the record you want to delete. All documents that are found will be deleted from index.

Body:
I have already read this question
Creating and updating Zend_Search_Lucene indexes.

But it has failed to answer to my problem. This article from zend, tells that updating the document is not possible. To update effectively, every document have to be deleted and re indexed.

$removePath = ...;
$hits = $index->find('path:' . $removePath);
foreach ($hits as $hit) {
    $index->delete($hit->id);
}

Now, this does not work for me. I gave the index Path in the $removePath and tried the code. It didn't work. If I use something relative to my particular index such as $index->find("title:test"); it throws

Fatal error:  Exception thrown without a stack frame in Unknown on line 0

I also tried using

  $query = new Zend_Search_Lucene_Search_Query_Term(new Zend_Search_Lucene_Index_Term('test', 'title'));
  $hits = $this -> index->find($query);

But it gave same result.

I do not even know how to debug that type of error. And even it gets debugged, I will only get the searched items rather than all the documents. So, all documents are not deleted.

Can anyone, tell me what am i doing wrong. How to update your search indexes?

Body:
Fatal error:  Exception thrown without
  a stack frame in Unknown on line 0

Means that you have thrown an exception where an exception cannot be thrown. Usually this occurs when you try to throw an exception in a php destructur or an php exception handler (destructors and exception handlers do not have a stack frame)

This error message is kind of cryptic because it gives you no hint where the error might be.

However this is a know issue: Using the index as static property

So you should call commit() on your index. It will prevent lucene from throwing the exception:

$this->index->commit();

To delete documents you have to interate through the index and delete each document.

$index = Zend_Search_Lucene::open('data/index');

$hits = $index->find('id:'.$id);

  foreach ($hits as $hit) {
     $index->delete($hit->id);
  }
}

So with id or path you identify the field that shoud match with the parameter from the record you want to delete. All documents that are found will be deleted from index.


问:
Currency conversion in R
I am trying to convert currency values from factor to numeric. The format is €110.5M €565K I was able to get rid of € sign, M and K letters but I also need to make the conversion as to show 110.5M=110.500.000 and 565K=565.000. Is there a way that you can suggest?

```<code>value<-as.numeric(gsub("[€MK]", "", as.character(strength[1:18207,1])))
</code>```

Data to be converted

```<code>€110.5M €565K
€77M    €405K
€118.5M €290K
</code>```

Title: Currency conversion in R

Body:
I am trying to convert currency values from factor to numeric. The format is €110.5M €565K I was able to get rid of € sign, M and K letters but I also need to make the conversion as to show 110.5M=110.500.000 and 565K=565.000. Is there a way that you can suggest?

value<-as.numeric(gsub("[€MK]", "", as.character(strength[1:18207,1])))

Data to be converted

€110.5M €565K
€77M    €405K
€118.5M €290K

Body:
Here is a similar base R option using sub:

input <- c("€110.5M", "€565K")
exp <- sapply(input, function(x) sub("€(\\d+(?:\\.\\d+)?)K", "\\1*1000",
                  sub("€(\\d+(?:\\.\\d+)?)M", "\\1*1000000", x)))
exp
sapply(exp, function(x) eval(parse(text=x)))

€110.5M           €565K
"110.5*1000000"      "565*1000"
  €110.5M     €565K
110500000    565000


问:
Resolv::DNS not resolving PTR for 192.168.x
This is my test code:

```<code>require 'resolv'

puts `dig @172.17.0.40 -x 203.208.60.1 +short`
puts `dig @172.17.0.40 -x 192.168.12.100 +short`

resolver = Resolv::DNS.new(
    :nameserver => ['172.17.0.40'],
    :search => ['example.com'],
    :ndots => 1
    )

puts resolver.getname('203.208.60.1')
puts resolver.getname('192.168.12.100')
</code>```

Running the above script results in:

```<code>crawl-203-208-60-1.googlebot.com.
asdf.example.com.
crawl-203-208-60-1.googlebot.com
/home/jskarpet/.rvm/rubies/ruby-2.1.3/lib/ruby/2.1.0/resolv.rb:431:in `getname': DNS result has no information for 192.168.12.100 (Resolv::ResolvError)
    from ruby.rb:14:in `<main>'
</code>```

Why does the lookup fail using Resolv, and not dig (and how to fix?)

答:
I faced what might have been the same problem today, after upgrading a DNS server from Debian Wheezy to Debian Jessie.  Suddenly I was getting:

```<code>/usr/lib/ruby/2.1.0/resolv.rb:431:in `getname': DNS result has no information for 192.168.12.100 (Resolv::ResolvError)
</code>```

I happened to notice unfamiliar capitals in IN-ADDR.ARPA here:

```<code>$ host 192.168.12.100
100.12.168.192.IN-ADDR.ARPA domain name pointer asdf.example.com.
$
</code>```

With older DNS servers, it was:

```<code>$ host 192.168.12.100
100.12.168.192.in-addr.arpa domain name pointer asdf.example.com.
$
</code>```

Even with the new server, the external IP example still had lower case:

```<code>$ host 203.208.60.1
1.60.208.203.in-addr.arpa domain name pointer crawl-203-208-60-1.googlebot.com.
$
</code>```

I noticed that the test case worked on Ruby 2.3.  The resolv.rb library is Pure Ruby and the 2.3 version now only runs on Ruby 2.1 but passes the test case.  That made it straightforward to track down the active ingredient to:

https://git.ruby-lang.org/ruby.git/commit/lib/resolv.rb?id=69a7bb31f917bd68d78460216aa2ef274428790e

... which was perhaps the crux of the fix for:

https://bugs.ruby-lang.org/issues/10550 (Resolv::DNS.getaddresses returns no IPs when nameserver returns in differing case than query)

I fixed it by monkey patching, in such a way that it would fix Ruby 1.8.7, 1.9.3 and 2.1.0 while leaving 2.3.3, which was already working, untouched:

```<code>require "resolv"

class Resolv
  class DNS
    class Name
if Resolv::DNS::Name.new("in-addr.arpa".split(".")) != Resolv::DNS::Name.new("IN-ADDR.ARPA".split("."))
      def ==(other)
        return false unless @absolute == other.absolute?
        return @labels.join('.').casecmp(other.to_a.join('.')).zero?
      end
end
    end
  end
end
</code>```

Body:
This is my test code:

require 'resolv'

puts `dig @172.17.0.40 -x 203.208.60.1 +short`
puts `dig @172.17.0.40 -x 192.168.12.100 +short`

resolver = Resolv::DNS.new(
    :nameserver => ['172.17.0.40'],
    :search => ['example.com'],
    :ndots => 1
    )

puts resolver.getname('203.208.60.1')
puts resolver.getname('192.168.12.100')

Running the above script results in:

crawl-203-208-60-1.googlebot.com.
asdf.example.com.
crawl-203-208-60-1.googlebot.com
/home/jskarpet/.rvm/rubies/ruby-2.1.3/lib/ruby/2.1.0/resolv.rb:431:in `getname': DNS result has no information for 192.168.12.100 (Resolv::ResolvError)
    from ruby.rb:14:in `'

Why does the lookup fail using Resolv, and not dig (and how to fix?)

Body:
I faced what might have been the same problem today, after upgrading a DNS server from Debian Wheezy to Debian Jessie.  Suddenly I was getting:

/usr/lib/ruby/2.1.0/resolv.rb:431:in `getname': DNS result has no information for 192.168.12.100 (Resolv::ResolvError)

I happened to notice unfamiliar capitals in IN-ADDR.ARPA here:

$ host 192.168.12.100
100.12.168.192.IN-ADDR.ARPA domain name pointer asdf.example.com.
$

With older DNS servers, it was:

$ host 192.168.12.100
100.12.168.192.in-addr.arpa domain name pointer asdf.example.com.
$

Even with the new server, the external IP example still had lower case:

$ host 203.208.60.1
1.60.208.203.in-addr.arpa domain name pointer crawl-203-208-60-1.googlebot.com.
$

I noticed that the test case worked on Ruby 2.3.  The resolv.rb library is Pure Ruby and the 2.3 version now only runs on Ruby 2.1 but passes the test case.  That made it straightforward to track down the active ingredient to:

https://git.ruby-lang.org/ruby.git/commit/lib/resolv.rb?id=69a7bb31f917bd68d78460216aa2ef274428790e

... which was perhaps the crux of the fix for:

https://bugs.ruby-lang.org/issues/10550 (Resolv::DNS.getaddresses returns no IPs when nameserver returns in differing case than query)

I fixed it by monkey patching, in such a way that it would fix Ruby 1.8.7, 1.9.3 and 2.1.0 while leaving 2.3.3, which was already working, untouched:

require "resolv"

class Resolv
  class DNS
    class Name
if Resolv::DNS::Name.new("in-addr.arpa".split(".")) != Resolv::DNS::Name.new("IN-ADDR.ARPA".split("."))
      def ==(other)
        return false unless @absolute == other.absolute?
        return @labels.join('.').casecmp(other.to_a.join('.')).zero?
      end
end
    end
  end
end


问:
I want to call a function when an element no longer has a specific class (no jquery)
I am making a plugin for a site where I can only use javascript. I want to execute code when il element with id = "gridview" no longer has the "hidden" class. Thank you for your help.

I already tried:

```<code>document.getElementById("id="eval_grid_tab"").addEventListener("click", start);
</code>```

This is the html

```<code><li id="eval_grid_tab"><a href="#gridview">Tabel</a></li>
<div id="gridview" class="rightsPanel smscTabsPanel hidden" style="height: 795px;">...</div>
</code>```

答:
To do this you need to use a MutationObserver. It monitors the DOM for changes (like classes being removed / added) and triggers a callback function for you to use anyway you see fit.

```<code>// Select the node that will be observed for mutations
var targetNode = document.getElementById('gridview');

// Options for the observer (which mutations to observe)
var config = { attributes: true };

// Callback function to execute when mutations are observed
var callback = function(mutationsList, observer) {
    for(var mutation of mutationsList) {
        if (mutation.type == 'attributes') {
            // Triggers when an attribute like 'class' is modified
            console.log('The ' + mutation.attributeName + ' attribute was modified.');
        }
    }
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);
</code>```

Later, you can stop observing with

observer.disconnect();

Body:
I am making a plugin for a site where I can only use javascript. I want to execute code when il element with id = "gridview" no longer has the "hidden" class. Thank you for your help.

I already tried:

document.getElementById("id="eval_grid_tab"").addEventListener("click", start);

This is the html

Tabel

...

Body:
To do this you need to use a MutationObserver. It monitors the DOM for changes (like classes being removed / added) and triggers a callback function for you to use anyway you see fit.

// Select the node that will be observed for mutations
var targetNode = document.getElementById('gridview');

// Options for the observer (which mutations to observe)
var config = { attributes: true };

// Callback function to execute when mutations are observed
var callback = function(mutationsList, observer) {
    for(var mutation of mutationsList) {
        if (mutation.type == 'attributes') {
            // Triggers when an attribute like 'class' is modified
            console.log('The ' + mutation.attributeName + ' attribute was modified.');
        }
    }
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

Later, you can stop observing with

observer.disconnect();


问:
cakephp timezone warning notice on debug enabling
In CakePHP-1.2, When i put debug on to 1 or 2 it gives me below timezone related warnings/notices.

Warning (2): date() [http://php.net/function.date]: It is not safe to rely on the system's timezone settings. You are required to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'Asia/Calcutta' for 'IST/5.0/no DST' instead [CORE/cake/libs/model/model.php, line 1149]

Any idea, how can i remove it?

答: like the error says, set the timezone properly, http://php.net/manual/en/function.date-default-timezone-set.php</p>


问:
How to get key from object in map function?
How to get the key from object in

```<code>{this.state.data.map((object, index) => (
      <div>object.key</div>

    ))}
</code>```

For example if this.state.data was

```<code> [{mykey1:23},{mykey2:24},{mykey3:34}]
</code>```

I would want it to return

```<code> <div>mykey1</div>
 <div>mykey2</div>
 <div>mykey3</div>
</code>```

答:
Use Object.keys():

```<code>{this.state.data.map(obj => <div>{Object.keys(obj)[0]}</div>)}
</code>```

Body:
How to get the key from object in

{this.state.data.map((object, index) => (

object.key

    ))}

For example if this.state.data was

 [{mykey1:23},{mykey2:24},{mykey3:34}]

I would want it to return

mykey1

mykey2

mykey3

Body:
Use Object.keys():

{this.state.data.map(obj => <div>{Object.keys(obj)[0]}</div>)}


问:
C Writing to absolute address does not update value
Im trying to write a basic page manager for my C kernel. The code goes like this:

```<code>#define NUM_PAGES 1024
#define PAGE_SIZE 4096
#define NULL 0

#define IMPORTANT_SEGMENT 0xC0900000

struct page {
    void * addr;
    int in_use;
};

struct page CORE_FILE[NUM_PAGES];

void mem_init() {
    for (int i = 0; i < NUM_PAGES; i++) {
        CORE_FILE[i].addr = (void*)IMPORTANT_SEGMENT+PAGE_SIZE*i;
        CORE_FILE[i].in_use = 0;
    }
}

void * allocate() {

    for (int i = 0; i < NUM_PAGES; i++) {
        if (!CORE_FILE[i].in_use) {
            CORE_FILE[i].in_use = 1;
            return CORE_FILE[i].addr;
        }
    }

    return NULL;
}

int deallocate(void* p) {

    for (int i = 0; i < NUM_PAGES; i++) {
        if (CORE_FILE[i].addr == p && CORE_FILE[i].in_use) {
            CORE_FILE[i].in_use = 0;
            return 0;
        }
    }
    return -1;
}
</code>```

CORE_FILE is an array of structs containing just one field for telling if the page is in use and an address (im using contiguous addresses growing from IMPORTANT_SEGMENT = 0xC0900000).

When i call allocate() it returns me the correct void* which i cast for example to char, but when i write to the address it simply does nothing.

I have checked the address to which is pointing with GDB and is the correct one.
But when i examine its contents they haven't been updated (Still 0).

```<code>void kmain(void) {
    mem_init();
    int * addr = (int*)allocate();
    *addr = 5;
}
</code>```

Im giving qemu 4 GB of RAM executing with:

```<code>qemu-system-i386 -m 4G -kernel kernel -gdb tcp::5022
</code>```

Perhaps im writing to non-existent memory or maybe im overwriting the address contents after. I don't know.

Any ideas will be appreciated.

Thank you in advance.

[edit] This is the bootloader im using:

```<code>bits 32
section .text
        ;multiboot spec
        align 4
        dd 0x1BADB002              ;magic
        dd 0x00                    ;flags
        dd - (0x1BADB002 + 0x00)   ;checksum. m+f+c should be zero

global start
global keyboard_handler
global read_port
global write_port
global load_idt

extern kmain        ;this is defined in the c file
extern keyboard_handler_main

read_port:
    mov edx, [esp + 4]
            ;al is the lower 8 bits of eax
    in al, dx   ;dx is the lower 16 bits of edx
    ret

write_port:
    mov   edx, [esp + 4]
    mov   al, [esp + 4 + 4]
    out   dx, al
    ret

load_idt:
    mov edx, [esp + 4]
    lidt [edx]
    sti                 ;turn on interrupts
    ret

keyboard_handler:
    call    keyboard_handler_main
    iretd

start:
    cli                 ;block interrupts
    mov esp, stack_space
    call kmain
    hlt                 ;halt the CPU

section .bss
resb 8192; 8KB for stack
stack_space:
</code>```

My link.ld

```<code>OUTPUT_FORMAT(elf32-i386)
ENTRY(start)
SECTIONS
 {
   . = 0x100000;
   .text : { *(.text) }
   . = 0x200000;
   .data : { *(.data) }
   . = 0x300000;
   .bss  : { *(.bss)  }
 }
</code>```

Edit2: I compile with this

```<code>nasm -f elf32 kernel.asm -o kasm.o
gcc -g -fno-stack-protector -fno-builtin -m32 -c memory.c -o memory.o
gcc -g -fno-stack-protector -fno-builtin -m32 -c kernel.c -o kc.o
ld -m elf_i386 -T link.ld -o kernel kasm.o memory.o kc.o
</code>```

答:
The problem is with protected and real mode, when the computer boots it does so in 16 bit real mode, which makes you able to address 1 MB of data. Everything over that wont be suitable for reading/writing. If i changed the IMPORTANT_SEGMENT to 0x300000 it works.

Now i have to create and load my gdt, enable the a20 line, enable protected mode, set the registers and jump to my code.

Body:
Im trying to write a basic page manager for my C kernel. The code goes like this:

#define NUM_PAGES 1024
#define PAGE_SIZE 4096
#define NULL 0

#define IMPORTANT_SEGMENT 0xC0900000

struct page {
    void * addr;
    int in_use;
};

struct page CORE_FILE[NUM_PAGES];

void mem_init() {
    for (int i = 0; i < NUM_PAGES; i++) {
        CORE_FILE[i].addr = (void*)IMPORTANT_SEGMENT+PAGE_SIZE*i;
        CORE_FILE[i].in_use = 0;
    }
}

void * allocate() {

    for (int i = 0; i < NUM_PAGES; i++) {
        if (!CORE_FILE[i].in_use) {
            CORE_FILE[i].in_use = 1;
            return CORE_FILE[i].addr;
        }
    }

    return NULL;
}

int deallocate(void* p) {

    for (int i = 0; i < NUM_PAGES; i++) {
        if (CORE_FILE[i].addr == p && CORE_FILE[i].in_use) {
            CORE_FILE[i].in_use = 0;
            return 0;
        }
    }
    return -1;
}

CORE_FILE is an array of structs containing just one field for telling if the page is in use and an address (im using contiguous addresses growing from IMPORTANT_SEGMENT = 0xC0900000).

When i call allocate() it returns me the correct void* which i cast for example to char, but when i write to the address it simply does nothing.

I have checked the address to which is pointing with GDB and is the correct one.
But when i examine its contents they haven't been updated (Still 0).

void kmain(void) {
    mem_init();
    int * addr = (int*)allocate();
    *addr = 5;
}

Im giving qemu 4 GB of RAM executing with:

qemu-system-i386 -m 4G -kernel kernel -gdb tcp::5022

Perhaps im writing to non-existent memory or maybe im overwriting the address contents after. I don't know.

Any ideas will be appreciated.

Thank you in advance.

[edit] This is the bootloader im using:

bits 32
section .text
        ;multiboot spec
        align 4
        dd 0x1BADB002              ;magic
        dd 0x00                    ;flags
        dd - (0x1BADB002 + 0x00)   ;checksum. m+f+c should be zero

global start
global keyboard_handler
global read_port
global write_port
global load_idt

extern kmain        ;this is defined in the c file
extern keyboard_handler_main

read_port:
    mov edx, [esp + 4]
            ;al is the lower 8 bits of eax
    in al, dx   ;dx is the lower 16 bits of edx
    ret

write_port:
    mov   edx, [esp + 4]
    mov   al, [esp + 4 + 4]
    out   dx, al
    ret

load_idt:
    mov edx, [esp + 4]
    lidt [edx]
    sti                 ;turn on interrupts
    ret

keyboard_handler:
    call    keyboard_handler_main
    iretd

start:
    cli                 ;block interrupts
    mov esp, stack_space
    call kmain
    hlt                 ;halt the CPU

section .bss
resb 8192; 8KB for stack
stack_space:

My link.ld

OUTPUT_FORMAT(elf32-i386)
ENTRY(start)
SECTIONS
 {
   . = 0x100000;
   .text : { *(.text) }
   . = 0x200000;
   .data : { *(.data) }
   . = 0x300000;
   .bss  : { *(.bss)  }
 }

Edit2: I compile with this

nasm -f elf32 kernel.asm -o kasm.o
gcc -g -fno-stack-protector -fno-builtin -m32 -c memory.c -o memory.o
gcc -g -fno-stack-protector -fno-builtin -m32 -c kernel.c -o kc.o
ld -m elf_i386 -T link.ld -o kernel kasm.o memory.o kc.o


问:
How do I install opencv using pip?
I need to install cv2 for a script that has been written for me. I tried  pip install cv2 and pip install open_cv and got the same problem - a warning message from dist.py and complains about zlib being not found. No cv2 installed. I also tried pyopenvc and pip install opencv-python.

So, I went to the opencv site and downloaded the relevant exe. Ran it - generated a heap of subdirectories and a make file and stuff.

What do I do now?

答:
Make a virtual enviroment using python3

```<code>virtualenv env_name --python="python3"
</code>```

and run the following command

```<code>pip3 install opencv-python
</code>```

to check it has installed correctly run

```<code>python3 -c "import cv2"
</code>```

Title: How do I install opencv using pip?

Body:
Make a virtual enviroment using python3

virtualenv env_name --python="python3"

and run the following command

pip3 install opencv-python

to check it has installed correctly run

python3 -c "import cv2"