问:
Logitech G Hub script - The code keeps running sometimes even after I release left mouse
Even after I release left mouse the script would sometimes keep clicking by itself how do I stop this.</p>

```<code>EnablePrimaryMouseButtonEvents(true);

function OnEvent(event, arg)
            if IsMouseButtonPressed(1) then
                repeat
                    Sleep(math.random(50, 75))
                    PressMouseButton(1)
                    Sleep(math.random(50, 75))
                    ReleaseMouseButton(1)
                until not IsMouseButtonPressed(1)
            end
end
</code>```

答:
It's impossible to both simulate LMB press/release and determine if it's pressed or released.

But there is a workaround: you can add alternative button for the same action as LMB.

For example, if LMB means "Fire" then add key "P" as alternative way to fire in the game.

```<code>local key_fire = "P"
EnablePrimaryMouseButtonEvents(true)

function OnEvent(event, arg)
   if event == "MOUSE_BUTTON_PRESSED" and arg == 1 then
      Sleep(math.random(100, 150))
      while IsMouseButtonPressed(1) do
         Sleep(math.random(50, 75))
         PressKey(key_fire)
         Sleep(math.random(50, 75))
         ReleaseKey(key_fire)
      end
   end
end
</code>```

You make the first shot by pressing LMB, and the script will make 2nd, 3rd,... shots by programmatically pressing P in the loop.

Body:
Even after I release left mouse the script would sometimes keep clicking by itself how do I stop this.

EnablePrimaryMouseButtonEvents(true);

function OnEvent(event, arg)
            if IsMouseButtonPressed(1) then
                repeat
                    Sleep(math.random(50, 75))
                    PressMouseButton(1)
                    Sleep(math.random(50, 75))
                    ReleaseMouseButton(1)
                until not IsMouseButtonPressed(1)
            end
end

Body:
It's impossible to both simulate LMB press/release and determine if it's pressed or released.

But there is a workaround: you can add alternative button for the same action as LMB.

For example, if LMB means "Fire" then add key "P" as alternative way to fire in the game.

local key_fire = "P"
EnablePrimaryMouseButtonEvents(true)

function OnEvent(event, arg)
   if event == "MOUSE_BUTTON_PRESSED" and arg == 1 then
      Sleep(math.random(100, 150))
      while IsMouseButtonPressed(1) do
         Sleep(math.random(50, 75))
         PressKey(key_fire)
         Sleep(math.random(50, 75))
         ReleaseKey(key_fire)
      end
   end
end

You make the first shot by pressing LMB, and the script will make 2nd, 3rd,... shots by programmatically pressing P in the loop.


来源: stackexchange

问:
Clean up table that has orphaned records
I have to remove orphaned records in Base Table.

Base Table

```<code>id | raw_data | unit
1  | 20 | kg
2  | 30 | km
3  | 10 | s
4  | 10 | s
5  | 20 | km/s
    6  | 70 | mpg
</code>```

Table A

```<code>id | field_1 | field_2
1  | 1 | 2
</code>```

Table B

```<code>id | field_1 | field_2
1  | 3 | 4
</code>```

The field_1 and field_2 in both Table A and Table B are referring to Base Table's primary key.

Since in Base Table record with id 5 and 6 is not referring from any table, this two are orphaned records, i want to remove it from database.

```<code>delete from base_table base
where not exists (select from table_a a where base.id = a.field_1
                    or base.id = a.field_2 )

                    and not exists (select from table_b b where base.id = b.field_1
                    or base.id = b.field_2)
</code>```

The problem is this query runs forever if my Base Table has a lot of records (2.5 million). And i might have 10 tables like Table A or Table B that has data referring to Base Table.

How can i clean up orphaned records on Base Table?

答:
Maybe just use UNION to get all ids of field_1 and field_2 of table_a and table_b, and use NOT IN to filter.

```<code>delete from base_table
where id NOT IN(
    select distinct field_1 from table_a
    union
    select distinct field_2 from table_a
    union
    select distinct field_1 from table_b
    union
    select distinct field_2 from table_b
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have to remove orphaned records in Base Table.

Base Table

id | raw_data | unit
1  | 20 | kg
2  | 30 | km
3  | 10 | s
4  | 10 | s
5  | 20 | km/s
    6  | 70 | mpg

Table A

id | field_1 | field_2
1  | 1 | 2

Table B

id | field_1 | field_2
1  | 3 | 4

The field_1 and field_2 in both Table A and Table B are referring to Base Table's primary key.

Since in Base Table record with id 5 and 6 is not referring from any table, this two are orphaned records, i want to remove it from database.

delete from base_table base
where not exists (select from table_a a where base.id = a.field_1
                    or base.id = a.field_2 )

                    and not exists (select from table_b b where base.id = b.field_1
                    or base.id = b.field_2)

The problem is this query runs forever if my Base Table has a lot of records (2.5 million). And i might have 10 tables like Table A or Table B that has data referring to Base Table.

How can i clean up orphaned records on Base Table?

Body:
Maybe just use UNION to get all ids of field_1 and field_2 of table_a and table_b, and use NOT IN to filter.

delete from base_table
where id NOT IN(
    select distinct field_1 from table_a
    union
    select distinct field_2 from table_a
    union
    select distinct field_1 from table_b
    union
    select distinct field_2 from table_b
)


问:
The Youtube-API for "Videos: insert" is not working properly
I'm trying to upload a video using the YouTube API.

I'm using the code snippet provided in the documentation page:

https://developers.google.com/youtube/v3/docs/videos/insert

I'm using the Python API.

I'm running this after providing a valid client secret file and file to upload.

I was able to authenticate using auth2, and provide a valid token.

I'm getting the following response:

```<code>{'kind': 'youtube#video', 'etag':   '"wdgS91PsEbtTfi20GmzFuZzYg2s/75EL94ZW60lJpJbXGn80dBaJI00"', 'id': 'Rz0n45vusps', 'snippet': {'publishedAt': '2020-05-30T05:23:07.000Z', 'channelId': 'UCAfompGqO1DYLi1WZ9GPYiw', 'title': 'Test video upload.', 'description': 'Description of uploaded video.', 'thumbnails': {'default': {'url': 'https://i9.ytimg.com/vi/Rz0n45vusps/default.jpg?sqp=CIDax_YF&rs=AOn4CLCt23wHAw-ViyVPCn5Sbxdh0v9Nzw', 'width': 120, 'height': 90}, 'medium': {'url': 'https://i9.ytimg.com/vi/Rz0n45vusps/mqdefault.jpg?sqp=CIDax_YF&rs=AOn4CLCshm-pBB2CeHW5ynQkhS4TA7zBWA', 'width': 320, 'height': 180}, 'high': {'url': 'https://i9.ytimg.com/vi/Rz0n45vusps/hqdefault.jpg?sqp=CIDax_YF&rs=AOn4CLDwNiO2tURd2POhFKrYOh6vYTfN6A', 'width': 480, 'height': 360}}, 'channelTitle': 'jvalansi84', 'categoryId': '22', 'liveBroadcastContent': 'none', 'localized': {'title': 'Test video upload.', 'description': 'Description of uploaded video.'}}, 'status': {'uploadStatus': 'uploaded', 'privacyStatus': 'private', 'license': 'youtube', 'embeddable': True, 'publicStatsViewable': True}}
</code>```

But I'm not seeing the actual video in my uploads.
What am I missing?

答:
The problem was that the video was a duplicate. I first uploaded manually, and then tried to use the API.
It would make sense to have some kind of feedback that the video is a duplicate through the API though.</p>

Body:
I'm trying to upload a video using the YouTube API.

I'm using the code snippet provided in the documentation page:

https://developers.google.com/youtube/v3/docs/videos/insert

I'm using the Python API.

I'm running this after providing a valid client secret file and file to upload.

I was able to authenticate using auth2, and provide a valid token.

I'm getting the following response:

{'kind': 'youtube#video', 'etag':   '"wdgS91PsEbtTfi20GmzFuZzYg2s/75EL94ZW60lJpJbXGn80dBaJI00"', 'id': 'Rz0n45vusps', 'snippet': {'publishedAt': '2020-05-30T05:23:07.000Z', 'channelId': 'UCAfompGqO1DYLi1WZ9GPYiw', 'title': 'Test video upload.', 'description': 'Description of uploaded video.', 'thumbnails': {'default': {'url': 'https://i9.ytimg.com/vi/Rz0n45vusps/default.jpg?sqp=CIDax_YF&rs=AOn4CLCt23wHAw-ViyVPCn5Sbxdh0v9Nzw', 'width': 120, 'height': 90}, 'medium': {'url': 'https://i9.ytimg.com/vi/Rz0n45vusps/mqdefault.jpg?sqp=CIDax_YF&rs=AOn4CLCshm-pBB2CeHW5ynQkhS4TA7zBWA', 'width': 320, 'height': 180}, 'high': {'url': 'https://i9.ytimg.com/vi/Rz0n45vusps/hqdefault.jpg?sqp=CIDax_YF&rs=AOn4CLDwNiO2tURd2POhFKrYOh6vYTfN6A', 'width': 480, 'height': 360}}, 'channelTitle': 'jvalansi84', 'categoryId': '22', 'liveBroadcastContent': 'none', 'localized': {'title': 'Test video upload.', 'description': 'Description of uploaded video.'}}, 'status': {'uploadStatus': 'uploaded', 'privacyStatus': 'private', 'license': 'youtube', 'embeddable': True, 'publicStatsViewable': True}}

But I'm not seeing the actual video in my uploads.
What am I missing?


问:
Show String contents in the OQL result when using MAT
When I execute the following OQL in Eclipse Memory Analyzer

```<code>SELECT key FROM com.google.common.cache.LocalCache$StrongAccessWriteEntry
</code>```

I got the following result

```<code>key
---------------------------------
java.lang.String [id=0x7bfa42f80]
java.lang.String [id=0x7bdf3a5b0]
java.lang.String [id=0x7bdf380c0]
java.lang.String [id=0x7bdf175e0]
......
---------------------------------
</code>```

I can check out the value of each result row by right-clicking it and select List Objects -> with outgoing references, that is not convenient. I want the result to be like this:

```<code>key
---------------------------------
java.lang.String [id=0x7bfa42f80]  apple
java.lang.String [id=0x7bdf3a5b0]  peach
java.lang.String [id=0x7bdf380c0]  pineapple
java.lang.String [id=0x7bdf175e0]  cherry
......
---------------------------------
</code>```

Assuming apple, peach, pineapple, cherry is the contents of each row.

In this way, I'm able to know the value of each row just by looking at it. Is there any way to do it?

答:
I figured it out, just use the following command</p>

```<code>SELECT key.toString() FROM com.google.common.cache.LocalCache$StrongAccessWriteEntry
</code>```

Body:
When I execute the following OQL in Eclipse Memory Analyzer

SELECT key FROM com.google.common.cache.LocalCache$StrongAccessWriteEntry

I got the following result

key
---------------------------------
java.lang.String [id=0x7bfa42f80]
java.lang.String [id=0x7bdf3a5b0]
java.lang.String [id=0x7bdf380c0]
java.lang.String [id=0x7bdf175e0]
......
---------------------------------

I can check out the value of each result row by right-clicking it and select List Objects -> with outgoing references, that is not convenient. I want the result to be like this:

key
---------------------------------
java.lang.String [id=0x7bfa42f80]  apple
java.lang.String [id=0x7bdf3a5b0]  peach
java.lang.String [id=0x7bdf380c0]  pineapple
java.lang.String [id=0x7bdf175e0]  cherry
......
---------------------------------

Assuming apple, peach, pineapple, cherry is the contents of each row.

In this way, I'm able to know the value of each row just by looking at it. Is there any way to do it?

Body:
I figured it out, just use the following command

SELECT key.toString() FROM com.google.common.cache.LocalCache$StrongAccessWriteEntry


问:
Using Multiple If Statements with While Loop
I'm trying to write a while loop that goes through a certain list looking for certain substrings. It will find words with those substrings and print out those strings.

Here is a example that works perfectly but for only one word:

```<code>lista = ['applepie','appleseed','bananacake','bananabread']

