问:
Serial communication with bytes (0x00 problem)
I have a problem while using serial communication for USB CDC.
I'm working on embedded STM microcontrollers and i wanted to pass binary data with pySerial.

I wanted to send binary codes directly but I am blocked by this 0x00 ..
My problem is when i want to send 0x00 byte, the next bytes seems to be ignored..

Here's the python script:

```<code>towrite = [ 0xFF, 0xx00 \xFF ]
nbSend = s.write(b'\xFF\x00\xFF')
print(nbSend)                                 #Displaying 3 here, that means 3 bytes are successfully sended
</code>```

Then the embedded script:

```<code>//Interrupt function that receive the data from serial com
static int8_t CDC_Receive_FS(uint8_t* Buf, uint32_t *Len)
{
  /* USER CODE BEGIN 6 */
  USBD_CDC_SetRxBuffer(&hUsbDeviceFS, &Buf[0]);
  USBD_CDC_ReceivePacket(&hUsbDeviceFS);

  char buffer[64];

  sprintf(buffer,"Length=%lu / Word=%c%c%c ",(unsigned long)*Len,Buf[0],Buf[1],Buf[2]);
  debugPrintln(&huart2, buffer)  //Function to print on serial to debug
  //Here that print "Length=3 / Word=ÿ "

  return (USBD_OK);
  /* USER CODE END 6 */
}
</code>```

As you can see, the second and ultimate characters (0x00, 0xFF) are not taken into account even if the number of bytes received is good ...
Any advice?

答:
It's the debugging that's not working, but the data transfer is just fine.

```<code>sprintf(buffer,"Length=%lu / Word=%c%c%c ",(unsigned long)*Len,Buf[0],Buf[1],Buf[2]);
</code>```

The second %c puts an actual NUL byte in the buffer, so everything else after it is ignored by the debugPrintln.

For testing, change to:

```<code>sprintf(buffer,"Length=%lu / Word=%02X %02X %02X",(unsigned long)*Len,Buf[0],Buf[1],Buf[2]);
</code>```

and see if it shows you all the bytes.

Body:
I have a problem while using serial communication for USB CDC.
I'm working on embedded STM microcontrollers and i wanted to pass binary data with pySerial.

I wanted to send binary codes directly but I am blocked by this 0x00 ..
My problem is when i want to send 0x00 byte, the next bytes seems to be ignored..

Here's the python script:

towrite = [ 0xFF, 0xx00 \xFF ]
nbSend = s.write(b'\xFF\x00\xFF')
print(nbSend)                                 #Displaying 3 here, that means 3 bytes are successfully sended

Then the embedded script:

//Interrupt function that receive the data from serial com
static int8_t CDC_Receive_FS(uint8_t* Buf, uint32_t *Len)
{
  /* USER CODE BEGIN 6 */
  USBD_CDC_SetRxBuffer(&hUsbDeviceFS, &Buf[0]);
  USBD_CDC_ReceivePacket(&hUsbDeviceFS);

  char buffer[64];

  sprintf(buffer,"Length=%lu / Word=%c%c%c ",(unsigned long)*Len,Buf[0],Buf[1],Buf[2]);
  debugPrintln(&huart2, buffer)  //Function to print on serial to debug
  //Here that print "Length=3 / Word=ÿ "

  return (USBD_OK);
  /* USER CODE END 6 */
}

As you can see, the second and ultimate characters (0x00, 0xFF) are not taken into account even if the number of bytes received is good ...
Any advice?

Body:
It's the debugging that's not working, but the data transfer is just fine.

sprintf(buffer,"Length=%lu / Word=%c%c%c ",(unsigned long)*Len,Buf[0],Buf[1],Buf[2]);

The second %c puts an actual NUL byte in the buffer, so everything else after it is ignored by the debugPrintln.

For testing, change to:

sprintf(buffer,"Length=%lu / Word=%02X %02X %02X",(unsigned long)*Len,Buf[0],Buf[1],Buf[2]);

and see if it shows you all the bytes.


来源: stackexchange

问:
View local:"UserControl" in ColumnDefinition(2)
I want to view UserControl inside ColumnDefinition(2)

MainWindow.xaml:

```<code><Grid Margin="0,0,0,0">
    <local:DockPanelTop />
    <local:DockPanelBtm />

    <Grid Margin="5,45,5,25" x:Name="MainGrid" x:FieldModifier="public">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="200" MaxWidth="400" MinWidth="0" x:Name="MainMenu" x:FieldModifier="public" />
            <ColumnDefinition Width="5" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <Rectangle Grid.Column="0" Fill="AliceBlue" />
        <GridSplitter HorizontalAlignment="Stretch" Background="#FFFF7E7E" Grid.Column="1" />
        <Rectangle Grid.Column="2" Fill="AntiqueWhite" />

        【"View this into ColumnDefinition(2)"<local:TreeView />】

    </Grid>
</code>```

Thanks.

答:
My Answer:</p>

```<code><local:TreeView Grid.Column="2"/>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to view UserControl inside ColumnDefinition(2)

MainWindow.xaml:

<Grid Margin="0,0,0,0">
    <local:DockPanelTop />
    <local:DockPanelBtm />

    <Grid Margin="5,45,5,25" x:Name="MainGrid" x:FieldModifier="public">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="200" MaxWidth="400" MinWidth="0" x:Name="MainMenu" x:FieldModifier="public" />
            <ColumnDefinition Width="5" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <Rectangle Grid.Column="0" Fill="AliceBlue" />
        <GridSplitter HorizontalAlignment="Stretch" Background="#FFFF7E7E" Grid.Column="1" />
        <Rectangle Grid.Column="2" Fill="AntiqueWhite" />

        【"View this into ColumnDefinition(2)"<local:TreeView />】

    </Grid>

Thanks.

Body:
My Answer:

<local:TreeView Grid.Column="2"/>


问:
Detect cycles in a genealogy graph during a Depth-first search
I'm loading horse genealogical data recursively.
For some wrong sets of data my recursion never stops... and that is because  there are cycles in the data.

How can I detect those cycles to stop recurring?

I thought of while recurring maintain a hashTable with all "visited" horses.
But that will find some false positives, because a horse CAN be twice in a tree.

What cannot happen is that a horse appear as a father or grandfather or great grandfather of ITSELF.

答:
A very simple way to detect this, is by checking that constraint itself:

What cannot happend is that a horse appear as a father or grandfather or greatgrandfather of ITSELF.

Whenever you insert a node in your tree, traverse the tree to the root to make sure that the horse does not exist as a any kind of parent.

To speed this up, you can associate a hashtable to each node, where you cache the answer of such a lookup. Then you don't have to search the entire path next time you insert a horse under that node.

OwnerDisplayName: Romias

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: Zuu

LastEditorDisplayName: Zuu


问:
Creating array of pointers to class object
Question:

Create an array of at least four pointers to Reader objects. Use the New operator to create at least four pointers to derived class objects and assign them to the array.

I'm not sure If I did it right or not.

Reader is the base class. John, David, Daniel, Mark are the derived class

```<code>int main(void)
{
     Reader *obj[4];

    obj[0] = new John();
    obj[1] = new David();
    obj[3] = new Daniel();
    obj[2] = new  Mark();

}
</code>```

Would this be right???

答:
Your code is correct.

And as @sharptooth suggested, make a practice of delete on the allocated obj[]s. In C++ new allocates memory and delete deallocates.

Body:
Question:

Create an array of at least four pointers to Reader objects. Use the New operator to create at least four pointers to derived class objects and assign them to the array.

I'm not sure If I did it right or not.

Reader is the base class. John, David, Daniel, Mark are the derived class

int main(void)
{
     Reader *obj[4];

    obj[0] = new John();
    obj[1] = new David();
    obj[3] = new Daniel();
    obj[2] = new  Mark();

}

Would this be right???


问:
how to deploy my maven project for devops pipeline
I have an devops project assignment that I am required to create a maven project and also create a CI/CD pipeline for it. I am quiet newbie in devops and struggling to understand some concepts.

I created a maven project and pushed it into bitbucket. By the way, I have 3 main branches which are master, test and development that I need to deploy them prod, qa and dev environments, respectively. Via Jenkins, I successfully created build automation.

However, I could not deploy the project because I am confused. Can I also deploy my project with Jenkins? Or do I need a something like Virtualbox to deploy? Also do I have to use Docker to deploy? I searched for web but could not make it clear.

Could you please help me understand the deployment process in this project?
Thanks in advance.

答:
Deployment processes are depends on your infrastructure. What do you use?

There are tons of deployment strategies according to business/development models. You can deploy your projects with Jenkins or any CI/CD tools that you chose. It doesn't matter at the end.

Here it's a good deployment strategies reading by Google.
https://cloud.google.com/solutions/application-deployment-and-testing-strategies


问:
Is their anyway to add a join to a query that returns the latest rows of a specific column using group by
```<code> "SELECT * FROM report
      where id
        IN (
             SELECT MAX(id)
              FROM report
               where org_id = '$id'
                GROUP BY request_i
             ) ";
</code>```

The code above gives me the latest row of each request_id per organization, which is exactly what i want but i need to use the FK in the table to get more details.
I want to join an organization & request table to the above query, so that i can use the FK to display certain things on my report page.

I tried the code below in different ways but i always get this error.

Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, bool given in C:\xampp\htdocs\mou1\organizationDetails.php on line 503

```<code>"SELECT * FROM report
      JOIN request ON
      report.id = report.request_id
      JOIN organization ON
      organization.id = report.org_id
      where id
        IN (
             SELECT MAX(id)
              FROM report
               where org_id = '$id'
                GROUP BY request_i
             ) ";
