问:
google cloud functions default environment variables not set
Are there any conditions to the default environment variables being set on google cloud function?

I have the following code:

func init() {
    projectID := os.Getenv("GCP_PROJECT")
    log.Printf("projectID: %s\n", projectID)

    functionName := os.Getenv("FUNCTION_NAME")
    log.Printf("functoinName: %s\n", functionName)

    region := os.Getenv("FUNCTION_REGION")
    log.Printf("region: %s\n", region)
}
```

<p>and the values are empty.</p>

<p>Even if I do:</p>

<pre class="lang-golang prettyprint-override"><code>func GameUpdate(ctx context.Context, e FirestoreEvent) error {
    functionName := os.Getenv("FUNCTION_NAME")
    log.Printf("functoinName: %s\n", functionName)
}
</code>```

They are still empty.

According to documentation, I would expect them to be set and available. But they are not :|

EDIT:

I am using go 1.13 as runtime and as Armatorix mentioned, these env variables are not available in that runtime...

Why I needed them was to write a wrapper for cloud.google.com/go/logging  to be able to tag the severity of the logs.

I ended up prepending my stdout logs with [INFO]/[ERROR], and creating a tag from it \[([A-Z]+)\].*. Bonus is that I don't have to do a network call in my function to ship the logs.

Still disappointing that these environment variables are not available.

答:
I have created a Feature Request on your behalf, in order for Cloud Functions Engineering team to implement the automatic set of these Environment Variables to the newer Runtime Versions, such as Node.js 10 and Go1.13.

You may "star" the issue so that it gets visibility and also include yourself in the "CC" section, in order to receive further updates posted on this thread.

I hope this helps.

Body:
Are there any conditions to the default environment variables being set on google cloud function?

I have the following code:

func init() {
    projectID := os.Getenv("GCP_PROJECT")
    log.Printf("projectID: %s\n", projectID)

    functionName := os.Getenv("FUNCTION_NAME")
    log.Printf("functoinName: %s\n", functionName)

    region := os.Getenv("FUNCTION_REGION")
    log.Printf("region: %s\n", region)
}

and the values are empty.

Even if I do:

func GameUpdate(ctx context.Context, e FirestoreEvent) error {
    functionName := os.Getenv("FUNCTION_NAME")
    log.Printf("functoinName: %s\n", functionName)
}

They are still empty.

According to documentation, I would expect them to be set and available. But they are not :|

EDIT:

I am using go 1.13 as runtime and as Armatorix mentioned, these env variables are not available in that runtime...

Why I needed them was to write a wrapper for cloud.google.com/go/logging  to be able to tag the severity of the logs.

I ended up prepending my stdout logs with [INFO]/[ERROR], and creating a tag from it \[([A-Z]+)\].*. Bonus is that I don't have to do a network call in my function to ship the logs.

Still disappointing that these environment variables are not available.


来源: stackexchange

问:
Tkinter Dynamically Create and Delete Buttons
I'm trying to dynamically delete the last button and create a new button on the next row via the command function shared by all the "+" button. However, with my current code, I've got nothing but one button staying at the very first row, and it never disappear as I wish and no new buttons appear below it either.</p>

```<code>import tkinter as tk
root = tk.Tk()
root.title('test1')
root.geometry('300x300')

def num_add():

    prev_row = int(btn_list[-1].grid_info()['row'])
    add_btn = tk.Button(root,text='+',command=num_add)
    btn_list.append(add_btn)
    r1 = prev_row +1
    btn_list[-1].grid(row=r1,column=0)

    btn_list[-2].grid_forget()

btn_list = []
add_btn = tk.Button(root,text='+',command=num_add)
add_btn.grid(row=0,column=0)
btn_list.append(add_btn)

root.mainloop()
</code>```

答:
It this what you need?: i used place(x,y)</p>

```<code>import tkinter as tk
root = tk.Tk()
root.title('test1')
root.geometry('300x300')
global i
def num_add():
    global i
    add_btn.place_forget()
    i=i+1
    add_btn.place(x=2, y=i*30+20)

i=0
add_btn = tk.Button(root,text='+',command=num_add)
add_btn.place(x=2, y=i*30+10)

root.mainloop()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to dynamically delete the last button and create a new button on the next row via the command function shared by all the "+" button. However, with my current code, I've got nothing but one button staying at the very first row, and it never disappear as I wish and no new buttons appear below it either.

import tkinter as tk
root = tk.Tk()
root.title('test1')
root.geometry('300x300')

def num_add():

    prev_row = int(btn_list[-1].grid_info()['row'])
    add_btn = tk.Button(root,text='+',command=num_add)
    btn_list.append(add_btn)
    r1 = prev_row +1
    btn_list[-1].grid(row=r1,column=0)

    btn_list[-2].grid_forget()

btn_list = []
add_btn = tk.Button(root,text='+',command=num_add)
add_btn.grid(row=0,column=0)
btn_list.append(add_btn)

root.mainloop()

Body:
It this what you need?: i used place(x,y)

import tkinter as tk
root = tk.Tk()
root.title('test1')
root.geometry('300x300')
global i
def num_add():
    global i
    add_btn.place_forget()
    i=i+1
    add_btn.place(x=2, y=i*30+20)

i=0
add_btn = tk.Button(root,text='+',command=num_add)
add_btn.place(x=2, y=i*30+10)

root.mainloop()


问:
Best way for update object with Nested schema
I have two model: ArticleModel and TagModel and May-To-Many relation between them.
I'm use marshmallow for [de]serializtion.

I want update or create ArticleModel instance and I want get from front-end following data

```<code>{
  'title': 'article',
  'tags': [1, 2, 4] // ids of TagModel instances
}
</code>```

I desided it

schemas

```<code>class ArticlePutPostSchema(Schema):
    tags = fields.List(fields.String())
</code>```

view

```<code>def post(self):
    json_data = request.get_json()
    data = ArticlePutPostSchema().load(data=json_data, partial=True)
    data["tags"] = list(
        TagModel.query.filter(TagModel.id.in_(data["tags"]))
    )
    article = ArticleModel(**data)
    db.session.add(article)
    db.session.commit()
    return jsonify(), 200
</code>```

But I think, that its bad way.

Also I tried to apply a Pluck field

```<code>Pluck(TagSchema, 'id', many=True)
</code>```

And I got [{'id': 1, 'id': 2, 'id': 4}].

It's also a bad way.

How can to solve it?

答:
A good way to do this is to define a nested schema in ArticlePutPostSchema as described here.

```<code>class TagModelSchema(Schema):
    id = fields.Integer()
    name = fields.String()

class ArticlePutPostSchema(Schema):
    tags = fields.List(fields.Nested(TagModelSchema))
</code>```

With the nested schema your data['tags'] should look like this:

```<code>[{id: 1, name: 'foo'}, {id: 2, name: 'bar'}, ... ]
</code>```

So you don't have to query TagModel anymore.

Maybe you have to refactor your ArticleModel an TagModel for this to work as expected. I.e. you need a db.relationship() between the two classes.

Body:
I have two model: ArticleModel and TagModel and May-To-Many relation between them.
I'm use marshmallow for [de]serializtion.

I want update or create ArticleModel instance and I want get from front-end following data

{
  'title': 'article',
  'tags': [1, 2, 4] // ids of TagModel instances
}

I desided it

schemas

class ArticlePutPostSchema(Schema):
    tags = fields.List(fields.String())

view

def post(self):
    json_data = request.get_json()
    data = ArticlePutPostSchema().load(data=json_data, partial=True)
    data["tags"] = list(
        TagModel.query.filter(TagModel.id.in_(data["tags"]))
    )
    article = ArticleModel(**data)
    db.session.add(article)
    db.session.commit()
    return jsonify(), 200

But I think, that its bad way.

Also I tried to apply a Pluck field

Pluck(TagSchema, 'id', many=True)

And I got [{'id': 1, 'id': 2, 'id': 4}].

It's also a bad way.

How can to solve it?

Body:
A good way to do this is to define a nested schema in ArticlePutPostSchema as described here.

class TagModelSchema(Schema):
    id = fields.Integer()
    name = fields.String()

class ArticlePutPostSchema(Schema):
    tags = fields.List(fields.Nested(TagModelSchema))

With the nested schema your data['tags'] should look like this:

[{id: 1, name: 'foo'}, {id: 2, name: 'bar'}, ... ]

So you don't have to query TagModel anymore.

Maybe you have to refactor your ArticleModel an TagModel for this to work as expected. I.e. you need a db.relationship() between the two classes.


问:
ConstraintLayout no longer fills gap with second view when first view is constrained with layout_constraintDimensionRatio
I ran into a problem when designing a fragment with a ConstraintLayout. I want two views inside the fragment stacked on top of each other, with the top view constrained to a ratio of 4:3 and the bottom one filling the rest of the available space. So I created the following layout, expecting the desired behavior:

```<code><androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/view_top"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@id/view_bottom"
        app:layout_constraintDimensionRatio="H,4:3"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/view_bottom"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/view_top" />