i = 0
z = len(lista)
while i < z:
    if ('pie' in lista[0+i]) == True:
        print(lista[0+i])
        break
    i = i  + 1
else:
    print('Not There Yet')
</code>```

This prints out applepie (which is what is desired!).

How do I go about fixing this while loop to add in multiple constraints?

I'm trying to do this:

```<code>lista = ['applepie','appleseed','bananacake','bananabread']

i = 0
z = len(lista)
while i < z:
    if ('pie' in lista[0+i]) == True:
        print(lista[0+i])
    if ('cake' in lista[0+1]) == True:
        print(lista[0+i])
    i = i  + 1
else:
    print('Not There Yet')
</code>```

This prints out:
applepie
Not There Yet

When I want this to print out:
applepie
bananacake

I used multiple 'if' statements, because I know if I want to use an 'elif', it will only run if the first 'if' statement is false.

Any help is appreciated!

答:
You have two issues smallish issues and I think one larger. The first of the two small ones are what Nick and Brenden noted above. The second is your conditional. It should be <= as opposed to the < you used.

The larger seems that you're having a problem conceptualizing the actual workings. For that, let me suggest you step through it here

Body:
I'm trying to write a while loop that goes through a certain list looking for certain substrings. It will find words with those substrings and print out those strings.

Here is a example that works perfectly but for only one word:

lista = ['applepie','appleseed','bananacake','bananabread']

i = 0
z = len(lista)
while i < z:
    if ('pie' in lista[0+i]) == True:
        print(lista[0+i])
        break
    i = i  + 1
else:
    print('Not There Yet')

This prints out applepie (which is what is desired!).

How do I go about fixing this while loop to add in multiple constraints?

I'm trying to do this:

lista = ['applepie','appleseed','bananacake','bananabread']

i = 0
z = len(lista)
while i < z:
    if ('pie' in lista[0+i]) == True:
        print(lista[0+i])
    if ('cake' in lista[0+1]) == True:
        print(lista[0+i])
    i = i  + 1
else:
    print('Not There Yet')

This prints out:
applepie
Not There Yet

When I want this to print out:
applepie
bananacake

I used multiple 'if' statements, because I know if I want to use an 'elif', it will only run if the first 'if' statement is false.

Any help is appreciated!

Body:
You have two issues smallish issues and I think one larger. The first of the two small ones are what Nick and Brenden noted above. The second is your conditional. It should be <= as opposed to the < you used.

The larger seems that you're having a problem conceptualizing the actual workings. For that, let me suggest you <a href="https://cscircles.cemc.uwaterloo.ca/visualize#code=lista+%3D+%5B'applepie','appleseed','bananacake','bananabread'%5D%0A%0Ai+%3D+0%0Az+%3D+len(lista)%0Awhile+i+%3C%3D+z%3A%0A++++if+('pie'+in+lista%5Bi%5D)+%3D%3D+True%3A%0A++++++++print(lista%5B0%2Bi%5D)%0A++++if+('cake'+in+lista%5Bi%5D)+%3D%3D+True%3A%0A++++++++print(lista%5B0%2Bi%5D)%0A++++i+%3D+i++%2B+1%0Aelse%3A%0A++++print('Not+There+Yet')&mode=display&raw_input=&curInstr=23" rel="nofollow noreferrer">step through it here


答:
Your current query is logically correct, and is possibly already the best option.  You could consider indexing the A and B tables:

```<code>CREATE INDEX idx_A ON TableA (field_1, field_2);
CREATE INDEX idx_B ON TableB (field_1, field_2);
</code>```

This might speed up the exists lookups in your current delete query, possibly making them dramatically faster.

Title: Clean up table that has orphaned records

Body:
Your current query is logically correct, and is possibly already the best option.  You could consider indexing the A and B tables:

CREATE INDEX idx_A ON TableA (field_1, field_2);
CREATE INDEX idx_B ON TableB (field_1, field_2);

This might speed up the exists lookups in your current delete query, possibly making them dramatically faster.


问:
Changing Character base on the given integer?
I am trying to change the given integer to a character

for example:

```<code>N = 5;
result = +-+-+;
</code>```

Right now I am having a hard time implementing this

What I have tried so far is this

```<code>    public void Main()
    {
        int integer;

        Console.WriteLine("How many strings : ");
        integer = Convert.ToInt32(Console.ReadLine());

        ChangeCharacter(integer);
    }

    public void ChangeCharacter(int A)
    {
        string p = "+";
        string m = "-";
        Console.WriteLine("Printing : " + A + " strings");

        for(int i = 0 ; i < A ; i++)
        {
            Console.WriteLine(p,m);
        }
    }

</code>```

the result is only : + + + + + it is not including the - sign

I am just new to c# and I am taking a coding exam to build my logic more . Sorry for my bad english because it is not my mother tongue.

答:
If you prefer a one-liner, LINQ would do the job as well:

int n = 5; // Expect: +-+-+

Console.WriteLine(new string(Enumerable.Range(0, n).Select(x => x % 2 == 0 ? '+' : '-').ToArray()));
```

<p>Explanation</p>

<pre class="lang-cs prettyprint-override"><code>new string(
  Enumerable.Range(0, n) // Generate n integers start from 0
    .Select(x =>         // for each integer,
      x % 2 == 0         // if it's even
      ? '+'              // return +
      : '-'              // otherwise -
    ).ToArray()          // convert selected characters into character array
  )
);
</code>```

Body:
I am trying to change the given integer to a character

for example:

N = 5;
result = +-+-+;

Right now I am having a hard time implementing this

What I have tried so far is this

    public void Main()
    {
        int integer;

        Console.WriteLine("How many strings : ");
        integer = Convert.ToInt32(Console.ReadLine());

        ChangeCharacter(integer);
    }

    public void ChangeCharacter(int A)
    {
        string p = "+";
        string m = "-";
        Console.WriteLine("Printing : " + A + " strings");

        for(int i = 0 ; i < A ; i++)
        {
            Console.WriteLine(p,m);
        }
    }

the result is only : + + + + + it is not including the - sign

I am just new to c# and I am taking a coding exam to build my logic more . Sorry for my bad english because it is not my mother tongue.

Body:
If you prefer a one-liner, LINQ would do the job as well:

int n = 5; // Expect: +-+-+

Console.WriteLine(new string(Enumerable.Range(0, n).Select(x => x % 2 == 0 ? '+' : '-').ToArray()));

Explanation

new string(
  Enumerable.Range(0, n) // Generate n integers start from 0
    .Select(x =>         // for each integer,
      x % 2 == 0         // if it's even
      ? '+'              // return +
      : '-'              // otherwise -
    ).ToArray()          // convert selected characters into character array
  )
);


问:
Need a delay to wait for GPS
Using the iPhone and objective C, is there a way to stall or perform a timing loop to allow for the GPS to catch up and return a valid set of coordinates?

Currently, the application runs too quickly and the GPS cannot supply the coordinates fast enough...

答: Either block to wait for data or don't update anything if no data received. There is of course usleep(), but without showing code and specifically how your loop is executed and by what mechanism (threaded or not) we can only answer in general terms.

ContentLicense: CC BY-SA 3.0

Title: Need a delay to wait for GPS


问:
Unrecognized font family on iOS simulator with React Native
I've added Linux Biolinum fonts (http://www.dafont.com/linux-biolinum.font, LinBiolinum_R.ttf, LinBiolinum_RB.ttf) to my React Native project. Android version is OK. But on iOS I always see error "Unrecognized font family LinBiolinum_R".

My style is:

```<code>customFontRegular: {
    fontFamily: 'LinBiolinum_R',
},
</code>```

I've tryied to rename font file and font family to "MyFont", but the error appears again on iOS.

Any ideas?

答:
In my case, it worked fine in Android but not in iOS. The font file name was PlayfairDisplay-VariableFont_wght.ttf. But when I opened that file I saw the name as:

.

So, I changed the file name to PlayfairDisplay-Regular.ttf and it worked pretty well!

Body:
I've added Linux Biolinum fonts (http://www.dafont.com/linux-biolinum.font, LinBiolinum_R.ttf, LinBiolinum_RB.ttf) to my React Native project. Android version is OK. But on iOS I always see error "Unrecognized font family LinBiolinum_R".

My style is:

customFontRegular: {
    fontFamily: 'LinBiolinum_R',
},

I've tryied to rename font file and font family to "MyFont", but the error appears again on iOS.

Any ideas?


问:
Basic React: why is a variable in local storage resetting to undefined after briefly being the desired value?
I am new to React and was writing some toy code whose desired behavior is to allow a user to enter their name in the form and the page will display "Hello {user's name}" after submitting.

However, the observed behavior is that the page flickers briefly to render "Hello {user's name}" and then returns to the default rendering as if no name had been submitted.

My current approach is to save the user's name in local storage upon submission with a useEffect. However, from observing console logs, the local storage appears to be resetting the "name" variable to undefined immediately after setting it to the inputted name. Below is the code.

```<code>function NameForm() {
  const [name, setName] = useState(window.localStorage.getItem("name") || "");
  useEffect(() => {
    setName(window.localStorage.setItem("name", name));
    console.log(name);
  }, [name]);
  return (
    <>
      <form
        onSubmit={event => {
          event.preventDefault();
          setName(event.target.elements.usernameInput.value);
          return false;
        }}
      >
        <label>Enter your name</label>
        <input id="usernameInput" />
        <button type="submit"> Submit</button>
      </form>
      <h1>Hello {name}</h1>
    </>
  );
}
export default function App() {
  return (
    <div className="App">
      <NameForm />
    </div>
  );
}
</code>```

Here is also the codesandbox used to run the code. https://codesandbox.io/s/modern-hill-gfkrp?file=/src/App.js:76-773

Why is this unexpected behavior occuring and how can I fix it?

Thanks!

答:
All you need to do is just apply a condition before setting the value. Once the form is submitted your name value is becoming undefined and that is getting stored.
You would state now that you have used useState(window.localStorage.getItem("name") || "") so how can it be undefined.
This is because of the race condition.It takes some time to setItem in localStorage and before it is setting your component is getting rendered.

Also you can use localStorage directly instead of using window.localStorage:
Here is what you need to do

 useEffect(() => {
    if(name)
    setName(window.localStorage.setItem("name", name));
    console.log(name);
  }, [name]);```

Body:
I am new to React and was writing some toy code whose desired behavior is to allow a user to enter their name in the form and the page will display "Hello {user's name}" after submitting.

However, the observed behavior is that the page flickers briefly to render "Hello {user's name}" and then returns to the default rendering as if no name had been submitted.