</code>```

Code Snippet

答:
Presumably, your query fails because id is ambiguous in the WHERE clause. You would need to qualify this column name:

```<code>SELECT *
FROM report
JOIN request ON request.id = report.request_id
JOIN organization ON organization.id = report.org_id
WHERE report.id IN (
    SELECT MAX(id)
    FROM report
    where org_id = '$id'
    GROUP BY request_id
)
</code>```

I fixed what seems like a typo in the join condition on request (you had ON report.id = report.request_id).

I would take one step forward and suggest to rewrite this query and use a correlated subquery. MySQL tend to poorly optimize IN flters with subqueries, while correlated subqueries generally perform very well if the proper index is available:

```<code>select *   -- you should enumerate the columns here
from report rep
inner join request req      on req.id = rep.request_id
inner join organization org on org.id = rep.org_id
where rep.id = (
    select max(rep1.id)
    from report rep1
    where rep1.org_id = ? and rep1.request_id = rep.request_id
)
</code>```

Note that I used table aliases to make the query more readable and shorten it. You should also use a parameterized query rather than concatenating variables in the query string (the ? stands for the query parameter here).

For performance with this query, you want an index on report(org_id, requsst_id, id).

Body:
 "SELECT * FROM report
      where id
        IN (
             SELECT MAX(id)
              FROM report
               where org_id = '$id'
                GROUP BY request_i
             ) ";

The code above gives me the latest row of each request_id per organization, which is exactly what i want but i need to use the FK in the table to get more details.
I want to join an organization & request table to the above query, so that i can use the FK to display certain things on my report page.

I tried the code below in different ways but i always get this error.

Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, bool given in C:\xampp\htdocs\mou1\organizationDetails.php on line 503

"SELECT * FROM report
      JOIN request ON
      report.id = report.request_id
      JOIN organization ON
      organization.id = report.org_id
      where id
        IN (
             SELECT MAX(id)
              FROM report
               where org_id = '$id'
                GROUP BY request_i
             ) ";

Code Snippet

Body:
Presumably, your query fails because id is ambiguous in the WHERE clause. You would need to qualify this column name:

SELECT *
FROM report
JOIN request ON request.id = report.request_id
JOIN organization ON organization.id = report.org_id
WHERE report.id IN (
    SELECT MAX(id)
    FROM report
    where org_id = '$id'
    GROUP BY request_id
)

I fixed what seems like a typo in the join condition on request (you had ON report.id = report.request_id).

I would take one step forward and suggest to rewrite this query and use a correlated subquery. MySQL tend to poorly optimize IN flters with subqueries, while correlated subqueries generally perform very well if the proper index is available:

select *   -- you should enumerate the columns here
from report rep
inner join request req      on req.id = rep.request_id
inner join organization org on org.id = rep.org_id
where rep.id = (
    select max(rep1.id)
    from report rep1
    where rep1.org_id = ? and rep1.request_id = rep.request_id
)

Note that I used table aliases to make the query more readable and shorten it. You should also use a parameterized query rather than concatenating variables in the query string (the ? stands for the query parameter here).

For performance with this query, you want an index on report(org_id, requsst_id, id).


问:
Azure Data Factory Pipeline to copy multiple tables fails
My first Post, Sorry in advance if i'm doing anything wrong

I've followed the instructions per the Microsoft Document below and created a data factory to copy multiple tables' data from an On-Prem database to Azure database.

here

The Pipeline fails with the following error :

```<code>PipelineName      : GetTableListAndTriggerCopyData
LastUpdated       : 3/20/2020 10:16:42 AM
Parameters        : {}
RunStart          : 3/20/2020 10:16:10 AM
RunEnd            : 3/20/2020 10:16:42 AM
DurationInMs      : 32430
Status            : Failed
Message           : Operation on target TriggerCopy failed:Operation on target IterateSQLTables failed: Activity failed because an inner activity failed
</code>```

Json data for both pipelines are as below:

1st Pipeline IterateAndCopySQLTables

```<code>{
"name": "IterateAndCopySQLTables",
"properties": {
    "activities": [
        {
            "name": "IterateSQLTables",
            "type": "ForEach",
            "typeProperties": {
                "isSequential": "false",
                "items": {
                    "value": "@pipeline().parameters.tableList",
                    "type": "Expression"
                },
                "activities": [
                    {
                        "name": "CopyData",
                        "description": "Copy data from On Prem SQL database to Azure SQL database",
                        "type": "Copy",
                        "inputs": [
                            {
                                "referenceName": "OnPremSourceDataset",
                                "type": "DatasetReference"
                            }
                        ],
                        "outputs": [
                            {
                                "referenceName": "AzureSinkDataset",
                                "type": "DatasetReference",
                                "parameters": {
                                    "SinkTableName": "[@{item().TABLE_NAME}]"
                                }
                            }
                        ],
                        "typeProperties": {
                            "source": {
                                "type": "SqlSource",
                                "sqlReaderQuery": "SELECT * FROM dbo.[@{item().TABLE_NAME}]"
                            },
                            "sink": {
                                "type": "AzureSqlSink",
                                "preCopyScript": "TRUNCATE TABLE dbo.[@{item().TABLE_NAME}]"
                            }

                        }
                    }
                ]
            }
        }
    ],
    "parameters": {
        "tableList": {
            "type": "Array"
        }
    }
}
}
</code>```

2nd PipeLine : GetTableListAndTriggerCopyData

```<code>{
"name":"GetTableListAndTriggerCopyData",
"properties":{
    "activities":[
        {
            "name": "LookupTableList",
            "description": "Retrieve the table list from On Prem SQL database",
            "type": "Lookup",
            "typeProperties": {
                "source": {
                    "type": "SqlSource",
                    "sqlReaderQuery": "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'dbo' and TABLE_NAME in ('Brd','Loc')"
                },
                "dataset": {
                    "referenceName": "OnPremSourceDataset",
                    "type": "DatasetReference"
                },
                "firstRowOnly": false
            }
        },
        {
            "name": "TriggerCopy",
            "type": "ExecutePipeline",
            "typeProperties": {
                "parameters": {
                    "tableList": {
                        "value": "@array(activity('LookupTableList').output.value)",
                        "type": "Expression"
                    }
                },
                "pipeline": {
                    "referenceName": "IterateAndCopySQLTables",
                    "type": "PipelineReference"
                },
                "waitOnCompletion": true
            },
            "dependsOn": [
                {
                    "activity": "LookupTableList",
                    "dependencyConditions": [
                        "Succeeded"
                    ]
                }
            ]
        }
    ]
}
}
</code>```

答:
Thanks all for ur comments.

The issue was in (GetTableListAndTriggerCopyData)

"value": "@array(activity('LookupTableList').output.value)",
 Is wrong, the correct syntax is :
"value": "@activity('LookupTableList').output.value)",

Body:
My first Post, Sorry in advance if i'm doing anything wrong

I've followed the instructions per the Microsoft Document below and created a data factory to copy multiple tables' data from an On-Prem database to Azure database.

here

The Pipeline fails with the following error :

PipelineName      : GetTableListAndTriggerCopyData
LastUpdated       : 3/20/2020 10:16:42 AM
Parameters        : {}
RunStart          : 3/20/2020 10:16:10 AM
RunEnd            : 3/20/2020 10:16:42 AM
DurationInMs      : 32430
Status            : Failed
Message           : Operation on target TriggerCopy failed:Operation on target IterateSQLTables failed: Activity failed because an inner activity failed

Json data for both pipelines are as below:

1st Pipeline IterateAndCopySQLTables

{
"name": "IterateAndCopySQLTables",
"properties": {
    "activities": [
        {
            "name": "IterateSQLTables",
            "type": "ForEach",
            "typeProperties": {
                "isSequential": "false",
                "items": {
                    "value": "@pipeline().parameters.tableList",
                    "type": "Expression"
                },
                "activities": [
                    {
                        "name": "CopyData",
                        "description": "Copy data from On Prem SQL database to Azure SQL database",
                        "type": "Copy",
                        "inputs": [
                            {
                                "referenceName": "OnPremSourceDataset",
                                "type": "DatasetReference"
                            }
                        ],
                        "outputs": [
                            {
                                "referenceName": "AzureSinkDataset",
                                "type": "DatasetReference",
                                "parameters": {
                                    "SinkTableName": "[@{item().TABLE_NAME}]"
                                }
                            }
                        ],
                        "typeProperties": {
                            "source": {
                                "type": "SqlSource",
                                "sqlReaderQuery": "SELECT * FROM dbo.[@{item().TABLE_NAME}]"
                            },
                            "sink": {
                                "type": "AzureSqlSink",
                                "preCopyScript": "TRUNCATE TABLE dbo.[@{item().TABLE_NAME}]"
                            }

                        }
                    }
                ]
            }
        }
    ],
    "parameters": {
        "tableList": {
            "type": "Array"
        }
    }
}
}

2nd PipeLine : GetTableListAndTriggerCopyData

{
"name":"GetTableListAndTriggerCopyData",
"properties":{
    "activities":[
        {
            "name": "LookupTableList",
            "description": "Retrieve the table list from On Prem SQL database",
            "type": "Lookup",
            "typeProperties": {
                "source": {
                    "type": "SqlSource",
                    "sqlReaderQuery": "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'dbo' and TABLE_NAME in ('Brd','Loc')"
                },
                "dataset": {
                    "referenceName": "OnPremSourceDataset",
                    "type": "DatasetReference"
                },
                "firstRowOnly": false
            }
        },
        {
            "name": "TriggerCopy",
            "type": "ExecutePipeline",
            "typeProperties": {
                "parameters": {
                    "tableList": {
                        "value": "@array(activity('LookupTableList').output.value)",
                        "type": "Expression"
                    }
                },
                "pipeline": {
                    "referenceName": "IterateAndCopySQLTables",
                    "type": "PipelineReference"
                },
                "waitOnCompletion": true
            },
            "dependsOn": [
                {
                    "activity": "LookupTableList",
                    "dependencyConditions": [
                        "Succeeded"
                    ]
                }
            ]
        }
    ]
}
}


问:
Set language of PasswordResetForm in Django?
I am manually resetting passwords but wonder how to set the language to the user's language instead of my own. I see there are many extra context fields but which one needs to be set?

```<code>for user in qs:
    reset_form = PasswordResetForm({'email': user.email})
    # reset_form.language?
    assert reset_form.is_valid()
    reset_form.save(request=request)
</code>```

I have added a field CustomUser.language which would be available in user.language above.

(While phrasing my question and looking for possibilities I found a working solution.)

答:
I came to the following solution, by setting the current language (session-wise) temporarily to the user's language:</p>

```<code>from django.utils import translation

temp_language = translation.get_language_from_request(request)
for user in qs:
    translation.activate(user.language)
    request.LANGUAGE_CODE = translation.get_language()
    reset_form = PasswordResetForm({'email': user.email})
    assert reset_form.is_valid()
    reset_form.save(request=request)
    # https://stackoverflow.com/questions/2336785/set-language-within-a-django-view/2336889#comment12481631_2336889
    translation.deactivate()