</ConstraintLayout>
</code>```

However, this layout does not produce the desired effect but instead leaves gaps between the views and on the top and bottom of the whole layout:

Why is the ratio being applied to both views? Is there a way to circumvent that behavior and have only the top view restricted to the 4:3 ratio?

答: While writing this question I actually found the solution I am looking for. Since the height of view_top is already given through the ratio there is no need for the app:layout_constraintBottom_toTopOf="@id/view_bottom"-constraint. By simply removing it the desired behavior is reached and the views look like this, without any gaps:

Body:
I ran into a problem when designing a fragment with a ConstraintLayout. I want two views inside the fragment stacked on top of each other, with the top view constrained to a ratio of 4:3 and the bottom one filling the rest of the available space. So I created the following layout, expecting the desired behavior:

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/view_top"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@id/view_bottom"
        app:layout_constraintDimensionRatio="H,4:3"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/view_bottom"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/view_top" />

</ConstraintLayout>

However, this layout does not produce the desired effect but instead leaves gaps between the views and on the top and bottom of the whole layout:

Why is the ratio being applied to both views? Is there a way to circumvent that behavior and have only the top view restricted to the 4:3 ratio?


问:
How to put transparent color for container in flutter
I want to put opacity for container which contain hexadecimal color code.

This is my color:

```<code>const color_transparent_black = const Color(0x80000000); //50%
</code>```

As you can see i add 80 mean 50 % transparency.

```<code>return Scaffold(
  backgroundColor: Colors.amber,...
  Container(
    // card view
    alignment: Alignment.center,
    margin: EdgeInsets.only(
        top: 20.0, bottom: 10.0, left: 30.0, right: 30.0),
    decoration: BoxDecoration(
      boxShadow: ([
        BoxShadow(color: Colors.black, blurRadius: 5.0)
      ]),
      color: main_color_transparense_black,
      borderRadius: BorderRadius.circular(14.0),
    ),
    child: Column( ...
</code>```

But Container is not transparent and it is completely black?I know with Opacity widget it is possible but i want to do this with color?

I read this post

This is not my answer.

答:
The code has no issue with you Color(0x80000000)

You are seeing black color is due to the box shadow color back. BoxShadow(color: Colors.black, blurRadius: 5.0). Try to change your BoxShadow as per your needs. Try giving some offset value for the shadow.

Body:
I want to put opacity for container which contain hexadecimal color code.

This is my color:

const color_transparent_black = const Color(0x80000000); //50%

As you can see i add 80 mean 50 % transparency.

return Scaffold(
  backgroundColor: Colors.amber,...
  Container(
    // card view
    alignment: Alignment.center,
    margin: EdgeInsets.only(
        top: 20.0, bottom: 10.0, left: 30.0, right: 30.0),
    decoration: BoxDecoration(
      boxShadow: ([
        BoxShadow(color: Colors.black, blurRadius: 5.0)
      ]),
      color: main_color_transparense_black,
      borderRadius: BorderRadius.circular(14.0),
    ),
    child: Column( ...

But Container is not transparent and it is completely black?I know with Opacity widget it is possible but i want to do this with color?

I read this post

This is not my answer.


问:
Select all values from last date that is shared between rows grouped by a value
I have a Postgresql table with a list of values for countries over time, and their continents. Values can be NULL. I’d like to get the sum for each continent over time, up to the latest date each continent has data for.

This is my table (view on DB Fiddle):

```<code>| continent | country | date       | value | id  |
| --------- | ------- | ---------- | ----- | --- |
| Europe    | Germany | 2020-05-25 | 10    | 1   |
| Europe    | Germany | 2020-05-26 | 11    | 2   |
| Europe    | Germany | 2020-05-27 | 12    | 3   |
| Europe    | Germany | 2020-05-28 | 13    | 4   |
| Europe    | Italy   | 2020-05-25 | 20    | 5   |
| Europe    | Italy   | 2020-05-26 | 21    | 6   |
| Europe    | Italy   | 2020-05-27 | 22    | 7   |
| Europe    | Italy   | 2020-05-28 | 23    | 8   |
| Europe    | France  | 2020-05-25 | 30    | 9   |
| Europe    | France  | 2020-05-26 | 31    | 10  |
| Europe    | France  | 2020-05-27 | 32    | 11  |
| Europe    | France  | 2020-05-28 | NULL  | 12  |
| Africa    | Congo   | 2020-05-25 | 40    | 13  |
| Africa    | Congo   | 2020-05-26 | 41    | 14  |
| Africa    | Congo   | 2020-05-27 | NULL  | 15  |
</code>```

And this is what I’d like to get back. Note that the Europe includes data up to the 27th, because France has no data for the 28th, and Africa up to the 26th, because that’s the last date its countries have data for.

```<code>| continent | date       | value |
| --------- | ---------- | ----- |
| Europe    | 2020-05-27 | 66    |
| Africa    | 2020-05-26 | 41    |
| Europe    | 2020-05-26 | 63    |
| Africa    | 2020-05-25 | 40    |
| Europe    | 2020-05-25 | 60    |
</code>```

I managed to almost get there by including the number of countries per continent that have data on each date.

SELECT
    countries.continent,
    countries.date,
    SUM(countries.value) AS value,
    COUNT(countries.country) AS countries_count
FROM
    countries
WHERE
    countries.value IS NOT NULL
GROUP BY
    countries.continent,
    countries.date
ORDER BY
    countries.date DESC,
    countries.continent;
```

```| continent | date       | value | countries_count |
| --------- | ---------- | ----- | --------------- |
| Europe    | 2020-05-28 | 36    | 2               |
| Europe    | 2020-05-27 | 66    | 3               |
| Africa    | 2020-05-26 | 41    | 1               |
| Europe    | 2020-05-26 | 63    | 3               |
| Africa    | 2020-05-25 | 40    | 1               |
| Europe    | 2020-05-25 | 60    | 3               |
```

<p>I also managed to get the number of countries per continent.</p>

<pre class="lang-sql prettyprint-override"><code>SELECT
    countries.continent,
    COUNT(DISTINCT countries.country) as number_of_countries
FROM
    countries
GROUP BY
    countries.continent;
</code>```

```<code>| continent | number_of_countries |
| --------- | ------------------- |
| Africa    | 1                   |
| Europe    | 3                   |
</code>```

I’m stuck on how to combine the two queries to filter out rows that haven’t got the full number of countries for the continent (e. g. select rows where countries_count is 3 for Europe and 1 for Africa.

This is the end result I’d like to get back:

```<code>| continent | date       | value |
| --------- | ---------- | ----- |
| Europe    | 2020-05-27 | 66    |
| Africa    | 2020-05-26 | 41    |
| Europe    | 2020-05-26 | 63    |
| Africa    | 2020-05-25 | 40    |
| Europe    | 2020-05-25 | 60    |
</code>```

Or maybe there’s a completely different way to go about this?

View on DB Fiddle

答:
You can compare the number of countries on the continent to the number available on each date -- and then just use dates where the two match ("complete data").

Unfortunately, Postgres does not support count(distinct) as a window function.  But you can do:

```<code>SELECT c.continent, c.date,
       SUM(c.value) AS value,
        COUNT(c.country) AS countries_count
FROM (SELECT c.*,
             COUNT(*) OVER (PARTITION BY continent, date) as num_on_date
      FROM countries c
      WHERE value IS NOT NULL
     ) c JOIN
     (SELECT continent, COUNT(DISTINCT country) as num_countries
      FROM countries
      GROUP BY continent
     ) cc
     ON cc.continent = c.continent
WHERE num_on_date = num_countries
GROUP BY c.continent, c.date
ORDER BY c.date DESC, c.continent;
</code>```

Here is a db<>fiddle.

You can also do this with a filter in the HAVING clause:

```<code>SELECT c.continent, c.date,
       SUM(c.value) AS value,
        COUNT(c.country) AS countries_count
FROM countries c
WHERE value IS NOT NULL
GROUP BY c.continent, c.date
HAVING COUNT(*) = (SELECT COUNT(DISTINCT c2.country)
                   FROM countries c2
                   WHERE c2.continent = c.continent
                  )
ORDER BY c.date DESC, c.continent;
</code>```

This does the aggregation and then only keeps the rows where the number of rows matches the number of countries.

Body:
I have a Postgresql table with a list of values for countries over time, and their continents. Values can be NULL. I’d like to get the sum for each continent over time, up to the latest date each continent has data for.

This is my table (view on DB Fiddle):

| continent | country | date       | value | id  |
| --------- | ------- | ---------- | ----- | --- |
| Europe    | Germany | 2020-05-25 | 10    | 1   |
| Europe    | Germany | 2020-05-26 | 11    | 2   |
| Europe    | Germany | 2020-05-27 | 12    | 3   |
| Europe    | Germany | 2020-05-28 | 13    | 4   |
| Europe    | Italy   | 2020-05-25 | 20    | 5   |
| Europe    | Italy   | 2020-05-26 | 21    | 6   |
| Europe    | Italy   | 2020-05-27 | 22    | 7   |
| Europe    | Italy   | 2020-05-28 | 23    | 8   |
| Europe    | France  | 2020-05-25 | 30    | 9   |
| Europe    | France  | 2020-05-26 | 31    | 10  |
| Europe    | France  | 2020-05-27 | 32    | 11  |
| Europe    | France  | 2020-05-28 | NULL  | 12  |
| Africa    | Congo   | 2020-05-25 | 40    | 13  |
| Africa    | Congo   | 2020-05-26 | 41    | 14  |
| Africa    | Congo   | 2020-05-27 | NULL  | 15  |

And this is what I’d like to get back. Note that the Europe includes data up to the 27th, because France has no data for the 28th, and Africa up to the 26th, because that’s the last date its countries have data for.

| continent | date       | value |
| --------- | ---------- | ----- |
| Europe    | 2020-05-27 | 66    |
| Africa    | 2020-05-26 | 41    |
| Europe    | 2020-05-26 | 63    |
| Africa    | 2020-05-25 | 40    |
| Europe    | 2020-05-25 | 60    |

I managed to almost get there by including the number of countries per continent that have data on each date.

SELECT
    countries.continent,
    countries.date,
    SUM(countries.value) AS value,
    COUNT(countries.country) AS countries_count
FROM
    countries
WHERE
    countries.value IS NOT NULL
GROUP BY
    countries.continent,
    countries.date
ORDER BY
    countries.date DESC,
    countries.continent;

| continent | date       | value | countries_count |
| --------- | ---------- | ----- | --------------- |
| Europe    | 2020-05-28 | 36    | 2               |
| Europe    | 2020-05-27 | 66    | 3               |
| Africa    | 2020-05-26 | 41    | 1               |
| Europe    | 2020-05-26 | 63    | 3               |
| Africa    | 2020-05-25 | 40    | 1               |
| Europe    | 2020-05-25 | 60    | 3               |

I also managed to get the number of countries per continent.

SELECT
    countries.continent,
    COUNT(DISTINCT countries.country) as number_of_countries
FROM
    countries
GROUP BY
    countries.continent;

| continent | number_of_countries |
| --------- | ------------------- |
| Africa    | 1                   |
| Europe    | 3                   |

I’m stuck on how to combine the two queries to filter out rows that haven’t got the full number of countries for the continent (e. g. select rows where countries_count is 3 for Europe and 1 for Africa.

This is the end result I’d like to get back:

| continent | date       | value |
| --------- | ---------- | ----- |
| Europe    | 2020-05-27 | 66    |
| Africa    | 2020-05-26 | 41    |
| Europe    | 2020-05-26 | 63    |
| Africa    | 2020-05-25 | 40    |
| Europe    | 2020-05-25 | 60    |

Or maybe there’s a completely different way to go about this?

View on DB Fiddle

Body:
You can compare the number of countries on the continent to the number available on each date -- and then just use dates where the two match ("complete data").

Unfortunately, Postgres does not support count(distinct) as a window function.  But you can do:

SELECT c.continent, c.date,
       SUM(c.value) AS value,
        COUNT(c.country) AS countries_count
FROM (SELECT c.*,
             COUNT(*) OVER (PARTITION BY continent, date) as num_on_date
      FROM countries c
      WHERE value IS NOT NULL
     ) c JOIN
     (SELECT continent, COUNT(DISTINCT country) as num_countries
      FROM countries
      GROUP BY continent
     ) cc
     ON cc.continent = c.continent
WHERE num_on_date = num_countries
GROUP BY c.continent, c.date
ORDER BY c.date DESC, c.continent;

Here is a db<>fiddle.

You can also do this with a filter in the HAVING clause:

SELECT c.continent, c.date,
       SUM(c.value) AS value,
        COUNT(c.country) AS countries_count
FROM countries c
WHERE value IS NOT NULL
GROUP BY c.continent, c.date
HAVING COUNT(*) = (SELECT COUNT(DISTINCT c2.country)
                   FROM countries c2
                   WHERE c2.continent = c.continent
                  )
ORDER BY c.date DESC, c.continent;

This does the aggregation and then only keeps the rows where the number of rows matches the number of countries.


问:
Should I update an android studio 4.0?
When trying to update Android Studio in version 4.0 this warning message appears "plugin incompatible with the new build found: Firebase Services" I would like to know if I should update and if doing so would cause a type of error with the projects I am working with integrating firebase?

答: If u want to remove this warning or if u have downloaded new update. All you have to do is Go to Settings > Plugins > Firebase Services , And uodate it. If update not available then uninstall it and reinstall it. It worked for me. And surely will worl for you. And make sure to update if u r using Firebase Services in your projects. Because it may create problem to you in using Firebase Services in new update This is image describing where to find it</p>

Title: Should I update an android studio 4.0?


问:
Convert string to decimal without losing the period
I have a numerical value in a string: 12.50000

When i want to convert that string to decimal using Convert.ToDecimal() it deletes the period and it becomes 1250000.

Is there a way to stop this? Because the final value is supposed to be 12.5, not 1250000.

答:
```<code>private void Test()
{
    var str = "12.50000";
    var y = decimal.TryParse(str, out var x);
    Debug.WriteLine(x);
}
</code>```

why not using decimal.TryParse ?

Body:
private void Test()
{
    var str = "12.50000";
    var y = decimal.TryParse(str, out var x);
    Debug.WriteLine(x);
}

why not using decimal.TryParse ?


问:
Accessing Video Content ONLY through an iOS App - How would I do that
I've got a client that wants to have a paid app providing his video instructional content on iOS, but of course we dont want people simply getting the video content directly without paying for the app.

Is there some simple way of doing this that I'm overlooking? He wants the content streamed so he can add content easily and periodically without app updates.

Perhaps using Youtube but having the videos password protected? Is there a service anyone has used with an appropriate iOS API that anyone has heard of?

答: I've never done this before, but you could do some kind of token exchange based on the device ID. When the app is first used, register the device ID with the content server, and use that in combination with a salted hash of some kind to identify the device when requesting the media from the server.</p>

ContentLicense: CC BY-SA 3.0


问:
Oracle Pivot and Pivot XML - ORA-00918: column ambiguously defined
Am trying to perform pivot operation. Pivot is working properly. In in case i wanted to pass the query dynamically instead of hard coded values. According to documentation in used Pivot XML, but it providing error. Any suggestion would be helpful,

Pivot working properly:

```<code>select * from
(select  column_name from cols where table_name = 'EMPLOYEES') aa
pivot
(
max(aa.column_name)
for column_name in ('EMPLOYEE_ID', 'FIRST_NAME')
);
</code>```

Pivot XML throwing error:

```<code>select * from
(select  column_name,  table_name from cols  where table_name = 'EMPLOYEES')
pivot xml
(
max(column_name)
for column_name in (select  column_name from cols where table_name = 'EMPLOYEES')
);

ORA-00918: column ambiguously defined
00918. 00000 -  "column ambiguously defined"
*Cause:
*Action:
</code>```

Tried providing aliases, but still its not helpful.

Do we have any other way to define sub query in IN clause

答:
Tried using PL/SQL statement and result is as expected. Below is the PL/SQL statement,</p>

```<code>declare

v_Sql1 varchar(1000);
v_Sql2 varchar(1000);

begin

select  (LISTAGG(chr(39)||column_name||chr(39), ',') WITHIN GROUP (ORDER BY column_id)) into v_Sql1 from cols where table_name = 'EMPLOYEES';

v_Sql2:= 'select * from
(select  column_name from cols where table_name = ''EMPLOYEES'')
pivot
(
max(column_name)
for column_name in (' || v_Sql1 || '))';

dbms_output.put_line(v_Sql1);
dbms_output.put_line(v_Sql2);

execute immediate v_Sql2;

end;
/
</code>```

Body:
Am trying to perform pivot operation. Pivot is working properly. In in case i wanted to pass the query dynamically instead of hard coded values. According to documentation in used Pivot XML, but it providing error. Any suggestion would be helpful,

Pivot working properly:

select * from
(select  column_name from cols where table_name = 'EMPLOYEES') aa
pivot
(
max(aa.column_name)
for column_name in ('EMPLOYEE_ID', 'FIRST_NAME')
);

Pivot XML throwing error:

select * from
(select  column_name,  table_name from cols  where table_name = 'EMPLOYEES')
pivot xml
(
max(column_name)
for column_name in (select  column_name from cols where table_name = 'EMPLOYEES')
);

ORA-00918: column ambiguously defined
00918. 00000 -  "column ambiguously defined"
*Cause:
*Action:

Tried providing aliases, but still its not helpful.

Do we have any other way to define sub query in IN clause

Body:
Tried using PL/SQL statement and result is as expected. Below is the PL/SQL statement,

declare

v_Sql1 varchar(1000);
v_Sql2 varchar(1000);

begin

select  (LISTAGG(chr(39)||column_name||chr(39), ',') WITHIN GROUP (ORDER BY column_id)) into v_Sql1 from cols where table_name = 'EMPLOYEES';

v_Sql2:= 'select * from
(select  column_name from cols where table_name = ''EMPLOYEES'')
pivot
(
max(column_name)
for column_name in (' || v_Sql1 || '))';

dbms_output.put_line(v_Sql1);
dbms_output.put_line(v_Sql2);

execute immediate v_Sql2;

end;
/


问:
How to bind to a Flag variable to a Xceed CheckComboBox
Given an object with a flag variable:

```<code>[Flags]
public enum fCondition
    {
        Scuffed = 1,
        Torn = 2,
        Stained = 4
    }

   public class AnEntity  : TableEntity, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        // This method is called by the Set accessor of each property.
        // The CallerMemberName attribute that is applied to the optional propertyName
        // parameter causes the property name of the caller to be substituted as an argument.
        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public int ConditionID { get; set; }
        public fCondition Condition
        {
            get => (fCondition)ConditionID;
            set {
                if (value != (fCondition)this.ConditionID)
                {
                    this.ConditionID = (int)value;
                    NotifyPropertyChanged();
                }
            }
        }
}
</code>```

An ObjectDataProvider to access the Flags

```<code><ObjectDataProvider x:Key="enmCondition" MethodName="GetValues" ObjectType="{x:Type core:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="enm:fCondition"></x:Type>
            </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</code>```

And the Xceed CheckComboBox

```<code><xctk:CheckComboBox  ItemsSource="{Binding Source={StaticResource enmCondition}}" />
</code>```

At this stage it is showing the list of Flags with the check box.
I would have assumed that I would need to:

```<code>SelectedItemsOverride="{Binding Path=Condition, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
</code>```

I have tried what seems to me to be all other logical combinations (not to metion some ones that seem illogical too, any help would be appreciated).

答:
How are you supposed to bind several checked items to a single Condition property? You can't.

SelectedItemsOverride should be bound to an IList source property:

```<code> public List<fCondition> SelectedConditions { get; } = new List<fCondition>();
</code>```

XAML:

```<code><xctk:CheckComboBox  ItemsSource="{Binding Source={StaticResource enmCondition}}"
                     SelectedItemsOverride="{Binding SelectedConditions}" />
</code>```

If you only want to select a single value, you should use an ordinary ComboBox:

```<code><ComboBox ItemsSource="{Binding Source={StaticResource enmCondition}}"
          SelectedItem="{Binding Condition}" />
</code>```

Body:
Given an object with a flag variable:

[Flags]
public enum fCondition
    {
        Scuffed = 1,
        Torn = 2,
        Stained = 4
    }

   public class AnEntity  : TableEntity, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        // This method is called by the Set accessor of each property.
        // The CallerMemberName attribute that is applied to the optional propertyName
        // parameter causes the property name of the caller to be substituted as an argument.
        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public int ConditionID { get; set; }
        public fCondition Condition
        {
            get => (fCondition)ConditionID;
            set {
                if (value != (fCondition)this.ConditionID)
                {
                    this.ConditionID = (int)value;
                    NotifyPropertyChanged();
                }
            }
        }
}

An ObjectDataProvider to access the Flags

<ObjectDataProvider x:Key="enmCondition" MethodName="GetValues" ObjectType="{x:Type core:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="enm:fCondition"></x:Type>
            </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

And the Xceed CheckComboBox

<xctk:CheckComboBox  ItemsSource="{Binding Source={StaticResource enmCondition}}" />

At this stage it is showing the list of Flags with the check box.
I would have assumed that I would need to:

SelectedItemsOverride="{Binding Path=Condition, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"

I have tried what seems to me to be all other logical combinations (not to metion some ones that seem illogical too, any help would be appreciated).

Body:
How are you supposed to bind several checked items to a single Condition property? You can't.

SelectedItemsOverride should be bound to an IList source property:

 public List<fCondition> SelectedConditions { get; } = new List<fCondition>();

XAML:

<xctk:CheckComboBox  ItemsSource="{Binding Source={StaticResource enmCondition}}"
                     SelectedItemsOverride="{Binding SelectedConditions}" />

If you only want to select a single value, you should use an ordinary ComboBox:

<ComboBox ItemsSource="{Binding Source={StaticResource enmCondition}}"
          SelectedItem="{Binding Condition}" />


问:
C++ for loop too slow
I'm trying to make an audio application with PortAudio. My callback function has been very slow and it has been creating constant underruns. I removed everything in the callback one by one until I found the issue: the for loop. I removed everything so that the only thing happening in the callback function is the for loop and it is still causing underruns. I know it is the for loop because when I reduce the number of iterations, the underruns go away.

```<code>static int patestCallback(const void *inputBuffer, void *outputBuffer,
                      unsigned long framesPerBuffer,
                      const PaStreamCallbackTimeInfo *timeInfo,
                      PaStreamCallbackFlags statusFlags, void *userData)
{
    int x = 0;
    for (int jj = 0; jj < 10000; jj++)
    {
        x++; // for testing, not actually used
    };
    return paContinue;
}
</code>```

Here is my full code for testing: https://gist.github.com/johnroper100/b87641f5609dbb49bc3c1121b1f4daf1

Not really necessary for this question, but I did the same callback in the python equivalent (sounddevice) and there are no issues.

答:
From the API documentation:

When a stream is running, PortAudio calls the stream callback periodically. The callback function is responsible for processing buffers of audio samples passed via the input and output parameters.

The PortAudio stream callback runs at very high or real-time priority. It is required to consistently meet its time deadlines. Do not allocate memory, access the file system, call library functions or call other functions from the stream callback that may block or take an unpredictable amount of time to complete.

In order for a stream to maintain glitch-free operation the callback must consume and return audio data faster than it is recorded and/or played. PortAudio anticipates that each callback invocation may execute for a duration approaching the duration of frameCount audio frames at the stream sample rate. It is reasonable to expect to be able to utilise 70% or more of the available CPU time in the PortAudio callback. However, due to buffer size adaption and other factors, not all host APIs are able to guarantee audio stability under heavy CPU load with arbitrary fixed callback buffer sizes. When high callback CPU utilisation is required the most robust behavior can be achieved by using paFramesPerBufferUnspecified as the Pa_OpenStream() framesPerBuffer parameter.

I highlighted the relevant part.

Title: C++ for loop too slow

Body:
I'm trying to make an audio application with PortAudio. My callback function has been very slow and it has been creating constant underruns. I removed everything in the callback one by one until I found the issue: the for loop. I removed everything so that the only thing happening in the callback function is the for loop and it is still causing underruns. I know it is the for loop because when I reduce the number of iterations, the underruns go away.

static int patestCallback(const void *inputBuffer, void *outputBuffer,
                      unsigned long framesPerBuffer,
                      const PaStreamCallbackTimeInfo *timeInfo,
                      PaStreamCallbackFlags statusFlags, void *userData)
{
    int x = 0;
    for (int jj = 0; jj < 10000; jj++)
    {
        x++; // for testing, not actually used
    };
    return paContinue;
}

Here is my full code for testing: https://gist.github.com/johnroper100/b87641f5609dbb49bc3c1121b1f4daf1

Not really necessary for this question, but I did the same callback in the python equivalent (sounddevice) and there are no issues.


问:
How to find the highest number of passenger of all round?
im a new problem solver. recently i came across this problem on codeforces website. i managed to get the two values required for each turn depending on the number of turn given by the user, but i cant find the highest number of passenger at stop out of all.</p>

```<code>#include <iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
    int turn,get_off,get_on,total_passenger,highest_total;
    cin>>turn;
    int* stops=new int(turn);
    for(int i=0;i<turn;i++){
        cin>>get_off>>get_on;
        total_passenger=get_on-get_off;
        stops[i]=total_passenger;
    }
    for(int i=0;i<turn;i++){
        if(stops[i]>stops[i+1]){
            highest_total=stops[i];
        }
    }
    cout<<highest_total<<endl;
    return 0;
}
</code>```

答:
You can initiate stops as an array I guess(int stops[turn]) as C++ now offers to allocate memory this way even inside any function. That may solve your problem.

Alongside you will have to check corner cases as your highest_total variable may provide garbage value. So while declaring the variable assign a value to it. I prefer initializing int highest_total=-1 here.

Actually you dont need an array or pointer here. This can be solved this way-

```<code>#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
    int turn,get_off,get_on,total_passenger=0;
    cin>>turn;
    int highest_total=-1;
    for(int i=0;i<turn;i++){
        cin>>get_off>>get_on;
        total_passenger=total_passenger+get_on-get_off;
        if(total_passenger>highest_total)
             highest_total=total_passenger;
    }
    cout<<highest_total<<endl;
    return 0;
}