My current approach is to save the user's name in local storage upon submission with a useEffect. However, from observing console logs, the local storage appears to be resetting the "name" variable to undefined immediately after setting it to the inputted name. Below is the code.

function NameForm() {
  const [name, setName] = useState(window.localStorage.getItem("name") || "");
  useEffect(() => {
    setName(window.localStorage.setItem("name", name));
    console.log(name);
  }, [name]);
  return (
    <>
      <form
        onSubmit={event => {
          event.preventDefault();
          setName(event.target.elements.usernameInput.value);
          return false;
        }}
      >
        Enter your name
        <input id="usernameInput" />
        <button type="submit"> Submit</button>
      </form>

Hello {name}

    </>
  );
}
export default function App() {
  return (

      <NameForm />

  );
}

Here is also the codesandbox used to run the code. https://codesandbox.io/s/modern-hill-gfkrp?file=/src/App.js:76-773

Why is this unexpected behavior occuring and how can I fix it?

Thanks!


问:
AWS ClientError when using Lambda and S3 to insert data to bucket
I am trying to put a json blob into an S3 bucket using lambda and I am getting the following error when looking at the cloudwatch logs

```<code>[ERROR] ClientError: An error occurred (AccessDenied) when calling the PutObject operation: Access Denied
Traceback (most recent call last):
  File "/var/task/main.py", line 147, in lambda_handler
    save_articles_and_comments(sub, submissions)
  File "/var/task/main.py", line 125, in save_articles_and_comments
    object.put(Body=json.dumps(articles))
  File "/var/task/boto3/resources/factory.py", line 520, in do_action
    response = action(self, *args, **kwargs)
  File "/var/task/boto3/resources/action.py", line 83, in __call__
    response = getattr(parent.meta.client, operation_name)(*args, **params)
  File "/var/task/botocore/client.py", line 316, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/var/task/botocore/client.py", line 635, in _make_api_call
    raise error_class(parsed_response, operation_name)
</code>```

All of the block public access settings are set to "off" and the bucket name in the code is the same as in S3. This is the code that is putting the json blob into their respeectable folders in my S3 bucket and the lambda handler

```<code>def save_articles_and_comments(sub, submissions):
    """
    """
    s3 = boto3.resource('s3')
    now = dt.datetime.utcnow()
    formatted_date = now.strftime("%Y-%m-%d-%H-%M-%S")

    articles, comments = data_for_subreddit(submissions)
    print("Number of articles, comments {}, {}".format(len(articles), len(comments)))
    articles_name = 'articles/' + formatted_date + '_' + sub + '_articles.json'
    comments_name = 'comments/' + formatted_date + '_' + sub + '_comments.json'
    object = s3.Object('diegos-reddit-bucket', articles_name)
    object.put(Body=json.dumps(articles))
    print("Finished writing articles to {}".format(articles_name))

    object = s3.Object('diegos-reddit-bucket', comments_name)
    object.put(Body=json.dumps(comments))
    print("Finished writing comments to {}".format(comments_name))

def lambda_handler(x, y):
    """
    """
    import time
    import random
    idx = random.randint(0, len(SUBREDDITS)-1)
    start = time.time()
    assert PRAW_KEY is not None
    sub = SUBREDDITS[idx]
    red = reddit_instance()
    subreddit = red.subreddit(sub)

    print("Pulling posts from {}, {}.".format(sub, "hot"))
    submissions = subreddit.hot()
    save_articles_and_comments(sub, submissions)
    print("="*50)

    print("Pulling posts from {}, {}.".format(sub, "new"))
    submissions = subreddit.new()
    save_articles_and_comments(sub, submissions)
    print("="*50)

    print("Pulling posts from {}, {}.".format(sub, "top"))
    submissions = subreddit.top()
    save_articles_and_comments(sub, submissions)
    print("="*50)

    print("Pulling posts from {}, {}.".format(sub, "rising"))
    submissions = subreddit.rising()
    save_articles_and_comments(sub, submissions)
    end = time.time()
    print("Elapsed time {}".format(end - start))

</code>```

I do not see what is the problem in the code for me to getting said error. swapped out my lambda_handler function with a main to test locally. With the main it works, and writes to the S3 bucket and its respected folders. When I try and run via AWS Lambda, I get said error after the function is done pulling posts from the first subreddit and trying to put the json blob into the folder in the S3 bucket. This is what my output is supposed to look like

```<code>Pulling posts from StockMarket, hot.
Number of articles, comments 101, 909
Finished writing articles to articles/2020-06-03-02-48-44_StockMarket_articles.json
Finished writing comments to comments/2020-06-03-02-48-44_StockMarket_comments.json
==================================================
Pulling posts from StockMarket, new.
Number of articles, comments 101, 778
Finished writing articles to articles/2020-06-03-02-49-10_StockMarket_articles.json
Finished writing comments to comments/2020-06-03-02-49-10_StockMarket_comments.json
==================================================
Pulling posts from StockMarket, top.
Number of articles, comments 101, 5116
Finished writing articles to articles/2020-06-03-02-49-36_StockMarket_articles.json
Finished writing comments to comments/2020-06-03-02-49-36_StockMarket_comments.json
==================================================
Pulling posts from StockMarket, rising.
Number of articles, comments 24, 170
Finished writing articles to articles/2020-06-03-02-52-10_StockMarket_articles.json
Finished writing comments to comments/2020-06-03-02-52-10_StockMarket_comments.json
Elapsed time 215.6588649749756
</code>```

Is there a problem in my code or is this a problem on the AWS side?

答:
The problem occurs because you have no permissions to write objects to the bucket:

PutObject operation: Access Denied

To rectify the issue, have to look at lambda execution role: does it have permissions to write to S3? Also can inspect bucket policy.

With the main it works, and writes to the S3 bucket and its respected folders. When I try and run via AWS Lambda, I get said error

When you test locally, your code is using your own permissions (your IAM user) to write to S3. Thus it works. When you execute the code on lambda, your function does not use your permissions. Instead it uses permissions defined in lambda execution role.

Body:
I am trying to put a json blob into an S3 bucket using lambda and I am getting the following error when looking at the cloudwatch logs

[ERROR] ClientError: An error occurred (AccessDenied) when calling the PutObject operation: Access Denied
Traceback (most recent call last):
  File "/var/task/main.py", line 147, in lambda_handler
    save_articles_and_comments(sub, submissions)
  File "/var/task/main.py", line 125, in save_articles_and_comments
    object.put(Body=json.dumps(articles))
  File "/var/task/boto3/resources/factory.py", line 520, in do_action
    response = action(self, *args, **kwargs)
  File "/var/task/boto3/resources/action.py", line 83, in __call__
    response = getattr(parent.meta.client, operation_name)(*args, **params)
  File "/var/task/botocore/client.py", line 316, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/var/task/botocore/client.py", line 635, in _make_api_call
    raise error_class(parsed_response, operation_name)

All of the block public access settings are set to "off" and the bucket name in the code is the same as in S3. This is the code that is putting the json blob into their respeectable folders in my S3 bucket and the lambda handler

def save_articles_and_comments(sub, submissions):
    """
    """
    s3 = boto3.resource('s3')
    now = dt.datetime.utcnow()
    formatted_date = now.strftime("%Y-%m-%d-%H-%M-%S")

    articles, comments = data_for_subreddit(submissions)
    print("Number of articles, comments {}, {}".format(len(articles), len(comments)))
    articles_name = 'articles/' + formatted_date + '_' + sub + '_articles.json'
    comments_name = 'comments/' + formatted_date + '_' + sub + '_comments.json'
    object = s3.Object('diegos-reddit-bucket', articles_name)
    object.put(Body=json.dumps(articles))
    print("Finished writing articles to {}".format(articles_name))

    object = s3.Object('diegos-reddit-bucket', comments_name)
    object.put(Body=json.dumps(comments))
    print("Finished writing comments to {}".format(comments_name))

def lambda_handler(x, y):
    """
    """
    import time
    import random
    idx = random.randint(0, len(SUBREDDITS)-1)
    start = time.time()
    assert PRAW_KEY is not None
    sub = SUBREDDITS[idx]
    red = reddit_instance()
    subreddit = red.subreddit(sub)

    print("Pulling posts from {}, {}.".format(sub, "hot"))
    submissions = subreddit.hot()
    save_articles_and_comments(sub, submissions)
    print("="*50)

    print("Pulling posts from {}, {}.".format(sub, "new"))
    submissions = subreddit.new()
    save_articles_and_comments(sub, submissions)
    print("="*50)

    print("Pulling posts from {}, {}.".format(sub, "top"))
    submissions = subreddit.top()
    save_articles_and_comments(sub, submissions)
    print("="*50)

    print("Pulling posts from {}, {}.".format(sub, "rising"))
    submissions = subreddit.rising()
    save_articles_and_comments(sub, submissions)
    end = time.time()
    print("Elapsed time {}".format(end - start))

I do not see what is the problem in the code for me to getting said error. swapped out my lambda_handler function with a main to test locally. With the main it works, and writes to the S3 bucket and its respected folders. When I try and run via AWS Lambda, I get said error after the function is done pulling posts from the first subreddit and trying to put the json blob into the folder in the S3 bucket. This is what my output is supposed to look like

Pulling posts from StockMarket, hot.
Number of articles, comments 101, 909
Finished writing articles to articles/2020-06-03-02-48-44_StockMarket_articles.json
Finished writing comments to comments/2020-06-03-02-48-44_StockMarket_comments.json
==================================================
Pulling posts from StockMarket, new.
Number of articles, comments 101, 778
Finished writing articles to articles/2020-06-03-02-49-10_StockMarket_articles.json
Finished writing comments to comments/2020-06-03-02-49-10_StockMarket_comments.json
==================================================
Pulling posts from StockMarket, top.
Number of articles, comments 101, 5116
Finished writing articles to articles/2020-06-03-02-49-36_StockMarket_articles.json
Finished writing comments to comments/2020-06-03-02-49-36_StockMarket_comments.json
==================================================
Pulling posts from StockMarket, rising.
Number of articles, comments 24, 170
Finished writing articles to articles/2020-06-03-02-52-10_StockMarket_articles.json
Finished writing comments to comments/2020-06-03-02-52-10_StockMarket_comments.json
Elapsed time 215.6588649749756

Is there a problem in my code or is this a problem on the AWS side?


答:
You can use any() to go through a list of conditions. It will evaluate to True when the condition is first met and False if it never happens. If you combine that with a regular python for loop, it will be nice a succinct:

```<code>lista = ['applepie','appleseed','bananacake','bananabread']
words = ['pie', 'cake']

for food in lista:
    if any(word in food for word in words):
        print(food)
</code>```

It prints:

```<code>applepie
bananacake
</code>```

You can also so the same thing as a list comprehension to get a list of words that match:

```<code>lista = ['applepie','appleseed','bananacake','bananabread']
words = ['pie', 'cake']

found = [food for food in lista if any(word in food for word in words)]
# ['applepie', 'bananacake']
</code>```

Generally speaking, Python discourages you from using indices in loops unless you really need to. It tends to be error prone and harder to read.

Title: Using Multiple If Statements with While Loop

Body:
You can use any() to go through a list of conditions. It will evaluate to True when the condition is first met and False if it never happens. If you combine that with a regular python for loop, it will be nice a succinct:

lista = ['applepie','appleseed','bananacake','bananabread']
words = ['pie', 'cake']