translation.activate(temp_language)
request.LANGUAGE_CODE = translation.get_language()
</code>```

Body:
I am manually resetting passwords but wonder how to set the language to the user's language instead of my own. I see there are many extra context fields but which one needs to be set?

for user in qs:
    reset_form = PasswordResetForm({'email': user.email})
    # reset_form.language?
    assert reset_form.is_valid()
    reset_form.save(request=request)

I have added a field CustomUser.language which would be available in user.language above.

(While phrasing my question and looking for possibilities I found a working solution.)

Body:
I came to the following solution, by setting the current language (session-wise) temporarily to the user's language:

from django.utils import translation

temp_language = translation.get_language_from_request(request)
for user in qs:
    translation.activate(user.language)
    request.LANGUAGE_CODE = translation.get_language()
    reset_form = PasswordResetForm({'email': user.email})
    assert reset_form.is_valid()
    reset_form.save(request=request)
    # https://stackoverflow.com/questions/2336785/set-language-within-a-django-view/2336889#comment12481631_2336889
    translation.deactivate()
translation.activate(temp_language)
request.LANGUAGE_CODE = translation.get_language()


问:
MySQL MyISAM data loss possibilities?
Many sites and script still use MySQL instead of PostgreSQL. I have a couple low-priority blogs and such that I don't want to migrate to another database so I'm using MySQL.

Here's the problem, their on a low-memory VPS. This means I can't enable InnoDB since it uses about 80MB of memory just to be loaded. So I have to risk running MyISAM.

With that in mind, what kind of data loss am I looking at with MyISAM? If there was a power-outage as someone was saving a blog post, would I just lose that post, or the whole database?

On these low-end-boxes I'm fine with losing some recent comments or a blog post as long as the whole database isn't lost.

答: MyISAM isn't ACID compliant and therefore lacks durability. It really depends on what costs more...memory to utilise InnoDB or downtime. MyISAM is certainly a viable option but what does your application require from the database layer? Using MyISAM can make life harder due to it's limitations but in certain scenarios MyISAM can be fine. Using only logical mysqldump backups will interrupt your service due to their locking nature. If you're utilising binary logging you can back these up to give you incremental backups that could be replayed to aid recovery should something corrupt in the MyISAM tables.</p>

Title: MySQL MyISAM data loss possibilities?


问:
Accesing more Window Extra Bytes than LongPointer
Im trying to figure out of how to correctly work with the Extra Bytes that you can let windows allocate for your windows and window classes.

If i'm reading the docs correctly, you can tell windows to allocate a specified amount of memory for your window or window class.
But there is only two methods i could find to access and modify said data, SetWindowLongPtr and GetWindowLongPtr.

Problem is, with those methods you can only set a LongPtr full of data, so 64 / 32 bits depending on your system.

Can somebody explain this to me, is there a method i am missing or is this as it should be?

答:
From the documentation for both Extra Class Memory and Extra Window Memory:

Because extra memory is allocated from the system's local heap, an application should use extra [class or window] memory sparingly. The RegisterClassEx function fails if the amount of extra [class or window] memory requested is greater than 40 bytes. If an application requires more than 40 bytes, it should allocate its own memory and store a pointer to the memory in the extra [class or window] memory.


问:
Update based on same column
I have a table like this:

```<code>ID | Flag
-----------
 1 | True
 1 | True
 1 | NULL
 1 | True
 1 | NULL
 2 | False
 2 | False
 2 | False
 2 | NULL
 2 | NULL
</code>```

And I want an output like this:

```<code>ID | Flag
-----------
 1 | True
 1 | True
 1 | True
 1 | True
 1 | True
 2 | False
 2 | False
 2 | False
 2 | False
 2 | False
</code>```

I want to replace nulls with the value assigned in different records. Is there a way to do it in a single update statement?

答:
You can also use exists:

```<code>update t
     set flag = exists (select 1 from t t2 where t2.id = t.id and t2.flag);
</code>```

The advantage of exists over a subquery with aggregation is performance:  the query can stop at the first row where flag is true.  This is a simple index lookup on an index on (id, flag).

Performance would be more improved by limiting the number of rows being updated.  That actually suggests two separate statements:

```<code>update t
    set flag = true
    where (flag is null or not flag) and
          exists (select 1 from t t2 where t2.id = t.id and t2.flag);

update t
    set flag = false
    where (flag is null or flag) and
          not exists (select 1 from t t2 where t2.id = t.id and not t2.flag);
</code>```

These could be combined into a single (more complicated) statement, but the sets being updated are disjoint.  This limits the updates to the rows that need to be updated, as well as limiting the subquery to a simple lookup (assuming an index on (id, flag)).

Title: Update based on same column

Body:
I have a table like this:

ID | Flag
-----------
 1 | True
 1 | True
 1 | NULL
 1 | True
 1 | NULL
 2 | False
 2 | False
 2 | False
 2 | NULL
 2 | NULL

And I want an output like this:

ID | Flag
-----------
 1 | True
 1 | True
 1 | True
 1 | True
 1 | True
 2 | False
 2 | False
 2 | False
 2 | False
 2 | False

I want to replace nulls with the value assigned in different records. Is there a way to do it in a single update statement?

Body:
You can also use exists:

update t
     set flag = exists (select 1 from t t2 where t2.id = t.id and t2.flag);

The advantage of exists over a subquery with aggregation is performance:  the query can stop at the first row where flag is true.  This is a simple index lookup on an index on (id, flag).

Performance would be more improved by limiting the number of rows being updated.  That actually suggests two separate statements:

update t
    set flag = true
    where (flag is null or not flag) and
          exists (select 1 from t t2 where t2.id = t.id and t2.flag);

update t
    set flag = false
    where (flag is null or flag) and
          not exists (select 1 from t t2 where t2.id = t.id and not t2.flag);

These could be combined into a single (more complicated) statement, but the sets being updated are disjoint.  This limits the updates to the rows that need to be updated, as well as limiting the subquery to a simple lookup (assuming an index on (id, flag)).


问:
run script on docker file to wait postgress
Hello i'm new to docker and linux and i don't know how to run a script for my docker to run after my postgress

this is my script:

```<code>until psql -c '\l'; do
  echo >&2 "$(date +%Y%m%dt%H%M%S) Postgres is unavailable - sleeping"
  sleep 1
done
echo >&2 "$(date +%Y%m%dt%H%M%S) Postgres is up - executing command"

exec ${@}
</code>```

my docker file :

```<code>FROM node:lts-alpine

RUN mkdir -p /home/node/api/node_modules && chown -R node:node /home/node/api

WORKDIR /home/node/api

COPY wait-pg.sh ormconfig.json .env package.json yarn.* ./

USER node

RUN yarn

COPY --chown=node:node . .

EXPOSE 4000

RUN chmod +x /wait-pg.sh

CMD ["yarn", "dev"]
</code>```

my docker compose:

```<code>version: '3.7'
services:
  db-pg:
    image: postgres:12
    container_name: db-pg
    ports:
      - '${DB_PORT}:5432'
    environment:
      ALLOW_EMPTY_PASSWORD: 'no'
      POSTGRES_USER: ${DB_USER}
      POSTGRES_PASSWORD: ${DB_PASS}
      POSTGRES_DB: ${DB_NAME}
    volumes:
      - ci-postgres-data:/data

  ci-api:
    build: .
    container_name: ci-api
    volumes:
      - .:/home/node/api
      - /home/node/api/node_modules
    ports:
      - '${SERVER_PORT}:${SERVER_PORT}'
    depends_on:
      - db-pg
    logging:
      driver: 'json-file'
      options:
        max-size: '10m'
        max-file: '5'

volumes:
  ci-postgres-data:
</code>```

If someone can help me like I would in my docker compose and in my dockerfile.
I would like to know how I can add my script to my docker file and docker compose

答:
Check the below Dockerfile

```<code>FROM node:lts-alpine

RUN mkdir -p /home/node/api/node_modules && chown -R node:node /home/node/api

WORKDIR /home/node/api

COPY wait-pg.sh ormconfig.json .env package.json yarn.* ./

USER node

RUN yarn

COPY --chown=node:node . .

EXPOSE 4000

CMD ["yarn", "dev"]
</code>```

Please try the below docker-compose.yml in which depends_on, healthcheck and links are added as web service depends on db service.

```<code>version: "2.1"
services:
  ci-api:
    build: .
    container_name: ci-api
    volumes:
      - .:/home/node/api
      - /home/node/api/node_modules
    ports:
      - '${SERVER_PORT}:${SERVER_PORT}'
    links:
      - db-pg
    depends_on:
      - db-pg
    logging:
      driver: 'json-file'
      options:
        max-size: '10m'
        max-file: '5'

  db-pg:
    image: postgres:12
    container_name: db-pg
    ports:
      - '${DB_PORT}:5432'
    environment:
      ALLOW_EMPTY_PASSWORD: 'no'
      POSTGRES_USER: ${DB_USER}
      POSTGRES_PASSWORD: ${DB_PASS}
      POSTGRES_DB: ${DB_NAME}
    volumes:
      - ci-postgres-data:/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER}"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  ci-postgres-data:
</code>```

Body:
Hello i'm new to docker and linux and i don't know how to run a script for my docker to run after my postgress

this is my script:

until psql -c '\l'; do
  echo >&2 "$(date +%Y%m%dt%H%M%S) Postgres is unavailable - sleeping"
  sleep 1
done
echo >&2 "$(date +%Y%m%dt%H%M%S) Postgres is up - executing command"

exec ${@}

my docker file :

FROM node:lts-alpine

RUN mkdir -p /home/node/api/node_modules && chown -R node:node /home/node/api

WORKDIR /home/node/api

COPY wait-pg.sh ormconfig.json .env package.json yarn.* ./

USER node

RUN yarn

COPY --chown=node:node . .

EXPOSE 4000

RUN chmod +x /wait-pg.sh

CMD ["yarn", "dev"]

my docker compose:

version: '3.7'
services:
  db-pg:
    image: postgres:12
    container_name: db-pg
    ports:
      - '${DB_PORT}:5432'
    environment:
      ALLOW_EMPTY_PASSWORD: 'no'
      POSTGRES_USER: ${DB_USER}
      POSTGRES_PASSWORD: ${DB_PASS}
      POSTGRES_DB: ${DB_NAME}
    volumes:
      - ci-postgres-data:/data

  ci-api:
    build: .
    container_name: ci-api
    volumes:
      - .:/home/node/api
      - /home/node/api/node_modules
    ports:
      - '${SERVER_PORT}:${SERVER_PORT}'
    depends_on:
      - db-pg
    logging:
      driver: 'json-file'
      options:
        max-size: '10m'
        max-file: '5'

volumes:
  ci-postgres-data:

If someone can help me like I would in my docker compose and in my dockerfile.
I would like to know how I can add my script to my docker file and docker compose

Body:
Check the below Dockerfile

FROM node:lts-alpine

RUN mkdir -p /home/node/api/node_modules && chown -R node:node /home/node/api

WORKDIR /home/node/api

COPY wait-pg.sh ormconfig.json .env package.json yarn.* ./

USER node

RUN yarn

COPY --chown=node:node . .

EXPOSE 4000

CMD ["yarn", "dev"]

Please try the below docker-compose.yml in which depends_on, healthcheck and links are added as web service depends on db service.

version: "2.1"
services:
  ci-api:
    build: .
    container_name: ci-api
    volumes:
      - .:/home/node/api
      - /home/node/api/node_modules
    ports:
      - '${SERVER_PORT}:${SERVER_PORT}'
    links:
      - db-pg
    depends_on:
      - db-pg
    logging:
      driver: 'json-file'
      options:
        max-size: '10m'
        max-file: '5'

  db-pg:
    image: postgres:12
    container_name: db-pg
    ports:
      - '${DB_PORT}:5432'
    environment:
      ALLOW_EMPTY_PASSWORD: 'no'
      POSTGRES_USER: ${DB_USER}
      POSTGRES_PASSWORD: ${DB_PASS}
      POSTGRES_DB: ${DB_NAME}
    volumes:
      - ci-postgres-data:/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER}"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  ci-postgres-data:


问:
Advice on Web Service or related technology
I am developing a system that must be able to receive an XML  messages (preferably without SOAP envelope) from other's company external system through the internet. I am not sure what technology is external system written in.
The developers from the external company must create a XML sending feature. I would like to minimazie their effort.
Is WCF good choice for that?

The OS will be either Windows XP with IIS 5.1 or Windows Server 2003 with IIS 6.0.
.NET Framework is 3.5.

Thanks.

答:
Picking out a technology requires more details.
Some of the basics are:
What's your budget ?
what resources do you have now?
Who will be responsible for maintainence, RFC later?
Will your 'product' be called for data communication or Will your product need to call them for data communication? </p>

<p>To process/generate XML, the free and simple ones are, for example, JAVA, PHP (and many others too).    </p>

Body:
Picking out a technology requires more details.
Some of the basics are:
What's your budget ?
what resources do you have now?
Who will be responsible for maintainence, RFC later?
Will your 'product' be called for data communication or Will your product need to call them for data communication?

To process/generate XML, the free and simple ones are, for example, JAVA, PHP (and many others too).


问:
Cannot getText from EditText in AlertDialog that has setView
I made a custom XML layout file, in there I have an EditText.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText
        android:layout_margin="20dp"
        android:id="@+id/length"
        android:layout_width="match_parent"
        android:inputType="number"
        android:hint="Vibration time(ms)"
        android:importantForAutofill="no"
        android:layout_height="wrap_content"/>
</LinearLayout>
</code>```