</code>```

Body:
im a new problem solver. recently i came across this problem on codeforces website. i managed to get the two values required for each turn depending on the number of turn given by the user, but i cant find the highest number of passenger at stop out of all.

#include <iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
    int turn,get_off,get_on,total_passenger,highest_total;
    cin>>turn;
    int* stops=new int(turn);
    for(int i=0;i<turn;i++){
        cin>>get_off>>get_on;
        total_passenger=get_on-get_off;
        stops[i]=total_passenger;
    }
    for(int i=0;i<turn;i++){
        if(stops[i]>stops[i+1]){
            highest_total=stops[i];
        }
    }
    cout<<highest_total<<endl;
    return 0;
}

Body:
You can initiate stops as an array I guess(int stops[turn]) as C++ now offers to allocate memory this way even inside any function. That may solve your problem.

Alongside you will have to check corner cases as your highest_total variable may provide garbage value. So while declaring the variable assign a value to it. I prefer initializing int highest_total=-1 here.

Actually you dont need an array or pointer here. This can be solved this way-

#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
    int turn,get_off,get_on,total_passenger=0;
    cin>>turn;
    int highest_total=-1;
    for(int i=0;i<turn;i++){
        cin>>get_off>>get_on;
        total_passenger=total_passenger+get_on-get_off;
        if(total_passenger>highest_total)
             highest_total=total_passenger;
    }
    cout<<highest_total<<endl;
    return 0;
}


问:
Python requiring an attribute be converted to a string
```<code>from sys import exit
from random import randint