for food in lista:
    if any(word in food for word in words):
        print(food)

It prints:

applepie
bananacake

You can also so the same thing as a list comprehension to get a list of words that match:

lista = ['applepie','appleseed','bananacake','bananabread']
words = ['pie', 'cake']

found = [food for food in lista if any(word in food for word in words)]
# ['applepie', 'bananacake']

Generally speaking, Python discourages you from using indices in loops unless you really need to. It tends to be error prone and harder to read.


问:
What StoreKit returns if user pays right before going into a tunnel
Apple doc says the following:

For example, if a user buys something in your app right before going into a tunnel, your app may not be able to deliver the purchased content if there is no network connection. The next time your app launches, StoreKit calls your transaction queue observer again and your app should handle the transaction and deliver the purchased content.

I wonder if the app receives anything through paymentQueue(_:updatedTransactions:) when StoreKit failed to finish the purchase in the tunnel?

My first thought was that StoreKit might return SKPaymentTransactionState.failed with a network connection related error domain or code. But if so, the app would call finishTransaction(_:) to remove the transaction in the payment queue. As a result, what was described in the last sentence of the above doc would never happen.

So, does that mean in above case StoreKit doesn't return anything and the app seems to be hanging to user? Will user have to kill the app to continue? Or maybe the purchase view (presented by StoreKit) doesn't block the application's UI so user can dismiss the purchase view and continue to use the app (I suppose the app doesn't implement an activity indicator view to block the UI)?

Thanks for any help.

答:
The situation described in Apple's document is that where the purchase has completed on Apple's side, but your app is unable to deliver the content.

For example, the user may have purchased a movie rental. The access to this rental needs to be recorded on your server.

If they enter a tunnel after Apple returns a .purchased status but before you can get a confirmation from your server that the purchase has been recorded, you wouldn't call completeTransaction since the transaction isn't complete until the purchase is recorded on your server.  You would presumably have a network error or timeout communicating with your server.

The pending transaction would remain in the queue for your app to retry later.


问:
discordjs my bot runs correctly when running locally but not with heroku
so if someone tries to run a command in a certain channel, my bot will (or should) delete the command and tell the user not to run commands in that channel, here's my code for that:

```<code>bot.on('message', msg=>{
    if(msg.channel.type === 'dm' || msg.author.id === bot.user.id || msg.author.id === '706663416697192489'){
    return;
    }
    else if(msg.content.startsWith("!") && msg.channel.id === '706662574606778490'){
    msg.delete()
    msg.reply('you can\'t send commands in this channel! Send commands in the <#707068673399193670> channel.').then(function(msg){
    msg.delete({timeout: 2000})
    })
    }
});
</code>```

this code works perfectly fine when i run my bot locally with ctrl+c "node .", but normally i run my bot with heroku so its running full time. the problem is when i run this code with heroku, the reply message doesn't get deleted. this isn't too good as if someone tries to run a command in my announcements channel, the command will be deleted but the bot's reply message wont be and everyone can see "you can\'t send commands in this channel! Send commands in the <#707068673399193670> channel." in announcements. all my other code works perfectly fine with heroku, except this. i feel this might be an issue on heroku's part but any advice?

答:
No it is not heroku's fault, you had duplicate variable names

bot.on('message', msg => {
    if (msg.channel.type === 'dm' || msg.author.id === bot.user.id || msg.author.id === '706663416697192489') return;
    if (msg.content.startsWith("!") && msg.channel.id === '706662574606778490') {
        msg.delete();
        msg.reply('you can\'t send commands in this channel! Send commands in the <#707068673399193670> channel.')
            .then(reply => reply.delete({ timeout: 2000 }));
    }
});
```

Body:
so if someone tries to run a command in a certain channel, my bot will (or should) delete the command and tell the user not to run commands in that channel, here's my code for that:

bot.on('message', msg=>{
    if(msg.channel.type === 'dm' || msg.author.id === bot.user.id || msg.author.id === '706663416697192489'){
    return;
    }
    else if(msg.content.startsWith("!") && msg.channel.id === '706662574606778490'){
    msg.delete()
    msg.reply('you can\'t send commands in this channel! Send commands in the <#707068673399193670> channel.').then(function(msg){
    msg.delete({timeout: 2000})
    })
    }
});

this code works perfectly fine when i run my bot locally with ctrl+c "node .", but normally i run my bot with heroku so its running full time. the problem is when i run this code with heroku, the reply message doesn't get deleted. this isn't too good as if someone tries to run a command in my announcements channel, the command will be deleted but the bot's reply message wont be and everyone can see "you can\'t send commands in this channel! Send commands in the <#707068673399193670> channel." in announcements. all my other code works perfectly fine with heroku, except this. i feel this might be an issue on heroku's part but any advice?


问:
PHP strip unknown file extension
I understand that using PHP's basename() function you can strip a known file extension from a path like so,

```<code>basename('path/to/file.php','.php')
</code>```

but what if you didn't know what extension the file had or the length of that extension? How would I accomplish this?

Thanks in advance!

答:
pathinfo() was already mentioned here, but I'd like to add that from PHP 5.2 it also has a simple way to access the filename WITHOUT the extension.

```<code>$filename = pathinfo('path/to/file.php', PATHINFO_FILENAME);
</code>```

The value of $filename will be file.

Title: PHP strip unknown file extension

Body:
I understand that using PHP's basename() function you can strip a known file extension from a path like so,

basename('path/to/file.php','.php')

but what if you didn't know what extension the file had or the length of that extension? How would I accomplish this?

Thanks in advance!

Body:
pathinfo() was already mentioned here, but I'd like to add that from PHP 5.2 it also has a simple way to access the filename WITHOUT the extension.

$filename = pathinfo('path/to/file.php', PATHINFO_FILENAME);

The value of $filename will be file.


问:
InfoSphere Data Replication 11.4.0 CDC configuration
I am trying to configure IIDR CDC from source DB2 (Unix) to target Hadoop. I have installed and created instance on CDC and installed AccessServer, however, i am not able to extract the data from DB2 to non-RDBMS DB. i need help to configure instance, schema and table to extract the DB.

LIST OF CURRENT INSTANCES

Name      Server Port Database      Schema      Status

iidrcdc   10901       CARD          UMT         running

答:
IBM IIDR ( InfoSphere Data Replication)  has different Engines  for various platforms.   They interact with a specific platform/database and require a specific configuration.

You can use the same  product installer from Fix Central to  install the DB2 Engine, and Also the IIDR for DataStage engine  ( which provides options to generate data in Hadoop through WebHDFS API Calls, in addition to flatfiles on local disk for DataStage).
This will require selecting a separate Engine to install to a SEPARATE  second installation path.   ** you can only have one set of instances/platform  per install path of IIDR, but you can have multiple engines installed on the same host. **

The IIDR community wiki page URL has changed but you can find it here :
https://www.ibm.com/support/pages/ibm-data-replication-community-wiki#Hadoop
along with a slide deck outlining the steps to configure a subscrpition to target Hadoop.
(https://ibm.ent.box.com/s/w9yxxqi4vs2cfd7v83321hoxgvc7xr9n )

You may need to be aware of  authentication setup for your Hadoop environment.  If  Kerberos authentication is needed,  you may need to identify the principal you are going to use and configure the keys.

With the Target Engine installed and instance created,  you can use the   Management Console  GUI tool  to  configure your  'Subscription' mapping from DB2  to  Hadoop.
(https://www.ibm.com/support/knowledgecenter/SSTRGZ_11.4.0/com.ibm.cdcdoc.mcadminguide.doc/concepts/map_to_hadoop.html )

Chris Schreiber,
IBM IIDR / CDC Team


问:
Java Selenium - Web element does not show up every time, but it shows up on some condition. How doI handle this?
public class LoginPage extends BasePage {

```<code>public LoginPage(WebDriver driver) {
    super(driver);
    // TODO Auto-generated constructor stub
}

private By username = By.id("userid");

private By password = By.id("Bharosa_Password_PadDataField");

private By continueButton = By.xpath("//input[@type ='submit']");

private By enterButton = By.xpath("/html/body/div[1]/div[2]/form/div/table/tbody/tr/td/map/area[5]");

private By continueButtonNxt = By.cssSelector("input[value=Continue][type=submit]");

private By verificationCodeField = By.id("Bharosa_Challenge_PadDataField");

private By enterButtonVerficationCode = By.xpath("/html/body/div[1]/div[2]/form/div/table/tbody/tr/td/map/area[5]");

private By landingPageTitle = By.xpath("//a/img[@class='logo-info']");

public WebElement getUsername() {
    return getWebElement(username);
}

public WebElement getPassword() {
    return  getWebElement(password);
}

public WebElement getContinueButtonNxt() {
    return getWebElement(continueButtonNxt);
}

public WebElement getContinuebutton() {
    return getWebElement(continueButton);
}

public WebElement getenterButtonVerficationCode() {
    return getWebElement(enterButtonVerficationCode);
}

public WebElement getVerificationCodeField() {
    return getWebElement(verificationCodeField);
}

public WebElement getEnterbutton() {
    return getWebElement(enterButton);
}

public LandingPage login(String user, String pass)
{

    getUsername().sendKeys(user);
    if(isElementPresent(continueButton).isDisplayed())
    {
    getContinuebutton().click();
    }
    getPassword().sendKeys(pass);
     getEnterbutton().submit();

     if(getContinueButtonNxt().isEnabled())
     {
     getContinueButtonNxt().click();
    getVerificationCodeField().sendKeys("888888");
     getenterButtonVerficationCode().submit();
     }
     else
     isElementPresentFluentWait(landingPageTitle);
     return new LandingPage(driver);
}
</code>```

}

Error
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"input[value=Continue][type=submit]"}
  (Session info: chrome=83.0.4103.61)
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.14.0', revision: 'aacccce0', time: '2018-08-02T20:19:58.91Z'
System info: host: 'EHL5CG009176X', ip: '10.0.0.17', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_251'
Driver info: org.openqa.selenium.chrome.ChromeDriver

答:
Do you have to hover over for the continueButtonNxt for it to be visible ? If so click on same blank spot and then click on the button.Have you implemented some wait methods on your test base ? Also, just a quick troubleshooting, implement thread.sleep(5000) and see if that works
Also, try using javascript executor and see if that works </p>

Body:
public class LoginPage extends BasePage {

public LoginPage(WebDriver driver) {
    super(driver);
    // TODO Auto-generated constructor stub
}

private By username = By.id("userid");

private By password = By.id("Bharosa_Password_PadDataField");

private By continueButton = By.xpath("//input[@type ='submit']");

private By enterButton = By.xpath("/html/body/div[1]/div[2]/form/div/table/tbody/tr/td/map/area[5]");

private By continueButtonNxt = By.cssSelector("input[value=Continue][type=submit]");

private By verificationCodeField = By.id("Bharosa_Challenge_PadDataField");

private By enterButtonVerficationCode = By.xpath("/html/body/div[1]/div[2]/form/div/table/tbody/tr/td/map/area[5]");

private By landingPageTitle = By.xpath("//a/img[@class='logo-info']");

public WebElement getUsername() {
    return getWebElement(username);
}

public WebElement getPassword() {
    return  getWebElement(password);
}

public WebElement getContinueButtonNxt() {
    return getWebElement(continueButtonNxt);
}

public WebElement getContinuebutton() {
    return getWebElement(continueButton);
}

public WebElement getenterButtonVerficationCode() {
    return getWebElement(enterButtonVerficationCode);
}

public WebElement getVerificationCodeField() {
    return getWebElement(verificationCodeField);
}

public WebElement getEnterbutton() {
    return getWebElement(enterButton);
}

public LandingPage login(String user, String pass)
{

    getUsername().sendKeys(user);
    if(isElementPresent(continueButton).isDisplayed())
    {
    getContinuebutton().click();
    }
    getPassword().sendKeys(pass);
     getEnterbutton().submit();

     if(getContinueButtonNxt().isEnabled())
     {
     getContinueButtonNxt().click();
    getVerificationCodeField().sendKeys("888888");
     getenterButtonVerficationCode().submit();
     }
     else
     isElementPresentFluentWait(landingPageTitle);
     return new LandingPage(driver);
}

}

Error
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"input[value=Continue][type=submit]"}
  (Session info: chrome=83.0.4103.61)
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.14.0', revision: 'aacccce0', time: '2018-08-02T20:19:58.91Z'
System info: host: 'EHL5CG009176X', ip: '10.0.0.17', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_251'
Driver info: org.openqa.selenium.chrome.ChromeDriver


问:
I am new to python with no previous coding experience. My program is supposed to display the price of a ticket depending on age. Why does it not work?
My code will display ticket price dependent on age. Why is it not working? This is exercise 7-5 from the Python Crash Course book.</p>

```<code>
prompt = "\nEnter Age: "
prompt += "\nEnter 'quit' when done."
age = ''