In another activity, I made an AlertDialog, then I setView to this layout. It was successful and I see EditText in the AlertDialog.
But the problem is, when I do this:

```<code>EditText edittext=(EditText)findViewById(R.id.length);
int time=Integer.parseInt(edittext.getText().toString());
</code>```

An error happens and say

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
</code>```

I don't know why it says null object because I gave EditText an ID.

答:
do it like this</p>

```<code>final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.your_layout);

.
.

EditText edittext=(EditText)dialog.findViewById(R.id.length);

dialog.show();
</code>```

Body:
I made a custom XML layout file, in there I have an EditText.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText
        android:layout_margin="20dp"
        android:id="@+id/length"
        android:layout_width="match_parent"
        android:inputType="number"
        android:hint="Vibration time(ms)"
        android:importantForAutofill="no"
        android:layout_height="wrap_content"/>
</LinearLayout>

In another activity, I made an AlertDialog, then I setView to this layout. It was successful and I see EditText in the AlertDialog.
But the problem is, when I do this:

EditText edittext=(EditText)findViewById(R.id.length);
int time=Integer.parseInt(edittext.getText().toString());

An error happens and say

java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference

I don't know why it says null object because I gave EditText an ID.

Body:
do it like this

final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.your_layout);

.
.

EditText edittext=(EditText)dialog.findViewById(R.id.length);

dialog.show();


问:
How to append some data into existing xlsx sheet R?
I´m trying to read a xlsx file and write one data frame into the same sheet of xlsx without remove the other rows of my data frame.

I tried with the library("XLConnect") and with the function appendWorksheet() but the data is not writing in the correct place, and with the library("xlsx") but I can´t find a function similar to appendWorksheet.

I just want to read my xlsx file and write my data that is into a data frame and write into the same xlsx file without removing the previous rows.

答:
There doesn't seem to be a great way to append data to an xlsx file. You can create a function which will read in the sheet and append data to the dataframe and then overwrite the xlsx.

```<code>library(xslx)
appendxlsx <- function(df2, path, sheetName) {
  df1 <- read.xlsx2(path, sheetName = sheetName)
  colnames(df2) <- colnames(df1)
  df <- rbind(df1, df2)
  write.xlsx2(df, path, sheetName = sheetName)
}
</code>```

Then you would just call the function supplying the updated dataframe (df2), the path to the xlsx, and the sheet name. Something like this:

```<code>appendxlsx(df2=df2, "/path/to/xlsx", sheetName = "Sheet1")
</code>```

Body:
There doesn't seem to be a great way to append data to an xlsx file. You can create a function which will read in the sheet and append data to the dataframe and then overwrite the xlsx.

library(xslx)
appendxlsx <- function(df2, path, sheetName) {
  df1 <- read.xlsx2(path, sheetName = sheetName)
  colnames(df2) <- colnames(df1)
  df <- rbind(df1, df2)
  write.xlsx2(df, path, sheetName = sheetName)
}

Then you would just call the function supplying the updated dataframe (df2), the path to the xlsx, and the sheet name. Something like this:

appendxlsx(df2=df2, "/path/to/xlsx", sheetName = "Sheet1")


问:
Job for artifactory.service failed
Ubuntu 20.04 LTS
I just installed oss version if JFrog Artifactory
To run artifactory I used systemctl start artifactory.service by getting this error:

```<code>Job for artifactory.service failed because the control process exited with error code.
See "systemctl status artifactory.service" and "journalctl -xe" for details.
</code>```

If I run systemctl status artifactory.service this is what I am getting

```<code>● artifactory.service - Artifactory service
     Loaded: loaded (/lib/systemd/system/artifactory.service; enabled; vendor preset: enabled)
     Active: inactive (dead)

