问:
Grabbing MySQL counts from loosely related tables with complex structure
MySQL here. I have the following data model in a Q&A database:

```<code>[questions]
===
question_id : PK           # ex: 12345
question_value : VARCHAR   # ex: 'What is your favorite food?'

[answers]
===
answer_id : PK              # ex: 23456
question_id : FK            # points to a questions.question_id
answer_value : VARCHAR      # ex: 'Pizza', 'French Fries', etc.

[user_answers]
===
user_answer_id : PK         # ex: 34567
question_id : FK            # points to a questions.question_id
user_answer_value : VARCHAR # ex: 'Pizza', 'French Fries', etc.
</code>```

...where [questions] is a table containing all the questions I will ask users, [answers] is a table containing all the possible answers for each question, and [user_answers] are the actual answers users give for a particular question. So the application uses [questions] and [answers] to present a user with a question & possible answers, then the user selects one of those answers, and that result gets written to the [user_answers] table.

One very important thing to note is that the application will guarantee that there are never any "orphaned" [user_answers], meaning, there will always be an [answers] record whose [answer_value] matches a [user_answers.user_answer_value]. So if there is a [user_answers.user_answer_value] in the database under a particular question_id, there will always be a matching [answers.answer_value]. Hence it is safe to match to the two "value fields" against each other in a query and not lose any data.

I realize this is not a great data model. But it is critical to point out that I simply cannot change it; its locked in and beyond my ability to make changes to, I'm simply stuck with it. And so unfortunately as much as I will want to, I cannot accept any answers that require changes to the data model.

Now then, I am trying to write a SQL query that -- for a given question_id -- returns the following columns:

the answers.answer_id as id

the answers.answer_value as answer

a count of how many user_answers existed for that particular answers.answer_id, using the value fields as a way of determining the match (i.e. "'Pizza' == 'Pizza'"), as popularity

So using the "favorite food" example from above, say that was the only question in the database, and the three possible answers were "Pizza", "French Fries" and "Cheeseburgers". Say 50 users had answered "Pizza", 65 users had answered "French Fries", and 12 users had answered "Cheeseburgers". Then the query would return results like so:

```<code>id      |     answer      |   popularity
==========================================
123     |   Pizza         |   50
456     |   French Fries  |   65
789     |   Cheeseburgers |   12
</code>```

Important to note: if an answer has never been selected by any user yet, then its count should be zero (0).

My best attempt so far at this query is:

```<code>SELECT
  a.answer_id as id,
  a.answer_value as answer,
  count(ua.answer_id) as popularity
FROM
  answers a
INNER JOIN
  user_answers ua
ON
  a.question_id = ua.question_id
WHERE
  a.question_id = ?   # provided by application
  AND
  a.answer_value = ua.answer_value
</code>```

However this doesn't look right to me. For one I don't believe an INNER JOIN is appropriate. I also believe I need to do a GROUP BY but I'm unsure of which table/column to group the count by.