while age != 'quit':

    age = input(prompt)
    print(age)
    if age != 'quit':
        if age > '13':
            print(f'You ticket price is $15.00.')
            print(f'Retrieve your ticket(s) below')

        if age <= '13' and age > '2':
            print(f'Your ticket price is $10.00.')
            print(f'Retrieve your ticket(s) below')

        if age < '3':
            print(f'Your ticket price is free')
            print(f'Retrieve your ticket below')

print(f'Thank You Enjoy the show')
</code>```

答: It will fix your problem if you do it this way: "if int(age) > 13:"(across all if statements) This way you "quit" functionality will still work! Happy coding!!</p>

Body:
My code will display ticket price dependent on age. Why is it not working? This is exercise 7-5 from the Python Crash Course book.

prompt = "\nEnter Age: "
prompt += "\nEnter 'quit' when done."
age = ''

while age != 'quit':

    age = input(prompt)
    print(age)
    if age != 'quit':
        if age > '13':
            print(f'You ticket price is $15.00.')
            print(f'Retrieve your ticket(s) below')

        if age <= '13' and age > '2':
            print(f'Your ticket price is $10.00.')
            print(f'Retrieve your ticket(s) below')

        if age < '3':
            print(f'Your ticket price is free')
            print(f'Retrieve your ticket below')

print(f'Thank You Enjoy the show')


问:
How can one Docker Container find the IP address of another Docker Container?
Working on my first MSA application, and trying to figure out how a Docker container can find the IP address of another Docker Container?  My containers know the name of the other container it needs to connect to, but that is it.  I can't use a "--link" option or docker-compose as the components can come an go at different times, and I need a programmatic way to find the IP address of the other containers and start connections to them.

I have to think this problem has already been solved long long ago, but my GoogleFoo must be very weak today, as I can't find anything!

Thanks for your help! :)

AAR:
So the issue is that on the default 'bridge' bridge network, the Docker DNS does NOT keep track of container names...all other network types it will.

So the accepted solution below is to use any other network and have the containers use that network.

I created another bridge network so that I can still do testing/dev work, and my containers can find one another by name now. For production, I will have to change the network to something like a 'macvlan' type.

If you are using something like Kubernetes, then you will need a Service Discovery solution like Zookeeper or Consul.

答:
You have to define network in your docker-compose as below

```<code>networks:
  my-network:
</code>```

And then make both the containers part of the same network.

```<code>networks:
  - my-network
</code>```

And they can access other docker service port using docker service name.

EDIT 2:
Without dokcer-compose I am able to communicate 2 containers as below:

1) Created netwrok - my-netwrok

```<code>docker network create -d bridge my-network
</code>```

2) Started 2 service unders same network

```<code>docker run -d --name eureka --network=my-network eureka-service:1.0
docker run -d --name facility --network=my-network facility-service:1.0
</code>```

3) Logged in to facility container

```<code>docker exec -it facility bash
</code>```

4) pinged eureka from inside facility container

```<code>bash-4.4# ping eureka
PING eureka (172.18.0.2): 56 data bytes
64 bytes from 172.18.0.2: seq=0 ttl=64 time=0.149 ms
64 bytes from 172.18.0.2: seq=1 ttl=64 time=0.078 ms
</code>```

Body:
You have to define network in your docker-compose as below

networks:
  my-network:

And then make both the containers part of the same network.

networks:
  - my-network

And they can access other docker service port using docker service name.

EDIT 2:
Without dokcer-compose I am able to communicate 2 containers as below:

1) Created netwrok - my-netwrok

docker network create -d bridge my-network

2) Started 2 service unders same network

docker run -d --name eureka --network=my-network eureka-service:1.0
docker run -d --name facility --network=my-network facility-service:1.0

3) Logged in to facility container

docker exec -it facility bash

4) pinged eureka from inside facility container

bash-4.4# ping eureka
PING eureka (172.18.0.2): 56 data bytes
64 bytes from 172.18.0.2: seq=0 ttl=64 time=0.149 ms
64 bytes from 172.18.0.2: seq=1 ttl=64 time=0.078 ms


问:
How to add an image to an svg container using D3.js
I've created a sample Asp.Net MVC 4 application where I've used D3.js to append an SVG element and then inside the SVG I've appended a text element (see code below).  This all works fine until I try to append an img to the SVG using a local png file.  The img gets appended to the DOM, but the img is not rendered on the page.  Any ideas what I'm doing wrong here, and how to go about fixing it?

```<code>@{
    ViewBag.Title = "Home Page";
}

<script src="~/Scripts/d3.v3.js"></script>
<script type="text/javascript">
    var svg = d3.select("body")
        .append("svg")
        .attr("width", 200)
        .attr("height", 100)
        .style("border", "1px solid black");

    var text = svg.selectAll("text")
        .data([0])
        .enter()
        .append("text")
        .text("Testing")
        .attr("x", "40")
        .attr("y", "60");

    var imgs = svg.selectAll("img").data([0]);
    imgs.enter()
        .append("img")
        .attr("xlink:href", "@Url.Content("~/Content/images/icons/refresh.png")")
        .attr("x", "60")
        .attr("y", "60")
        .attr("width", "20")
        .attr("height", "20");

</script>
</code>```

@Richard Marr - Below is an attempt to do the same thing in straight HTML, which gives me the same result.  I'm not sure about my code to get the refresh.png file from the local drive this way.

```<code><!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <script src="http://d3js.org/d3.v2.js"></script>

    </head>
    <body>
        <script type="text/javascript">
            var svg = d3.select("body")
                .append("svg")
                .attr("width", 200)
                .attr("height", 100)
                .style("border", "1px solid black");

            var text = svg.selectAll("text")
                .data([0])
                .enter()
                .append("text")
                .text("Testing")
                .attr("x", "40")
                .attr("y", "60");

            var imgs = svg.selectAll("img").data([0]);
                imgs.enter()
                .append("svg:img")
                .attr("xlink:href", "file:///D:/d3js_projects/refresh.png")
                .attr("x", "60")
                .attr("y", "60")
                .attr("width", "20")
                .attr("height", "20");

        </script>
    </body>
</html>
</code>```

答:
I do not know why, but the image should not be duplicated, tripled, etc ... should remove the previous one and load it again but with another rotation data. This is my code:

data.csv
enter image description here

```<code>d3.csv("data/data.csv").then(function(data){
//console.log(data);
// Clean data
formattedData = data.map(function(id){
id.rot_1 = +id.rot_1;
        id.trans_1 = +id.trans_1;
        return id;
});
// First run of the visualization
update(formattedData[0]);})

$("#play-button")
.on("click", function(){
    var button = $(this);
    if (button.text() == "Play"){
        button.text("Pause");
        interval = setInterval(step, 1000);
    }
    else {
        button.text("Play");
        clearInterval(interval);
    }})

function step(){
// At the end of our data, loop back
time = (time < 76) ? time+1 : 0
update(formattedData[time]); }

function update(data) {
// Standard transition time for the visualization
var t = d3.transition()
    .duration(1000);

//console.log(d3.selectAll(data));
//console.log(data)

// original
var imgs1 = g.append("image") // en vez de g es svg
.attr("xlink:href", "img/picturetest.png");

// EXIT old elements not present in new data.
imgs1.exit()
    .attr("class", "exit")
    .selectAll("svg:image")
    .remove();

//console.log(data)

// ENTER new elements present in new data.
imgs1.enter()
    .append("svg:image") // svg:image
    //.attr("xlink:href", "img/picturetest.png")
    .attr("class", "enter")
    .merge(imgs1)
    .transition(t)
        .attr("x", 0) // 150
        .attr("y", 0) // 80
        .attr("width", 200)
        .attr("height", 200)
        .attr("transform", "rotate("+data.rot_1+") translate("+data.trans_1+")" ); }`
</code>```

Body:
I've created a sample Asp.Net MVC 4 application where I've used D3.js to append an SVG element and then inside the SVG I've appended a text element (see code below).  This all works fine until I try to append an img to the SVG using a local png file.  The img gets appended to the DOM, but the img is not rendered on the page.  Any ideas what I'm doing wrong here, and how to go about fixing it?

@{
    ViewBag.Title = "Home Page";
}

@Richard Marr - Below is an attempt to do the same thing in straight HTML, which gives me the same result.  I'm not sure about my code to get the refresh.png file from the local drive this way.

<!DOCTYPE html>

        <meta charset="utf-8">

Body:
I do not know why, but the image should not be duplicated, tripled, etc ... should remove the previous one and load it again but with another rotation data. This is my code:

data.csv
enter image description here

d3.csv("data/data.csv").then(function(data){
//console.log(data);
// Clean data
formattedData = data.map(function(id){
id.rot_1 = +id.rot_1;
        id.trans_1 = +id.trans_1;
        return id;
});
// First run of the visualization
update(formattedData[0]);})

$("#play-button")
.on("click", function(){
    var button = $(this);
    if (button.text() == "Play"){
        button.text("Pause");
        interval = setInterval(step, 1000);
    }
    else {
        button.text("Play");
        clearInterval(interval);
    }})

function step(){
// At the end of our data, loop back
time = (time < 76) ? time+1 : 0
update(formattedData[time]); }

function update(data) {
// Standard transition time for the visualization
var t = d3.transition()
    .duration(1000);

//console.log(d3.selectAll(data));
//console.log(data)

// original
var imgs1 = g.append("image") // en vez de g es svg
.attr("xlink:href", "img/picturetest.png");

// EXIT old elements not present in new data.
imgs1.exit()
    .attr("class", "exit")
    .selectAll("svg:image")
    .remove();

//console.log(data)

// ENTER new elements present in new data.
imgs1.enter()
    .append("svg:image") // svg:image
    //.attr("xlink:href", "img/picturetest.png")
    .attr("class", "enter")
    .merge(imgs1)
    .transition(t)
        .attr("x", 0) // 150
        .attr("y", 0) // 80
        .attr("width", 200)
        .attr("height", 200)
        .attr("transform", "rotate("+data.rot_1+") translate("+data.trans_1+")" ); }`


问:
React Native upload to S3 with presigned URL
Been trying with no luck to upload an image to S3 from React Native using pre-signed url.  Here is my code:

generate pre-signed url in node:

```<code>const s3 = new aws.S3();