Jun 01 00:25:42 siddharth-HP-Notebook systemd[1]: Stopped Artifactory service.
Jun 01 00:25:42 siddharth-HP-Notebook systemd[1]: Starting Artifactory service...
Jun 01 00:25:43 siddharth-HP-Notebook artifactoryManage.sh[17274]: 2020-05-31T18:55:43.286Z [shell] [INFO ] [] [artifac>
Jun 01 00:25:43 siddharth-HP-Notebook systemd[1]: artifactory.service: Can't open PID file /run/artifactory.pid (yet?) >
Jun 01 00:25:43 siddharth-HP-Notebook systemd[1]: artifactory.service: Failed with result 'protocol'.
Jun 01 00:25:43 siddharth-HP-Notebook systemd[1]: Failed to start Artifactory service.
Jun 01 00:25:48 siddharth-HP-Notebook systemd[1]: Stopped Artifactory service.
Jun 01 00:25:48 siddharth-HP-Notebook systemd[1]: /lib/systemd/system/artifactory.service:10: PIDFile= references a pat>
Jun 01 00:31:37 siddharth-HP-Notebook systemd[1]: /lib/systemd/system/artifactory.service:10: PIDFile= references a pat>
Jun 01 00:31:38 siddharth-HP-Notebook systemd[1]: /lib/systemd/system/artifactory.service:10: PIDFile= references a pat>
</code>```

Also during the installation, I got this error in the end that can be helpful:

```<code>Triggering migration script, this will migrate if needed ...
chown: invalid user: ‘artifactory:artifactory’
[WARN] Could not set owner of [/opt/jfrog/artifactory/var/etc] to [artifactory:artifactory]
Processing triggers for systemd (245.4-4ubuntu3.1) ...
</code>```

答:
Be sure that PID file is there:
Jun 01 00:25:43 siddharth-HP-Notebook systemd[1]: artifactory.service: Can't open PID file /run/artifactory.pid (yet?) >

If it's there, you need to check permissions and your service file to check what's your path of PID file

Title: Job for artifactory.service failed

Body:
Ubuntu 20.04 LTS
I just installed oss version if JFrog Artifactory
To run artifactory I used systemctl start artifactory.service by getting this error:

Job for artifactory.service failed because the control process exited with error code.
See "systemctl status artifactory.service" and "journalctl -xe" for details.

If I run systemctl status artifactory.service this is what I am getting

● artifactory.service - Artifactory service
     Loaded: loaded (/lib/systemd/system/artifactory.service; enabled; vendor preset: enabled)
     Active: inactive (dead)

Jun 01 00:25:42 siddharth-HP-Notebook systemd[1]: Stopped Artifactory service.
Jun 01 00:25:42 siddharth-HP-Notebook systemd[1]: Starting Artifactory service...
Jun 01 00:25:43 siddharth-HP-Notebook artifactoryManage.sh[17274]: 2020-05-31T18:55:43.286Z [shell] [INFO ] [] [artifac>
Jun 01 00:25:43 siddharth-HP-Notebook systemd[1]: artifactory.service: Can't open PID file /run/artifactory.pid (yet?) >
Jun 01 00:25:43 siddharth-HP-Notebook systemd[1]: artifactory.service: Failed with result 'protocol'.
Jun 01 00:25:43 siddharth-HP-Notebook systemd[1]: Failed to start Artifactory service.
Jun 01 00:25:48 siddharth-HP-Notebook systemd[1]: Stopped Artifactory service.
Jun 01 00:25:48 siddharth-HP-Notebook systemd[1]: /lib/systemd/system/artifactory.service:10: PIDFile= references a pat>
Jun 01 00:31:37 siddharth-HP-Notebook systemd[1]: /lib/systemd/system/artifactory.service:10: PIDFile= references a pat>
Jun 01 00:31:38 siddharth-HP-Notebook systemd[1]: /lib/systemd/system/artifactory.service:10: PIDFile= references a pat>

Also during the installation, I got this error in the end that can be helpful:

Triggering migration script, this will migrate if needed ...
chown: invalid user: ‘artifactory:artifactory’
[WARN] Could not set owner of [/opt/jfrog/artifactory/var/etc] to [artifactory:artifactory]
Processing triggers for systemd (245.4-4ubuntu3.1) ...


问:
Calculate the number of unordered pairs in an array whose bitwise "AND" is a power of 2 in O(n) or O(n*log(n))
How to calculate number of unordered pairs in an array whose bitwise AND is a power of 2. For ex if the array is [10,7,2,8,3]. The answer is 6.
Explanation(0-based index):

a[0]&a[1] = 2

a[0]&a[2] = 2

a[0]&a[3] = 8

a[0]&a[4] = 2

a[1]&a[2] = 2

a[2]&a[4] = 2

The only approach that comes to my mind is brute force. How to optimize it to perform in O(n) or O(n*log(n))?

The constraints on the size of array can be at max 10^5. And the value in that array can be upto 10^12.

Here is the brute force code that I tried.

    int ans = 0;
    for (int i = 0; i < a.length; i++) {
        for (int j = i + 1; j < a.length; j++) {
            long and = a[i] & a[j];
            if ((and & (and - 1)) == 0 && and != 0)
                ans++;
        }
    }
    System.out.println(ans);
```

答:
Transform your array of values into an array of index sets, where each set corresponds to a particular bit and contains the indexes of the value from the original set that have the bit set.  For example, your example array A = [10,7,2,8,3] becomes B = [{1,4}, {0,1,2,4}, {1}, {0,3}].  A fixed-sized array of bitvectors is an ideal data structure for this, as it makes set union/intersection/setminus relatively easy and efficient.

Once you have that array of sets B (takes O(nm) time where m is the size of your integers in bits), iterate over every element i of A again, computing ∑j|Bj∖i∖⋃kBk:k≠j∧i∈Bk|:i∈Bj.  Add those all together and divide by 2, and that should be the number of pairs (the "divide by 2" is because this counts each pair twice, as what it is counting is the number of numbers each number pairs with).  Should only take O(nm2) assuming you count the setminus operations as O(1) -- if you count them as O(n), then you're back to O(n2), but at least your constant factor should be small if you have efficient bitsets.

Pseudocode:

```<code>foreach A[i] in A:
    foreach bit in A[i]:
        B[bit] += {i}

pairs = 0
foreach A[i] in A:
    foreach B[j] in B:
        if i in B[j]:
            tmp = B[j] - {i}
            foreach B[k] in B:
                if k != j && i in B[k]:
                    tmp -= B[k]
            pairs += |tmp|

return pairs/2
</code>```

Body:
Transform your array of values into an array of index sets, where each set corresponds to a particular bit and contains the indexes of the value from the original set that have the bit set.  For example, your example array A = [10,7,2,8,3] becomes B = [{1,4}, {0,1,2,4}, {1}, {0,3}].  A fixed-sized array of bitvectors is an ideal data structure for this, as it makes set union/intersection/setminus relatively easy and efficient.

Once you have that array of sets B (takes O(nm) time where m is the size of your integers in bits), iterate over every element i of A again, computing ∑j|Bj∖i∖⋃kBk:k≠j∧i∈Bk|:i∈Bj.  Add those all together and divide by 2, and that should be the number of pairs (the "divide by 2" is because this counts each pair twice, as what it is counting is the number of numbers each number pairs with).  Should only take O(nm2) assuming you count the setminus operations as O(1) -- if you count them as O(n), then you're back to O(n2), but at least your constant factor should be small if you have efficient bitsets.

Pseudocode:

foreach A[i] in A:
    foreach bit in A[i]:
        B[bit] += {i}

pairs = 0
foreach A[i] in A:
    foreach B[j] in B:
        if i in B[j]:
            tmp = B[j] - {i}
            foreach B[k] in B:
                if k != j && i in B[k]:
                    tmp -= B[k]
            pairs += |tmp|

return pairs/2


问:
Can't create multiple sqlite tables
I've been trying to create a database which contains two tables but for some reason I keep getting this error I've looked at other peoples code and from what I can see its the exact same... I also try to run it one at a time but it only makes one table not both... I may just be missing something small?

Code

```<code>import sqlite3

connie = sqlite3.connect('pb.db')

c = connie.cursor()

c.execute("""
CREATE TABLE users(
_ID INTEGER PRIMARY KEY,
username TEXT,
password TEXT
);
CREATE TABLE results(
_ID INTEGER PRIMARY KEY,
users_id INTEGER,
simresult INTEGER,
FOREIGN KEY(users_ID) REFERENCES users(_ID)
);
""")

connie.commit()
</code>```

Error

```<code>Traceback (most recent call last):
  File "C:/Users/britsge/OneDrive - Iona College/Year 11/DSO/PowerballSite/db-create-user.py", line 19, in <module>
    """)
sqlite3.Warning: You can only execute one statement at a time.

</code>```

答:
```<code>c.execute("""
CREATE TABLE users(
_ID INTEGER PRIMARY KEY,
username TEXT,
password TEXT
);
""")

c.execute("""
CREATE TABLE results(
_ID INTEGER PRIMARY KEY,
users_id INTEGER,
simresult INTEGER,
FOREIGN KEY(users_ID) REFERENCES users(_ID)
);
""")

connie.commit()
</code>```

Title: Can't create multiple sqlite tables

Body:
I've been trying to create a database which contains two tables but for some reason I keep getting this error I've looked at other peoples code and from what I can see its the exact same... I also try to run it one at a time but it only makes one table not both... I may just be missing something small?

Code

import sqlite3

connie = sqlite3.connect('pb.db')

c = connie.cursor()

c.execute("""
CREATE TABLE users(
_ID INTEGER PRIMARY KEY,
username TEXT,
password TEXT
);
CREATE TABLE results(
_ID INTEGER PRIMARY KEY,
users_id INTEGER,
simresult INTEGER,
FOREIGN KEY(users_ID) REFERENCES users(_ID)
);
""")

connie.commit()

Error

Traceback (most recent call last):
  File "C:/Users/britsge/OneDrive - Iona College/Year 11/DSO/PowerballSite/db-create-user.py", line 19, in <module>
    """)
sqlite3.Warning: You can only execute one statement at a time.


问:
Visual Studio Code suddenly lost autocomplete with Unity
I have been programming on Unity with VSCode for the past two months and had very few issues about it. But suddenly, it has stopped the autocomplete, even thought I tried several approaches that I found online.

I have all the extensions needed for the development (C# (1.22), Debugger for Unity(2.7.5), Unity Code Snippets (1.3.0), Unity Tools (1.2.3) and am currently using Unity 2019.3.8f1 on Windows 10.

I have already changed the External Script Editor to work with VSCode but with no luck. I have also tried to delete all .csproj files, to restart computer/internet, all with no luck either

It says on my output panel that it is installing C# dependencies, but it never ends downloading them.

What is the possible cause of this problem ? I have found that many people have this kind of error, but they are always when trying to use VSCode with Unity for their first time. In my case I have been using for a long time and it has suddenly stopped.

Thanks in advance.

答:
C# vscode extensions works by having the actual c# heavy lifting in a separate language server process "omnisharp.exe", and actual typescript extensions is mostly glue. So whenever c# extension gets updated, extensions manually downloads new version of omnisharp.exe.

As far as I know, all language services are turned off while new omnisharp.exe is downloading. Why your download is failing, I can't tell you really without more info, it could be something on your end.

I suggest you first try to uninstall/install c# extensions, as that may help if extension folder got corrupted in any way. If that doesn't help, try setting "omnisharp.path" vscode settings to "1.35.2" or "1.35.1" or similar, to manually target version.


问:
how to show original file structure in intellij?
I imported seldon-core to intellij, which tried to separate the files to different projects automatically.

How to disable this? I need to view all the files in original/same structure with the git repo, like:

Thanks

UPDATE

It STILL DOES NOT work now even I did the following:

When importing project, we need choose Project format as .ipr (file based).

Then, we need select Project Files

答:
Have you tried switching between the options under projects? There is an option with project files

Project Files shows the exact file structure as your git repo.


问:
Proper way to create a POST in PHP in woocommerce plugin
Is this a valid POST request in PHP in a woocommerce plugin?
Is the syntax correct and will it work?
Are there any ways I could improve this?

Seems there are a lot of ways to do this in PHP and don't know about the positive and negatives to pick one.

Wordpress plugin docs recommend: wp_remote_post()
Someone else recommend curl.

And then this approach which I've used:

protected function generate_vm_request($order_id){
        $order  = wc_get_order( $order_id );
        $post_data = array();
        $post_data['x_account_id'] = $this->test_api_key;
        $post_data['x_amount'] = $order-> get_total() ;
        $post_data['x_currency'] = version_compare( WC_VERSION, '3.0.0', '<' ) ?
        $query1 = implode('', array_map(
            function ($v, $k) {
                return $k.$v;
            },
            $post_data,
            array_keys($post_data)
            ));
        $vm_query  =  http_build_query($post_data, '', '&');
        $vm_url = $this->VMURL;
        $opts = array('http' =>
            array(
              'method'  => 'POST',
              'header'  => 'Content-Type: application/x-www-form-urlencoded',
              'content' => $vm_query,
            )
          );
        $context  = stream_context_create($opts);
        $result = file_get_contents($vm_url, false, $context);
}
```

What is the best way?

答:
By using wp_remote_post() you can simplify your function down to:

```<code>protected function generate_vm_request($order_id){
    $order  = wc_get_order( $order_id );
    $post_data = array();
    $post_data['x_account_id'] = $this->test_api_key;
    $post_data['x_amount'] = $order->get_total() ;
    $post_data['x_currency'] = version_compare( WC_VERSION, '3.0.0', '<' ) ?

    $result = wp_remote_post( $this->VMURL, $post_data );
}
</code>```

Body:
Is this a valid POST request in PHP in a woocommerce plugin?
Is the syntax correct and will it work?
Are there any ways I could improve this?

Seems there are a lot of ways to do this in PHP and don't know about the positive and negatives to pick one.

Wordpress plugin docs recommend: wp_remote_post()
Someone else recommend curl.

And then this approach which I've used:

protected function generate_vm_request($order_id){
        $order  = wc_get_order( $order_id );
        $post_data = array();
        $post_data['x_account_id'] = $this->test_api_key;
        $post_data['x_amount'] = $order-> get_total() ;
        $post_data['x_currency'] = version_compare( WC_VERSION, '3.0.0', '<' ) ?
        $query1 = implode('', array_map(
            function ($v, $k) {
                return $k.$v;
            },
            $post_data,
            array_keys($post_data)
            ));
        $vm_query  =  http_build_query($post_data, '', '&');
        $vm_url = $this->VMURL;
        $opts = array('http' =>
            array(
              'method'  => 'POST',
              'header'  => 'Content-Type: application/x-www-form-urlencoded',
              'content' => $vm_query,
            )
          );
        $context  = stream_context_create($opts);
        $result = file_get_contents($vm_url, false, $context);
}

What is the best way?

Body:
By using wp_remote_post() you can simplify your function down to:

protected function generate_vm_request($order_id){
    $order  = wc_get_order( $order_id );
    $post_data = array();
    $post_data['x_account_id'] = $this->test_api_key;
    $post_data['x_amount'] = $order->get_total() ;
    $post_data['x_currency'] = version_compare( WC_VERSION, '3.0.0', '<' ) ?

    $result = wp_remote_post( $this->VMURL, $post_data );
}


问:
How to share html component amount different page
In ASP.NET, I have a master page, and five other pages which are under master page.

In all five pages, I need to implement a button, after clicking it, will generate different download results.

My original implementation is, in all five page, will all have a "Button", so in code behind will have corresponding event method to generate the download.

But my approach, will have duplicated html compoents.

Is there a way I can define the download button in my master page, when clicking button in different page, event method from different page will be invoked?

答: I don't know what exactly You want to achieve, but maybe it would be better to have one aspx with the button and load the correct ascx file to this page according to some criteria? Each ascx can derive from some interface with some method, f.e. Click(), and each time the button on aspx is clicked, the Click() method from currently loaded ascx can be called.</p>


问:
Gremlin where query won't use values from labeled vertices
I'm trying to find the edge between 2 vertexes in a single query on Neptun, but something is really weird.

Here's the query

```<code>g.V().has("PRINCIPAL", "principal id", "Test User").as("principal").id().as("principal_id")
.select("principal").out().hasLabel("LICENSE").as("license").valueMap(true).as("license_vm")
.select("license").in("is attached to").as("attachments")
.select("license").inE().where(outV().hasId(select("principal").id()))

.valueMap(true)
</code>```

I know it's complicated, but here's the idea:

Visit a PRINCIPAL vertex, save a reference to is as "principal" and a reference to its id as "principal_id"

Visit its out() vertices and label them as "license", I'm also saving their valuemaps for later

return to license, and get all of the in() vertices that are associated by an edge labelled "is attached to", save a reference to those as "attachments"

return to license, but now, I want to get the in-edge that points to my "principal" (from earlier).  This is where it gets weird, no matter what I do here, I can't get it to recognize the principal in a where clause.  THe above example fails, but if I copy-paste the literal id, it works fine

What am I missing?

答:
Replace the where step on the second to last line of the query with:

```<code>filter(out().where(eq('principal')).by(T.id))
</code>```

That should get it working.

The hasId step can take either a predicate such as gt(123) or a list of one or more ID values. That's why it works when you use the ID value.

Body:
I'm trying to find the edge between 2 vertexes in a single query on Neptun, but something is really weird.

Here's the query

g.V().has("PRINCIPAL", "principal id", "Test User").as("principal").id().as("principal_id")
.select("principal").out().hasLabel("LICENSE").as("license").valueMap(true).as("license_vm")
.select("license").in("is attached to").as("attachments")
.select("license").inE().where(outV().hasId(select("principal").id()))

.valueMap(true)

I know it's complicated, but here's the idea:

Visit a PRINCIPAL vertex, save a reference to is as "principal" and a reference to its id as "principal_id"

Visit its out() vertices and label them as "license", I'm also saving their valuemaps for later

return to license, and get all of the in() vertices that are associated by an edge labelled "is attached to", save a reference to those as "attachments"

return to license, but now, I want to get the in-edge that points to my "principal" (from earlier).  This is where it gets weird, no matter what I do here, I can't get it to recognize the principal in a where clause.  THe above example fails, but if I copy-paste the literal id, it works fine

What am I missing?

Body:
Replace the where step on the second to last line of the query with:

filter(out().where(eq('principal')).by(T.id))

That should get it working.

The hasId step can take either a predicate such as gt(123) or a list of one or more ID values. That's why it works when you use the ID value.


问:
My View works fine for my Desktop but doesn't work right for my mobile
Hello some one can help me to fix this ?

In my Desktop browser my fragment view works fine  but in my mobile it doesn't...

Desktop

Mobile

this is my View :

```<code><core:FragmentDefinition xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:custom="meusapps.testeAppOpenUI5.control">
<ScrollContainer id="root1" horizontal="false" vertical="true" height="100%">
    <List id="listaProposta" headerText="Propostas em Tramitação" items="{ path: 'modelProposta>/'}">
        <CustomListItem >
            <HBox  width="100%">
                <HBox width="75%">
                    <HBox alignContent="Center" alignItems="Center">
                        <Avatar src="{modelProposta>detalheAutores/ultimoStatus/urlFoto}" initials="{modelProposta>initials}" displaySize="M" showBorder="true"
                            class="sapUiSmallMarginBegin sapUiSmallMarginTopBottom"/>
                    </HBox>
                    <VBox class="sapUiSmallMarginBegin sapUiSmallMarginTopBottom">
                        <Label text="{modelProposta>proposta/siglaTipo} {modelProposta>proposta/numero}/{modelProposta>proposta/ano}" design="Bold" wrapping="true"/>
                        <Label text="{modelProposta>proposta/ementa}" wrapping="true"/>
                    </VBox>
                </HBox>
                <HBox width="25%">
                    <VBox class="sapUiSmallMarginBegin sapUiSmallMarginTopBottom">
                        <HBox alignContent="Center" alignItems="Center" class="sapUiSmallMarginBottom">
                            <Button icon="sap-icon://thumb-up" type="Accept" press="onAgreePress" class="sapUiSmallMarginBegin sapUiMediumMarginEnd roundButton"/>
                            <Button icon="sap-icon://thumb-down" type="Reject" press="onDisagreePress" class="sapUiMediumMarginEnd roundButton"/>
                            <Button icon="sap-icon://decline" press="onRemovePress" class="roundButton"/>
                        </HBox>
                        <custom:Rating id="pi-with-animation" class="sapUiSmallMarginBottom sapUiSizeCompact" percentValue="50" displayValue="50%" state="Success"
                             displayOnly="true"/>
                    </VBox>
                </HBox>
            </HBox>
        </CustomListItem>
    </List>
</ScrollContainer>
</code>```

thank you in advance

答: I solved the problem following the advice of @Marc, I changed the control CustomListItem to ResponsiveTable  and used the popin  for the third column </p>

Body:
Hello some one can help me to fix this ?

In my Desktop browser my fragment view works fine  but in my mobile it doesn't...

Desktop

Mobile

this is my View :

<core:FragmentDefinition xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:custom="meusapps.testeAppOpenUI5.control">
<ScrollContainer id="root1" horizontal="false" vertical="true" height="100%">
    <List id="listaProposta" headerText="Propostas em Tramitação" items="{ path: 'modelProposta>/'}">
        <CustomListItem >
            <HBox  width="100%">
                <HBox width="75%">
                    <HBox alignContent="Center" alignItems="Center">
                        <Avatar src="{modelProposta>detalheAutores/ultimoStatus/urlFoto}" initials="{modelProposta>initials}" displaySize="M" showBorder="true"
                            class="sapUiSmallMarginBegin sapUiSmallMarginTopBottom"/>
                    </HBox>
                    <VBox class="sapUiSmallMarginBegin sapUiSmallMarginTopBottom">
                        proposta/siglaTipo} {modelProposta>proposta/numero}/{modelProposta>proposta/ano}" design="Bold" wrapping="true"/>
                        proposta/ementa}" wrapping="true"/>
                    </VBox>
                </HBox>
                <HBox width="25%">
                    <VBox class="sapUiSmallMarginBegin sapUiSmallMarginTopBottom">
                        <HBox alignContent="Center" alignItems="Center" class="sapUiSmallMarginBottom">
                            <Button icon="sap-icon://thumb-up" type="Accept" press="onAgreePress" class="sapUiSmallMarginBegin sapUiMediumMarginEnd roundButton"/>
                            <Button icon="sap-icon://thumb-down" type="Reject" press="onDisagreePress" class="sapUiMediumMarginEnd roundButton"/>
                            <Button icon="sap-icon://decline" press="onRemovePress" class="roundButton"/>
                        </HBox>
                        <custom:Rating id="pi-with-animation" class="sapUiSmallMarginBottom sapUiSizeCompact" percentValue="50" displayValue="50%" state="Success"
                             displayOnly="true"/>
                    </VBox>
                </HBox>
            </HBox>
        </CustomListItem>
    </List>
</ScrollContainer>

thank you in advance


答:
Use a global (g), multi-line (m) RegExp to match any pipe (\|) at the start of a line (^)

// here's your original string
let tOut = `| D| Gbm| G| A|
| D| Gbm| G| A|
| Bm| Gbm| G| D|
| Bm| Gbm| G| A|
| D| Gbm| G| A|
| D| Gbm| G| A|
| Bm| Gbm| G| D|
| Bm| E| G| G A|
| D| Gbm|`

// replace the pipes
tOut = tOut.replace(/^\| ?/mg, '')

console.log(tOut)
// document.write(tOut)```

The above also removes the space following the pipe if it's present. If you want to keep the space, change the regex to /^\|/mg.

Title: Javascript Delete First Character on Each Line of String

Body:
I need to remove the first character of a string "|" on each line in javascript.

| D| Gbm| G| A|
| D| Gbm| G| A|
| Bm| Gbm| G| D|
| Bm| Gbm| G| A|
| D| Gbm| G| A|
| D| Gbm| G| A|
| Bm| Gbm| G| D|
| Bm| E| G| G A|
| D| Gbm|

end results needed:

 D| Gbm| G| A|
 D| Gbm| G| A|
 Bm| Gbm| G| D|
 Bm| Gbm| G| A|
 D| Gbm| G| A|
 D| Gbm| G| A|
 Bm| Gbm| G| D|
 Bm| E| G| G A|
 D| Gbm|

This is the page I need to edit to get just the chords.
I removed the quotes with

tOut = tOut.replace("\"", "");

http://www.lesession.co.uk/abc/abcChordsOut.htm
This is the text input in ABC Notation format:

X:1
T:Guitar
L:1/8
K:D
Q:1/4=120
R:Medium Boogie
M:4/4
| "D"D,2 A,,D, D,2 [C,A,,]_B,,/2=B,,/2 | "Gbm"_G,,3 _G,,/2E,,/2 _G,,2 _D,/2=D,/2_E,/2=E,/2 | "G"G,3 G, G,3 =G,, | "A"A,,3 A,, A,,2 B,,2 |
| "D"A,,3 =D,/2A,,/2 D,2 F,G, | "Gbm"_G,,3 _G,,/2E,,/2 _G,,2 _D,_G,, | "G"=G,,3 G,,/2E,,/2 G,,2 B,,=D, | "A"A,2 G,A, A,E, A,,2 |
| "Bm"B,,2 =C,B,,/2A,,/2 B,,2 A,,2 | "Gbm"_G,3 _G,/2=F,/2 _G,2 _D,2 | "G"=G,3 =D, G,2 A,2 | "D"[D3^G,3] D D2 B,/2C/2A,/2^C,/2=C,/2 |
| "Bm"B,,3 B,,/2A,,/2 B,,3 F,,/2E,,/2 | "Gbm"_G,,3 _G,, E,,/2_G,,3/2 A,,_D, | "G"=G,,3 G,,/2E,,/2 G,,2 B,,/2G,,/2_B,,/2^G,,/2 | "A"A,,3 A,, A,,A,,=B,,C, |
| "D"D,3 D,/2A,,/2 D,2 A,2 | "Gbm"_G,,3 _G,,/2=F,,/2 _G,,3 E,, | "G"=G,,3 G,,/2E,,/2 G,,2 B,,3/2=C,/2 | "A"A,,4  z4 |
| "D" z3/2 B,,/2 ^C,D, A,,/2D,3/2- D,3/2A,/2 | "Gbm"_G,,3 _G,, E,,/2_G,,3/2 A,,_D, | "G"=G,,3 G,,/2E,,/2 G,,2 _B,,=D, | "A"A,,3 A,, A,,2 E,,2 |
| "Bm"B,2 B,2 [B,3D,3] F, | "Gbm"_G,,3 _G,,/2E,,/2 _G,,2 _D,_G,, | "G"=G,,3 G,,/2E,,/2 G,,2 =B,,[=D,A,,-- ] | "D"[D,3A,,3] D,  z4 |
| "Bm" z4  z2  z F,/2=F,/2 | "E"E,,3 E,, E,,2 B,,E,,/2G,,/2- | "G"G,,2- G,,/2G,,E,,/2 G,,3/2B,,/2- B,,2 | "G"_A,/2G,3/2 B,G, "A"=A,2 A,,2 |
| "D" z8 | "Gbm" z8 |

after it has been formatted it is pasted into the Java app Impro-Visor to give the chords.

Body:
Use a global (g), multi-line (m) RegExp to match any pipe (\|) at the start of a line (^)

// here's your original string
let tOut = `| D| Gbm| G| A|
| D| Gbm| G| A|
| Bm| Gbm| G| D|
| Bm| Gbm| G| A|
| D| Gbm| G| A|
| D| Gbm| G| A|
| Bm| Gbm| G| D|
| Bm| E| G| G A|
| D| Gbm|`

// replace the pipes
tOut = tOut.replace(/^\| ?/mg, '')

console.log(tOut)
// document.write(tOut)

The above also removes the space following the pipe if it's present. If you want to keep the space, change the regex to /^\|/mg.


问:
how do i append content of a dictionary to a list in python?
```<code>import csv

with open('filename.csv') as csv_file:
    datarow = csv.reader(filename, delimiter=',')
    dict_places = {}
    list_places = []
    for row in datarow:
        dict_places['Continent'] = row[0]
        dict_places['Country'] = row[1]
        dict_places['Capital'] = row[2]
        print(list_places.append(dict_places))
</code>```

I am reading  a csv file filename.csv , I am not  getting the desired result like below.

[{'Continent': 'Europe', 'Country': 'Spain', 'Capital': 'Madrid'}, {'Continent': 'Europe', 'Country': 'Portugal', 'Capital': 'Lisbon'}', {'Continent': 'Europe', 'Country': 'England', 'Capital': 'London'}]

答:
Move your declaration for dict_places inside the loop:

```<code>list_places = []
for row in datarow:
    dict_places = {}
    dict_places['Continent'] = row[0]
    dict_places['Country'] = row[1]
    dict_places['Capital'] = row[2]
    print(list_places.append(dict_places))
</code>```

Otherwise you're just replacing the values in the same dictionary on each iteration and you'll end up with a list of the same dictionary

Body:
import csv

with open('filename.csv') as csv_file:
    datarow = csv.reader(filename, delimiter=',')
    dict_places = {}
    list_places = []
    for row in datarow:
        dict_places['Continent'] = row[0]
        dict_places['Country'] = row[1]
        dict_places['Capital'] = row[2]
        print(list_places.append(dict_places))

I am reading  a csv file filename.csv , I am not  getting the desired result like below.

[{'Continent': 'Europe', 'Country': 'Spain', 'Capital': 'Madrid'}, {'Continent': 'Europe', 'Country': 'Portugal', 'Capital': 'Lisbon'}', {'Continent': 'Europe', 'Country': 'England', 'Capital': 'London'}]

Body:
Move your declaration for dict_places inside the loop:

list_places = []
for row in datarow:
    dict_places = {}
    dict_places['Continent'] = row[0]
    dict_places['Country'] = row[1]
    dict_places['Capital'] = row[2]
    print(list_places.append(dict_places))

Otherwise you're just replacing the values in the same dictionary on each iteration and you'll end up with a list of the same dictionary


问:
HTML color input change event on Safari fires to often
I'm trying to use the browser native HTML color input in Safari on MacOS. I have the problem that the change event fires to often if an user tries to pick a color from the following view in the color picker.

I only need the color when the user is finished with his selection or respectively closes the color picker.

According to the Mozilla documentation:

The change event is fired when the user dismisses the color picker.

is only fired when the user dismisses the picker.

Is this a bug in Safari on MacOS?

How do I get the last selected color?

答:
Cross-browser event differences are a common problem. My suggestion is below:

Try the oninput attribute to trigger a function when an input is finally confirmed.

e.g.

```<code><input type="color" value="#ff0000" id="bgcolor" name="bgcolor" oninput="changeBackground(bgcolor.value)">
</code>```

The triggered function looks like:

```<code>function changeBackground(colorValue){
    document.body.style.backgroundColor = colorValue;
}
</code>```

Change the style to the style you wish to change if it is not background color.

Body:
Cross-browser event differences are a common problem. My suggestion is below:

Try the oninput attribute to trigger a function when an input is finally confirmed.

e.g.

<input type="color" value="#ff0000" id="bgcolor" name="bgcolor" oninput="changeBackground(bgcolor.value)">

The triggered function looks like:

function changeBackground(colorValue){
    document.body.style.backgroundColor = colorValue;
}

Change the style to the style you wish to change if it is not background color.


问:
React-Markdown disable parsing of underscore
I'm using react-markdown to render markdown strings.

However in my strings, I have underscore to indicate blank words to fill in

e.g My ____________ is awesome.

However it renders as "__, even when i disable  type, it renders only __ but i want it to be the original __________

Or is there another renderer which can do it?

答:
Seems a hard task with official API. According to my tests, unwrapDisallowed doesn't help as it's an option to be even more restrictive (remove the strong markers with content altogether).

And depending on your codebase and the depth of integration of react-markdown, selecting another Markdown renderer may be a big task (polished styling, customizations, ...)

You could fork the lib and try to remove the strong parsing, but then you have the burden of building and re-integrating upstream patches as long as you're using the component. A modification that could be merged upstream would be a solution, but I can imagine that such a modification is no easy task, as most maintainers prefer generic solutions (in my experience).

My proposal is a workaround as a compromise:

You could replace all underscores  with something similar looking before assigning the content to react-markdown. The parser wouldn't interpret this as "strong" markup. Possible candidate: e.g. '\uff3f' (https://www.fileformat.info/info/unicode/char/ff3f/index.htm) (caveat: wider than a regular underscore)


问:
Google OAuth - Where to Store Client ID
I followed this link to allow my users to authenticate via google:

https://dev.to/jorgecf/integrating-google-authentication-with-your-angular-app-4j2a

However, I have to have my Google Client ID in my UI code:

```<code>return pload.then(async () => {
  await gapi.auth2
    .init({ client_id: 'abc123' })  // Put my client ID here. How should I store this?
    .then(auth => {
      this.gapiSetup = true;
      this.authInstance = auth;
    });
});
</code>```

Is that a security issue? If so, where/how would I store that?

答:
I received similar questions so  I think is a valid question.

Oauth2 flow needs the client_id int the browser, so is not a security issue.

Why? : Because that's how it's defined the OAUTH2 SPECIFICATION

https://www.rfc-editor.org/rfc/rfc6749#section-4.1.1

Why client_id is required?

Your angular code needs the client_id to generate the auth url and then perform a redirection to that url. No matter the oauth2 provider (google, facebook, etc), that url has the following syntax:

```<code>https://auth.acme.com/auth?response_type=code&redirect_uri=https://myweb.com/callback&client_id=******
</code>```

Note redirect_uri and client_id fields.

This auth url is responsible to show the login form, receive the credentials and perform the redirection to redirect_uri sending the code value

What would be an issue?

To have the secret in your frontend(angular) woull be the security issue.

This secret must be used together with client id and another fields to retrieve the access_token in your case from google. This token will permit you  consume google apis (drive, map, etc) if you have the correct permissions.

This flow must be in your backend

How partial hide it?

Create the auth url in your backend and return it to your frontend with a 302 http code. Browser will perform a instantaneous redirection.

I said partial, because a curious budy could stop the redirection (esc key) or use the browser console and view your auth url which contains the client_id field

Feel free to use this room https://chat.stackoverflow.com/rooms/215054/oauth2-budy to ask another questions related to oauth2

Title: Google OAuth - Where to Store Client ID

Body:
I followed this link to allow my users to authenticate via google:

https://dev.to/jorgecf/integrating-google-authentication-with-your-angular-app-4j2a

However, I have to have my Google Client ID in my UI code:

return pload.then(async () => {
  await gapi.auth2
    .init({ client_id: 'abc123' })  // Put my client ID here. How should I store this?
    .then(auth => {
      this.gapiSetup = true;
      this.authInstance = auth;
    });
});

Is that a security issue? If so, where/how would I store that?

Body:
I received similar questions so  I think is a valid question.

Oauth2 flow needs the client_id int the browser, so is not a security issue.

Why? : Because that's how it's defined the OAUTH2 SPECIFICATION

https://www.rfc-editor.org/rfc/rfc6749#section-4.1.1

Why client_id is required?

Your angular code needs the client_id to generate the auth url and then perform a redirection to that url. No matter the oauth2 provider (google, facebook, etc), that url has the following syntax:

https://auth.acme.com/auth?response_type=code&redirect_uri=https://myweb.com/callback&client_id=******

Note redirect_uri and client_id fields.

This auth url is responsible to show the login form, receive the credentials and perform the redirection to redirect_uri sending the code value

What would be an issue?

To have the secret in your frontend(angular) woull be the security issue.

This secret must be used together with client id and another fields to retrieve the access_token in your case from google. This token will permit you  consume google apis (drive, map, etc) if you have the correct permissions.

This flow must be in your backend

How partial hide it?

Create the auth url in your backend and return it to your frontend with a 302 http code. Browser will perform a instantaneous redirection.

I said partial, because a curious budy could stop the redirection (esc key) or use the browser console and view your auth url which contains the client_id field

Feel free to use this room https://chat.stackoverflow.com/rooms/215054/oauth2-budy to ask another questions related to oauth2


问:
How reliable is NSWorkspace's runningApplications?
I want to terminate some applications execution after an amount of time passed. I am polling NSWorkspace's runningApplications for a lack of something to observe on (if the application is just running, does it notify of anything?)

My issue is that applications are only sometimes terminated, sometimes they take a few seconds after the time they should be closed (according to an internal timer) and sometimes they do not terminate at all!

I tried using both terminate and forceTerminate methods.

In the code snippet, apps_ is a vector of strings containing application names. It is updated regularly by another thread and its data is received before running the below code. They all run inside an es_handler_block_t

```<code>NSArray<NSRunningApplication *> *running_apps = [NSWorkspace sharedWorkspace].runningApplications;
for (const auto &app_ : apps_) {
    //std::cout << app_ << "\n";
    for (NSRunningApplication *app in running_apps) {
        if ([[NSString stringWithUTF8String:app_.c_str()] isEqualToString:[app.executableURL lastPathComponent]] ) {
            std::string app_name = [[app.executableURL absoluteString] UTF8String];
            std::cout << "Terminating app " << app_name << "\n";
            bool res_f = [app forceTerminate];
            bool res_t = [app terminate];
            LOG_DBG("Force terminate: %d", res_f);
            LOG_DBG("Terminate: %d", res_t);
            break;
        }
    }
}
</code>```

I read in runningApplications documentation that "this property will only change when the main run loop runs in a common mode". What does it mean?

I suppose it is something related to runningApplication's polling, as inserting a breakpoint in the above code (before the if check) and then resuming execution instantly kills the application that would otherwise still run.

I am not blocking the main function. I only have an Endpoint Security class for the framework, networking is done on some other thread, and I return with NSApplicationMain(argc, argv);

What could be the issue? Thanks.

EDIT: I am leveraging the Cocoa Framework to create an agent that displays only in the system tray and it has root privileges. Preventing apps from launching is successfully achieved using the Endpoint Security Framework, but I did not find a reliable way to kill already running applications that works every time.

LATER EDIT: I managed to add an observer to [[NSWorkspace sharedWorkspace] notificationCenter], but what notification should I subscribe to for an application that is running? I tried with hide but it does not work if the user just clicks on the red window button, only if he hides the app from the dock. But I still want to close it even if there is no interaction between the user and the running app.

答:
Terminating apps reliably on macOS depends on a lot of factors, such as:

Entitlements

How the app was launched

If there are any background apps keeping the main app alive as soon as it crashes or is quit by another process

For example, your app may be allowed to terminate one app, but, for example, if you kill a process that was launched by  launchd with a KeepAlive command using a plist like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>KeepAlive</key>
    <true/>
    <key>Label</key>
    <string>com.bundleidentifierOf.AnUnquitabbleApp</string>
    <key>ProgramArguments</key>
    <array>
        <string>/path/to/the/AnUnquitableApp</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>
</code>```

You will be in a for surprise, because the moment you try to do so, launchd will relaunch it immediately, and it will seem as though the app was not killed, but it was. You can see that an app is relaunched, when its PID changes every time you try to kill it.

You can check that using the command:

```<code>ps -ax
</code>```

in Terminal to list all processes running on your Mac. If you want to know whether an application is running, then use:

```<code>ps -ax | grep "AnUnquitableAppNameHere"
</code>```

and then you can kill it by using its PID with

```<code>kill <PID>
</code>```

This will help you to determine which apps you can kill with a simple QUIT signal, which ones you will need to use stronger signals to terminate them and the ones are unquitable, because to kill them requires privileges or entitlements your app may not have. Read the man page of ps and kill to learn more about your target apps.

There are many other ways on macOS to gain persistence, and if you want to understand how to reliably quit apps, you need to understand how they gained persistence in the first place.

For example, if a user has admin / superuser privileges, it can gain persistence by installing a daemon in /Library/LaunchDaemons. If your app has no root privileges, it is unlikely you will be able to kill that process.

Another way for apps to maintain persistence besides a launchd plist is , for example, have a background app that will relaunch the main app as soon as the latter is forced to quit. An example is that if you use kill to kill the latest version of Microsoft Word you will see that it will be relaunched by such a helper that will complain that Wordwas forced to quit.

The nicest way to kill an app is actually to send it a Quit Apple Event and that is what I usually do.

I do not want to discourage you, but what you are trying to achieve is more difficult that it might seem in the first place. And even if you succeed, remember that the user may kill your app and that will defeat what you are trying to achieve, unless it is kept alive by a launchd plist or another form of persistence.

Now if you want to observe which apps were killed or launched without polling, I definitely recommend that you read TN2050.

Now replying to your specific questions:

"this property will only change when the main run loop runs in a
  common mode"

This means that you need to have a running loop for NSRunningApplication to be updated. If you have a GUI app, such a loop is already installed for you. If your app is a CLI, then this is not installed and you need to install such a running loop yourself . If you are using Objective-C then you can do as recommended in this question.

Therefore, what you are trying to achieve has a lot of caveats, and you need to be aware of them before proceeding.

Body:
I want to terminate some applications execution after an amount of time passed. I am polling NSWorkspace's runningApplications for a lack of something to observe on (if the application is just running, does it notify of anything?)

My issue is that applications are only sometimes terminated, sometimes they take a few seconds after the time they should be closed (according to an internal timer) and sometimes they do not terminate at all!

I tried using both terminate and forceTerminate methods.

In the code snippet, apps_ is a vector of strings containing application names. It is updated regularly by another thread and its data is received before running the below code. They all run inside an es_handler_block_t

NSArray<NSRunningApplication *> *running_apps = [NSWorkspace sharedWorkspace].runningApplications;
for (const auto &app_ : apps_) {
    //std::cout << app_ << "\n";
    for (NSRunningApplication *app in running_apps) {
        if ([[NSString stringWithUTF8String:app_.c_str()] isEqualToString:[app.executableURL lastPathComponent]] ) {
            std::string app_name = [[app.executableURL absoluteString] UTF8String];
            std::cout << "Terminating app " << app_name << "\n";
            bool res_f = [app forceTerminate];
            bool res_t = [app terminate];
            LOG_DBG("Force terminate: %d", res_f);
            LOG_DBG("Terminate: %d", res_t);
            break;
        }
    }
}

I read in runningApplications documentation that "this property will only change when the main run loop runs in a common mode". What does it mean?

I suppose it is something related to runningApplication's polling, as inserting a breakpoint in the above code (before the if check) and then resuming execution instantly kills the application that would otherwise still run.

I am not blocking the main function. I only have an Endpoint Security class for the framework, networking is done on some other thread, and I return with NSApplicationMain(argc, argv);

What could be the issue? Thanks.

EDIT: I am leveraging the Cocoa Framework to create an agent that displays only in the system tray and it has root privileges. Preventing apps from launching is successfully achieved using the Endpoint Security Framework, but I did not find a reliable way to kill already running applications that works every time.

LATER EDIT: I managed to add an observer to [[NSWorkspace sharedWorkspace] notificationCenter], but what notification should I subscribe to for an application that is running? I tried with hide but it does not work if the user just clicks on the red window button, only if he hides the app from the dock. But I still want to close it even if there is no interaction between the user and the running app.

Body:
Terminating apps reliably on macOS depends on a lot of factors, such as:

Entitlements

How the app was launched

If there are any background apps keeping the main app alive as soon as it crashes or is quit by another process

For example, your app may be allowed to terminate one app, but, for example, if you kill a process that was launched by  launchd with a KeepAlive command using a plist like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>KeepAlive</key>
    <true/>
    <key>Label</key>
    <string>com.bundleidentifierOf.AnUnquitabbleApp</string>
    <key>ProgramArguments</key>
    <array>
        <string>/path/to/the/AnUnquitableApp</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>

You will be in a for surprise, because the moment you try to do so, launchd will relaunch it immediately, and it will seem as though the app was not killed, but it was. You can see that an app is relaunched, when its PID changes every time you try to kill it.

You can check that using the command:

ps -ax

in Terminal to list all processes running on your Mac. If you want to know whether an application is running, then use:

ps -ax | grep "AnUnquitableAppNameHere"

and then you can kill it by using its PID with

kill <PID>

This will help you to determine which apps you can kill with a simple QUIT signal, which ones you will need to use stronger signals to terminate them and the ones are unquitable, because to kill them requires privileges or entitlements your app may not have. Read the man page of ps and kill to learn more about your target apps.

There are many other ways on macOS to gain persistence, and if you want to understand how to reliably quit apps, you need to understand how they gained persistence in the first place.

For example, if a user has admin / superuser privileges, it can gain persistence by installing a daemon in /Library/LaunchDaemons. If your app has no root privileges, it is unlikely you will be able to kill that process.

Another way for apps to maintain persistence besides a launchd plist is , for example, have a background app that will relaunch the main app as soon as the latter is forced to quit. An example is that if you use kill to kill the latest version of Microsoft Word you will see that it will be relaunched by such a helper that will complain that Wordwas forced to quit.

The nicest way to kill an app is actually to send it a Quit Apple Event and that is what I usually do.

I do not want to discourage you, but what you are trying to achieve is more difficult that it might seem in the first place. And even if you succeed, remember that the user may kill your app and that will defeat what you are trying to achieve, unless it is kept alive by a launchd plist or another form of persistence.

Now if you want to observe which apps were killed or launched without polling, I definitely recommend that you read TN2050.

Now replying to your specific questions:

"this property will only change when the main run loop runs in a
  common mode"

This means that you need to have a running loop for NSRunningApplication to be updated. If you have a GUI app, such a loop is already installed for you. If your app is a CLI, then this is not installed and you need to install such a running loop yourself . If you are using Objective-C then you can do as recommended in this question.

Therefore, what you are trying to achieve has a lot of caveats, and you need to be aware of them before proceeding.


问:
Enum element with associated values must have at least one associated value
This syntax of defining enum with associated values used to work fine with Swift 4.2

```<code>enum NetworkService {
    case lookUp(type: String)
    case allLookUps()
}
</code>```

When I am trying to convert my code in Xcode 10.2 and Swift 5, it is throwing error saying

Enum element with associated values must have at least one associated
  value

It doesn't make any sense in this particular case to have associated value for allLookUps(). So what is the best practice here in Swift 5?

答:
You do not need to have the parenthesis in your second case "allLookUps"
Only include the parenthesis when you want to add an associated value to the Enum case.

source: https://youtu.be/EwHmyAUeG3I

Body:
This syntax of defining enum with associated values used to work fine with Swift 4.2

enum NetworkService {
    case lookUp(type: String)
    case allLookUps()
}

When I am trying to convert my code in Xcode 10.2 and Swift 5, it is throwing error saying

Enum element with associated values must have at least one associated
  value

It doesn't make any sense in this particular case to have associated value for allLookUps(). So what is the best practice here in Swift 5?


问:
Self syntax in iPhone development
What is the difference between the following two approaches for the self syntax to access the object properties:-

Approach 1:-

```<code>    self.effortView = [[EffortView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
    self.effortView.effortTableView = [[UITableView alloc]initWithFrame:CGRectMake(25, 25, 300, 420) style:UITableViewStyleGrouped];
</code>```

Approach 2:-

```<code>    effortView = [[EffortView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
    effortView.effortTableView = [[UITableView alloc]initWithFrame:CGRectMake(25, 25, 300, 420) style:UITableViewStyleGrouped];
</code>```

effortView is defined as a property, and synthesized, to the Class addressed as self in Approach 1. Both of the approaches work.

I am using Xcode 4.0 iPhone SDK 4.3 on Mac 10.6.6.

Please enlighten me.

Thank you All

答:
If the property is declared like this

```<code>@property (nonatomic, assign) EffortView *effortView;
</code>```

both approaches are equivalent. In the case the property is declared like this

```<code>@property (nonatomic, retain) EffortView *effortView;
</code>```

the code [[EffortView alloc] init...]; first generates a retained EffortView instance and then the 'assignment' self.effortView = ... retains this instance again. Therefore to balance the retain count you have to release the generated instance.

Title: Self syntax in iPhone development

Body:
What is the difference between the following two approaches for the self syntax to access the object properties:-

Approach 1:-

    self.effortView = [[EffortView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
    self.effortView.effortTableView = [[UITableView alloc]initWithFrame:CGRectMake(25, 25, 300, 420) style:UITableViewStyleGrouped];

Approach 2:-

    effortView = [[EffortView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
    effortView.effortTableView = [[UITableView alloc]initWithFrame:CGRectMake(25, 25, 300, 420) style:UITableViewStyleGrouped];

effortView is defined as a property, and synthesized, to the Class addressed as self in Approach 1. Both of the approaches work.

I am using Xcode 4.0 iPhone SDK 4.3 on Mac 10.6.6.

Please enlighten me.

Thank you All

Body:
If the property is declared like this

@property (nonatomic, assign) EffortView *effortView;

both approaches are equivalent. In the case the property is declared like this

@property (nonatomic, retain) EffortView *effortView;

the code [[EffortView alloc] init...]; first generates a retained EffortView instance and then the 'assignment' self.effortView = ... retains this instance again. Therefore to balance the retain count you have to release the generated instance.