class Map(object):

 def death():
    print quips[randint (0, len(quips)-1)]
    exit(1)

 def princess_lives_here():
    print "You see a beautiful Princess with a shiny crown."
    print "She offers you some cake."

    eat_it = raw_input(">")

    if eat_it == "eat it":
        print "You explode like a pinata full of frogs."
        print "The Princess cackles and eats the frogs. Yum!"
        return 'death'

    elif eat_it == "do not eat it":
        print "She throws the cake at you and it cuts off your head."
        print "The last thing you see is her munching on your face. Yum!"
        return 'death'

    elif eat_it == "make her eat it":
        print "The Princess screams as you cram the cake in her mouth."
        print "Then she smiles and cries and thank you for saving her."
        print "She points to a tiny door and says, 'The Koi needs cake too.'"
        print "She gives you the very last bit of cake and shoves you in."
        return 'gold_koi_pond'

    else:
        print "The Princess looks at you confused and just points at the cake."
        return 'princess_lives_here'

class Engine(object):

 def __init__(self, start, quips):
    self.quips = [
        "You died. You suck at this.",
        "Your mom would be proud, if she were smarter",
        "Such a luser.",
        "I have a small puppy that's better at this."
    ]
    self.start = start

 def play(self):
    next = self.start

    while True:
        print "\n-----"
        room = getattr(self, next)
        next = room()

m = Map()
e = Engine(m, "princess_lives_here")

e.play()
</code>```

Trace back i get in terminal is:

```<code>    Traceback (most recent call last):
  File "ec42.py", line 162, in <module>
    e.play()
  File "ec42.py", line 156, in play
    room = getattr(self, next)