const s3Params = {
  Bucket: bucket,
  Key: fileName,
  Expires: 60,
  ContentType: 'image/jpeg',
  ACL: 'public-read'
};

return s3.getSignedUrl('putObject', s3Params);
</code>```

here is RN request to S3:

```<code>var file = {
  uri: game.pictureToSubmitUri,
  type: 'image/jpeg',
  name: 'image.jpg',
};

const xhr = new XMLHttpRequest();
var body = new FormData();
body.append('file', file);
xhr.open('PUT', signedRequest);
xhr.onreadystatechange = () => {
  if(xhr.readyState === 4){
    if(xhr.status === 200){
      alert('Posted!');
    }
    else{
      alert('Could not upload file.');
   }
 }
};
xhr.send(body);
</code>```

game.pictureToSubmitUri = assets-library://asset/asset.JPG?id=A282A2C5-31C8-489F-9652-7D3BD5A1FAA4&ext=JPG

signedRequest = https://my-bucket.s3-us-west-1.amazonaws.com/8bd2d4b9-3206-4bff-944d-e06f872d8be3?AWSAccessKeyId=AKIAIOLHQY4GAXN26FOQ&Content-Type=image%2Fjpeg&Expires=1465671117&Signature=bkQIp5lgzuYrt2vyl7rqpCXPcps%3D&x-amz-acl=public-read

Error message:

```<code><Code>SignatureDoesNotMatch</Code>
<Message>
The request signature we calculated does not match the signature you provided. Check your key and signing method.
</Message>
</code>```

I can successfully curl and image to S3 using the generated url, and I seem to be able to successfully post to requestb.in from RN (however I can only see the raw data on requestb.in so not 100% sure the image is properly there).

Based on all this, I've narrowed my issue down to 1) my image is not correctly uploading period, or 2) somehow the way S3 wants my request is different then how it is coming in.

Any help would be muuuuuucchhhh appreciated!

UPDATE

Can successfully post from RN to S3 if body is just text ({'data': 'foo'}).  Perhaps AWS does not like mutliform data?  How can I send as just a file in RN???

答:
sorry if none worked for any body. took me 5 days to get this to work . 5 crazy days of no result until my sleepy eyes turned green after little nap. Guess i had a sweet dream that brought the idea. so quickly say u have an end point on ur server to generate the sign url for the request from react native end or from react side or any web frontier. i would be doing this for both react native and react(can serve for html pages and angular pages).

WEB APPROACH

UPLOAD IMAGE TO S3 BUCKET PRESIGNED URI

```<code>/*
      Function to carry out the actual PUT request to S3 using the signed request from the app.
    */
    function uploadFile(file, signedRequest, url){
     // document.getElementById('preview').src = url; // THE PREVIEW PORTION
        //    document.getElementById('avatar-url').value = url; //
      const xhr = new XMLHttpRequest();
      xhr.open('PUT', signedRequest);
      xhr.onreadystatechange = () => {
        if(xhr.readyState === 4){
          if(xhr.status === 200){
            document.getElementById('preview').src = url;
           // document.getElementById('avatar-url').value = url;
          }
          else{
            alert('Could not upload file.');
          }
        }
      };
      xhr.send(file);
    }

    /*
      Function to get the temporary signed request from the app.
      If request successful, continue to upload the file using this signed
      request.
    */
    function getSignedRequest(file){
      const xhr = new XMLHttpRequest();

      xhr.open('GET', 'http://localhost:1234'+`/sign-s3?file-name=${file.name}&file-type=${file.type}`);
        xhr.setRequestHeader('Access-Control-Allow-Headers', '*');
    xhr.setRequestHeader('Content-type', 'application/json');
    xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
      xhr.onreadystatechange = () => {
        if(xhr.readyState === 4){
          if(xhr.status === 200){
            const response = JSON.parse(xhr.responseText);
            uploadFile(file, response.signedRequest, response.url);
          }
          else{
            alert('Could not get signed URL.');
          }
        }
      };
      xhr.send();
    }

    /*
     Function called when file input updated. If there is a file selected, then
     start upload procedure by asking for a signed request from the app.
    */
    function initUpload(){
      const files = document.getElementById('file-input').files;
      const file = files[0];
      if(file == null){
        return alert('No file selected.');
      }
      getSignedRequest(file);
    }

    /*
     Bind listeners when the page loads.
    */

   //check if user is actually on the profile page
//just ensure that the id profile page exist  on your html
  if (document.getElementById('profile-page')) {
    document.addEventListener('DOMContentLoaded',() => {

      ///here is ur upload trigger bttn effect

        document.getElementById('file-input').onchange = initUpload;
    });

  }

</code>```

Body:
Been trying with no luck to upload an image to S3 from React Native using pre-signed url.  Here is my code:

generate pre-signed url in node:

const s3 = new aws.S3();

const s3Params = {
  Bucket: bucket,
  Key: fileName,
  Expires: 60,
  ContentType: 'image/jpeg',
  ACL: 'public-read'
};

return s3.getSignedUrl('putObject', s3Params);

here is RN request to S3:

var file = {
  uri: game.pictureToSubmitUri,
  type: 'image/jpeg',
  name: 'image.jpg',
};

const xhr = new XMLHttpRequest();
var body = new FormData();
body.append('file', file);
xhr.open('PUT', signedRequest);
xhr.onreadystatechange = () => {
  if(xhr.readyState === 4){
    if(xhr.status === 200){
      alert('Posted!');
    }
    else{
      alert('Could not upload file.');
   }
 }
};
xhr.send(body);

game.pictureToSubmitUri = assets-library://asset/asset.JPG?id=A282A2C5-31C8-489F-9652-7D3BD5A1FAA4&ext=JPG

signedRequest = https://my-bucket.s3-us-west-1.amazonaws.com/8bd2d4b9-3206-4bff-944d-e06f872d8be3?AWSAccessKeyId=AKIAIOLHQY4GAXN26FOQ&Content-Type=image%2Fjpeg&Expires=1465671117&Signature=bkQIp5lgzuYrt2vyl7rqpCXPcps%3D&x-amz-acl=public-read

Error message:

SignatureDoesNotMatch
<Message>
The request signature we calculated does not match the signature you provided. Check your key and signing method.
</Message>

I can successfully curl and image to S3 using the generated url, and I seem to be able to successfully post to requestb.in from RN (however I can only see the raw data on requestb.in so not 100% sure the image is properly there).

Based on all this, I've narrowed my issue down to 1) my image is not correctly uploading period, or 2) somehow the way S3 wants my request is different then how it is coming in.

Any help would be muuuuuucchhhh appreciated!

UPDATE

Can successfully post from RN to S3 if body is just text ({'data': 'foo'}).  Perhaps AWS does not like mutliform data?  How can I send as just a file in RN???

Body:
sorry if none worked for any body. took me 5 days to get this to work . 5 crazy days of no result until my sleepy eyes turned green after little nap. Guess i had a sweet dream that brought the idea. so quickly say u have an end point on ur server to generate the sign url for the request from react native end or from react side or any web frontier. i would be doing this for both react native and react(can serve for html pages and angular pages).

WEB APPROACH

UPLOAD IMAGE TO S3 BUCKET PRESIGNED URI

/*
      Function to carry out the actual PUT request to S3 using the signed request from the app.
    */
    function uploadFile(file, signedRequest, url){
     // document.getElementById('preview').src = url; // THE PREVIEW PORTION
        //    document.getElementById('avatar-url').value = url; //
      const xhr = new XMLHttpRequest();
      xhr.open('PUT', signedRequest);
      xhr.onreadystatechange = () => {
        if(xhr.readyState === 4){
          if(xhr.status === 200){
            document.getElementById('preview').src = url;
           // document.getElementById('avatar-url').value = url;
          }
          else{
            alert('Could not upload file.');
          }
        }
      };
      xhr.send(file);
    }

    /*
      Function to get the temporary signed request from the app.
      If request successful, continue to upload the file using this signed
      request.
    */
    function getSignedRequest(file){
      const xhr = new XMLHttpRequest();

      xhr.open('GET', 'http://localhost:1234'+`/sign-s3?file-name=${file.name}&file-type=${file.type}`);
        xhr.setRequestHeader('Access-Control-Allow-Headers', '*');
    xhr.setRequestHeader('Content-type', 'application/json');
    xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
      xhr.onreadystatechange = () => {
        if(xhr.readyState === 4){
          if(xhr.status === 200){
            const response = JSON.parse(xhr.responseText);
            uploadFile(file, response.signedRequest, response.url);
          }
          else{
            alert('Could not get signed URL.');
          }
        }
      };
      xhr.send();
    }

    /*
     Function called when file input updated. If there is a file selected, then
     start upload procedure by asking for a signed request from the app.
    */
    function initUpload(){
      const files = document.getElementById('file-input').files;
      const file = files[0];
      if(file == null){
        return alert('No file selected.');
      }
      getSignedRequest(file);
    }

    /*
     Bind listeners when the page loads.
    */

   //check if user is actually on the profile page
//just ensure that the id profile page exist  on your html
  if (document.getElementById('profile-page')) {
    document.addEventListener('DOMContentLoaded',() => {

      ///here is ur upload trigger bttn effect

        document.getElementById('file-input').onchange = initUpload;
    });

  }


问:
Submit POST data from controller to another website in Rails

User submits a form with some basic data.

The data is received and treated by an action in the controller and more information that needs to remain private is added.

Then I need to send a post request to an external website with all of the combined data from the controller.

What is the best way to do this?

答:
If you want to send JSON, all you need is something like the following (tested in Rails 6):

Net::HTTP.post(
  URI('https://example.com/some/path'),
  { "this is the": "request body" }.to_json,
  'Content-Type' => 'application/json'
)
```


问:
How to install the R package movMF for use with rpy2?
I'm doing a multispectral clustering project and I am trying to import the R package movMF into python using rpy2. However, I cannot get conda to install the package. I've tried each of the below.

conda install -c r-movMF

conda install -f r-movMF

and,

```<code>conda skeleton cran movMF
conda-build r-movMF
conda install --use-local r-movMF
</code>```

however I always get the error:

```<code>PackagesNotFoundError: The following packages are not available from current channels:

- r-movmf

Current channels:

- file:///C:/Users/Everett/anaconda3/conda-bld/win-64
- file:///C:/Users/Everett/anaconda3/conda-bld/noarch
- https://conda.anaconda.org/r/win-64
- https://conda.anaconda.org/r/noarch
- https://repo.anaconda.com/pkgs/main/win-64
- https://repo.anaconda.com/pkgs/main/noarch
- https://repo.anaconda.com/pkgs/r/win-64
- https://repo.anaconda.com/pkgs/r/noarch
- https://repo.anaconda.com/pkgs/msys2/win-64
- https://repo.anaconda.com/pkgs/msys2/noarch

To search for alternate channels that may provide the conda package you're
looking for, navigate to

https://anaconda.org

and use the search bar at the top of the page.
</code>```