Its important to note that in reality there will be hundreds of questions in this DB, each with 4 - 8 answers, and there will be hundreds (possibly thousands) of users providing answers, so its important that this query (which provides popularity counts for each question's answer) only include counts for user answers matching answers that are tied to the same "parent" question ID. Can anyone spot where I'm going awry?

答:
I guess it is as simple as:

```<code>SELECT answers.answer_id, answers.answer_value, COUNT(user_answers.user_answer_id)
FROM answers
LEFT JOIN user_answers ON answers.answer_value = user_answers.user_answer_value
WHERE answers.question_id = ?
GROUP BY answers.answer_id, answers.answer_value
</code>```

The LEFT JOIN ensures that zero counts are included.

PS: The database design has some issues. I would rather change it to user_answers(user_answer_id, answer_id).

Body:
MySQL here. I have the following data model in a Q&A database:

[questions]
===
question_id : PK           # ex: 12345
question_value : VARCHAR   # ex: 'What is your favorite food?'

[answers]
===
answer_id : PK              # ex: 23456
question_id : FK            # points to a questions.question_id
answer_value : VARCHAR      # ex: 'Pizza', 'French Fries', etc.

[user_answers]
===
user_answer_id : PK         # ex: 34567
question_id : FK            # points to a questions.question_id
user_answer_value : VARCHAR # ex: 'Pizza', 'French Fries', etc.

...where [questions] is a table containing all the questions I will ask users, [answers] is a table containing all the possible answers for each question, and [user_answers] are the actual answers users give for a particular question. So the application uses [questions] and [answers] to present a user with a question & possible answers, then the user selects one of those answers, and that result gets written to the [user_answers] table.

One very important thing to note is that the application will guarantee that there are never any "orphaned" [user_answers], meaning, there will always be an [answers] record whose [answer_value] matches a [user_answers.user_answer_value]. So if there is a [user_answers.user_answer_value] in the database under a particular question_id, there will always be a matching [answers.answer_value]. Hence it is safe to match to the two "value fields" against each other in a query and not lose any data.

I realize this is not a great data model. But it is critical to point out that I simply cannot change it; its locked in and beyond my ability to make changes to, I'm simply stuck with it. And so unfortunately as much as I will want to, I cannot accept any answers that require changes to the data model.

Now then, I am trying to write a SQL query that -- for a given question_id -- returns the following columns:

the answers.answer_id as id

the answers.answer_value as answer

a count of how many user_answers existed for that particular answers.answer_id, using the value fields as a way of determining the match (i.e. "'Pizza' == 'Pizza'"), as popularity

So using the "favorite food" example from above, say that was the only question in the database, and the three possible answers were "Pizza", "French Fries" and "Cheeseburgers". Say 50 users had answered "Pizza", 65 users had answered "French Fries", and 12 users had answered "Cheeseburgers". Then the query would return results like so:

id      |     answer      |   popularity
==========================================
123     |   Pizza         |   50
456     |   French Fries  |   65
789     |   Cheeseburgers |   12

Important to note: if an answer has never been selected by any user yet, then its count should be zero (0).

My best attempt so far at this query is:

SELECT
  a.answer_id as id,
  a.answer_value as answer,
  count(ua.answer_id) as popularity
FROM
  answers a
INNER JOIN
  user_answers ua
ON
  a.question_id = ua.question_id
WHERE
  a.question_id = ?   # provided by application
  AND
  a.answer_value = ua.answer_value

However this doesn't look right to me. For one I don't believe an INNER JOIN is appropriate. I also believe I need to do a GROUP BY but I'm unsure of which table/column to group the count by.

Its important to note that in reality there will be hundreds of questions in this DB, each with 4 - 8 answers, and there will be hundreds (possibly thousands) of users providing answers, so its important that this query (which provides popularity counts for each question's answer) only include counts for user answers matching answers that are tied to the same "parent" question ID. Can anyone spot where I'm going awry?

Body:
I guess it is as simple as:

SELECT answers.answer_id, answers.answer_value, COUNT(user_answers.user_answer_id)
FROM answers
LEFT JOIN user_answers ON answers.answer_value = user_answers.user_answer_value
WHERE answers.question_id = ?
GROUP BY answers.answer_id, answers.answer_value

The LEFT JOIN ensures that zero counts are included.

PS: The database design has some issues. I would rather change it to user_answers(user_answer_id, answer_id).


来源: stackexchange

问:
Lock SQL Table/Row and using NOLOCK/READPAST
I am the end-user of a highly updated Microsoft SQL Server DB containing dozens of tables with hunreds of millions of rows each.
A banking DB is a good example for what I am working with, with the exception that in my DB UPDATE statement are rearly used and INSERT statements are used frequently (once a row as entered a table, it rarely changes).
I, personally, not using any UPDATE/INSERT statement, only SELECT statement (with complex WHERE/ JOIN/ CROSS/ GROUP clues).

I have some questions about locking and using NOLOCK/READPAST.

1.how can I know if a query I am using is locking only a row or the entire table?
for example, I noticed this query didn't locked other users from inserting new data to the table:

```<code>SELECT *
FROM Table
</code>```

while this query did:

```<code>SELECT COUNT(Date)
FROM Table
</code>```

This is of course just examples, not actual full queris I am using.
As I mentioned, rows rarely changing so locking a row isn't concerning me but locking a table is highly concerning.

2.I would like to know the risks of using NOLOCK/READPAST in my queries (to revoke any concern I might have about locking a table from updating).
I searched about it a lot but I could not find a full answer.
I dont care If by using NOLOCK/READPAST I might get past data (that again, data i rarely changes) or I might miss some newly added data.
I did read in a couple of places that using NOLOCK might cause duplicate data/ corrupted data, this is a problem for me.

3.what exactly is the diffrent between READPASY and NOLOCK? which one is "safer" regarding the concerns mentiond above

Thank you.

答:
This is highly dependent on your servers settings. Generally speaking, you want to lock records, even when you are just reading them because you don't want data to change while you are reading it. This isn't just something that affects updated records, but also inserts. You can learn more about read commits and snapshop isolation here:
https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/snapshot-isolation-in-sql-server

Both NOLOCK/READPAST should be avoided at all cost. There are a very small handful of scenarios where these make sense, but they are exceedingly rare. You are better off optimizing your query to perform better and reduce the amount of records being locked and the time that the records spend being locked. One case that I can see NOLOCK being useful would be a log table that only has inserts, and your query doesn't join the data to other tables, AND a dirty record wouldn't cause problems.

NOLOCK doesn't lock records that it reads. The risk here is that records you are reading can literally change mid read. This means you can begin reading a record and get some values for some columns before the update was made and some column values from after the update. If another transaction rolls back you could end up reading records that were never actually committed to the database.
READPAST skips any rows that are locked. If another query runs and the criteria causes rows 1-25 of 100 to be locked while you are querying the same data you are only going to see records 26-100. To your query locked rows don't exist.
Great article with the details:
https://www.mssqltips.com/sqlservertip/4468/compare-sql-server-nolock-and-readpast-table-hints/

You would be far better served by spending time learning to optimize your queries to reduce the number of records they need to lock, and improving the performance so that the amount of time those locks exist is kept to a minimum.

ContentLicense: CC BY-SA 4.0

Body:
I am the end-user of a highly updated Microsoft SQL Server DB containing dozens of tables with hunreds of millions of rows each.
A banking DB is a good example for what I am working with, with the exception that in my DB UPDATE statement are rearly used and INSERT statements are used frequently (once a row as entered a table, it rarely changes).
I, personally, not using any UPDATE/INSERT statement, only SELECT statement (with complex WHERE/ JOIN/ CROSS/ GROUP clues).

I have some questions about locking and using NOLOCK/READPAST.

1.how can I know if a query I am using is locking only a row or the entire table?
for example, I noticed this query didn't locked other users from inserting new data to the table:

SELECT *
FROM Table

while this query did:

SELECT COUNT(Date)
FROM Table

This is of course just examples, not actual full queris I am using.
As I mentioned, rows rarely changing so locking a row isn't concerning me but locking a table is highly concerning.

2.I would like to know the risks of using NOLOCK/READPAST in my queries (to revoke any concern I might have about locking a table from updating).
I searched about it a lot but I could not find a full answer.
I dont care If by using NOLOCK/READPAST I might get past data (that again, data i rarely changes) or I might miss some newly added data.
I did read in a couple of places that using NOLOCK might cause duplicate data/ corrupted data, this is a problem for me.

3.what exactly is the diffrent between READPASY and NOLOCK? which one is "safer" regarding the concerns mentiond above

Thank you.


问:
AttributeError at /media/.. when requesting file in media folder Django development stage
When I am reqeuesting media files (.png in this case) in the media folder in development I get this error:

AttributeError at /media/test.png
This FileResponse instance has no content attribute. Use streaming_content instead.

Request: http://localhost:8000/media/test.png

I added below to the url patterns:

```<code>urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

And below to the settings:

```<code>STATIC_ROOT = BASE_DIR / 'static'
STATIC_URL = '/static/'
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'
</code>```

Static files are working just fine.

What do I overlook?
Thanks!

答:
I found the problem.
In the newer django version staticfiles are rendered with a streamingHttpResponse, this doesn't have a content attribute.

I found below code in my code that points to the (non existing) content attribute:

```<code>if b'<html' in response.content[:100].lower():
</code>```

I added this to resolve the problem:

```<code>if not hasattr(response, 'content'):
    return response
if b'<html' in response.content[:100].lower():
</code>```

Thanks all!

Body:
When I am reqeuesting media files (.png in this case) in the media folder in development I get this error:

AttributeError at /media/test.png
This FileResponse instance has no content attribute. Use streaming_content instead.

Request: http://localhost:8000/media/test.png

I added below to the url patterns:

urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

And below to the settings:

STATIC_ROOT = BASE_DIR / 'static'
STATIC_URL = '/static/'
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'

Static files are working just fine.

What do I overlook?
Thanks!

Body:
I found the problem.
In the newer django version staticfiles are rendered with a streamingHttpResponse, this doesn't have a content attribute.

I found below code in my code that points to the (non existing) content attribute:

if b'<html' in response.content[:100].lower():

I added this to resolve the problem:

if not hasattr(response, 'content'):
    return response
if b'<html' in response.content[:100].lower():

Thanks all!


问:
How to check generated strings against a text file
I'm trying to have the user input a string of characters with one asterisk. The asterisk indicates a character that can be subbed out for a vowel (a,e,i,o,u) in order to see what substitutions produce valid words.
Essentially, I want to take an input "l*g" and have it return "lag, leg, log, lug" because "lig" is not a valid English word. Below I have invalid words to be represented as "x".

I've gotten it to properly output each possible combination (e.g., including "lig"), but once I try to compare these words with the text file I'm referencing (for the list of valid words), it'll only return 5 lines of x's. I'm guessing it's that I'm improperly importing or reading the file?

Here's the link to the file I'm looking at so you can see the formatting:
https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/packages/corpora/words.zip
Using the "en" file ~2.5MB

It's not in a dictionary layout i.e. no corresponding keys/values, just lines (maybe I could use the line number as the index, but I don't know how to do that). What can I change to check the test words to narrow down which are valid words based on the text file?

```<code>with open(os.path.expanduser('~/Downloads/words/en')) as f:
    words = f.readlines()

inputted_word = input("Enter a word with ' * ' as the missing letter: ")
letters = []
for l in inputted_word:
    letters.append(l)

### find the index of the blank
asterisk = inputted_word.index('*') # also used a redundant int(), works fine

### sub in vowels
vowels = ['a','e','i','o','u']
list_of_new_words = []
for v in vowels:
    letters[asterisk] = v
    new_word = ''.join(letters)
    list_of_new_words.append(new_word)

for w in list_of_new_words:
    if w in words:
        print(new_word)
    else:
        print('x')
</code>```

There are probably more efficient ways to do this, but I'm brand new to this. The last two for loops could probably be combined but debugging it was tougher that way.

答:
print(list_of_new_words)
```
<p>gives</p>
```['lag', 'leg', 'lig', 'log', 'lug']
```
<p>So far, so good.</p>
<p>But this :</p>
```for w in list_of_new_words:
    if w in words:
        print(new_word)
    else:
        print('x')
```
<p>Here you print <code>new_word</code>, which is defined in the previous <code>for</code> loop :</p>
<pre class="lang-py prettyprint-override"><code>for v in vowels:
    letters[asterisk] = v
    new_word = ''.join(letters)  # <----
    list_of_new_words.append(new_word)
</code>```

So after the loop, new_word still has the last value it was assigned to : "lug" (if the script input was l*g).

You probably meant w instead ?

```<code>for w in list_of_new_words:
    if w in words:
        print(w)
    else:
        print('x')
</code>```

But it still prints 5 xs ...

So that means that w in words is always False. How is that ?

Looking at words :

print(words[0:10])  # the first 10 will suffice
```
<pre class="lang-py prettyprint-override"><code>['A\n', 'a\n', 'aa\n', 'aal\n', 'aalii\n', 'aam\n', 'Aani\n', 'aardvark\n', 'aardwolf\n', 'Aaron\n']
</code>```

All the words from the dictionary contain a newline character (\n) at the end. I guess you were not aware that it is what readlines do. So I recommend using :

```<code>words = f.read().splitlines()
</code>```

instead.

With these 2 modifications (w and splitlines) :

```<code>Enter a word with ' * ' as the missing letter: l*g
lag
leg
x
log
lug
</code>```

Body:
I'm trying to have the user input a string of characters with one asterisk. The asterisk indicates a character that can be subbed out for a vowel (a,e,i,o,u) in order to see what substitutions produce valid words.
Essentially, I want to take an input "l*g" and have it return "lag, leg, log, lug" because "lig" is not a valid English word. Below I have invalid words to be represented as "x".

I've gotten it to properly output each possible combination (e.g., including "lig"), but once I try to compare these words with the text file I'm referencing (for the list of valid words), it'll only return 5 lines of x's. I'm guessing it's that I'm improperly importing or reading the file?

Here's the link to the file I'm looking at so you can see the formatting:
https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/packages/corpora/words.zip
Using the "en" file ~2.5MB

It's not in a dictionary layout i.e. no corresponding keys/values, just lines (maybe I could use the line number as the index, but I don't know how to do that). What can I change to check the test words to narrow down which are valid words based on the text file?

with open(os.path.expanduser('~/Downloads/words/en')) as f:
    words = f.readlines()

inputted_word = input("Enter a word with ' * ' as the missing letter: ")
letters = []
for l in inputted_word:
    letters.append(l)

### find the index of the blank
asterisk = inputted_word.index('*') # also used a redundant int(), works fine

### sub in vowels
vowels = ['a','e','i','o','u']
list_of_new_words = []
for v in vowels:
    letters[asterisk] = v
    new_word = ''.join(letters)
    list_of_new_words.append(new_word)

for w in list_of_new_words:
    if w in words:
        print(new_word)
    else:
        print('x')

There are probably more efficient ways to do this, but I'm brand new to this. The last two for loops could probably be combined but debugging it was tougher that way.

Body:
print(list_of_new_words)

gives

['lag', 'leg', 'lig', 'log', 'lug']

So far, so good.

But this :

for w in list_of_new_words:
    if w in words:
        print(new_word)
    else:
        print('x')

Here you print new_word, which is defined in the previous for loop :

for v in vowels:
    letters[asterisk] = v
    new_word = ''.join(letters)  # <----
    list_of_new_words.append(new_word)

So after the loop, new_word still has the last value it was assigned to : "lug" (if the script input was l*g).

You probably meant w instead ?

for w in list_of_new_words:
    if w in words:
        print(w)
    else:
        print('x')

But it still prints 5 xs ...

So that means that w in words is always False. How is that ?

Looking at words :

print(words[0:10])  # the first 10 will suffice

['A\n', 'a\n', 'aa\n', 'aal\n', 'aalii\n', 'aam\n', 'Aani\n', 'aardvark\n', 'aardwolf\n', 'Aaron\n']

All the words from the dictionary contain a newline character (\n) at the end. I guess you were not aware that it is what readlines do. So I recommend using :

words = f.read().splitlines()

instead.

With these 2 modifications (w and splitlines) :

Enter a word with ' * ' as the missing letter: l*g
lag
leg
x
log
lug


问:
C++ Polymorphic behaviour with global array of Base Class type
Why is the code below able to demonstrate polymorphic behaviour

```<code>TwoDShapes* s2d[2];

int main()
{
    Circle c1(/*parameter*/);
    Rectangle s1(/*parameter*/);

    s2d[0] = &c1;
    s2d[1] = &s1;

    for (int i = 0; i < 2; i++)
        cout << s2d[i]->toString() << endl;

    return 0;
}
</code>```

BUT the code below throws an error

```<code>void test();

TwoDShapes* s2d[2];

int main()
{
    test();

    for (int i = 0; i < 2; i++)
        cout << s2d[i]->toString() << endl;

    return 0;
}

void test()
{
    Circle c1(/*parameter*/);
    Rectangle s1(/*parameter*/);

    s2d[0] = &c1;
    s2d[1] = &s1;
}
</code>```

I noticed that when I try to initialise the contents of the array within another function other than main(), the Base class'(TwoDShapes) toString() method gets invoked instead of the Derived classes'(Circle and Rectangle) toString() method.
But when I do the same thing within main(), it is able to display polymorphic behaviour.

Below is my Base and Derived classes

```<code>// Base Class
class TwoDShapes
{
public:
    TwoDShapes();
    virtual string toString();

string TwoDShapes::toString()
{
    return "Inside Base Class toString method";
}

// Derived classes
class Circle : public TwoDShapes
{
public:
    Circle(/*parameter*/);
    string toString() override;
};

string Circle::toString()
{
    return "Inside Circle toString method";
}

</code>```

*Edit 1: Included a more complete code

答: The problem is in your test function, where you create two local objects (c1 and s1) and save their addresses. However, when that function returns, those two objects' lifetimes will end, and the s2d[0] and s2d[1] values will be dangling pointers.

Body:
Why is the code below able to demonstrate polymorphic behaviour

TwoDShapes* s2d[2];

int main()
{
    Circle c1(/*parameter*/);
    Rectangle s1(/*parameter*/);

    s2d[0] = &c1;
    s2d[1] = &s1;

    for (int i = 0; i < 2; i++)
        cout << s2d[i]->toString() << endl;

    return 0;
}

BUT the code below throws an error

void test();

TwoDShapes* s2d[2];

int main()
{
    test();

    for (int i = 0; i < 2; i++)
        cout << s2d[i]->toString() << endl;

    return 0;
}

void test()
{
    Circle c1(/*parameter*/);
    Rectangle s1(/*parameter*/);

    s2d[0] = &c1;
    s2d[1] = &s1;
}

I noticed that when I try to initialise the contents of the array within another function other than main(), the Base class'(TwoDShapes) toString() method gets invoked instead of the Derived classes'(Circle and Rectangle) toString() method.
But when I do the same thing within main(), it is able to display polymorphic behaviour.

Below is my Base and Derived classes

// Base Class
class TwoDShapes
{
public:
    TwoDShapes();
    virtual string toString();

string TwoDShapes::toString()
{
    return "Inside Base Class toString method";
}

// Derived classes
class Circle : public TwoDShapes
{
public:
    Circle(/*parameter*/);
    string toString() override;
};

string Circle::toString()
{
    return "Inside Circle toString method";
}

*Edit 1: Included a more complete code


问:
dynamically retriving the x,y position of an element in canvas
I have this code

```<code>        <Canvas x:Name="SampleCanvas" Background="#F5F7F9"  MouseLeftButtonDown="brdMovable_MouseLeftButtonDown" MouseLeftButtonUp="brdMovable_MouseLeftButtonUp" MouseMove="brdMovable_MouseMove" Height="570" Width="875">
         <chartingToolkit:Chart  x:Name="mcChart" Loaded="mcChart_Loaded"  Width="400" Height="250" Canvas.Left="190" Canvas.Top="5" MouseLeftButtonDown="brdMovable_MouseLeftButtonDown"
                             Background="LightSteelBlue">
                        <chartingToolkit:Chart.RenderTransform>
                            <ScaleTransform x:Name="scaleTransform"></ScaleTransform>
                        </chartingToolkit:Chart.RenderTransform>
                        <chartingToolkit:Chart.Series>
                            <chartingToolkit:ColumnSeries Title="Experience"  IndependentValueBinding="{Binding Path=ModelName}" DependentValueBinding="{Binding  Path=SaleCount}">
                            </chartingToolkit:ColumnSeries>
                        </chartingToolkit:Chart.Series>
                    </chartingToolkit:Chart>
          </canvas>
</code>```

Now i want to retrieve the canvas.Left position and canvas.Top positions of mcChart dynamically in codebehind.

How can i do that ?
Thanks.

答:
You need a reference to the mcChart. Then you can use the Attached Property accessor to get the current value:

```<code>double left = Canvas.GetLeft(mcChart);
double top  = Canvas.GetTop(mcChart);
</code>```

To set the values in code:

```<code>Canvas.SetLeft(mcChart, 50);
Canvas.SetTop(mcChart, 100);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this code

        <Canvas x:Name="SampleCanvas" Background="#F5F7F9"  MouseLeftButtonDown="brdMovable_MouseLeftButtonDown" MouseLeftButtonUp="brdMovable_MouseLeftButtonUp" MouseMove="brdMovable_MouseMove" Height="570" Width="875">
         <chartingToolkit:Chart  x:Name="mcChart" Loaded="mcChart_Loaded"  Width="400" Height="250" Canvas.Left="190" Canvas.Top="5" MouseLeftButtonDown="brdMovable_MouseLeftButtonDown"
                             Background="LightSteelBlue">
                        <chartingToolkit:Chart.RenderTransform>
                            <ScaleTransform x:Name="scaleTransform"></ScaleTransform>
                        </chartingToolkit:Chart.RenderTransform>
                        <chartingToolkit:Chart.Series>
                            <chartingToolkit:ColumnSeries Title="Experience"  IndependentValueBinding="{Binding Path=ModelName}" DependentValueBinding="{Binding  Path=SaleCount}">
                            </chartingToolkit:ColumnSeries>
                        </chartingToolkit:Chart.Series>
                    </chartingToolkit:Chart>
          </canvas>

Now i want to retrieve the canvas.Left position and canvas.Top positions of mcChart dynamically in codebehind.

How can i do that ?
Thanks.

Body:
You need a reference to the mcChart. Then you can use the Attached Property accessor to get the current value:

double left = Canvas.GetLeft(mcChart);
double top  = Canvas.GetTop(mcChart);

To set the values in code:

Canvas.SetLeft(mcChart, 50);
Canvas.SetTop(mcChart, 100);


问:
Google LockService doesn't seem to work at all
I'm trying to use the LockService class.
But it doesn't seem to work at all!!

I have a button in a sheet (a drawing, in fact) that calls a method.

And at the beginnng of that method I have:

```<code>var Lock = LockService.getScriptLock();
var TryLock = Lock.tryLock(5000);
Browser.msgBox(TryLock.toString());
if (!TryLock)
{
  return;
}

Browser.msgBox("Haslock " + Lock.hasLock().toString());

//script's body, nothing related to Locks
//everything related to the current (and only) document

Lock.releaseLock();
</code>```

So, in first place, TryLock is ALWAYS true! No matter how many times I press the button to run two, three or ten scripts at once. (The script is long enough to take about one minute).

And second, hasLock is ALWAYS false! That is completely against the documentation.

Am I missing something?

答:
Actually, the reason is the UI-object (Browser.msgBox()) drops the lock. Avoid or move the UI objects to reach concurrency.</p>
```<code>var Lock = LockService.getScriptLock();
var TryLock = Lock.tryLock(10000);

Logger.log(Lock.hasLock()); // true
Logger.log(Lock.hasLock()); // true

Browser.msgBox(Lock.hasLock()); // true
Browser.msgBox(Lock.hasLock()); // false
</code>```

Body:
I'm trying to use the LockService class.
But it doesn't seem to work at all!!

I have a button in a sheet (a drawing, in fact) that calls a method.

And at the beginnng of that method I have:

var Lock = LockService.getScriptLock();
var TryLock = Lock.tryLock(5000);
Browser.msgBox(TryLock.toString());
if (!TryLock)
{
  return;
}

Browser.msgBox("Haslock " + Lock.hasLock().toString());

//script's body, nothing related to Locks
//everything related to the current (and only) document

Lock.releaseLock();

So, in first place, TryLock is ALWAYS true! No matter how many times I press the button to run two, three or ten scripts at once. (The script is long enough to take about one minute).

And second, hasLock is ALWAYS false! That is completely against the documentation.

Am I missing something?

Body:
Actually, the reason is the UI-object (Browser.msgBox()) drops the lock. Avoid or move the UI objects to reach concurrency.

var Lock = LockService.getScriptLock();
var TryLock = Lock.tryLock(10000);

Logger.log(Lock.hasLock()); // true
Logger.log(Lock.hasLock()); // true

Browser.msgBox(Lock.hasLock()); // true
Browser.msgBox(Lock.hasLock()); // false


问:
Select only records without future dates via join
There are 2 tables: events and dates. One event could have multiple dates.

I would like to select only those events which don't have corresponding dates in the future.

I tried the following query

```<code>SELECT e.id_event FROM events e RIGHT JOIN dates d ON e.id_event=d.id_event AND !(d.date > NOW())
</code>```

but it shows events which has both dates in past and in future.

Sample data

Events table

id_event

1

2

Dates table

id_event
date

1
2020-10-10

1
2030-10-10

2
2020-10-10

The query should return only one record, id_event =  2.

答:
A couple of ways to do this

```<code>create table t1(id_event int, date date);

insert into t values (1),(2);
insert into t1 values (1,'2020-01-01'),(1,'2030-01-01'),(2,'2020-01-01');

SELECT e.id_event
FROM t e
left JOIN t1 d ON e.id_event=d.id_event
group by e.ID_event having max(d.date) < now()
;

SELECT e.id_event
FROM t e
left JOIN t1 d ON e.id_event=d.id_event
where not exists(select 1 from t1 t2 where t2.id_event = d.id_event and t2.date > now())
;
</code>```

First may not be useful if you intend to take more columns from either table..

Body:
There are 2 tables: events and dates. One event could have multiple dates.

I would like to select only those events which don't have corresponding dates in the future.

I tried the following query

SELECT e.id_event FROM events e RIGHT JOIN dates d ON e.id_event=d.id_event AND !(d.date > NOW())

but it shows events which has both dates in past and in future.

Sample data

Events table

id_event

1

2

Dates table

id_event
date

1
2020-10-10

1
2030-10-10

2
2020-10-10

The query should return only one record, id_event =  2.

Body:
A couple of ways to do this

create table t1(id_event int, date date);

insert into t values (1),(2);
insert into t1 values (1,'2020-01-01'),(1,'2030-01-01'),(2,'2020-01-01');

SELECT e.id_event
FROM t e
left JOIN t1 d ON e.id_event=d.id_event
group by e.ID_event having max(d.date) < now()
;

SELECT e.id_event
FROM t e
left JOIN t1 d ON e.id_event=d.id_event
where not exists(select 1 from t1 t2 where t2.id_event = d.id_event and t2.date > now())
;

First may not be useful if you intend to take more columns from either table..


问:
Need support in LWJGL - Setting the type of texture
Can somebody help me setting different texture types? (GL_LINEAR, GL_NEAREST, etc) I'm using   the slick-util lybrary with netbeans. The problem is that i can't set to different types.
I documented about and found out that if i want to use MIP_MAPs then i need to create them. Problem is that i cant create them. So the question is !
 How can i create with or without slick-util textures and how can i set them to different texture types. I know how it's made in c++ but haven't got implemented in java ?

Thank you for you're time,
 Zsurzsa,

答:
Mipmapping means that for every texture you need to specify a so called image pyramid. In laymans terms you start with layer 0 and for each following layer you half-down round-up the resolution until you hit a image size of 1×1.

OpenGL (and any other mipmapping renderer) will only apply a mipmapped texture if it's complete. You can specify minimum and maximum levels to be used, but all the levels inbetween must be supplied.

I don't know slick utils, but if it offers you to scale images you could use something like this (pseudocode)

```<code>level = 0
while ceil(image.width) > 1 or ceil(image.height) > 1:
   glTexImage(GL_TEXTURE_2D, level, image.width, image.height, ...)
   image.scale(0.5, 0.5)
   level = level + 1
</code>```

Body:
Mipmapping means that for every texture you need to specify a so called image pyramid. In laymans terms you start with layer 0 and for each following layer you half-down round-up the resolution until you hit a image size of 1×1.

OpenGL (and any other mipmapping renderer) will only apply a mipmapped texture if it's complete. You can specify minimum and maximum levels to be used, but all the levels inbetween must be supplied.

I don't know slick utils, but if it offers you to scale images you could use something like this (pseudocode)

level = 0
while ceil(image.width) > 1 or ceil(image.height) > 1:
   glTexImage(GL_TEXTURE_2D, level, image.width, image.height, ...)
   image.scale(0.5, 0.5)
   level = level + 1


问:
How to transform observations to column and reprensent the number of occurence of these observations
Here is a subset of my dataset. Patients had different types of adverse events (variables) with different types of severity (observations). I would like to create additional variables representing severity ("severe", "severe", "moderate") and have the number of severity types for each patient.

```<code>mydata<-structure(list(record_id = c("2", "4", "5", "9", "10", "11",
    "12", "15", "22", "23"), `Dégré Cytolyse hep ` = structure(c(NA,
    3L, NA, NA, 1L, NA, 2L, NA, 3L, NA), .Label = c("modéré", "grave",
    "sévère"), class = "factor"), `Dégré Trble digest` = structure(c(1L,
    NA, NA, NA, NA, 2L, 1L, 1L, NA, 3L), .Label = c("modéré", "grave",
    "sévère"), class = "factor"), `Dégré Erupt cutanées` = structure(c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_), .Label = c("modéré",
    "grave", "sévère"), class = "factor"), `Dégré Ins renale` = structure(c(NA,
    NA, NA, 1L, NA, NA, NA, NA, NA, NA), .Label = c("modéré", "grave",
    "sévère"), class = "factor"), `Dégré Neuropath` = structure(c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_), .Label = c("modéré",
    "grave", "sévère"), class = "factor"), `Dégré Autre 1` = structure(c(NA,
    NA, 1L, NA, NA, 1L, NA, 1L, 3L, NA), .Label = c("modéré", "grave",
    "sévère"), class = "factor"), `Dégré Autre 2` = structure(c(NA,
    NA, NA, NA, NA, 1L, NA, 1L, NA, NA), .Label = c("modéré", "grave",
    "sévère"), class = "factor"), `Dégré Autre 3` = structure(c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_), .Label = c("modéré",
    "grave", "sévère"), class = "factor"), `Dégré Autre 4` = structure(c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_), .Label = c("modéré",
    "grave", "sévère"), class = "factor"), `Dégré Autre 5` = structure(c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_), .Label = c("modéré",
    "grave", "sévère"), class = "factor")), row.names = c(NA, 10L
    ), class = "data.frame")
</code>```

The expected dataset will be:

```<code>   record_id Dégré Cytolyse hep  Dégré Trble digest Dégré Erupt cutanées Dégré Ins renale Dégré Neuropath Dégré Autre 1 Dégré Autre 2 Dégré Autre 3 Dégré Autre 4 Dégré Autre 5 modéré sévère grave
1          2                <NA>             modéré                 <NA>             <NA>            <NA>          <NA>          <NA>          <NA>          <NA>          <NA>      1      0     0
2          4              sévère               <NA>                 <NA>             <NA>            <NA>          <NA>          <NA>          <NA>          <NA>          <NA>      0      1     0
3          5                <NA>               <NA>                 <NA>             <NA>            <NA>        modéré          <NA>          <NA>          <NA>          <NA>      1      0     0
4          9                <NA>               <NA>                 <NA>           modéré            <NA>          <NA>          <NA>          <NA>          <NA>          <NA>      1      0     0
5         10              modéré               <NA>                 <NA>             <NA>            <NA>          <NA>          <NA>          <NA>          <NA>          <NA>      1      0     0
6         11                <NA>              grave                 <NA>             <NA>            <NA>        modéré        modéré          <NA>          <NA>          <NA>      2      0     1
7         12               grave             modéré                 <NA>             <NA>            <NA>          <NA>          <NA>          <NA>          <NA>          <NA>      1      0     1
8         15                <NA>             modéré                 <NA>             <NA>            <NA>        modéré        modéré          <NA>          <NA>          <NA>      3      0     0
9         22              sévère               <NA>                 <NA>             <NA>            <NA>        sévère          <NA>          <NA>          <NA>          <NA>      0      2     0
10        23                <NA>             sévère                 <NA>             <NA>            <NA>          <NA>          <NA>          <NA>          <NA>          <NA>      0      1     0
</code>```

答:
This is very similat to a question I answered about a week ago. Using apply() and a user-written function:

```<code># Defining useful function, to be passed within apply().
useful.fun = function(x) sum(x == i, na.rm = TRUE)

for (i in c("modéré", "sévère", "grave")) # Iterating over possible severity levels.
{
  mydata$temp = apply(mydata, MARGIN = 1, useful.fun) # Requested results.
  colnames(mydata)[dim(mydata)[[2]]] = i # Renaming new column.
}
</code>```

Body:
Here is a subset of my dataset. Patients had different types of adverse events (variables) with different types of severity (observations). I would like to create additional variables representing severity ("severe", "severe", "moderate") and have the number of severity types for each patient.

mydata<-structure(list(record_id = c("2", "4", "5", "9", "10", "11",
    "12", "15", "22", "23"), `Dégré Cytolyse hep ` = structure(c(NA,
    3L, NA, NA, 1L, NA, 2L, NA, 3L, NA), .Label = c("modéré", "grave",
    "sévère"), class = "factor"), `Dégré Trble digest` = structure(c(1L,
    NA, NA, NA, NA, 2L, 1L, 1L, NA, 3L), .Label = c("modéré", "grave",
    "sévère"), class = "factor"), `Dégré Erupt cutanées` = structure(c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_), .Label = c("modéré",
    "grave", "sévère"), class = "factor"), `Dégré Ins renale` = structure(c(NA,
    NA, NA, 1L, NA, NA, NA, NA, NA, NA), .Label = c("modéré", "grave",
    "sévère"), class = "factor"), `Dégré Neuropath` = structure(c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_), .Label = c("modéré",
    "grave", "sévère"), class = "factor"), `Dégré Autre 1` = structure(c(NA,
    NA, 1L, NA, NA, 1L, NA, 1L, 3L, NA), .Label = c("modéré", "grave",
    "sévère"), class = "factor"), `Dégré Autre 2` = structure(c(NA,
    NA, NA, NA, NA, 1L, NA, 1L, NA, NA), .Label = c("modéré", "grave",
    "sévère"), class = "factor"), `Dégré Autre 3` = structure(c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_), .Label = c("modéré",
    "grave", "sévère"), class = "factor"), `Dégré Autre 4` = structure(c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_), .Label = c("modéré",
    "grave", "sévère"), class = "factor"), `Dégré Autre 5` = structure(c(NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,
    NA_integer_, NA_integer_, NA_integer_, NA_integer_), .Label = c("modéré",
    "grave", "sévère"), class = "factor")), row.names = c(NA, 10L
    ), class = "data.frame")