TypeError: getattr(): attribute name must be string
</code>```

I have been working on this far too long, and just cannot nail it down. The main issue is getting the map class to run inside the engine class as an object. thanks in advance for the help.

答:
The error message actually tells you quite clearly what is wrong here :-)

```<code>room = getattr(self, next)
</code>```

should go more along the lines of

```<code>room = getattr(self, 'next')
</code>```

as described in the Python documentation

But this is only part of the problem here. If I guess right on what you've omitted in your code sample you will probably also need to add a __call__ method to your map object. Otherwise room = getattr(self, next) doesn't make all that much sense :-) Well that and the rest of the code that is probably missing here ;-)

Also all the method definitions on the Map class are missing the "self" argument.

Body:
from sys import exit
from random import randint

class Map(object):

 def death():
    print quips[randint (0, len(quips)-1)]
    exit(1)

 def princess_lives_here():
    print "You see a beautiful Princess with a shiny crown."
    print "She offers you some cake."

    eat_it = raw_input(">")

    if eat_it == "eat it":
        print "You explode like a pinata full of frogs."
        print "The Princess cackles and eats the frogs. Yum!"
        return 'death'

    elif eat_it == "do not eat it":
        print "She throws the cake at you and it cuts off your head."
        print "The last thing you see is her munching on your face. Yum!"
        return 'death'

    elif eat_it == "make her eat it":
        print "The Princess screams as you cram the cake in her mouth."
        print "Then she smiles and cries and thank you for saving her."
        print "She points to a tiny door and says, 'The Koi needs cake too.'"
        print "She gives you the very last bit of cake and shoves you in."
        return 'gold_koi_pond'

    else:
        print "The Princess looks at you confused and just points at the cake."
        return 'princess_lives_here'

class Engine(object):

 def __init__(self, start, quips):
    self.quips = [
        "You died. You suck at this.",
        "Your mom would be proud, if she were smarter",
        "Such a luser.",
        "I have a small puppy that's better at this."
    ]
    self.start = start

 def play(self):
    next = self.start

    while True:
        print "\n-----"
        room = getattr(self, next)
        next = room()

m = Map()
e = Engine(m, "princess_lives_here")

e.play()

Trace back i get in terminal is:

    Traceback (most recent call last):
  File "ec42.py", line 162, in <module>
    e.play()
  File "ec42.py", line 156, in play
    room = getattr(self, next)
TypeError: getattr(): attribute name must be string

I have been working on this far too long, and just cannot nail it down. The main issue is getting the map class to run inside the engine class as an object. thanks in advance for the help.

Body:
The error message actually tells you quite clearly what is wrong here :-)

room = getattr(self, next)

should go more along the lines of

room = getattr(self, 'next')

as described in the Python documentation

But this is only part of the problem here. If I guess right on what you've omitted in your code sample you will probably also need to add a __call__ method to your map object. Otherwise room = getattr(self, next) doesn't make all that much sense :-) Well that and the rest of the code that is probably missing here ;-)

Also all the method definitions on the Map class are missing the "self" argument.


问:
Copy file from HDFS to SFTP server using Python with streaming method
I have a pyspark pipeline that should export a table as CSV file to HDFS and to SFTP server (data will be taken by CRM team after).

To export to HDFS, it is very sample and it works like a charm,
But to export data to sftp file I did this:

```<code>def export_to_sftp():
    dataframe.coalesce(1).options(codec=compression).write.mode("overwrite").option('encoding',encoding).csv(file_to_hdfs, header=True, nullValue='', sep=';')
    copyToLocalFile(file_to_hdfs,local_machine_file) # copy from HDFS to LOCAL using hadoop API
    cnopts = pysftp.CnOpts()
    hostkeys = None
    if cnopts.hostkeys.lookup(server) is not None:
        hostkeys = cnopts.hostkeys
        cnopts.hostkeys = None
        try:
            with pysftp.Connection(host=server, username=login,
                               password=password, cnopts=cnopts) as sftp:
                if hostkeys is not None:
                    hostkeys.add(server, sftp.remote_server_key.get_name(), sftp.remote_server_key)
                    hostkeys.save(pysftp.helpers.known_hosts())
                    sftp.put(local_machine_file, sftp_path)
        except Exception as e:
            log.exception(e)
        finally:
            log.info("Cleaning up)
            shutil.rmtree(local_tmp)
</code>```

This method works fine when files are not too large but for some tables it doesn't works as in my local linux machine I don't have enough disk space,

So is it possible to use pysftp to copy a remote file from HDFS to SFTP in stream method without copy to local machine?

答:
If I understand your question correctly, you are looking for something like below.

Open a stream (file-like object) from HDFS

and upload it to SFTP using pysftp Connection.putfo:

```<code>with hdfs.open("/hadoop/path/filename") as f,
     sftp.putfo("/sftp/path/filename", f)
</code>```

Obligatory warning: Do not set cnopts.hostkeys = None, unless you do not care about security. For the correct solution see Verify host key with pysftp.

Body:
I have a pyspark pipeline that should export a table as CSV file to HDFS and to SFTP server (data will be taken by CRM team after).

To export to HDFS, it is very sample and it works like a charm,
But to export data to sftp file I did this:

def export_to_sftp():
    dataframe.coalesce(1).options(codec=compression).write.mode("overwrite").option('encoding',encoding).csv(file_to_hdfs, header=True, nullValue='', sep=';')
    copyToLocalFile(file_to_hdfs,local_machine_file) # copy from HDFS to LOCAL using hadoop API
    cnopts = pysftp.CnOpts()
    hostkeys = None
    if cnopts.hostkeys.lookup(server) is not None:
        hostkeys = cnopts.hostkeys
        cnopts.hostkeys = None
        try:
            with pysftp.Connection(host=server, username=login,
                               password=password, cnopts=cnopts) as sftp:
                if hostkeys is not None:
                    hostkeys.add(server, sftp.remote_server_key.get_name(), sftp.remote_server_key)
                    hostkeys.save(pysftp.helpers.known_hosts())
                    sftp.put(local_machine_file, sftp_path)
        except Exception as e:
            log.exception(e)
        finally:
            log.info("Cleaning up)
            shutil.rmtree(local_tmp)

This method works fine when files are not too large but for some tables it doesn't works as in my local linux machine I don't have enough disk space,

So is it possible to use pysftp to copy a remote file from HDFS to SFTP in stream method without copy to local machine?

Body:
If I understand your question correctly, you are looking for something like below.

Open a stream (file-like object) from HDFS

and upload it to SFTP using pysftp Connection.putfo:

with hdfs.open("/hadoop/path/filename") as f,
     sftp.putfo("/sftp/path/filename", f)

Obligatory warning: Do not set cnopts.hostkeys = None, unless you do not care about security. For the correct solution see Verify host key with pysftp.


问:
I am using MinGw compiler, whenever I'm trying to debug the code gets error failed. And why its location is of cygwin as I am using mingw
```<code>Active debugger config: GDB/CDB debugger:Default
Building to ensure sources are up-to-date
Selecting target:
Debug
Adding source dir: H:\C Language\Character-Strings-(Demonstration)-Utilizing-common-string-functions-Source-code\
Adding source dir: H:\C Language\Character-Strings-(Demonstration)-Utilizing-common-string-functions-Source-code\
Adding file: H:\C Language\Character-Strings-(Demonstration)-Utilizing-common-string-functions-Source-code\bin\Debug\CommonStringFunctionsExample.exe
Changing directory to: "H:/C Language/Character-Strings-(Demonstration)-Utilizing-common-string-functions-Source-code/."
Set variable: PATH=.;C:\Program Files\mingw-w64\mingw64\bin;C:\Program Files\mingw-w64\mingw64;C:\Cygwin\bin;C:\Cygwin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Windows\System32;C:\Windows;C:\Windows\System32\wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C:\Windows\System32\OpenSSH;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\Intel\WiFi\bin;C:\Program Files\Common Files\Intel\WirelessCommon;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;F:\runtime\win64;F:\tools\pcb\bin;F:\tools\fet\bin;F:\tools\specctra\bin;F:\tools\bin;F:\tools\PSpice\Library;F:\tools\Capture;C:\Program Files (x86)\IVI Foundation\VISA\WinNT\Bin;C:\Program Files\IVI Foundation\VISA\Win64\Bin;F:\bin;C:\Program Files\Git\cmd;C:\Users\saihi\AppData\Local\Microsoft\WindowsApps;C:\Users\saihi\Anaconda3\Library\ssl;C:\ProgramData\saihi\atom\bin;C:\Users\saihi\AppData\Local\Programs\Microsoft VS Code\bin
Starting debugger: C:\Program Files\mingw-w64\mingw64\bin\gdb.exe -nx -fullname -quiet  -args "H:/C Language/Character-Strings-(Demonstration)-Utilizing-common-string-functions-Source-code/bin/Debug/CommonStringFunctionsExample.exe"
done
Setting breakpoints
Debugger name and version: GNU gdb (GDB) 8.1
Starting the debuggee failed: No executable specified, use `target exec'.
Debugger finished with status 0
</code>```

答:
You will need GDB to debug code built with MinGW's gcc.

Here's a link explaining how it can be done: https://code.visualstudio.com/docs/cpp/cpp-debug

Also it looks like you're using an old version (GDB 8.1 while the current version is 9.2). Check out http://winlibs.com/ for a build of the latest version of MinGW-w64 which includes GDB 9.2.


问:
What is the difference between a browser request and a curl request?
https://psycnet.apa.org/record/2016-47119-002

When I access the above URL by chrome (in a private window), I can see the first request which corresponds to the following curl command. But when I call this curl command in the command line, it will be detected by distil network showing

.

This looks strange to me as this is the first request. Unless there is a difference between the requests send by curl and chrome, there is no way by which distil network can tell what request is sent by a bot or by a real browser. Does anybody know what is the difference between the curl request and the chrome request?

```<code>curl 'https://psycnet.apa.org/record/2016-47119-002' \
  -H 'Connection: keep-alive' \
  -H 'Pragma: no-cache' \
  -H 'Cache-Control: no-cache' \
  -H 'Upgrade-Insecure-Requests: 1' \
  -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36' \
  -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' \
  -H 'Sec-Fetch-Site: none' \
  -H 'Sec-Fetch-Mode: navigate' \
  -H 'Sec-Fetch-User: ?1' \
  -H 'Sec-Fetch-Dest: document' \
  -H 'Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7' \
  --compressed
</code>```

P.S. The problem is same if I use firefox to extract the corresponding curl command. So the difference between firefox request and curl request is also relevant.

Body:
https://psycnet.apa.org/record/2016-47119-002

When I access the above URL by chrome (in a private window), I can see the first request which corresponds to the following curl command. But when I call this curl command in the command line, it will be detected by distil network showing

.

This looks strange to me as this is the first request. Unless there is a difference between the requests send by curl and chrome, there is no way by which distil network can tell what request is sent by a bot or by a real browser. Does anybody know what is the difference between the curl request and the chrome request?

curl 'https://psycnet.apa.org/record/2016-47119-002' \
  -H 'Connection: keep-alive' \
  -H 'Pragma: no-cache' \
  -H 'Cache-Control: no-cache' \
  -H 'Upgrade-Insecure-Requests: 1' \
  -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36' \
  -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' \
  -H 'Sec-Fetch-Site: none' \
  -H 'Sec-Fetch-Mode: navigate' \
  -H 'Sec-Fetch-User: ?1' \
  -H 'Sec-Fetch-Dest: document' \
  -H 'Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7' \
  --compressed

P.S. The problem is same if I use firefox to extract the corresponding curl command. So the difference between firefox request and curl request is also relevant.

Body:
There is no difference.

To find out how Distill (their web-scraping protection system) works, you need to look at the initial response HTML:

When I make the request in Chrome and look at the initial response in the Dev Tools (make sure "Preserve log" is checked) I see that the response is actually a short web-page that contains an embedded <script> which performs some simple "is this user-agent a web-browser?" checks, like running scripts that look for JavaScript DOM objects that won't exist outside of a web-browser (assuming the HTTP user-agent is capable of running scripts at all - which cURL and wget aren't, by the way).