Searching anaconda.org pulls up nothing. How can I get this package installed so that I can import it using rpy2.

Solution:
I found a solution here: https://stackoverflow.com/a/55300553/6604617

In anaconda prompt enter this:

R --slave -e "install.packages('movMF', repos='http://cran.us.r-project.org')"

I'm not sure why this works so anyone who does please post an explanation. Thank you in advance!

答:
conda/anaconda makes packages for various bits of software available, among which a list of R packages curated by the maintainers of the conda/anaconda repositories.

However, that list does not cover all of the thousands of R packages in existence. Running R's install.packages() will let you install packages for R's own central package archive.

Body:
I'm doing a multispectral clustering project and I am trying to import the R package movMF into python using rpy2. However, I cannot get conda to install the package. I've tried each of the below.

conda install -c r-movMF

conda install -f r-movMF

and,

conda skeleton cran movMF
conda-build r-movMF
conda install --use-local r-movMF

however I always get the error:

PackagesNotFoundError: The following packages are not available from current channels:

- r-movmf

Current channels:

- file:///C:/Users/Everett/anaconda3/conda-bld/win-64
- file:///C:/Users/Everett/anaconda3/conda-bld/noarch
- https://conda.anaconda.org/r/win-64
- https://conda.anaconda.org/r/noarch
- https://repo.anaconda.com/pkgs/main/win-64
- https://repo.anaconda.com/pkgs/main/noarch
- https://repo.anaconda.com/pkgs/r/win-64
- https://repo.anaconda.com/pkgs/r/noarch
- https://repo.anaconda.com/pkgs/msys2/win-64
- https://repo.anaconda.com/pkgs/msys2/noarch

To search for alternate channels that may provide the conda package you're
looking for, navigate to

https://anaconda.org

and use the search bar at the top of the page.

Searching anaconda.org pulls up nothing. How can I get this package installed so that I can import it using rpy2.

Solution:
I found a solution here: https://stackoverflow.com/a/55300553/6604617

In anaconda prompt enter this:

R --slave -e "install.packages('movMF', repos='http://cran.us.r-project.org')"

I'm not sure why this works so anyone who does please post an explanation. Thank you in advance!


问:
How to write a python program to find the second most repeated word in a given string
I have the string as Welcome to Datacurators.tech and i need to find out second most repeated character in the given string. I need to use only basic python code ( not to use import or def functions). i have the below code but it gives me count of all the characters. Expected output ( e,c,o,a) output could be in any order.

```<code>stri = "Welcome to Datacurators.tech"
counts={}
for i in stri:
    counts[i]=stri.count(i)
print (counts)
</code>```

答:
you can add this block to your code:

```<code>second_max = sorted(set(counts.values()))[-2]
# the above line fails if the string length is less than 2 or the unique character count is less than 2, so you need to check for that
seconds = [k for k in counts if counts[k] == second_max]
print(seconds)
</code>```

Also, notice that for each character in stri a stri.count() is called which is O(n).
So that means with your algorithm the time complexity is O(n^2) (where n is the string size).

You can do this in O(nlogn):

```<code>stri = "Welcome to Datacurators.tech"
counts={x:0 for x in stri}
for i in stri:
    counts[i] += 1

# then just add the same block from above.
</code>```

As @Pynchia mentioned defaultdict or Counter would be the way to go, but you wanted no imports.

Note: You can do better than O(nlogn).

Body:
I have the string as Welcome to Datacurators.tech and i need to find out second most repeated character in the given string. I need to use only basic python code ( not to use import or def functions). i have the below code but it gives me count of all the characters. Expected output ( e,c,o,a) output could be in any order.

stri = "Welcome to Datacurators.tech"
counts={}
for i in stri:
    counts[i]=stri.count(i)
print (counts)

Body:
you can add this block to your code:

second_max = sorted(set(counts.values()))[-2]
# the above line fails if the string length is less than 2 or the unique character count is less than 2, so you need to check for that
seconds = [k for k in counts if counts[k] == second_max]
print(seconds)

Also, notice that for each character in stri a stri.count() is called which is O(n).
So that means with your algorithm the time complexity is O(n^2) (where n is the string size).

You can do this in O(nlogn):

stri = "Welcome to Datacurators.tech"
counts={x:0 for x in stri}
for i in stri:
    counts[i] += 1

# then just add the same block from above.

As @Pynchia mentioned defaultdict or Counter would be the way to go, but you wanted no imports.

Note: You can do better than O(nlogn).


问:
NodeJS App Deployment Error in Heroku via Github Push
I am trying to deploy my app in Heroku server to be available in my customized domain name. Everything builds locally, but When I try to deploy in Heroku, the following error pops up. Please help.

This is my build log:

```<code>        -----> Node.js app detected

     -----> Creating runtime environment

   NPM_CONFIG_LOGLEVEL=error
   NODE_ENV=production
   NODE_MODULES_CACHE=true
   NODE_VERBOSE=false

    -----> Installing binaries
   engines.node (package.json):  unspecified
   engines.npm (package.json):   unspecified (use default)

   Resolving node version 12.x...
   Downloading and installing node 12.16.3...
   Using default npm version: 6.14.4

    -----> Restoring cache
   Cached directories were not restored due to a change in version of node, npm, yarn or stack
   Module installation may take longer for this build

   -----> Installing dependencies
   Installing node modules
   npm ERR! code EINVALIDTAGNAME
   npm ERR! Invalid tag name "[object Object]": Tags may not have any characters that encodeURIComponent encodes.

   npm ERR! A complete log of this run can be found in:
   npm ERR!     /tmp/npmcache.vvKxN/_logs/2020-05-23T20_24_41_347Z-debug.log
   -----> Build failed

   We're sorry-this build is failing! You can troubleshoot common issues here:
   https://devcenter.heroku.com/articles/troubleshooting-node-deploys

   Some possible problems:

   - Node version not specified in package.json
     https://devcenter.heroku.com/articles/nodejs-support#specifying-a-node-js-version

   Love,
   Heroku
</code>```

!     Push rejected, failed to compile Node.js app.
 !     Push failed

答:
You have possible problem 'Node version not specified in package.json'. You need to describe what version of node and npm or yarn you have using.

Why is my Node.js build failing because of an invalid semver requirement? might help.

Body:
I am trying to deploy my app in Heroku server to be available in my customized domain name. Everything builds locally, but When I try to deploy in Heroku, the following error pops up. Please help.

This is my build log:

        -----> Node.js app detected

     -----> Creating runtime environment

   NPM_CONFIG_LOGLEVEL=error
   NODE_ENV=production
   NODE_MODULES_CACHE=true
   NODE_VERBOSE=false

    -----> Installing binaries
   engines.node (package.json):  unspecified
   engines.npm (package.json):   unspecified (use default)

   Resolving node version 12.x...
   Downloading and installing node 12.16.3...
   Using default npm version: 6.14.4

    -----> Restoring cache
   Cached directories were not restored due to a change in version of node, npm, yarn or stack
   Module installation may take longer for this build

   -----> Installing dependencies
   Installing node modules
   npm ERR! code EINVALIDTAGNAME
   npm ERR! Invalid tag name "[object Object]": Tags may not have any characters that encodeURIComponent encodes.

   npm ERR! A complete log of this run can be found in:
   npm ERR!     /tmp/npmcache.vvKxN/_logs/2020-05-23T20_24_41_347Z-debug.log
   -----> Build failed

   We're sorry-this build is failing! You can troubleshoot common issues here:
   https://devcenter.heroku.com/articles/troubleshooting-node-deploys

   Some possible problems:

   - Node version not specified in package.json
     https://devcenter.heroku.com/articles/nodejs-support#specifying-a-node-js-version

   Love,
   Heroku

!     Push rejected, failed to compile Node.js app.
 !     Push failed


答:
What you are trying to accomplish is need to be done in another way. You need to set local storage when user submits the name. After that you can also call setName to update component. What you want to do in componentDidMount is get name from local storage. I edit the sandbox you provided. Also i am leaving a copy below. sandbox

```<code>import React, { useState, useEffect } from "react";
import "./styles.css";

function NameForm() {
  const [name, setName] = useState(window.localStorage.getItem("name") || "");
  useEffect(() => {
    setName(window.localStorage.getItem("name"));
    console.log(name);
  }, [name]);

  return (
    <>
      <form
        onSubmit={event => {
          event.preventDefault();
          let new_name = event.target.elements.usernameInput.value;
          window.localStorage.setItem("name", new_name);
          setName(new_name);
          return false;
        }}
      >
        <label>Enter your name</label>
        <input id="usernameInput" />
        <button type="submit"> Submit</button>
      </form>
      <h1>Hello {name}</h1>
    </>
  );
}
export default function App() {
  return (
    <div className="App">
      <NameForm />
    </div>
  );
}
</code>```

Title: Basic React: why is a variable in local storage resetting to undefined after briefly being the desired value?

Body:
I am new to React and was writing some toy code whose desired behavior is to allow a user to enter their name in the form and the page will display "Hello {user's name}" after submitting.

However, the observed behavior is that the page flickers briefly to render "Hello {user's name}" and then returns to the default rendering as if no name had been submitted.

My current approach is to save the user's name in local storage upon submission with a useEffect. However, from observing console logs, the local storage appears to be resetting the "name" variable to undefined immediately after setting it to the inputted name. Below is the code.

function NameForm() {
  const [name, setName] = useState(window.localStorage.getItem("name") || "");
  useEffect(() => {
    setName(window.localStorage.setItem("name", name));
    console.log(name);
  }, [name]);
  return (
    <>
      <form
        onSubmit={event => {
          event.preventDefault();
          setName(event.target.elements.usernameInput.value);
          return false;
        }}
      >
        Enter your name
        <input id="usernameInput" />
        <button type="submit"> Submit</button>
      </form>

Hello {name}

    </>
  );
}
export default function App() {
  return (

      <NameForm />

  );
}

Here is also the codesandbox used to run the code. https://codesandbox.io/s/modern-hill-gfkrp?file=/src/App.js:76-773

Why is this unexpected behavior occuring and how can I fix it?

Thanks!

Body:
What you are trying to accomplish is need to be done in another way. You need to set local storage when user submits the name. After that you can also call setName to update component. What you want to do in componentDidMount is get name from local storage. I edit the sandbox you provided. Also i am leaving a copy below. sandbox

import React, { useState, useEffect } from "react";
import "./styles.css";

function NameForm() {
  const [name, setName] = useState(window.localStorage.getItem("name") || "");
  useEffect(() => {
    setName(window.localStorage.getItem("name"));
    console.log(name);
  }, [name]);

  return (
    <>
      <form
        onSubmit={event => {
          event.preventDefault();
          let new_name = event.target.elements.usernameInput.value;
          window.localStorage.setItem("name", new_name);
          setName(new_name);
          return false;
        }}
      >
        <label>Enter your name</label>
        <input id="usernameInput" />
        <button type="submit"> Submit</button>
      </form>
      <h1>Hello {name}</h1>
    </>
  );
}
export default function App() {
  return (
    <div className="App">
      <NameForm />
    </div>
  );
}


问:
Can't calculate total price > 30

For the order items table, get the items for order #6 where the total price is greater than 30

```<code>USE sql_store;

{ SELECT order_id, product_id,quantity, unit_price,
quantity*unit_price AS total_price

FROM order_items
WHERE order_id = 6 AND total_price > 30

}
</code>```