The expected dataset will be:

   record_id Dégré Cytolyse hep  Dégré Trble digest Dégré Erupt cutanées Dégré Ins renale Dégré Neuropath Dégré Autre 1 Dégré Autre 2 Dégré Autre 3 Dégré Autre 4 Dégré Autre 5 modéré sévère grave
1          2                <NA>             modéré                 <NA>             <NA>            <NA>          <NA>          <NA>          <NA>          <NA>          <NA>      1      0     0
2          4              sévère               <NA>                 <NA>             <NA>            <NA>          <NA>          <NA>          <NA>          <NA>          <NA>      0      1     0
3          5                <NA>               <NA>                 <NA>             <NA>            <NA>        modéré          <NA>          <NA>          <NA>          <NA>      1      0     0
4          9                <NA>               <NA>                 <NA>           modéré            <NA>          <NA>          <NA>          <NA>          <NA>          <NA>      1      0     0
5         10              modéré               <NA>                 <NA>             <NA>            <NA>          <NA>          <NA>          <NA>          <NA>          <NA>      1      0     0
6         11                <NA>              grave                 <NA>             <NA>            <NA>        modéré        modéré          <NA>          <NA>          <NA>      2      0     1
7         12               grave             modéré                 <NA>             <NA>            <NA>          <NA>          <NA>          <NA>          <NA>          <NA>      1      0     1
8         15                <NA>             modéré                 <NA>             <NA>            <NA>        modéré        modéré          <NA>          <NA>          <NA>      3      0     0
9         22              sévère               <NA>                 <NA>             <NA>            <NA>        sévère          <NA>          <NA>          <NA>          <NA>      0      2     0
10        23                <NA>             sévère                 <NA>             <NA>            <NA>          <NA>          <NA>          <NA>          <NA>          <NA>      0      1     0