If the script considers your user-agent to be a web-browser then it performs another request for the real content using a dynamically generated password (I didn't look at the details for how that works) - which is why you can't re-request the real content using cURL or wget as the password is unique for each request.

Here's a screenshot of the <script> element in the initial page response, and notice the lack of real actual content in the page's HTML.

If you disable JavaScript in your browser you won't be able to access that web-page at all.

This kind of anti-scraping system protects web-pages against requests from user-agents that lack the means to evaluate JavaScript - so it will block curl, wget, HttpClient, and in-browser fetch/XMLHttpRequests (at least not without further work).

You'd think this system would render a site un-indexable by search-engine spiders - but that's an old (and entrenched) belief and practice: because until the late-2000s the main search engine spiders (Google, Bing/Windows Live Search, Yahoo, etc) only indexed raw HTML and didn't run JavaScript - but since then the search-engine spiders started running JavaScript and even started indexing sites not using custom-built spider HTML-parser engines but using actual web-browser engines (Google really started it, so that they could index script-heavy websites, especially single-page-applications using Angular, Vue, etc). When I worked at Microsoft I got to use the Bing crawler system for some product research projects and that used a special build of Internet Explorer to "run" web-pages that it visited.


问:
how to find string which has number
I want to find string which has number using spark.</p>

```<code>Example : String = "abc def ghi2 xyz4"
Answer : ghi2 xyz4
</code>```

答:
Split the input to Seq

Add where clause with regex + rlike function to check for digits

Map to String .map(row => row.getString(0))

Concatenate and output the string

```<code>import org.apache.spark.sql.functions._

object CheckDigitInString {

  def main(args: Array[String]): Unit = {
    val input = "abc def ghi2 xyz4"
    val spark = Constant.getSparkSess
    import spark.implicits._
    val inputDf = input.split(" ").toSeq.toDF

    val output = inputDf.where(col("value").rlike(".*[0-9]+.*"))
      .map(row => row.getString(0))
      .collect().mkString(" ")
    println(output)
  }

}

</code>```

Title: how to find string which has number

Body:
I want to find string which has number using spark.

Example : String = "abc def ghi2 xyz4"
Answer : ghi2 xyz4

Body:
Split the input to Seq

Add where clause with regex + rlike function to check for digits

Map to String .map(row => row.getString(0))

Concatenate and output the string

import org.apache.spark.sql.functions._

object CheckDigitInString {

  def main(args: Array[String]): Unit = {
    val input = "abc def ghi2 xyz4"
    val spark = Constant.getSparkSess
    import spark.implicits._
    val inputDf = input.split(" ").toSeq.toDF

    val output = inputDf.where(col("value").rlike(".*[0-9]+.*"))
      .map(row => row.getString(0))
      .collect().mkString(" ")
    println(output)
  }

}


问:
Using enums as status returned status indicators in C#
Just wondering what the general consensus was about returning enums from methods indicating the status. The notion of returning codes (ints) is pretty innate in oldschool systems programming (C) but I am wondering if the methodology for indicating the status has changed.

thanks

Edit: I am aware that enums are basically int values. I'm inquiring about the sheer practice of having methods start throwing around status codes (be them enums or ints) to indicate statuses altogether. It seems like a good practice but I was wondering if there is any negative feelings about the idea.

I would always choose an enum over an int return for a status code.

答: Just thinking out loud here but why not just return an object (class), the Type which will depend on how you need to use it. For example one class might just contain a message string while another might contain a number of records updated integer.</p>

OwnerDisplayName: Chance

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Chance


问:
How to do "where exists" in Arel
How do you do a query that includes a "where exists" in Arel? For example on a query like this to show all the suppliers with at least one order:

```<code>SELECT *
FROM suppliers
WHERE EXISTS
  (SELECT *
    FROM orders
    WHERE suppliers.supplier_id = orders.supplier_id);
</code>```

I see "exists" in the Arel docs http://rubydoc.info/gems/arel/2.0.7/Arel/Nodes/Exists but I'm having trouble using it.

答:
I think that you can neatly use a counter_cache for this one :

http://asciicasts.com/episodes/23-counter-cache-column

Title: How to do "where exists" in Arel

Body:
How do you do a query that includes a "where exists" in Arel? For example on a query like this to show all the suppliers with at least one order:

SELECT *
FROM suppliers
WHERE EXISTS
  (SELECT *
    FROM orders
    WHERE suppliers.supplier_id = orders.supplier_id);

I see "exists" in the Arel docs http://rubydoc.info/gems/arel/2.0.7/Arel/Nodes/Exists but I'm having trouble using it.


问:
Combining date and time using moment causing deprecation warning
In my nodejs application, I have user-based input for starting date and starting time for achieving some task. I need to combine start date and start time input by the user and insert it into one DateTime object format as: 2020-05-29T10:43:39.278Z. Here is the code:

```<code>function(start_time, start_date){
    const time = moment(start_time).format('LT');
    console.log('show timing', time); // gives, 4:12 PM

    const d = moment(start_date).format('L');
    console.log('new date', d); //gives, 05/29/2020

    const final_start_date = moment(d +' '+ time).format();
    console.log('final_start_date', final_start_date)
  }
</code>```

But console.log('final_start_date', final_start_date) throws an error as :

```<code>Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Arguments:
[0] _isAMomentObject: true, _isUTC: false, _useUTC: false, _l: undefined, _i: 05/29/2020 4:12 PM, _f: undefined, _strict: undefined, _locale: [object Object]
Error
</code>```

The arguments start_time and start_date are stored in MongoDB as ISO format with a Date type.
I am unable to understand where things are getting wrong, kindly help to resolve the issue.

------------------UPDATION------------------

```<code> const START_TIME = moment(start_time, "hh:mm:ss").format("LT"),
    END_TIME = moment(end_time, "hh:mm:ss").format("LT");

  const START_DATE = moment(start_date, "DD/MM/YYYY").format("L"),
    END_DATE = moment(end_date, "DD/MM/YYYY").format("L");

    console.log("START-TIME: ", START_TIME);
    console.log("END-TIME: ", END_TIME)

    console.log("START-DATE: ", START_DATE);
    console.log("END-DATE: ", END_DATE)

  const START_AT = moment(START_DATE + " " + START_TIME, "DD/MM/YYYY hh:mm:ss").format(),
    END_AT = moment(END_DATE + " " + END_TIME, "DD/MM/YYYY hh:mm:ss").format();

    console.log("START-AT: ", START_AT);
    console.log("END-AT: ", END_AT)
</code>```

console.logs()

```<code>START-TIME:  8:29 PM
END-TIME:  8:30 PM
START-DATE:  05/29/2020
END-DATE:  05/29/2020
START-AT:  Invalid date
END-AT:  Invalid date
</code>```

答:
moment() takes 2 parameters

Date String

Format

You need to pass second parameter so that it will correctly convert your date.

Just added format for each moment constructor and deprecation warning went away.

Modified your code as:

```<code>    var fn = function(start_time, start_date){
    const time = moment(start_time, "h:mm a").format('LT');
    console.log('show timing', time); // gives, 4:12 PM

    const d = moment(start_date, "MM/DD/YYYY").format('L');
    console.log('new date', d); //gives, 05/29/2020

    const final_start_date = moment(d +' '+ time, "MM/DD/YYYY h:mm a").format();
    console.log('final_start_date', final_start_date)
  }

  fn("4:12 PM", "05/29/2020");
</code>```

Note: You don't need second parameter if you pass date string in ISO
  format like this moment("2020-05-29T16:55:35+05:30").format()

Body:
In my nodejs application, I have user-based input for starting date and starting time for achieving some task. I need to combine start date and start time input by the user and insert it into one DateTime object format as: 2020-05-29T10:43:39.278Z. Here is the code:

function(start_time, start_date){
    const time = moment(start_time).format('LT');
    console.log('show timing', time); // gives, 4:12 PM

    const d = moment(start_date).format('L');
    console.log('new date', d); //gives, 05/29/2020

    const final_start_date = moment(d +' '+ time).format();
    console.log('final_start_date', final_start_date)
  }

But console.log('final_start_date', final_start_date) throws an error as :

Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Arguments:
[0] _isAMomentObject: true, _isUTC: false, _useUTC: false, _l: undefined, _i: 05/29/2020 4:12 PM, _f: undefined, _strict: undefined, _locale: [object Object]
Error

The arguments start_time and start_date are stored in MongoDB as ISO format with a Date type.
I am unable to understand where things are getting wrong, kindly help to resolve the issue.

------------------UPDATION------------------

 const START_TIME = moment(start_time, "hh:mm:ss").format("LT"),
    END_TIME = moment(end_time, "hh:mm:ss").format("LT");

  const START_DATE = moment(start_date, "DD/MM/YYYY").format("L"),
    END_DATE = moment(end_date, "DD/MM/YYYY").format("L");

    console.log("START-TIME: ", START_TIME);
    console.log("END-TIME: ", END_TIME)

    console.log("START-DATE: ", START_DATE);
    console.log("END-DATE: ", END_DATE)

  const START_AT = moment(START_DATE + " " + START_TIME, "DD/MM/YYYY hh:mm:ss").format(),
    END_AT = moment(END_DATE + " " + END_TIME, "DD/MM/YYYY hh:mm:ss").format();

    console.log("START-AT: ", START_AT);
    console.log("END-AT: ", END_AT)

console.logs()

START-TIME:  8:29 PM
END-TIME:  8:30 PM
START-DATE:  05/29/2020
END-DATE:  05/29/2020
START-AT:  Invalid date
END-AT:  Invalid date

Body:
moment() takes 2 parameters

Date String

Format

You need to pass second parameter so that it will correctly convert your date.

Just added format for each moment constructor and deprecation warning went away.

Modified your code as:

    var fn = function(start_time, start_date){
    const time = moment(start_time, "h:mm a").format('LT');
    console.log('show timing', time); // gives, 4:12 PM

    const d = moment(start_date, "MM/DD/YYYY").format('L');
    console.log('new date', d); //gives, 05/29/2020

    const final_start_date = moment(d +' '+ time, "MM/DD/YYYY h:mm a").format();
    console.log('final_start_date', final_start_date)
  }

  fn("4:12 PM", "05/29/2020");

Note: You don't need second parameter if you pass date string in ISO
  format like this moment("2020-05-29T16:55:35+05:30").format()


问:
Sass @use not working with separated mixin files into master mixin file (ERR: Undefined Mixin)
I'm a bit newer to sass, but when I was learning it the Sass website said to start using @use instead of import, so after a lot of trial and error I finally figured out how to use it pretty much the same as import.

Note: I'm using Prepros for compiling.

I have this mixin in it's own file inside of a mixins folder:

```<code>// scss/mixins/_flex.scss

@mixin flex($flex-flow: row, $justify-content: center, $align-items: center) {
    display: flex;
    justify-content: $justify-content;
    align-items: $align-items;
    flex-flow: $flex-flow;
}
</code>```

I tried @useing it in my main _mixins.scss file:

```<code>// scss/_mixins.scss

@use "mixins/flex" as *;

</code>```

Then I tried using it in another one of my files containing common elements:

```<code>// scss/_common_elements.scss

@use "mixins" as *;

.flex {
  @include flex();
}

</code>```

Then I receive the error inside of Prepros log: Undefined Mixin where I call the @include flex(); line (inside of _common_elements.scss)

It was working until I decided to put the mixins in their own separate folder, but this is the same as how it's setup inside of Bootstraps source code.

This whole process of using @use has been really confusing.

Does anyone know why I might be getting this error?

答:
I managed to fix it!

ALSO: If you can help me edit this question / answer to better explain it with proper language, please post suggestions and I'll update it.

In the _mixins.scss file I needed to use @forward "mixins/flex" instead of @use "mixins/flex" as *;:

Like this:

```<code>// scss/_mixins.scss

@forward "mixins/flex";
@forward "mixins/overlay";
@forward "mixins/etc...";
</code>```

I wish they would've made this something more clear on the actual sass @use documentation.

Here are the actual docs to @forward.

Body:
I'm a bit newer to sass, but when I was learning it the Sass website said to start using @use instead of import, so after a lot of trial and error I finally figured out how to use it pretty much the same as import.

Note: I'm using Prepros for compiling.

I have this mixin in it's own file inside of a mixins folder:

// scss/mixins/_flex.scss

@mixin flex($flex-flow: row, $justify-content: center, $align-items: center) {
    display: flex;
    justify-content: $justify-content;
    align-items: $align-items;
    flex-flow: $flex-flow;
}

I tried @useing it in my main _mixins.scss file:

// scss/_mixins.scss

@use "mixins/flex" as *;

Then I tried using it in another one of my files containing common elements:

// scss/_common_elements.scss

@use "mixins" as *;

.flex {
  @include flex();
}

Then I receive the error inside of Prepros log: Undefined Mixin where I call the @include flex(); line (inside of _common_elements.scss)

It was working until I decided to put the mixins in their own separate folder, but this is the same as how it's setup inside of Bootstraps source code.

This whole process of using @use has been really confusing.

Does anyone know why I might be getting this error?

Body:
I managed to fix it!

ALSO: If you can help me edit this question / answer to better explain it with proper language, please post suggestions and I'll update it.

In the _mixins.scss file I needed to use @forward "mixins/flex" instead of @use "mixins/flex" as *;:

Like this:

// scss/_mixins.scss

@forward "mixins/flex";
@forward "mixins/overlay";
@forward "mixins/etc...";

I wish they would've made this something more clear on the actual sass @use documentation.

Here are the actual docs to @forward.


问:
How to get the URL of a file on AWS S3, return path without AWS Key
I need to use Lambda function ( Python), I need to get S3 path. It should look like this:

s3://some-path-to-the-location-of-generated-text/generated-text.txt

That URL client need to see in browser, without AWS Key, because presigned urls i don't need.

Thank you so much!

答:
You need to use AWS S3 bucket policy which should allow read to all for given file.

Your bucket policy should look like as follows:

```<code> {

  "Statement":[
    {
      "Sid":"PublicRead",
      "Effect":"Allow",
      "Principal": "*",
      "Action":["s3:GetObject"],
      "Resource":["arn:aws:s3:::<name of bucket>/<file that you want everyone can read>"]
    }
}
</code>```

Example - https://docs.aws.amazon.com/AmazonS3/latest/dev/example-bucket-policies.html#example-bucket-policies-use-case-2

Body:
You need to use AWS S3 bucket policy which should allow read to all for given file.

Your bucket policy should look like as follows:

 {

  "Statement":[
    {
      "Sid":"PublicRead",
      "Effect":"Allow",
      "Principal": "*",
      "Action":["s3:GetObject"],
      "Resource":["arn:aws:s3:::<name of bucket>/<file that you want everyone can read>"]
    }
}

Example - https://docs.aws.amazon.com/AmazonS3/latest/dev/example-bucket-policies.html#example-bucket-policies-use-case-2


问:
DataTables add column dynamically to table
I'm using DataTables (datatables.net) to display data from an Ajax source and having trouble customizing it. One thing I would like to do is add a column so I can have for example an 'edit' button for each row.

The closest thing to that in the examples is here but I can't get that to work with an ajax source.

Currently, I'm using the following code to display my table:

```<code>fnServerObjectToArray = function ( aElements ){
    return function ( sSource, aoData, fnCallback ) {
        $.ajax( {
            "dataType": 'json',
            "type": "POST",
            "url": sSource,
            "data": aoData,
            "success": function (json) {
                var a = [];
                for ( var i=0, iLen=json.aaData.length ; i<iLen ; i++ ) {
                    var inner = [];
                    for ( var j=0, jLen=aElements.length ; j<jLen ; j++ ) {

                        inner.push( json.aaData[i][aElements[j]] );
                    }
                    a.push( inner );
                }
                json.aaData = a;
                fnCallback(json);
            }
        } );
    }
}

$(document).ready(function() {
    $('#example').dataTable( {
        "bProcessing": true,
        "sAjaxSource": 'get_data.php',
        "fnServerData": fnServerObjectToArray( [ 'username', 'email' ] )
    } );
});
</code>```

答:
Why don't you use fnRenderFunction in the aoColumns? As an example:

```<code>aoColumns: [ { "bVisible": false} , null, null, null, null,
  { "sName": "ID",
    "bSearchable": false,
    "bSortable": false,
    "fnRender": function (oObj) {
       return "<a href='EditData.php?id=" + oObj.aData[0] + "'>Edit</a>";
     }
  }
]
</code>```

You can use it to format the value from the server side.

See similar example on the http://jquery-datatables-editable.googlecode.com/svn/trunk/ajax-inlinebuttons.html (ignore specific settings for the editable plugin)

Body:
I'm using DataTables (datatables.net) to display data from an Ajax source and having trouble customizing it. One thing I would like to do is add a column so I can have for example an 'edit' button for each row.

The closest thing to that in the examples is here but I can't get that to work with an ajax source.

Currently, I'm using the following code to display my table:

fnServerObjectToArray = function ( aElements ){
    return function ( sSource, aoData, fnCallback ) {
        $.ajax( {
            "dataType": 'json',
            "type": "POST",
            "url": sSource,
            "data": aoData,
            "success": function (json) {
                var a = [];
                for ( var i=0, iLen=json.aaData.length ; i<iLen ; i++ ) {
                    var inner = [];
                    for ( var j=0, jLen=aElements.length ; j<jLen ; j++ ) {

                        inner.push( json.aaData[i][aElements[j]] );
                    }
                    a.push( inner );
                }
                json.aaData = a;
                fnCallback(json);
            }
        } );
    }
}

$(document).ready(function() {
    $('#example').dataTable( {
        "bProcessing": true,
        "sAjaxSource": 'get_data.php',
        "fnServerData": fnServerObjectToArray( [ 'username', 'email' ] )
    } );
});

Body:
Why don't you use fnRenderFunction in the aoColumns? As an example:

aoColumns: [ { "bVisible": false} , null, null, null, null,
  { "sName": "ID",
    "bSearchable": false,
    "bSortable": false,
    "fnRender": function (oObj) {
       return "<a href='EditData.php?id=" + oObj.aData[0] + "'>Edit</a>";
     }
  }
]

You can use it to format the value from the server side.

See similar example on the http://jquery-datatables-editable.googlecode.com/svn/trunk/ajax-inlinebuttons.html (ignore specific settings for the editable plugin)


问:
How would I go About Getting a Global Variables value in another form?
So I am new to Programming and I am working In Visual Studios c# Windows application Forms,
and I have a button on the first form That needs to set a Glabel Bool To true when pressed while also opening the second form.

On the second forms startup I need it to tell if that bool is set to true or false, to enable a button(on the second Form) or keep it disabled(if False.

Here Is the First Forms Code:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Project
{
    public partial class FirstPage: Form
    {
        public FirstPage()
        {
            InitializeComponent();
        }

        public bool IsManager = false;

        public static class Global
        {
            public static bool IsManager = false;
        }

        private void Button_Btn_Click(object sender, EventArgs e)
        {
            this.hide();
            Form2 f2 = new form2(IsManager);
            f2.ShowDialog();

            IsManager = true;
        }
    }
}
</code>```

Here is my second Forms Code:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Project
{
    public partial class SecondPage : Form
    {
        public FirstPage()
        {
            InitializeComponent();
            IsManager = isManager;
        }
        private bool isManager;

        private void setButtonVisibility()
        {
            if(isManager == true)
            {
                MessageBox.Show("Button Message Display")
            }
        {

        //Need to check if the Global variable is true or false on page load to set a button to either enabled or disabled
    }
}
</code>```

Hopefully this makes sense If not let me know :) Thank You!

答:
You can acomplish this by passing the variable to the constructor of the second form.
Let's assume you want to send the IsManager value to the second form. Call the second form while passing the value to the constructor:

```<code>Form2 f2 = new Form2(IsManager);
</code>```

In the second form, read the value:

```<code>public partial class Form2 : Form
{
    private bool IsManager;
    public Form2(bool isManager)
    {
        InitializeComponent();
        IsManager = isManager;
    }
    //Render button or whatever based on IsManager value;
}
</code>```

EDIT: To check if the button needs to be enabled or not:

```<code>public partial class Form2 : Form
{
    private bool IsManager;
    public Form2(bool isManager)
    {
        InitializeComponent();
        IsManager = isManager;
        setButtonVisibility(); //call method setVisibility() -> this is what was missing in your code

    }
    private void setButtonVisibility()
    {
        if(IsManager == true)
        {
            MessageBox.Show("Button Message Display");
            //or YourButton.Enable = true; in order to enable it.
        }
    }
}
</code>```

In your second form, there are a couple of issues:

Class name and constructor name are not the same;

The parameter for the Form2 constructor is missing;

isManager should be assigned the value of IsManager which should have been passed as a parameter to the constructor.

Body:
So I am new to Programming and I am working In Visual Studios c# Windows application Forms,
and I have a button on the first form That needs to set a Glabel Bool To true when pressed while also opening the second form.

On the second forms startup I need it to tell if that bool is set to true or false, to enable a button(on the second Form) or keep it disabled(if False.

Here Is the First Forms Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Project
{
    public partial class FirstPage: Form
    {
        public FirstPage()
        {
            InitializeComponent();
        }

        public bool IsManager = false;

        public static class Global
        {
            public static bool IsManager = false;
        }

        private void Button_Btn_Click(object sender, EventArgs e)
        {
            this.hide();
            Form2 f2 = new form2(IsManager);
            f2.ShowDialog();

            IsManager = true;
        }
    }
}

Here is my second Forms Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Project
{
    public partial class SecondPage : Form
    {
        public FirstPage()
        {
            InitializeComponent();
            IsManager = isManager;
        }
        private bool isManager;

        private void setButtonVisibility()
        {
            if(isManager == true)
            {
                MessageBox.Show("Button Message Display")
            }
        {

        //Need to check if the Global variable is true or false on page load to set a button to either enabled or disabled
    }
}

Hopefully this makes sense If not let me know :) Thank You!

Body:
You can acomplish this by passing the variable to the constructor of the second form.
Let's assume you want to send the IsManager value to the second form. Call the second form while passing the value to the constructor:

Form2 f2 = new Form2(IsManager);

In the second form, read the value:

public partial class Form2 : Form
{
    private bool IsManager;
    public Form2(bool isManager)
    {
        InitializeComponent();
        IsManager = isManager;
    }
    //Render button or whatever based on IsManager value;
}

EDIT: To check if the button needs to be enabled or not:

public partial class Form2 : Form
{
    private bool IsManager;
    public Form2(bool isManager)
    {
        InitializeComponent();
        IsManager = isManager;
        setButtonVisibility(); //call method setVisibility() -> this is what was missing in your code

    }
    private void setButtonVisibility()
    {
        if(IsManager == true)
        {
            MessageBox.Show("Button Message Display");
            //or YourButton.Enable = true; in order to enable it.
        }
    }
}

In your second form, there are a couple of issues:

Class name and constructor name are not the same;

The parameter for the Form2 constructor is missing;

isManager should be assigned the value of IsManager which should have been passed as a parameter to the constructor.


问:
Difference between .pb and .h5
What is the main difference between .pb format of tensorflow and .h5 format of keras to store models? Is there any reason to choose one over the other?

答:
Different file formats with different characteristics, both used by tensorflow to save models (.h5 specifically by keras).

.pb - protobuf

It is a way to store some structured data (in this case a neural network),project is open source and currently overviewed by Google.

Example

```<code>person {
  name: "John Doe"
  email: "jdoe@example.com"
}
</code>```

Simple class containing two fields, you can load it in one of multiple supported languages (e.g. C++, Go), parse, modify and send to someone else in binary format.

Advantages

really small and efficient to parse (when compared to say .xml), hence often used for data transfer across the web

used by Tensorflow's Serving when you want to take your model to production (e.g. inference over the web)

language agnostic - binary format can be read by multiple languages (Java, Python, Objective-C, and C++ among others)

advised to use since tf2.0 , you can see official serializing guide

saves various metadata (optimizers, losses etc. if using keras's model)

Disadvantages

SavedModel is conceptually harder to grasp than single file

creates folder where weights are

Sources

You can read about this format here

.h5 - HDF5 binary data format

Used originally by keras to save models (keras is now officially part of tensorflow). It is less general and more "data-oriented", less programmatic than .pb.

Advantages

Used to save giant data (so some neural networks would fit well)

Common file saving format

Everything saved in one file (weights, losses, optimizers used with keras etc.)

Disadvantages

Cannot be used with Tensorflow Serving but you can simply convert it to .pb via keras.experimental.export_saved_model(model, 'path_to_saved_model')

All in all

Use the simpler one (.h5) if you don't need to productionize your model (or it's reasonably far away). Use .pb if you are going for production or just want to standardize on single format across all tensorflow provided tools.

Title: Difference between .pb and .h5

Body:
Different file formats with different characteristics, both used by tensorflow to save models (.h5 specifically by keras).

.pb - protobuf

It is a way to store some structured data (in this case a neural network),project is open source and currently overviewed by Google.

Example

person {
  name: "John Doe"
  email: "jdoe@example.com"
}

Simple class containing two fields, you can load it in one of multiple supported languages (e.g. C++, Go), parse, modify and send to someone else in binary format.

Advantages

really small and efficient to parse (when compared to say .xml), hence often used for data transfer across the web

used by Tensorflow's Serving when you want to take your model to production (e.g. inference over the web)

language agnostic - binary format can be read by multiple languages (Java, Python, Objective-C, and C++ among others)

advised to use since tf2.0 , you can see official serializing guide

saves various metadata (optimizers, losses etc. if using keras's model)

Disadvantages

SavedModel is conceptually harder to grasp than single file

creates folder where weights are

Sources

You can read about this format here

.h5 - HDF5 binary data format

Used originally by keras to save models (keras is now officially part of tensorflow). It is less general and more "data-oriented", less programmatic than .pb.

Advantages

Used to save giant data (so some neural networks would fit well)

Common file saving format

Everything saved in one file (weights, losses, optimizers used with keras etc.)

Disadvantages

Cannot be used with Tensorflow Serving but you can simply convert it to .pb via keras.experimental.export_saved_model(model, 'path_to_saved_model')

All in all

Use the simpler one (.h5) if you don't need to productionize your model (or it's reasonably far away). Use .pb if you are going for production or just want to standardize on single format across all tensorflow provided tools.


问:
Fill an array with distanced random integers
I need an array to be filled with random integers
Those integers should be very distinct from each other i.e. must at least be 20 units of separation between each items

This is what i have tried so far :

var all = [];
var i = 0;

randomDiff();

function randomDiff() {
    var num1 = randomNumber(10, 290); //chose a first random num in the range...
    all[0] = num1; //...put it in first index of array
    do // until you have 12 items...
    {
        var temp = randomNumber(10, 290); //...you pick a temporary num
        var j;
        for (j = 0; j < all.length; j++) // for each item already in the array
        {
            if ((temp < all[i] - 10) || (temp > all[i] + 10)) // if the temporary num is different enough                                                            from others members...
            {
                all.push(temp); //then you can store it
                i++; //increment until....
                console.log(all[i]);
            }
        }
    }
    while (i < 11) // ...it is filled with 12 items in array
}
////////////Radom in int range function///////////////////////////////////////
function randomNumber(min, max) {
    return Math.floor(Math.random() * (max - min) + min);
}
```

but always unsuccessful, including infinite loops...

答:
Have a look on something like this:

function randomNumber(min, max) {
    return Math.floor(Math.random() * (max - min) + min);
}

const LIST_SIZE = 20;
const DISTANCE = 10;

const STOP_AFTER_ATTEMPT = 2000;
const randomList = [];

let attempt = 0;
while(randomList.length < LIST_SIZE && attempt < STOP_AFTER_ATTEMPT) {

  const num = randomNumber(10, 290);

  const numberExistsWithSmallerDistance = randomList.some(r => Math.abs(r - num) < DISTANCE)

  if (!numberExistsWithSmallerDistance) {
    randomList.push(num);
  }

  attempt++;
}
if (randomList.length === LIST_SIZE) {
    console.log(randomList);
} else {
    console.log("Failed to create array with distnct values after ", attempt, " tries");
}
```

Body:
I need an array to be filled with random integers
Those integers should be very distinct from each other i.e. must at least be 20 units of separation between each items

This is what i have tried so far :

var all = [];
var i = 0;

randomDiff();

function randomDiff() {
    var num1 = randomNumber(10, 290); //chose a first random num in the range...
    all[0] = num1; //...put it in first index of array
    do // until you have 12 items...
    {
        var temp = randomNumber(10, 290); //...you pick a temporary num
        var j;
        for (j = 0; j < all.length; j++) // for each item already in the array
        {
            if ((temp < all[i] - 10) || (temp > all[i] + 10)) // if the temporary num is different enough                                                            from others members...
            {
                all.push(temp); //then you can store it
                i++; //increment until....
                console.log(all[i]);
            }
        }
    }
    while (i < 11) // ...it is filled with 12 items in array
}
////////////Radom in int range function///////////////////////////////////////
function randomNumber(min, max) {
    return Math.floor(Math.random() * (max - min) + min);
}

but always unsuccessful, including infinite loops...


问:
Is there a way to iterate through node.run_state data in a Chef recipe?
Is there a way to iterate through node.run_state data?
This is in a RHEL environment with Active Directory users.
I have a ruby block that populates node.run_state.  I have to have this run at converge time, because the overall cookbook will be used for build automation.  On the very first run, the cookbook installs Centrify, then later needs to run adquery to gather user info for populating home directories with SSH keys.

On a chef-client run, I see this:

```<code>       Compiling Cookbooks...
       {}
</code>```

Obviously, that's the puts running in compile time against an empty hash.
At converge time, nothing happens in the loop with the 2 directory and 1 template resource.

Here is the relevant piece of the recipe:

```<code>ruby_block 'set uid, gid, and homedir for users' do
  block do
    base_attr['ssh_keys'].each do |user, pubkeys|
  # next unless Dir.exist?(homedir)
      node.run_state[user] = {}
      puts "Checking user #{user}..."
      if local_users.key?(user)
        node.run_state[user]['homedir'] = local_users[user]['homedir']
        node.run_state[user]['uid'] = local_users[user]['uid'].to_i
        node.run_state[user]['gid'] = local_users[user]['gid'].to_i
      elsif centrify_users.key?(user)
        node.run_state[user]['homedir'] = centrify_users[user]['homedir']
        node.run_state[user]['uid'] = centrify_users[user]['uid'].to_i
        node.run_state[user]['gid'] = centrify_users[user]['gid'].to_i
      else
        puts "user #{user} not found."
        # Place holder values.
        node.run_state[user]['homedir'] = "/tmp/#{user}"
        node.run_state[user]['uid'] = 0
        node.run_state[user]['gid'] = 0
      end
    end
  end
end
  # Dir.exist? guard should bypass compile-time error.
  # "name is a required property"
  # next unless Dir.exist?(homedir)
puts node.run_state
node.run_state.each do |user|
  directory node.run_state[user]['homedir'] do
    owner node.run_state[user]['uid']
    group node.run_state[user]['gid']
    mode '0700'
  end

  directory "#{node.run_state[user]['homedir']}/.ssh" do
    owner node.run_state[user]['uid']
    group node.run_state[user]['gid']
    mode '0700'
  end

  template "#{node.run_state[user]['homedir']}/.ssh/authorized_keys" do
    owner node.run_state[user]['uid']
    group node.run_state[user]['gid']
    mode '0600'
    source 'authorized_keys.erb'
    variables(
      sshkeys: base_attr['ssh_keys'][user]
    )
  end
end
</code>```

Any ideas how to make this work?

答:
As you are setting node.run_state in the execution phase, you also need to read it in execution phase. Currently your node.run_state.each is skipped, because, as you noted correctly, node.run_state is empty.

So you need to move this node.run_state.each execution into execution phase. One possibility is to create a ruby_block and move your cycle there, unfortunately you can't use the resource methods there as in recipe, but you can use resource classes directly:

ruby_block 'Create ssh authorized keys' do
  block do
    node.run_state.each do |user|
      d = Chef::Resource::Directory.new(node.run_state[user]['homedir'], run_context)
      d.owner node.run_state[user]['uid']
      d.group node.run_state[user]['gid']
      d.mode '0700'
      d.run_action :create

      d = Chef::Resource::Directory.new("#{node.run_state[user]['homedir']}/.ssh", run_context)
      d.owner node.run_state[user]['uid']
      d.group node.run_state[user]['gid']
      d.mode '0700'
      d.run_action :create

      t = Chef::Resource::Template.new("#{node.run_state[user]['homedir']}/.ssh/authorized_keys", run_context)
      t.owner node.run_state[user]['uid']
      t.group node.run_state[user]['gid']
      t.mode '0600'
      t.source 'authorized_keys.erb'
      t.variables(sshkeys: base_attr['ssh_keys'][user])
      t.run_action :create
    end
  end
end
```

Body:
Is there a way to iterate through node.run_state data?
This is in a RHEL environment with Active Directory users.
I have a ruby block that populates node.run_state.  I have to have this run at converge time, because the overall cookbook will be used for build automation.  On the very first run, the cookbook installs Centrify, then later needs to run adquery to gather user info for populating home directories with SSH keys.

On a chef-client run, I see this:

       Compiling Cookbooks...
       {}

Obviously, that's the puts running in compile time against an empty hash.
At converge time, nothing happens in the loop with the 2 directory and 1 template resource.

Here is the relevant piece of the recipe:

ruby_block 'set uid, gid, and homedir for users' do
  block do
    base_attr['ssh_keys'].each do |user, pubkeys|
  # next unless Dir.exist?(homedir)
      node.run_state[user] = {}
      puts "Checking user #{user}..."
      if local_users.key?(user)
        node.run_state[user]['homedir'] = local_users[user]['homedir']
        node.run_state[user]['uid'] = local_users[user]['uid'].to_i
        node.run_state[user]['gid'] = local_users[user]['gid'].to_i
      elsif centrify_users.key?(user)
        node.run_state[user]['homedir'] = centrify_users[user]['homedir']
        node.run_state[user]['uid'] = centrify_users[user]['uid'].to_i
        node.run_state[user]['gid'] = centrify_users[user]['gid'].to_i
      else
        puts "user #{user} not found."
        # Place holder values.
        node.run_state[user]['homedir'] = "/tmp/#{user}"
        node.run_state[user]['uid'] = 0
        node.run_state[user]['gid'] = 0
      end
    end
  end
end
  # Dir.exist? guard should bypass compile-time error.
  # "name is a required property"
  # next unless Dir.exist?(homedir)
puts node.run_state
node.run_state.each do |user|
  directory node.run_state[user]['homedir'] do
    owner node.run_state[user]['uid']
    group node.run_state[user]['gid']
    mode '0700'
  end

  directory "#{node.run_state[user]['homedir']}/.ssh" do
    owner node.run_state[user]['uid']
    group node.run_state[user]['gid']
    mode '0700'
  end

  template "#{node.run_state[user]['homedir']}/.ssh/authorized_keys" do
    owner node.run_state[user]['uid']
    group node.run_state[user]['gid']
    mode '0600'
    source 'authorized_keys.erb'
    variables(
      sshkeys: base_attr['ssh_keys'][user]
    )
  end
end

Any ideas how to make this work?