ERROR CODE:

答:
put the math expression in parenthesis:</p>

```<code>SELECT order_id, product_id,quantity, unit_price, (quantity*unit_price)
FROM order_items
WHERE order_id = 6 AND (quantity*unit_price) > 30
</code>```

Title: Can't calculate total price > 30

Body:
For the order items table, get the items for order #6 where the total price is greater than 30

USE sql_store;

{ SELECT order_id, product_id,quantity, unit_price,
quantity*unit_price AS total_price

FROM order_items
WHERE order_id = 6 AND total_price > 30

}

ERROR CODE:

Body:
put the math expression in parenthesis:

SELECT order_id, product_id,quantity, unit_price, (quantity*unit_price)
FROM order_items
WHERE order_id = 6 AND (quantity*unit_price) > 30


问:
Complementary Encryption & Decryption functions between Oracle and .Net
I'm looking for code that encrypts a string in Oracle PL/SQL using DBMS_CRYPTO and its matching decryption code in .Net framework. Both will need to use the same Key, IV and padding mode (where necessary). I'm not very verse in cryptography algorithms but if someone can provide the exact code for both sides i'd be very grateful... thanks!

My colleague is using the following code to encrypt a text "Test1234", the result of which is: 54AA98D8DE586F346E54B179AB71C6D7

```<code>G_CHARACTER_SET VARCHAR2(10) := 'AL32UTF8';

G_STRING VARCHAR2(32) := '12345678901234567890123456789012';

G_KEY RAW(250) := utl_i18n.string_to_raw
                  ( data => G_STRING,
                    dst_charset => G_CHARACTER_SET );

G_ENCRYPTION_TYPE PLS_INTEGER := dbms_crypto.pad_zero
                                + dbms_crypto.encrypt_aes256
                                + dbms_crypto.chain_cbc;

FUNCTION encryptSSN( p_ssn IN VARCHAR2 ) RETURN RAW
IS

l_ssn RAW(32) := UTL_I18N.STRING_TO_RAW( p_ssn, G_CHARACTER_SET );

l_encrypted RAW(32);

BEGIN

l_encrypted := dbms_crypto.encrypt
               ( src => l_ssn,
                 typ => G_ENCRYPTION_TYPE,
                 key => G_KEY );

RETURN l_encrypted;

END encrypt_ssn;
</code>```

In my .Net code, i tried this as a complementary function to encrypt the same way, but it gives me a totally different result!

```<code>public static string EncryptAES(string text)
    {
        AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
        aes.Key = Encoding.UTF8.GetBytes("12345678901234567890123456789012");
        aes.IV = Encoding.UTF8.GetBytes("0123456789ABCDEF"); // Oracle's Default IV
        aes.Mode = CipherMode.CBC;
        aes.Padding = PaddingMode.Zeros;

        // Convert string to byte array
        byte[] src = Encoding.UTF8.GetBytes(text);

        // encryption
        using (ICryptoTransform encrypt = aes.CreateEncryptor())
        {
            byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);

            // Convert byte array to Base64 strings
            return Convert.ToBase64String(dest);
        }
    }
</code>```

答:
Oracle's default IV is NULL according to: https://docs.oracle.com/cd/B28359_01/appdev.111/b28419/d_crypto.htm#i1002112

.NET will not allow a NULL IV, so change the mode to ECB.

Modifying your code to the below returns the value expected as per your question:

```<code>public static string EncryptAES(string text)
        {
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            aes.Key = Encoding.UTF8.GetBytes("12345678901234567890123456789012");
            //aes.IV = Encoding.UTF8.GetBytes("0123456789ABCDEF"); - Remove
            aes.Mode = CipherMode.ECB; // Change mode to ECB
            aes.Padding = PaddingMode.Zeros;

            // Convert string to byte array
            byte[] src = Encoding.UTF8.GetBytes(text);

            // encryption
            using (ICryptoTransform encrypt = aes.CreateEncryptor())
            {
                byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);

                StringBuilder hex = new StringBuilder(dest.Length * 2);
                foreach (byte b in dest)
                    hex.AppendFormat("{0:x2}", b);
                Console.WriteLine(hex);

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

Body:
I'm looking for code that encrypts a string in Oracle PL/SQL using DBMS_CRYPTO and its matching decryption code in .Net framework. Both will need to use the same Key, IV and padding mode (where necessary). I'm not very verse in cryptography algorithms but if someone can provide the exact code for both sides i'd be very grateful... thanks!

My colleague is using the following code to encrypt a text "Test1234", the result of which is: 54AA98D8DE586F346E54B179AB71C6D7

G_CHARACTER_SET VARCHAR2(10) := 'AL32UTF8';

G_STRING VARCHAR2(32) := '12345678901234567890123456789012';

G_KEY RAW(250) := utl_i18n.string_to_raw
                  ( data => G_STRING,
                    dst_charset => G_CHARACTER_SET );

G_ENCRYPTION_TYPE PLS_INTEGER := dbms_crypto.pad_zero
                                + dbms_crypto.encrypt_aes256
                                + dbms_crypto.chain_cbc;

FUNCTION encryptSSN( p_ssn IN VARCHAR2 ) RETURN RAW
IS

l_ssn RAW(32) := UTL_I18N.STRING_TO_RAW( p_ssn, G_CHARACTER_SET );

l_encrypted RAW(32);

BEGIN

l_encrypted := dbms_crypto.encrypt
               ( src => l_ssn,
                 typ => G_ENCRYPTION_TYPE,
                 key => G_KEY );

RETURN l_encrypted;

END encrypt_ssn;

In my .Net code, i tried this as a complementary function to encrypt the same way, but it gives me a totally different result!

public static string EncryptAES(string text)
    {
        AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
        aes.Key = Encoding.UTF8.GetBytes("12345678901234567890123456789012");
        aes.IV = Encoding.UTF8.GetBytes("0123456789ABCDEF"); // Oracle's Default IV
        aes.Mode = CipherMode.CBC;
        aes.Padding = PaddingMode.Zeros;

        // Convert string to byte array
        byte[] src = Encoding.UTF8.GetBytes(text);

        // encryption
        using (ICryptoTransform encrypt = aes.CreateEncryptor())
        {
            byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);

            // Convert byte array to Base64 strings
            return Convert.ToBase64String(dest);
        }
    }

Body:
Oracle's default IV is NULL according to: https://docs.oracle.com/cd/B28359_01/appdev.111/b28419/d_crypto.htm#i1002112

.NET will not allow a NULL IV, so change the mode to ECB.

Modifying your code to the below returns the value expected as per your question:

public static string EncryptAES(string text)
        {
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            aes.Key = Encoding.UTF8.GetBytes("12345678901234567890123456789012");
            //aes.IV = Encoding.UTF8.GetBytes("0123456789ABCDEF"); - Remove
            aes.Mode = CipherMode.ECB; // Change mode to ECB
            aes.Padding = PaddingMode.Zeros;

            // Convert string to byte array
            byte[] src = Encoding.UTF8.GetBytes(text);

            // encryption
            using (ICryptoTransform encrypt = aes.CreateEncryptor())
            {
                byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);

                StringBuilder hex = new StringBuilder(dest.Length * 2);
                foreach (byte b in dest)
                    hex.AppendFormat("{0:x2}", b);
                Console.WriteLine(hex);

                return hex.ToString() ;
            }
        }


问:
Visual Studio 2019 Exports C# Program as DLL instead of EXE?
I am very confused because I created a new project in Visual Studio 2019. I have tried this three separate times with different projects, and each time it exports as a DLL instead of an EXE. Here are the steps to reproduce this problem:

New project

Console App (.NET Core)

Set details for new project, and hit the "Create" button

Add Microsoft.Win32.Registry NuGet package to project

Add the following code:

```<code>using Microsoft.Win32;
using System;

namespace Key_Statistics_Startup_Changer {
    class Program {
        static void Main(string[] args) {
            if (args[0] == "CREATE_STARTUP") {
                RegistryKey rkey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                rkey.SetValue("Key Statistics", @"C:\Program Files\Key Statistics\Key Statistics.exe");
            }
            else if (args[0] == "REMOVE_STARTUP") {
                RegistryKey rkey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                rkey.DeleteValue("Key Statistics");
            }
        }
    }
}
</code>```

Build and run project

When I do this, the program does create or remove the desired registry from startup (what the code is trying to accomplish), when I input arguments through Visual Studio. However, when this project is built, my Key Statistics Startup Changer\bin\Debug folder gives me a sub-directory netcoreapp2.1 with the following files:

Key Statistics Startup Changer.deps.json

  Key Statistics Startup Changer.dll

  Key Statistics Startup Changer.pdb

  Key Statistics Startup Changer.runtimeconfig.dev.json

  Key Statistics Startup Changer.runtimeconfig.json

I am positive that I have the right folder where it would export, and every time I re-create the steps (making sure I don't select C# DLL project), this happens.

What's the deal here?

答: Right click on the project and go to properties. Choose the Application tab and, on the right side, you have an option called Output Type. You can choose whatever you want; for example, if you want your project to emit a DLL, just choose Class Library.

Body:
I am very confused because I created a new project in Visual Studio 2019. I have tried this three separate times with different projects, and each time it exports as a DLL instead of an EXE. Here are the steps to reproduce this problem:

New project

Console App (.NET Core)

Set details for new project, and hit the "Create" button

Add Microsoft.Win32.Registry NuGet package to project

Add the following code:

using Microsoft.Win32;
using System;

namespace Key_Statistics_Startup_Changer {
    class Program {
        static void Main(string[] args) {
            if (args[0] == "CREATE_STARTUP") {
                RegistryKey rkey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                rkey.SetValue("Key Statistics", @"C:\Program Files\Key Statistics\Key Statistics.exe");
            }
            else if (args[0] == "REMOVE_STARTUP") {
                RegistryKey rkey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
                rkey.DeleteValue("Key Statistics");
            }
        }
    }
}

Build and run project

When I do this, the program does create or remove the desired registry from startup (what the code is trying to accomplish), when I input arguments through Visual Studio. However, when this project is built, my Key Statistics Startup Changer\bin\Debug folder gives me a sub-directory netcoreapp2.1 with the following files:

Key Statistics Startup Changer.deps.json

  Key Statistics Startup Changer.dll

  Key Statistics Startup Changer.pdb

  Key Statistics Startup Changer.runtimeconfig.dev.json

  Key Statistics Startup Changer.runtimeconfig.json

I am positive that I have the right folder where it would export, and every time I re-create the steps (making sure I don't select C# DLL project), this happens.

What's the deal here?


问:
Simple java lib for text templating?
I need to template some email texts. Nothing fancy, just replace something like @name@ with real value. No pictures, no fancy formatting etc.

What java lib could you recommend? The simplier the better.

答:
StringTemplate is another option. The five-minute introduction gives some basic examples and syntax.</p>

```<code>StringTemplate hello = new StringTemplate("Hello, $name$",
                                          DefaultTemplateLexer.class);
hello.setAttribute("name", "World");
System.out.println(hello.toString());
</code>```

Title: Simple java lib for text templating?

Body:
StringTemplate is another option. The five-minute introduction gives some basic examples and syntax.

StringTemplate hello = new StringTemplate("Hello, $name$",
                                          DefaultTemplateLexer.class);
hello.setAttribute("name", "World");
System.out.println(hello.toString());