Body:
This is very similat to a question I answered about a week ago. Using apply() and a user-written function:

# Defining useful function, to be passed within apply().
useful.fun = function(x) sum(x == i, na.rm = TRUE)

for (i in c("modéré", "sévère", "grave")) # Iterating over possible severity levels.
{
  mydata$temp = apply(mydata, MARGIN = 1, useful.fun) # Requested results.
  colnames(mydata)[dim(mydata)[[2]]] = i # Renaming new column.
}


答:
You can try this query (Demo):

```<code>SELECT evt.id_event
FROM events evt
WHERE evt.id_event NOT IN (
  SELECT e.id_event
  FROM events e
  INNER JOIN dates d
  ON e.id_event=d.id_event
  AND d.date > CURDATE()
);
</code>```

Here, at first, all event ids with future dates are found out, and then event ids are selected which are not in the previously found out event ids.

Title: Select only records without future dates via join

Body:
You can try this query (Demo):

SELECT evt.id_event
FROM events evt
WHERE evt.id_event NOT IN (
  SELECT e.id_event
  FROM events e
  INNER JOIN dates d
  ON e.id_event=d.id_event
  AND d.date > CURDATE()
);

Here, at first, all event ids with future dates are found out, and then event ids are selected which are not in the previously found out event ids.


问:
AWS S3 cross account policy
I would like to set a policy for a S3 bucket that is restricted to a VPC-ID(using a S3 endpoint). I have two accounts, A and B. I want a IAM user in A to access a bucket in B.

https://docs.aws.amazon.com/AmazonS3/latest/userguide/example-bucket-policies-vpc-endpoint.html

```<code>{    "Version": "2012-10-17",    "Id": "Policy1415115909153",    "Statement": [
 {
   "Sid": "Access-to-specific-VPC-only",
   "Principal": "*",
   "Action": "s3:*",
   "Effect": "Deny",
   "Resource": ["arn:aws:s3:::awsexamplebucket1",
                "arn:aws:s3:::awsexamplebucket1/*"],
   "Condition": {
     "StringNotEquals": {
       "aws:SourceVpc": "vpc-111bbb22"
     }
   }
 }    ] }
</code>```

Above won't work, but following will:

```<code>{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Principal": "*",
        "Action": "s3:*",
        "Resource": [
            "arn:aws:s3:::bucket",
            "arn:aws:s3:::bucket/*"
        ],
        "Condition": {
            "StringEquals": {
                "aws:SourceVpc": "vpc-111111111111"
            }
        }
    }
]
</code>```

}

Feels like best practices is to use a deny policy. Anyone has an idea why and how solve it?

答: As pointed out you need to allow as-well. Combine both policies and it will work.</p>

Title: AWS S3 cross account policy

Body:
I would like to set a policy for a S3 bucket that is restricted to a VPC-ID(using a S3 endpoint). I have two accounts, A and B. I want a IAM user in A to access a bucket in B.

https://docs.aws.amazon.com/AmazonS3/latest/userguide/example-bucket-policies-vpc-endpoint.html

{    "Version": "2012-10-17",    "Id": "Policy1415115909153",    "Statement": [
 {
   "Sid": "Access-to-specific-VPC-only",
   "Principal": "*",
   "Action": "s3:*",
   "Effect": "Deny",
   "Resource": ["arn:aws:s3:::awsexamplebucket1",
                "arn:aws:s3:::awsexamplebucket1/*"],
   "Condition": {
     "StringNotEquals": {
       "aws:SourceVpc": "vpc-111bbb22"
     }
   }
 }    ] }

Above won't work, but following will:

{
"Version": "2012-10-17",
"Statement": [
    {
        "Effect": "Allow",
        "Principal": "*",
        "Action": "s3:*",
        "Resource": [
            "arn:aws:s3:::bucket",
            "arn:aws:s3:::bucket/*"
        ],
        "Condition": {
            "StringEquals": {
                "aws:SourceVpc": "vpc-111111111111"
            }
        }
    }
]

}

Feels like best practices is to use a deny policy. Anyone has an idea why and how solve it?


问:
How to fire keyboard events in Javascript using onClick?
I have an existing function that gets called when KeyD is pressed.

I want to trigger an KeyD event (without actually pressing keyD on keyboard) as soon as I click on some button.

Is it possible in Javascript?

答:
You need to create a new KeyboardEvent, and provide a key for KeyboardEventInit dictionary which is the second argument.

Then use dispatchEvent to trigger the event on the element.

let elem = document.querySelector("input");

elem.addEventListener("keypress", (e) => {
  if(e.key === "d"){
    keyDPressed();
  }
});

elem.addEventListener("click", (e) => {
    let eve = new KeyboardEvent('keypress',{ key : "d"})
    e.target.dispatchEvent(eve);
});

function keyDPressed(e) {   //function that gets called when key D is pressed
  console.log("d was pressed");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input value="Click here" type="button"></code>```

Body:
You need to create a new KeyboardEvent, and provide a key for KeyboardEventInit dictionary which is the second argument.

Then use dispatchEvent to trigger the event on the element.

let elem = document.querySelector("input");

elem.addEventListener("keypress", (e) => {
  if(e.key === "d"){
    keyDPressed();
  }
});

elem.addEventListener("click", (e) => {
    let eve = new KeyboardEvent('keypress',{ key : "d"})
    e.target.dispatchEvent(eve);
});

function keyDPressed(e) {   //function that gets called when key D is pressed
  console.log("d was pressed");
}

<input value="Click here" type="button">


问:
How to make a Disabled Input also Required with Angular Reactive Form?
I have an input which will be populated when the user clicks on a dialog. So for this I had to make it disabled, because I don't want the user to manually input the value.
The only problem is that this input must be required, and I couldn't make it so far.

I have tried to add 'required' directive in the input and also tried adding Validator.required on the form creation, but none of these made the field required for the form.

```<code>createUnityForm(): FormGroup {
    return this._formBuilder.group({
        id      : [this.unity.id],
        description: [this.unity.description],
        floor: [{value: this.unity.floor, disabled: true}, Validators.required]
    });
}

<mat-form-field appearance="outline" floatLabel="always" class="mr-16" fxFlex>
    <mat-label>{{'UNITY.FLOOR' | translate}}</mat-label>
    <input matInput placeholder="{{'UNITY.SELECT-FLOOR' | translate}}"
        name="floor"
        formControlName="floor"
        required>
</mat-form-field>

<button *ngIf="action === 'edit'"
    mat-button
    class="save-button"
    (click)="matDialogRef.close(['save',unityForm])"
    [disabled]="unityForm.invalid"
    aria-label="save">
        {{'GENERAL.SAVE' | translate}}
</button>
</code>```

unityForm is valid even when there's nothing in the input

答:
You can't, reactive forms don't use validators on disabled fields.
I think it's a good way to do like this:

-HTML

```<code><input
type="text"
formControlName="controlName"
[ngClass]="{ 'is-invalid':
(c.controlName.errors || c.controlName.disabled)
&& submited }"/>
</code>```

-TypeScript

```<code>submited = false;

form: FormGroup = this.formBuilder.group({
    controlName: [{ value: '', disabled: true }, Validators.required]
});

get c(): { [key: string]: AbstractControl } {
    return this.form.controls;
}

save(): void {
    this.submited = true;
    if (this.form.invalid
       || this.formControl.controlname.value === '') {
     return;
}
</code>```

-CSS

```<code>.is-invalid {
  border: 1px solid #dc3545;
}
</code>```

When you click on button for SAVE, required field will get red border if there is no value

Body:
I have an input which will be populated when the user clicks on a dialog. So for this I had to make it disabled, because I don't want the user to manually input the value.
The only problem is that this input must be required, and I couldn't make it so far.

I have tried to add 'required' directive in the input and also tried adding Validator.required on the form creation, but none of these made the field required for the form.

createUnityForm(): FormGroup {
    return this._formBuilder.group({
        id      : [this.unity.id],
        description: [this.unity.description],
        floor: [{value: this.unity.floor, disabled: true}, Validators.required]
    });
}

<mat-form-field appearance="outline" floatLabel="always" class="mr-16" fxFlex>
    <mat-label>{{'UNITY.FLOOR' | translate}}</mat-label>
    <input matInput placeholder="{{'UNITY.SELECT-FLOOR' | translate}}"
        name="floor"
        formControlName="floor"
        required>
</mat-form-field>

<button *ngIf="action === 'edit'"
    mat-button
    class="save-button"
    (click)="matDialogRef.close(['save',unityForm])"
    [disabled]="unityForm.invalid"
    aria-label="save">
        {{'GENERAL.SAVE' | translate}}
</button>

unityForm is valid even when there's nothing in the input

Body:
You can't, reactive forms don't use validators on disabled fields.
I think it's a good way to do like this:

-HTML

<input
type="text"
formControlName="controlName"
[ngClass]="{ 'is-invalid':
(c.controlName.errors || c.controlName.disabled)
&& submited }"/>

-TypeScript

submited = false;

form: FormGroup = this.formBuilder.group({
    controlName: [{ value: '', disabled: true }, Validators.required]
});

get c(): { [key: string]: AbstractControl } {
    return this.form.controls;
}

save(): void {
    this.submited = true;
    if (this.form.invalid
       || this.formControl.controlname.value === '') {
     return;
}

-CSS

.is-invalid {
  border: 1px solid #dc3545;
}

When you click on button for SAVE, required field will get red border if there is no value


问:
generate 4 digit random number using substring
I am trying to execute below code:

```<code>var a = Math.floor(100000 + Math.random() * 900000);
a = a.substring(-2);
</code>```

I am getting error like undefined is not a function at line 2, but when I try to do alert(a), it has something. What is wrong here?

答:
Just pass Length of to number that need to be generated</p>
```<code>  await this.randomInteger(4);
  async randomInteger(number) {

    let length = parseInt(number);
    let string:string = number.toString();
    let min = 1* parseInt( string.padEnd(length,"0") ) ;
    let max =   parseInt( string.padEnd(length,"9") );

    return Math.floor(
      Math.random() * (max - min + 1) + min
    )
  }
</code>```

Body:
I am trying to execute below code:

var a = Math.floor(100000 + Math.random() * 900000);
a = a.substring(-2);

I am getting error like undefined is not a function at line 2, but when I try to do alert(a), it has something. What is wrong here?

Body:
Just pass Length of to number that need to be generated

  await this.randomInteger(4);
  async randomInteger(number) {

    let length = parseInt(number);
    let string:string = number.toString();
    let min = 1* parseInt( string.padEnd(length,"0") ) ;
    let max =   parseInt( string.padEnd(length,"9") );

    return Math.floor(
      Math.random() * (max - min + 1) + min
    )
  }


问:
Create a new variable in pre-existing column
I am a beginner of R and I would like to create a new variable "Overall" and "Profit (sum of profits of 1st and 2nd term per company) under each column</p>
```<code>Company Term Profit
   A    1st   300
   B    1st   400
   A    2nd   500
   B    2nd   200
</code>```

答:
use dplyr package for data manipulation
specify grouping parameters and use mutate() to create additional variable

```<code># let this be your data
df = read.delim('x.txt', sep = ',')

data.frame(df) %>%
group_by(Company, Term) %>%
  mutate(`Sum of profits` = sum(Profit))
</code>```

ouput:

```<code>  Company Term      Profit `Sum of profits`
  <chr>   <chr>      <int>            <int>
1   "A"    "1st"      300              300
2   "B"    "1st"      400              400
3   "A"    "2nd"      500              500
4   "B"    "2nd"      200              200
</code>```

Body:
I am a beginner of R and I would like to create a new variable "Overall" and "Profit (sum of profits of 1st and 2nd term per company) under each column

Company Term Profit
   A    1st   300
   B    1st   400
   A    2nd   500
   B    2nd   200

Body:
use dplyr package for data manipulation
specify grouping parameters and use mutate() to create additional variable

# let this be your data
df = read.delim('x.txt', sep = ',')

data.frame(df) %>%
group_by(Company, Term) %>%
  mutate(`Sum of profits` = sum(Profit))

ouput:

  Company Term      Profit `Sum of profits`
  <chr>   <chr>      <int>            <int>
1   "A"    "1st"      300              300
2   "B"    "1st"      400              400
3   "A"    "2nd"      500              500
4   "B"    "2nd"      200              200


问:
do consumer lag of one consumer will affect other consumer in a same group id with different topics
I have one group Id "my-consumer-group-id" and 3 topics with their own consumers
say

```<code>"my-consumer-1" consumed to "topic1" with groupId "my-consumer-group-id"
"my-consumer-2" consumed to "topic2" with groupId "my-consumer-group-id"
"my-consumer-3" consumed to "topic3" with groupId "my-consumer-group-id"
</code>```

I observed "my-consumer-1" has 2 million records with 600k consumer lag,
will this affect other consumers from being processed their own message? in terms of the performance, is it better to have a separate consumer groupId for each consumer?

答:
It is best practice to use a different group for each.

While the lag on one won't affect the other consumers, using the same group means that if there is a rebalance on one topic, it will cause a rebalance of all your consumers, including those consuming from different topics.

Body:
I have one group Id "my-consumer-group-id" and 3 topics with their own consumers
say

"my-consumer-1" consumed to "topic1" with groupId "my-consumer-group-id"
"my-consumer-2" consumed to "topic2" with groupId "my-consumer-group-id"
"my-consumer-3" consumed to "topic3" with groupId "my-consumer-group-id"

I observed "my-consumer-1" has 2 million records with 600k consumer lag,
will this affect other consumers from being processed their own message? in terms of the performance, is it better to have a separate consumer groupId for each consumer?


问:
Chinese Characters Are Misspelled in OI Operations
I try to write chinese character but take a wrong result

For Instance :

```<code>import java.io.*;
import java.nio.*;

class x {

   public static void main(String... args) throws Exception {
        OutputStreamWriter outputStreamWriter =
          new OutputStreamWriter(new FileOutputStream(new File("practice.csv"), true), "GBK");

        outputStreamWriter.write("常用场景");
        outputStreamWriter.write("Helo World!");
        outputStreamWriter.flush();
        outputStreamWriter.close();
    }
}
</code>```

Response : ????¡±¡§??????Helo World!

I tried to change charset utf-8, utf-16 but it doesn't anything and lastly I tried to add BufferedWriter but unfortunately it doesn't anything again.

then I considered to change csv to txt, but again same result. What am I doing wrong ?

答:
I found it finally. Firstly very thanks for helping @Kayaman and @user16320675.

In fact, everything was correct. This problem's resource is csv files is opened by excel. When you want to open csv files directly in excel, it opens according to the encoding of the current computer language. We just have a option in Windows 10 EN(manually Data Import). I used the windows 10 EN and excel uses ANSI for windows 10 EN.

My Solution : I added to chinese language pack to my windows 10 computer and I changed the excel editing language (chinese for default) and everything worked.

Body:
I try to write chinese character but take a wrong result

For Instance :

import java.io.*;
import java.nio.*;

class x {

   public static void main(String... args) throws Exception {
        OutputStreamWriter outputStreamWriter =
          new OutputStreamWriter(new FileOutputStream(new File("practice.csv"), true), "GBK");

        outputStreamWriter.write("常用场景");
        outputStreamWriter.write("Helo World!");
        outputStreamWriter.flush();
        outputStreamWriter.close();
    }
}

Response : ????¡±¡§??????Helo World!

I tried to change charset utf-8, utf-16 but it doesn't anything and lastly I tried to add BufferedWriter but unfortunately it doesn't anything again.

then I considered to change csv to txt, but again same result. What am I doing wrong ?


问:
opam init failure upon attempted OCaml installation on MacOS 10.14.16
I am attempting to install OCaml via the OCaml opam package manager on MacOs. I have successfully installed opam via homebrew. Initiating the package manager with opam init yields the following error:

```<code>[ERROR] Could not update repository "default":
        OpamDownload.Download_fail(_, "Curl failed: \"/usr/bin/curl
        --write-out %{http_code}\\\\n --retry 3 --retry-delay 2
        --user-agent opam/2.1.0 -L -o
        /private/var/folders/c_/6splkz692w16x82lzgnsxgfr0000gn/T/opam-57814-6b2069/index.tar.gz.part
        -- https://opam.ocaml.org/index.tar.gz\" exited with code 60")
[ERROR] Initial download of repository failed.
</code>```

What can I do to facilitate successful connection to the repository and initialise opam?

答:
I ran into the same issue and I found a workaround on the OCaml forum: here. (Credits to UnixJunkie)

You can run:

```<code>opam init github git+https://github.com/ocaml/opam-repository.git
</code>```

This should avoid the certificate issues.

I tried to use ivg's solution but must have made a mistake in moving the .pem files, so I couldn't get that solution to work. The workaround was quick.

Update

The reason opam init failed for me was because curl was installed with snap on my system.
Try to run opam init -verbose and that could reveal more about why you ran into an error.
In my case I needed to install other things with opam and it kept failing every time. So snap uninstall curl and then sudo apt install curl fixed things. (Was only able to figure this out with help from my professor)

Body:
I am attempting to install OCaml via the OCaml opam package manager on MacOs. I have successfully installed opam via homebrew. Initiating the package manager with opam init yields the following error:

[ERROR] Could not update repository "default":
        OpamDownload.Download_fail(_, "Curl failed: \"/usr/bin/curl
        --write-out %{http_code}\\\\n --retry 3 --retry-delay 2
        --user-agent opam/2.1.0 -L -o
        /private/var/folders/c_/6splkz692w16x82lzgnsxgfr0000gn/T/opam-57814-6b2069/index.tar.gz.part
        -- https://opam.ocaml.org/index.tar.gz\" exited with code 60")
[ERROR] Initial download of repository failed.

What can I do to facilitate successful connection to the repository and initialise opam?

Body:
I ran into the same issue and I found a workaround on the OCaml forum: here. (Credits to UnixJunkie)

You can run:

opam init github git+https://github.com/ocaml/opam-repository.git

This should avoid the certificate issues.

I tried to use ivg's solution but must have made a mistake in moving the .pem files, so I couldn't get that solution to work. The workaround was quick.

Update

The reason opam init failed for me was because curl was installed with snap on my system.
Try to run opam init -verbose and that could reveal more about why you ran into an error.
In my case I needed to install other things with opam and it kept failing every time. So snap uninstall curl and then sudo apt install curl fixed things. (Was only able to figure this out with help from my professor)


问:
Can I do multiple SQL requests as a single request
here's the situation, i have 3 tables that look like this.

```<code>table foo
type number
a    1
b    2
c    3
d    4

table bar
number shape
1      square
2      circle
3      triangle
4      rectangle

table foobar
shape     colour
square    red
circle    green
triangle  blue
rectangle yellow
triangle  purple
</code>```

they all also have unique ids that I have not listed.

I have type but I want to find colour. now I could do three SQL requests to get it but as the SQL is likely to be the bottleneck so I was wondering if I could combine the three SQL requests into one request.

Is it possible to do this and would it run faster than three separate SQL requests

1 would return red and 3 would return blue and purple.

答:
```<code>SELECT fb.colour
FROM foo AS f
INNER JOIN bar AS b ON f.number = b.number
INNER JOIN foobar AS fb ON b.shape = fb.shape
WHERE f.type = "YOURTYPE"
</code>```

You can use  JOINS to join the rows and use a where clause to specify the type you want. It would definitely be faster then doing this:

```<code>SELECT number FROM foo WHERE type="YOURTYPE"
SELECT shape  FROM bar WHERE number="NUMBERRETRIEVEDFROM"
SELECT colour FROM foobar WHERE shape="SHAPE"
</code>```

Body:
here's the situation, i have 3 tables that look like this.

table foo
type number
a    1
b    2
c    3
d    4

table bar
number shape
1      square
2      circle
3      triangle
4      rectangle

table foobar
shape     colour
square    red
circle    green
triangle  blue
rectangle yellow
triangle  purple

they all also have unique ids that I have not listed.

I have type but I want to find colour. now I could do three SQL requests to get it but as the SQL is likely to be the bottleneck so I was wondering if I could combine the three SQL requests into one request.

Is it possible to do this and would it run faster than three separate SQL requests

1 would return red and 3 would return blue and purple.

Body:
SELECT fb.colour
FROM foo AS f
INNER JOIN bar AS b ON f.number = b.number
INNER JOIN foobar AS fb ON b.shape = fb.shape
WHERE f.type = "YOURTYPE"

You can use  JOINS to join the rows and use a where clause to specify the type you want. It would definitely be faster then doing this:

SELECT number FROM foo WHERE type="YOURTYPE"
SELECT shape  FROM bar WHERE number="NUMBERRETRIEVEDFROM"
SELECT colour FROM foobar WHERE shape="SHAPE"


问:
Gradle jar not running. Could not find or load main class
I have created a very basic gradle java project that prints "Hello Word". The main class builds and runs fine. When i try to run java -jar out\artifacts\helloWorld_jar\helloWorld.jar on the command line it gives me this error

```<code>Error: Could not find or load main class com.exmple.helloWorld
Caused by: java.lang.ClassNotFoundException: com.exmple.helloWorld
</code>```

here is how my directory looks

```<code>|-gradle
|-.idea
|-build
|-gradle
|-META-INF
|-out
 | -artifacts
 | -helloWorld_jar
 | -helloWorld.jar
|-src
 |-main
  |-java
   |- com.exmple
    |-helloWorld
 |-test
|build.gradle
etc...
</code>```

My build.gradle file looks like this:

```<code>plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}
jar{
    manifest{
        attributes "Main-Class": "com.exmple.helloWorld"
    }

}
dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
}

test {
    useJUnitPlatform()
}

</code>```

I have tried both single quotes and double quotes and it still runs an error. Any ideas on how to fix this? I have been trying for a few days now.

PS. example is spelt wrong, but its spelt exmple throughout

答:
If the full classname is com.exmpl.helloWorld, then the source directory structure should be:

```<code>|-src
 |-main
  |-java
   |-com
    |-exmpl
     |-helloWorld.java
</code>```

not

```<code>|-src
 |-main
  |-java
   |-com.exmple
    |-helloWorld
</code>```

Please read What does "Could not find or load main class" mean? for more information.  (It explains in depth the many things that can cause this problem.)

Body:
I have created a very basic gradle java project that prints "Hello Word". The main class builds and runs fine. When i try to run java -jar out\artifacts\helloWorld_jar\helloWorld.jar on the command line it gives me this error

Error: Could not find or load main class com.exmple.helloWorld
Caused by: java.lang.ClassNotFoundException: com.exmple.helloWorld

here is how my directory looks

|-gradle
|-.idea
|-build
|-gradle
|-META-INF
|-out
 | -artifacts
 | -helloWorld_jar
 | -helloWorld.jar
|-src
 |-main
  |-java
   |- com.exmple
    |-helloWorld
 |-test
|build.gradle
etc...

My build.gradle file looks like this:

plugins {
    id 'java'
}

group 'org.example'
version '1.0-SNAPSHOT'

repositories {
    mavenCentral()
}
jar{
    manifest{
        attributes "Main-Class": "com.exmple.helloWorld"
    }

}
dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
}

test {
    useJUnitPlatform()
}

I have tried both single quotes and double quotes and it still runs an error. Any ideas on how to fix this? I have been trying for a few days now.

PS. example is spelt wrong, but its spelt exmple throughout

Body:
If the full classname is com.exmpl.helloWorld, then the source directory structure should be:

|-src
 |-main
  |-java
   |-com
    |-exmpl
     |-helloWorld.java

not

|-src
 |-main
  |-java
   |-com.exmple
    |-helloWorld

Please read What does "Could not find or load main class" mean? for more information.  (It explains in depth the many things that can cause this problem.)


问:
Python SQL Error: 2003 (HY000): Can't connect to MySQL server on '192.168.1.1:3306' (10061) SSMS
it seems I can't connect to my SQL Server Management Studios (installed on a Win machine) database and I don't know why since some other scheduled Python jobs I personally created that execute other queries work just fine.

This is an example of my code:

```<code>import sys
import mysql.connector

try:

  conn = mysql.connector.connect(
      host="192.168.1.1",
      user="sa",
      password="sa",
      database="Test"
  )
  cursor = conn.cursor()

  query = "SELECT * FROM [DB] WHERE [Art] = 'EX'"
  cursor.execute(query)
  row = cursor.fetchall()

  if cursor.rowcount == 0:
     print("No results")
     sys.exit()

except Exception as e:

  print(e)
</code>```

Everytime throws the error 2003 (HY000): Can't connect to MySQL server on '192.168.1.1:3306' (10061)

And yes, I checked if any services were down (like written on other answers I found on the internet) but they all were up

I tried to execute my script on 2 other PCs but it didn't work

I even tried restarting the server and guess what, it didn't work

Thanks in advance

答:
According to my understanding, you are trying to connect with Microsoft SQL Server Management Studio using Python.

If so, you need pyodbc python module.

To install pyodbc module, open cmd and run the following:

```<code>python -m pip install pyodbc
</code>```

Now, to connect database :

```<code>import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
                    'Server=username\SQLEXPRESS;'
                    'Trusted_Connection=yes;')
</code>```

Replace 'username' with your desktop username

find pyodbc documentation here

also you can follow this

Body:
it seems I can't connect to my SQL Server Management Studios (installed on a Win machine) database and I don't know why since some other scheduled Python jobs I personally created that execute other queries work just fine.

This is an example of my code:

import sys
import mysql.connector

try:

  conn = mysql.connector.connect(
      host="192.168.1.1",
      user="sa",
      password="sa",
      database="Test"
  )
  cursor = conn.cursor()

  query = "SELECT * FROM [DB] WHERE [Art] = 'EX'"
  cursor.execute(query)
  row = cursor.fetchall()

  if cursor.rowcount == 0:
     print("No results")
     sys.exit()

except Exception as e:

  print(e)

Everytime throws the error 2003 (HY000): Can't connect to MySQL server on '192.168.1.1:3306' (10061)

And yes, I checked if any services were down (like written on other answers I found on the internet) but they all were up

I tried to execute my script on 2 other PCs but it didn't work

I even tried restarting the server and guess what, it didn't work

Thanks in advance

Body:
According to my understanding, you are trying to connect with Microsoft SQL Server Management Studio using Python.

If so, you need pyodbc python module.

To install pyodbc module, open cmd and run the following:

python -m pip install pyodbc

Now, to connect database :

import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
                    'Server=username\SQLEXPRESS;'
                    'Trusted_Connection=yes;')

Replace 'username' with your desktop username

find pyodbc documentation here

also you can follow this


问:
Is it possible to make a layout auto adjust from Row layout to Column layout while changing windows size in browser?
I am trying to create a flutter web App. I have created a Row with Form with 3 TextFormFields. My Requirement is: If i change the web page's window Size big to small, That TextFormFields should be viewed as Column Layout, And if i change the size from small to big that TextFormFields should be viewed as row layout. And someTimes i will use TextFormFields more than 3. If it is possible How to do. Or If any other Ideas aso Please let me know. Or Let me know incase any other widgets are there Rather than that row and column.
My Example code with Row:</p>
```<code>SingleChildScrollView(
                    child: Row(
                      children: [
                        Form(
                          key: _formkey,
                          child: Align(
                            alignment: Alignment.topCenter,
                            child: Card(
                              child: Padding(
                                padding: const EdgeInsets.all(16),
                                child: Row(
                                  children: [
                                    ConstrainedBox(
                                      constraints:
                                          const BoxConstraints(maxWidth: 400),
                                      child: TextFormField(
                                        readOnly: true,
                                        decoration: const InputDecoration(
                                          border: OutlineInputBorder(),
                                          filled: true,
                                          labelText: '1',
                                        ),
                                      ),
                                    ),
                                    const SizedBox(
                                      width: 10,
                                    ),
                                    ConstrainedBox(
                                      constraints:
                                          const BoxConstraints(maxWidth: 400),
                                      child: TextFormField(
                                        readOnly: true,
                                        decoration: const InputDecoration(
                                          border: OutlineInputBorder(),
                                          filled: true,
                                          labelText: '2',
                                        ),
                                      ),
                                    ),
                                    const SizedBox(
                                      width: 10,
                                    ),
                                    ConstrainedBox(
                                      constraints:
                                          const BoxConstraints(maxWidth: 400),
                                      child: TextFormField(
                                        readOnly: true,
                                        decoration: const InputDecoration(
                                          border: OutlineInputBorder(),
                                          filled: true,
                                          labelText: '3',
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
</code>```

答: You can use MediaQuery to measure the height and width of device and according to that you can provide the height and width in percentage.</p>

Body:
I am trying to create a flutter web App. I have created a Row with Form with 3 TextFormFields. My Requirement is: If i change the web page's window Size big to small, That TextFormFields should be viewed as Column Layout, And if i change the size from small to big that TextFormFields should be viewed as row layout. And someTimes i will use TextFormFields more than 3. If it is possible How to do. Or If any other Ideas aso Please let me know. Or Let me know incase any other widgets are there Rather than that row and column.
My Example code with Row:

SingleChildScrollView(
                    child: Row(
                      children: [
                        Form(
                          key: _formkey,
                          child: Align(
                            alignment: Alignment.topCenter,
                            child: Card(
                              child: Padding(
                                padding: const EdgeInsets.all(16),
                                child: Row(
                                  children: [
                                    ConstrainedBox(
                                      constraints:
                                          const BoxConstraints(maxWidth: 400),
                                      child: TextFormField(
                                        readOnly: true,
                                        decoration: const InputDecoration(
                                          border: OutlineInputBorder(),
                                          filled: true,
                                          labelText: '1',
                                        ),
                                      ),
                                    ),
                                    const SizedBox(
                                      width: 10,
                                    ),
                                    ConstrainedBox(
                                      constraints:
                                          const BoxConstraints(maxWidth: 400),
                                      child: TextFormField(
                                        readOnly: true,
                                        decoration: const InputDecoration(
                                          border: OutlineInputBorder(),
                                          filled: true,
                                          labelText: '2',
                                        ),
                                      ),
                                    ),
                                    const SizedBox(
                                      width: 10,
                                    ),
                                    ConstrainedBox(
                                      constraints:
                                          const BoxConstraints(maxWidth: 400),
                                      child: TextFormField(
                                        readOnly: true,
                                        decoration: const InputDecoration(
                                          border: OutlineInputBorder(),
                                          filled: true,
                                          labelText: '3',
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),


问:
Unable to extract VirtualNetwork Name using SCVMM powershell modules
Im trying to extract virtual network information for a VM using powershell, i tried using regular expression but for VM's with more than 1 NIC im unable to see output

Below is the output which i need..

```<code>PS C:\> get-vm sql.IAN01.Host | select -ExpandProperty virtualnetworkadapters | select virtualnetwork

VirtualNetwork
--------------
VirtualUplink
iSCSI1
iSCSI2
VirtualUplink
</code>```

But when i try using regular expressions it does not give me an output, Network comes blank

```<code>PS C:\> Get-VM sql.IAN01.Host | Select @{Name="VMName";Expression={$_.name}},@{Name="Network
";Expression={@((get-vm $_.name | select -ExpandProperty virtualnetworkadapters).virtualnetwork)}}

VMName                                                      Network
------                                                      -------
sql.IADPSQLHST1N01.Hosting
</code>```

Can anyone please help me out!!

答:
Try this:</p>

```<code>Get-VM sql.IAN01.Host | Select-Object @{Name="VMName";Expression={$_.name}},@{Name='VirtualNetwork';e={$_.VirtualNetworkAdapters | Foreach-Object{$_.VirtualNetwork}}}
</code>```

Body:
Im trying to extract virtual network information for a VM using powershell, i tried using regular expression but for VM's with more than 1 NIC im unable to see output

Below is the output which i need..

PS C:\> get-vm sql.IAN01.Host | select -ExpandProperty virtualnetworkadapters | select virtualnetwork

VirtualNetwork
--------------
VirtualUplink
iSCSI1
iSCSI2
VirtualUplink

But when i try using regular expressions it does not give me an output, Network comes blank

PS C:\> Get-VM sql.IAN01.Host | Select @{Name="VMName";Expression={$_.name}},@{Name="Network
";Expression={@((get-vm $_.name | select -ExpandProperty virtualnetworkadapters).virtualnetwork)}}

VMName                                                      Network
------                                                      -------
sql.IADPSQLHST1N01.Hosting

Can anyone please help me out!!

Body:
Try this:

Get-VM sql.IAN01.Host | Select-Object @{Name="VMName";Expression={$_.name}},@{Name='VirtualNetwork';e={$_.VirtualNetworkAdapters | Foreach-Object{$_.VirtualNetwork}}}


问:
How to extract object orientation from video stream (Webcam) - Python
I found this guide which teaches how to refine the orientation of objects from images. I would love to know if it can and should be used to analyze the orientation of objects displayed in video streams.

The basis for the work is from the scientific publication found in this video. I want to know how they got information about the direction of the Fish's face.

Thanks,
Avishai

答:
You will probably need library like opencv to get orientation information from the image. You can apply threshold after converting this image to grayscale and extract contour of the image. After that you need to follow something like below pattern to get orientation. Very easy, just a little bit search you can find a lot of similar examples as well.</p>
```<code>rectangle_for_angle = cv2.minAreaRect(cntrs[0])
angle = rectangle_for_angle[-1]
rect_points = cv2.boxPoints(rectangle_for_angle)
rect_points_result = np.int0(rect_points)
#You can also draw rotated image
cv2.drawContours(image,[rect_points_result],0,(0,0,255),2)
</code>```

Body:
You will probably need library like opencv to get orientation information from the image. You can apply threshold after converting this image to grayscale and extract contour of the image. After that you need to follow something like below pattern to get orientation. Very easy, just a little bit search you can find a lot of similar examples as well.

rectangle_for_angle = cv2.minAreaRect(cntrs[0])
angle = rectangle_for_angle[-1]
rect_points = cv2.boxPoints(rectangle_for_angle)
rect_points_result = np.int0(rect_points)
#You can also draw rotated image
cv2.drawContours(image,[rect_points_result],0,(0,0,255),2)


问:
How to sum data by date filter in Javascript?
I try to find a solution to sum cost data (to group thme by day) with ISO date information in object.

My data object looks like :

```<code>0: {id: 45, title: 'abo', cost: 10, recurrent: true, date: '2022-02-09T20:43:30.139Z'}
1: {id: 123, title: 'test 4', cost: 20, recurrent: false, date: '2022-02-09T20:43:30.139Z'}
2: {id: 125, title: 'test 3', cost: 50, recurrent: false, date: '2022-02-06T23:00:00.000Z'}
3: {id: 125, title: 'test 2', cost: 100, recurrent: false, date: '2022-02-05T10:00:00.000Z'}
4: {id: 125, title: 'test 1', cost: 122, recurrent: false, date: '2022-02-04T23:00:00.000Z'}
</code>```

The expected result :
sumData = [222,50,30]

Total cost for the 2022-02-05 = 222

Total cost for the 2022-02-06 = 50

Total cost for the 2022-02-09 = 30

I try to sum with something like that :

```<code>    let currentDate     = '';
    let currentTotal    = 0;
    let sumData         = [];

    if(data) {
        for (let index = 0; index < data.length; index++) {

            //init date to compare with
            if(currentDate === '') {
                currentDate = new Date(data[index].date);
                currentTotal = data[index].cost;
            }
            else {
                const nextDate =  new Date(data[index].date);
                //test if is same day, sum expenses and add in sumData array
                if(currentDate.getFullYear() === nextDate.getFullYear() &&
                currentDate.getMonth() === nextDate.getMonth() &&
                currentDate.getDate() === nextDate.getDate())
                {
                    console.log('DATE = ' + currentDate.getDate());
                    console.log(data[index].date);
                    console.log('COST = ' + data[index].cost);
                    console.log('currentTotal = ' + currentTotal);
                    currentTotal = currentTotal + data[index].cost;
                    console.log(index + ' - COST = ' + data[index].cost);
                    console.log('TOTAL = ' + currentTotal);
                    console.log('===========');
                }
                else {
                    //push last valid sum before reset
                    currentTotal = 0;
                    //reset sum with last data
                    currentTotal = data[index].cost;
                }
                currentDate =  new Date(data[index].date);
            }
        }
    }
    console.log('== SUM data ==');
    sumData.push(currentTotal);

</code>```

答:
You can do it this way.

Please note that I updated your last date, as it was 2022-02-04 instead of 2022-02-05 as it is told in your question.

var array = [
{id: 45, title: 'abo', cost: 10, recurrent: true, date: '2022-02-09T20:43:30.139Z'},
{id: 123, title: 'test 4', cost: 20, recurrent: false, date: '2022-02-09T20:43:30.139Z'},
{id: 125, title: 'test 3', cost: 50, recurrent: false, date: '2022-02-06T23:00:00.000Z'},
{id: 125, title: 'test 2', cost: 100, recurrent: false, date: '2022-02-05T10:00:00.000Z'},
{id: 125, title: 'test 1', cost: 122, recurrent: false, date: '2022-02-05T23:00:00.000Z'},
];

var result = [];

array.reduce(function(res, value) {
  let onlyDate = value.date.split('T')[0];

  // Second approach is just to take first 10 characters of a substring like this:
  // let onlyDate = value.date.substring(0, 10);

  if (!res[onlyDate]) {
    res[onlyDate] = { date: onlyDate, cost: 0 };
    result.push(res[onlyDate])
  }
  res[onlyDate].cost += value.cost;
  return res;
}, {});

console.log("Result in format date/cost");
console.log(result);

const onlyCostsResult = result.map(item => item.cost);
console.log("Only costs");
console.log(onlyCostsResult);```

Body:
I try to find a solution to sum cost data (to group thme by day) with ISO date information in object.

My data object looks like :

0: {id: 45, title: 'abo', cost: 10, recurrent: true, date: '2022-02-09T20:43:30.139Z'}
1: {id: 123, title: 'test 4', cost: 20, recurrent: false, date: '2022-02-09T20:43:30.139Z'}
2: {id: 125, title: 'test 3', cost: 50, recurrent: false, date: '2022-02-06T23:00:00.000Z'}
3: {id: 125, title: 'test 2', cost: 100, recurrent: false, date: '2022-02-05T10:00:00.000Z'}
4: {id: 125, title: 'test 1', cost: 122, recurrent: false, date: '2022-02-04T23:00:00.000Z'}

The expected result :
sumData = [222,50,30]

Total cost for the 2022-02-05 = 222

Total cost for the 2022-02-06 = 50

Total cost for the 2022-02-09 = 30

I try to sum with something like that :

    let currentDate     = '';
    let currentTotal    = 0;
    let sumData         = [];

    if(data) {
        for (let index = 0; index < data.length; index++) {

            //init date to compare with
            if(currentDate === '') {
                currentDate = new Date(data[index].date);
                currentTotal = data[index].cost;
            }
            else {
                const nextDate =  new Date(data[index].date);
                //test if is same day, sum expenses and add in sumData array
                if(currentDate.getFullYear() === nextDate.getFullYear() &&
                currentDate.getMonth() === nextDate.getMonth() &&
                currentDate.getDate() === nextDate.getDate())
                {
                    console.log('DATE = ' + currentDate.getDate());
                    console.log(data[index].date);
                    console.log('COST = ' + data[index].cost);
                    console.log('currentTotal = ' + currentTotal);
                    currentTotal = currentTotal + data[index].cost;
                    console.log(index + ' - COST = ' + data[index].cost);
                    console.log('TOTAL = ' + currentTotal);
                    console.log('===========');
                }
                else {
                    //push last valid sum before reset
                    currentTotal = 0;
                    //reset sum with last data
                    currentTotal = data[index].cost;
                }
                currentDate =  new Date(data[index].date);
            }
        }
    }
    console.log('== SUM data ==');
    sumData.push(currentTotal);


问:
Non interactive samba user creation via ansible
Although the following command works when typing in in shell

```<code>echo -ne "myser\nmypass\n" | smbpasswd -a -s myuser
</code>```

The following task fails in ansible

```<code>  - name: add dms samba user
    command: echo -ne "myuser\nmypass\n" | smbpasswd -a -s myuser
    notify: restart samba
</code>```

It does not produce any errors, but the user is not created.

Working with ansible 2.3.0.0 on Ubuntu 16.0.4.

答:
I improved the code from siwyd and Tormod Macleod slightly.
Thanks to both of you!

- name: shell - create samba users
  shell: >
    set -e -o pipefail
    && (pdbedit --user={{ item.username }} 2>&1 > /dev/null)
    || (echo '{{ item.password }}'; echo '{{ item.password }}')
    | smbpasswd -s -a {{ item.username }}
  args:
    executable: /bin/bash
  register: samba_create_users
  changed_when: "'Added user' in samba_create_users.stdout"
  loop: "{{ samba_users }}"
  no_log: true

- name: shell - set samba passwords correctly
  shell: >
    set -e -o pipefail
    && (smbclient -U {{ item.username }}%{{ item.password }} -L 127.0.0.1 2>&1 > /dev/null)
    || (echo '{{ item.password }}'; echo '{{ item.password }}')
    | smbpasswd {{ item.username }}
  args:
    executable: /bin/bash
  register: samba_verify_users
  changed_when: "'New SMB password' in samba_verify_users.stdout"
  loop: "{{ samba_users }}"
  no_log: true
```

Changes:

Added pipefail to satisfy Ansible Lint (https://ansible-lint.readthedocs.io/en/latest/default_rules.html#risky-shell-pipe)

Changed executable to /bin/bash, beacause /bin/sh doesn't know pipefail

Added no_log to prevent password logging if the task fails

Removed loop_control label, since logging is disabled

Used loop instead of with_items

Body:
Although the following command works when typing in in shell

echo -ne "myser\nmypass\n" | smbpasswd -a -s myuser

The following task fails in ansible

  - name: add dms samba user
    command: echo -ne "myuser\nmypass\n" | smbpasswd -a -s myuser
    notify: restart samba

It does not produce any errors, but the user is not created.

Working with ansible 2.3.0.0 on Ubuntu 16.0.4.

Body:
I improved the code from siwyd and Tormod Macleod slightly.
Thanks to both of you!

- name: shell - create samba users
  shell: >
    set -e -o pipefail
    && (pdbedit --user={{ item.username }} 2>&1 > /dev/null)
    || (echo '{{ item.password }}'; echo '{{ item.password }}')
    | smbpasswd -s -a {{ item.username }}
  args:
    executable: /bin/bash
  register: samba_create_users
  changed_when: "'Added user' in samba_create_users.stdout"
  loop: "{{ samba_users }}"
  no_log: true

- name: shell - set samba passwords correctly
  shell: >
    set -e -o pipefail
    && (smbclient -U {{ item.username }}%{{ item.password }} -L 127.0.0.1 2>&1 > /dev/null)
    || (echo '{{ item.password }}'; echo '{{ item.password }}')
    | smbpasswd {{ item.username }}
  args:
    executable: /bin/bash
  register: samba_verify_users
  changed_when: "'New SMB password' in samba_verify_users.stdout"
  loop: "{{ samba_users }}"
  no_log: true

Changes:

Added pipefail to satisfy Ansible Lint (https://ansible-lint.readthedocs.io/en/latest/default_rules.html#risky-shell-pipe)

Changed executable to /bin/bash, beacause /bin/sh doesn't know pipefail

Added no_log to prevent password logging if the task fails

Removed loop_control label, since logging is disabled

Used loop instead of with_items


问:
Unity 3D interaction with UI Image
I am creating a 3D game and in the UI, there is an image that I want to print different things when the user puts the cursor on different parts of the Image. In a 2D game, I would add child objects to the image and add polygon colliders to them, and use OnMouseOver() method. But as I understand, this doesn't work on UI. I also tried OnPointerEnter() method and it works but I can't split the image into different parts using this. I tried to split the image into small parts using an external tool and putting them side by side and making a whole image but Unity recognizes all images as rectangular images (I am trying to make this for Girl with a Pearl Earring painting so shapes are irregular. ). How can I do this?</p>

答:
While this is not the best solution, you can get the current mouse position and check first if it's "inside" the picture, and then check for different parts
(For example if the image is between [100,100] to [300,300], and one part is between [100,100] to [150,150], you can check if the mouse is between those coordinates).

So you would get the position:

```<code>Vector2 mousePosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
float x1 = imageBoundry, x2 = imageBoundry;
float y1 = //Same but Y
if mousePosition.X between x1 and x2 && mousePosition.Y between y1 and y2
{
    Check, in which part of the image the cursor is at, and decide then
}
</code>```

Or, you can raycast and check the tag, and if the tag matches to the image's one, check for the specific part

```<code> ray = Camera.main.ScreenPointToRay(Input.mousePosition);
 if(Physics.Raycast(ray, hit))
 {
     if (hit.collider.gameObject.CompareTag(YOUR_TAG))
     {
         Check for inner boundaries.
     }
 }
</code>```

Title: Unity 3D interaction with UI Image

Body:
While this is not the best solution, you can get the current mouse position and check first if it's "inside" the picture, and then check for different parts
(For example if the image is between [100,100] to [300,300], and one part is between [100,100] to [150,150], you can check if the mouse is between those coordinates).

So you would get the position:

Vector2 mousePosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
float x1 = imageBoundry, x2 = imageBoundry;
float y1 = //Same but Y
if mousePosition.X between x1 and x2 && mousePosition.Y between y1 and y2
{
    Check, in which part of the image the cursor is at, and decide then
}

Or, you can raycast and check the tag, and if the tag matches to the image's one, check for the specific part

 ray = Camera.main.ScreenPointToRay(Input.mousePosition);
 if(Physics.Raycast(ray, hit))
 {
     if (hit.collider.gameObject.CompareTag(YOUR_TAG))
     {
         Check for inner boundaries.
     }
 }