问:
Why does AtomicPtr disallow dynamically sized types?
I wanted to create an AtomicPtr to a slice but I was surprised to find out that I couldn't.

```<code>struct MyObject {
    ptr: AtomicPtr<[u32]>
}
</code>```

yields the error:

```<code>error[E0277]: the size for values of type `[u32]` cannot be known at compilation time
 --> src/lib.rs:4:5
  |
4 |     ptr: AtomicPtr<[u32]>
  |     ^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `[u32]`
  = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
  = note: required by `std::sync::atomic::AtomicPtr`
</code>```

See it on the Rust Playground

I personally can't see why this would be the case but I might be missing something. Is there a reason for this restriction? And is there a workaround for achieving the same functionality?

答:
It is intentional that AtomicPtr<T> works only with T: Sized because in rust
slices and trait objects are fat pointers (the size double respect to normal pointer).

Actually it is not possible to have T: ?Sized because this prevents the guarantee of atomic operation
for some platforms, for example ARM.

See here for more details.

Body:
I wanted to create an AtomicPtr to a slice but I was surprised to find out that I couldn't.

struct MyObject {
    ptr: AtomicPtr<[u32]>
}

yields the error:

error[E0277]: the size for values of type `[u32]` cannot be known at compilation time
 --> src/lib.rs:4:5
  |
4 |     ptr: AtomicPtr<[u32]>
  |     ^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `[u32]`
  = note: to learn more, visit <https://doc.rust-lang.org/book/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
  = note: required by `std::sync::atomic::AtomicPtr`

See it on the Rust Playground

I personally can't see why this would be the case but I might be missing something. Is there a reason for this restriction? And is there a workaround for achieving the same functionality?


来源: stackexchange

问:
Do you know of a good program for editing/translating resource (.rc) files?
I'm building a C++/MFC program in a multilingual environment. I have one main (national) language and three international languages. Every time I add a feature to the program I have to keep the international languages up-to-date with the national one. The resource editor in Visual Studio is not very helpful because I frequently end up leaving a string, dialog box, etc., untranslated.

I wonder if you guys know of a program that can edit resource (.rc) files and

Build a file that includes only the strings to be translated and their respective IDs and accepts the same (or similar) file in another language (this would be helpful since usually the translation is done by someone else), or

Handle the translations itself, allowing to view the same string in different languages at the same time.

答:
In my experience, internationalization requires a little more than translating strings. Many strings when translated, require more space on a dialog. Because of this it's useful to be able to customize the dialogs for each language. Otherwise you have to create dialogs with extra space for the translated strings which then looks less than optimal when displayed in English.

Quite a while back I was using a translation tool for an MFC application but the company that produced the software stopped selling it. When I tried to find a reasonably priced replacement I did not find one.

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: djeidot

OwnerDisplayName: jmatthias


问:
Using the g++ C++ compiler from cygwin
I am trying to execute my first "Hello World!" in C++. I am using Windows XP, and I have installed cygwin, in which the g++ C++ compiler is installed. I have written a small hello-world program, and saved it in hello.cpp. From the command prompt I write:

g++ hello.cpp

But I get:

'g++' is not recognized as an internal or external command, operable program or batch file.

I have installed cygwin in my D:\programs\cygwin. I have made another directory with my hello-world file in D:\cpp. Something with my installation or my paths seems to be not Ok, but I cannot figure what. I have run the exe file of cygwin, and in the installation directory I have got all necessary files, I think: bin folder, lib, Cygwin.bat, etc.

I have read that in case of such error message I should check whether the cygwin1.dll file is copied into the main folder of Windows. Is this the C:\WINDOWS directory? I have looked there, and I don't have such a file there. I have cygwin1.dll in the bin folder of cygwin: D:\programs\cygwin\bin.
Also, how do I check whether the bin folder (D:\programs\cygwin\bin) is considered in the search path of commands?

I think that the hello-world program shouldn't contain any syntax errors, I have just copied it. Also, when I write

g++ -v

I get the same error message: that the command is not recognized.
I would appreciate if someone give me a hint what should I look at. Thank you.

Here is the code of the hello-world program:

```<code>#include <iostream>
using namespace std;

int main() {
  cout <<"Hello World!"<<endl;
  return 0;
}
</code>```

I have installed g++, and now when I type g++ -v, I get: Reading specs from: \d\cygnus\cygwin-b20\H-i586-cygwin32\bin..\lib\gcc-lib\i586-cygwin32\egcs-2.91.57\specs gcc version egcs-2.91.57 19980901 (egcs-1.1 release)

In the bin directory I have both g++.exe, and gcc.exe. I don't understand why I get "gcc" above and not "g++". I don't know how important this is, but I receive an error message when I try to compile the program in the DOS command prompt:

g++ hello.cpp

I get:

```<code>hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
</code>```

And here is what I get when I try to compile the program in the cygwin shell:

```<code>hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
</code>```

答: Are you sure you installed g++? G++ is C++ compiler, not C compiler. If you only installed C compiler, you would have command gcc but not command g++

Title: Using the g++ C++ compiler from cygwin

Body:
I am trying to execute my first "Hello World!" in C++. I am using Windows XP, and I have installed cygwin, in which the g++ C++ compiler is installed. I have written a small hello-world program, and saved it in hello.cpp. From the command prompt I write:

g++ hello.cpp

But I get:

'g++' is not recognized as an internal or external command, operable program or batch file.

I have installed cygwin in my D:\programs\cygwin. I have made another directory with my hello-world file in D:\cpp. Something with my installation or my paths seems to be not Ok, but I cannot figure what. I have run the exe file of cygwin, and in the installation directory I have got all necessary files, I think: bin folder, lib, Cygwin.bat, etc.

I have read that in case of such error message I should check whether the cygwin1.dll file is copied into the main folder of Windows. Is this the C:\WINDOWS directory? I have looked there, and I don't have such a file there. I have cygwin1.dll in the bin folder of cygwin: D:\programs\cygwin\bin.
Also, how do I check whether the bin folder (D:\programs\cygwin\bin) is considered in the search path of commands?

I think that the hello-world program shouldn't contain any syntax errors, I have just copied it. Also, when I write

g++ -v

I get the same error message: that the command is not recognized.
I would appreciate if someone give me a hint what should I look at. Thank you.

Here is the code of the hello-world program:

#include <iostream>
using namespace std;

int main() {
  cout <<"Hello World!"<<endl;
  return 0;
}

I have installed g++, and now when I type g++ -v, I get: Reading specs from: \d\cygnus\cygwin-b20\H-i586-cygwin32\bin..\lib\gcc-lib\i586-cygwin32\egcs-2.91.57\specs gcc version egcs-2.91.57 19980901 (egcs-1.1 release)

In the bin directory I have both g++.exe, and gcc.exe. I don't understand why I get "gcc" above and not "g++". I don't know how important this is, but I receive an error message when I try to compile the program in the DOS command prompt:

g++ hello.cpp

I get:

hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)

And here is what I get when I try to compile the program in the cygwin shell:

hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files

LastEditorDisplayName: Rich B

OwnerDisplayName: Milan Babuškov


问:
How to set database login information from variable?
I am using MyBatis in a Java project. I know that database access information such as host, database name, username and password are stored in configuration.xml. But I would like to know if I can set these login information from inside my Java program.

It's because my application is accessing different databases on different addresses and I am configuring them in the application. Please help me.

答:
First write the information regarding driver,username,password in some file and read that file contents in your java application

Properties properties=new Properties();

properties.load("INPUTSTREAM");

ContentLicense: CC BY-SA 3.0


问:
Unable to use .find() to get value from table/form
Trying to wrap my head around this for a while now. Some guru needs to help me out, it would be greatly appreciated. I don't know why it is not working.

$(".form").on('submit', function(event) {
  event.preventDefault(); //prevent the forms default action
  var surname = $(this).find(".surname");
  console.log(surname);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <form class="form" method="post" action="nextpage.php">
    <tr>
      <td class="name">john</td>
      <td class="surname">smith</td>
      <td>british</td>
      <td><button type="submit" class="btn btn-info btn-sm">Submit</button></td>
    </tr>

  </form>

  <form class="form" method="post" action="nextpage.php">
    <tr>
      <td class="name">bob</td>
      <td class="surname">doe</td>
      <td>american</td>
      <td><button type="submit" class="btn btn-info btn-sm">Submit</button></td>
    </tr>
  </form>
</table></code>```

So if i click on the first submit button i should see john, and the second, bob.

答: just put the class="form" and action inside the tr tag and it'll works.</p>

ContentLicense: CC BY-SA 4.0

Body:
Trying to wrap my head around this for a while now. Some guru needs to help me out, it would be greatly appreciated. I don't know why it is not working.

$(".form").on('submit', function(event) {
  event.preventDefault(); //prevent the forms default action
  var surname = $(this).find(".surname");
  console.log(surname);
});

  <form class="form" method="post" action="nextpage.php">

      john
      smith
      british
      <button type="submit" class="btn btn-info btn-sm">Submit</button>

  </form>

  <form class="form" method="post" action="nextpage.php">

      bob
      doe
      american
      <button type="submit" class="btn btn-info btn-sm">Submit</button>

  </form>

So if i click on the first submit button i should see john, and the second, bob.


问:
How to pass the gallery image to another Statefull Screen in flutter
Here is my code:</p>

```<code>Future getImage() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);

    setState(() {
      _image = image;
      print('Image Path $_image');
    });
  }
</code>```

答:
The image returned from ImagePicker.pickImage(...) is a File object that you can pass around to other widgets, just like you would with any other object. For example, consider this snippet, where NewPage takes a File image object as a parameter:

  Future<void> navigateOnImage() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);

    Navigator.of(context)
      .push(MaterialPageRoute(builder: (_) => NewPage(image)));
  }
```

Another option may be to convert the File object to a more handy object for your use case, such as a UInt8List object, with the File.readAsBytes method. Then you can pass that around just like in the example above.

Check out this flutter.dev article for more info on passing data when navigating.

Body:
Here is my code:

Future getImage() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);

    setState(() {
      _image = image;
      print('Image Path $_image');
    });
  }

Body:
The image returned from ImagePicker.pickImage(...) is a File object that you can pass around to other widgets, just like you would with any other object. For example, consider this snippet, where NewPage takes a File image object as a parameter:

  Future<void> navigateOnImage() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);

    Navigator.of(context)
      .push(MaterialPageRoute(builder: (_) => NewPage(image)));
  }

Another option may be to convert the File object to a more handy object for your use case, such as a UInt8List object, with the File.readAsBytes method. Then you can pass that around just like in the example above.

Check out this flutter.dev article for more info on passing data when navigating.


问:
How to pass data from child component to its parent in ReactJS?
I'm trying to send data from a child component to its parent as follow:

```<code>const ParentComponent = React.createClass({
    getInitialState() {
        return {
            language: '',
        };
    },
    handleLanguageCode: function(langValue) {
        this.setState({language: langValue});
    },

    render() {
         return (
                <div className="col-sm-9" >
                    <SelectLanguage onSelectLanguage={this.handleLanguage}/>
                </div>
        );
});
</code>```

and here is the child component:

```<code>export const SelectLanguage = React.createClass({
    getInitialState: function(){
        return{
            selectedCode: '',
            selectedLanguage: '',
        };
    },

    handleLangChange: function (e) {
        var lang = this.state.selectedLanguage;
        var code = this.state.selectedCode;
        this.props.onSelectLanguage({selectedLanguage: lang});
        this.props.onSelectLanguage({selectedCode: code});
    },

    render() {
        var json = require("json!../languages.json");
        var jsonArray = json.languages;
        return (
            <div >
                <DropdownList ref='dropdown'
                    data={jsonArray}
                    value={this.state.selectedLanguage}
                    caseSensitive={false}
                    minLength={3}
                    filter='contains'
                    onChange={this.handleLangChange} />
            </div>
        );
    }
});
</code>```

What I need is to get the selected value by user in the parent component. I'm getting this error:

```<code>Uncaught TypeError: this.props.onSelectLanguage is not a function
</code>```

Can anyone help me to find the problem?

P.S. The child component is creating a dropdown from a json file, and I need the dropdown list to show both elements of the json array next to each other(like: "aaa,english" as the first choice!)

```<code>{
   "languages":[
      [
         "aaa",
         "english"
      ],
      [
         "aab",
         "swedish"
      ],
}
</code>```

答:
Considering React Function Components and using Hooks are getting more popular these days , I will give a simple example of how to Passing data from child to parent component

in Parent Function Component we will have :

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

then

```<code>const [childData, setChildData] = useState("");
</code>```

and passing setChildData (which do a job similar to this.setState in Class Components) to Child

```<code>return( <ChildComponent passChildData={setChildData} /> )
</code>```

in Child Component first we get the receiving props

```<code>function ChildComponent(props){ return (...) }
</code>```

then you can pass data anyhow like using a handler function

```<code>const functionHandler = (data) => {

props.passChildData(data);

}
</code>```

Body:
I'm trying to send data from a child component to its parent as follow:

const ParentComponent = React.createClass({
    getInitialState() {
        return {
            language: '',
        };
    },
    handleLanguageCode: function(langValue) {
        this.setState({language: langValue});
    },

    render() {
         return (

                    <SelectLanguage onSelectLanguage={this.handleLanguage}/>

        );
});

and here is the child component:

export const SelectLanguage = React.createClass({
    getInitialState: function(){
        return{
            selectedCode: '',
            selectedLanguage: '',
        };
    },

    handleLangChange: function (e) {
        var lang = this.state.selectedLanguage;
        var code = this.state.selectedCode;
        this.props.onSelectLanguage({selectedLanguage: lang});
        this.props.onSelectLanguage({selectedCode: code});
    },

    render() {
        var json = require("json!../languages.json");
        var jsonArray = json.languages;
        return (

                <DropdownList ref='dropdown'
                    data={jsonArray}
                    value={this.state.selectedLanguage}
                    caseSensitive={false}
                    minLength={3}
                    filter='contains'
                    onChange={this.handleLangChange} />

        );
    }
});

What I need is to get the selected value by user in the parent component. I'm getting this error:

Uncaught TypeError: this.props.onSelectLanguage is not a function

Can anyone help me to find the problem?

P.S. The child component is creating a dropdown from a json file, and I need the dropdown list to show both elements of the json array next to each other(like: "aaa,english" as the first choice!)

{
   "languages":[
      [
         "aaa",
         "english"
      ],
      [
         "aab",
         "swedish"
      ],
}

Body:
Considering React Function Components and using Hooks are getting more popular these days , I will give a simple example of how to Passing data from child to parent component

in Parent Function Component we will have :

import React, { useState } from "react";

then

const [childData, setChildData] = useState("");

and passing setChildData (which do a job similar to this.setState in Class Components) to Child

return( <ChildComponent passChildData={setChildData} /> )

in Child Component first we get the receiving props

function ChildComponent(props){ return (...) }

then you can pass data anyhow like using a handler function

const functionHandler = (data) => {

props.passChildData(data);

}


问:
i have 3 text boxes for Day , Month and Year .From this need to calculate a date
I have 3 textboxes for Day, Month and Year. From this need to calculate a date. And need subtraction functionality also ( Calculation on Current date)

Eg: Current date = 20-02-2020 , Day -1 and Month - 1 and Year = 1 then the result = 21-03-2021

答:
Do you need to only substract or add too? What is the format of your text boxes?

There are several ways of doing this, depending on your input. One example:

```<code>var yourDate = DateTime.Now.AddDays(TextBox1).AddMonths(TextBox2).AddYears(TextBox3);
</code>```

Or you can substract two DateTimes from each other.

Body:
Do you need to only substract or add too? What is the format of your text boxes?

There are several ways of doing this, depending on your input. One example:

var yourDate = DateTime.Now.AddDays(TextBox1).AddMonths(TextBox2).AddYears(TextBox3);

Or you can substract two DateTimes from each other.


问:
Dynamics CRM 8.2 - Outlook 365 - Hyperlink not recognized
When clicking on "Email a link" from a Dynamics CRM form, Outlook opens with the link, but this link is not recognized as hyperlink, so not clickable.

Did you also experience this problem?

答:
When I click "Email a Link" it does open my outlook and gives result as below

```<code>Account Name

<https://crm.abc.com/Dev/main.aspx?etc=1&extraqs=formid%3d11933125-02ea-4830-90cd-4ba00df70b6a&id=%7bB6B35FD0-B9C3-E311-88E2-00505693000C%7d&pagetype=entityrecord>
</code>```

Which is the expected and correct behavior.

Body:
When I click "Email a Link" it does open my outlook and gives result as below

Account Name

<https://crm.abc.com/Dev/main.aspx?etc=1&extraqs=formid%3d11933125-02ea-4830-90cd-4ba00df70b6a&id=%7bB6B35FD0-B9C3-E311-88E2-00505693000C%7d&pagetype=entityrecord>

Which is the expected and correct behavior.


答:
First convert list of dictionaries to DataFrame, then get YY-MM format of datetimes:

```<code>df = pd.DataFrame(a)
g = pd.to_datetime(df['time']).dt.strftime('%Y-%m')
</code>```

And in dict comprehension create dictionary of lists:

```<code>d1 = {k: v.to_dict('r') for k, v in df.groupby(g)}
</code>```

Another solution if performance is important: with collections.defaultdict:

```<code>from collections import defaultdict

d = defaultdict(list)
for x in a:
    d[x['time'][:7]].append(x)
d = dict(d)
</code>```

Title: pandas group by day or week or month

Body:
I'm a pandas beginner.

I have the following data:

a = [
    {"content": '1', "time": '2020-01-01'}, {"content": '4', "time": '2020-01-01'},
    {"content": '2', "time": '2020-01-02'},
    {"content": '3', "time": '2020-02-01'}, {"content": '4', "time": '2020-02-02'},
    {"content": '5', "time": '2020-03-01'}, {"content": '6', "time": '2020-03-02'}
]

And I want:

2020-01: [{"content": '1', "time": '2020-01-01'},{"content": '4', "time": '2020-01-01'},
     {"content": '2', "time": '2020-01-02'},]

2020-02: [{"content": '3', "time": '2020-02-01'}, {"content": '4', "time": '2020-02-02'},]

2020-03: [{"content": '5', "time": '2020-03-01'}, {"content": '6', "time": '2020-03-02'}]

Body:
First convert list of dictionaries to DataFrame, then get YY-MM format of datetimes:

df = pd.DataFrame(a)
g = pd.to_datetime(df['time']).dt.strftime('%Y-%m')

And in dict comprehension create dictionary of lists:

d1 = {k: v.to_dict('r') for k, v in df.groupby(g)}

Another solution if performance is important: with collections.defaultdict:

from collections import defaultdict

d = defaultdict(list)
for x in a:
    d[x['time'][:7]].append(x)
d = dict(d)


问:
Spring integration inbound-gateway Fire an event when queue is empty
I'm a newbie around but I'll try to be consice.

```
{INPUT QUEUE}->[INBOUND-GATEWAY-1]-->[ROUTER]----------->(ACTIVATOR)<---------------
                                        \                                          /
                                         \-->{HOLD QUEUE}--->[INBOUND-GATEWAY-2]--^
```

I'm having an scenario in which I have to dynamically change routing conditions in a flow like the former. Messages comming from a queue are sent to an activator to be processed, or another queue to be put on hold. At certain time, I have to close INBOUND-GATEWAY-1 so no new messages come into the flow, and open INBOUND-GATEWAY-2 to let all messages from HOLD QUEUE be processed. Once all messages from HOLD QUEUE were been consumed, both gateways must me closed/opened as they were before. The thing here is how could I know when HOLD QUEUE is empty so I could trigger a method in which gateway-1 could be started?

I'd be grateful if somebody could help me.

Thanks in advance

答:
I would put this functionality into the inbound gateway processors. For example:

Gateway1Processor:

start(): Start consumer off the main
queue and process.

stop(): Stop consumer.

Gateway2Processor:

start(): Start consumer off the HOLD queue. Specify an appropriate timeout. When timeout is fired, (the HOLD queue is empty) call stop().

stop(): Start Gateway1Processor and stop this consumer.

Therefore, the operating sequence would be:

Start Gateway1Processor

At a certain time, call Gateway1Processor.stop() and Gateway2Processor.start()

Gateway2Processor will drain the HOLD queue, restart Gateway1Processor and then stop.

Go To #2.

Body:
I'm a newbie around but I'll try to be consice.

{INPUT QUEUE}->[INBOUND-GATEWAY-1]-->[ROUTER]----------->(ACTIVATOR)<---------------
                                        \                                          /
                                         \-->{HOLD QUEUE}--->[INBOUND-GATEWAY-2]--^

I'm having an scenario in which I have to dynamically change routing conditions in a flow like the former. Messages comming from a queue are sent to an activator to be processed, or another queue to be put on hold. At certain time, I have to close INBOUND-GATEWAY-1 so no new messages come into the flow, and open INBOUND-GATEWAY-2 to let all messages from HOLD QUEUE be processed. Once all messages from HOLD QUEUE were been consumed, both gateways must me closed/opened as they were before. The thing here is how could I know when HOLD QUEUE is empty so I could trigger a method in which gateway-1 could be started?

I'd be grateful if somebody could help me.

Thanks in advance


问:
How to implement a triggerless .NET Core Console App as a continuous Azure WebJob?
All the code samples I've seen so far for Azure WebJobs rely on some kind of trigger (e.g. TimerTrigger or QueueTrigger).
I am looking specifically at WebJobs SDK 3.x, by the way.

So. For a triggerless WebJob (Windows Service-alike one), am I expected to use NoAutomaticTrigger and find a way to kickoff my "main" code manually?

Or should I resort to implementing and registering a class that implements the IHostedService interface?
So far that's the approach I'm taking but it feels more of a hack than a recommended way.
I have not even tried to deploy this code and only ran it on my local machine, so I am afraid that the publishing process will confirm my code is not suitable for Azure WebJobs in its current form.

EntryPoint.cs

This is how the application is being bootstrap when the process is starting.

using Microsoft.Azure.ServiceBus;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace AbcCorp.Jobs
{
    public static class Program
    {
        static async Task Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", false)
                .Build();

            var hostBuilder = new HostBuilder()
                .ConfigureWebJobs(builder => { builder.AddAzureStorageCoreServices(); })
                .ConfigureServices(serviceCollection =>
                {
                    ConfigureServices(serviceCollection, config);
                    serviceCollection.AddHostedService<ConsoleApplication>();
                });

            using (var host = hostBuilder.Build())
                await host.RunAsync();
        }

        private static IServiceCollection ConfigureServices(IServiceCollection services, IConfigurationRoot configuration)
        {
            services.AddTransient<ConsoleApplication>();
            // ... more DI registrations
            return services;
        }
    }
}
```

<p><strong>ConsoleApplication.cs</strong></p>

<p>This would normally be implemented as a function with a trigger.
The thing is, I want this code to only run once on the process startup.
It will start listening on the service bus events using the regular <code>Microsoft.Azure.ServiceBus</code> SDK package.</p>

<pre class="lang-cs prettyprint-override"><code>using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using AbcCorp.Internal.Microsoft.Azure.ServiceBus;
using AbcCorp.Api.Messaging;

namespace AbcCorp.Jobs
{
    public sealed class ConsoleApplication: IHostedService
    {
        private readonly IReceiver<SubmissionNotification> _messageReceiver;
        private readonly MessageHandler _messageHandler;

        public ConsoleApplication(IReceiver<SubmissionNotification> messageReceiver, MessageHandler messageHandler)
        {
            _messageReceiver = messageReceiver;
            _messageHandler = messageHandler;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _messageReceiver.StartListening(_messageHandler.HandleMessage, _messageHandler.HandleException);
            return Task.Delay(Timeout.Infinite);
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _messageReceiver.Dispose();
            return Task.CompletedTask;
        }
    }
}
</code>```

答:
You can check @george chen's answer from this post How to create service bus trigger webjob?

where instead of creating a receiver and registering a message handler, you can use the in built queue trigger and and write your message handler logic inside it.

Body:
All the code samples I've seen so far for Azure WebJobs rely on some kind of trigger (e.g. TimerTrigger or QueueTrigger).
I am looking specifically at WebJobs SDK 3.x, by the way.

So. For a triggerless WebJob (Windows Service-alike one), am I expected to use NoAutomaticTrigger and find a way to kickoff my "main" code manually?

Or should I resort to implementing and registering a class that implements the IHostedService interface?
So far that's the approach I'm taking but it feels more of a hack than a recommended way.
I have not even tried to deploy this code and only ran it on my local machine, so I am afraid that the publishing process will confirm my code is not suitable for Azure WebJobs in its current form.

EntryPoint.cs

This is how the application is being bootstrap when the process is starting.

using Microsoft.Azure.ServiceBus;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace AbcCorp.Jobs
{
    public static class Program
    {
        static async Task Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", false)
                .Build();

            var hostBuilder = new HostBuilder()
                .ConfigureWebJobs(builder => { builder.AddAzureStorageCoreServices(); })
                .ConfigureServices(serviceCollection =>
                {
                    ConfigureServices(serviceCollection, config);
                    serviceCollection.AddHostedService<ConsoleApplication>();
                });

            using (var host = hostBuilder.Build())
                await host.RunAsync();
        }

        private static IServiceCollection ConfigureServices(IServiceCollection services, IConfigurationRoot configuration)
        {
            services.AddTransient<ConsoleApplication>();
            // ... more DI registrations
            return services;
        }
    }
}

ConsoleApplication.cs

This would normally be implemented as a function with a trigger.
The thing is, I want this code to only run once on the process startup.
It will start listening on the service bus events using the regular Microsoft.Azure.ServiceBus SDK package.

using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using AbcCorp.Internal.Microsoft.Azure.ServiceBus;
using AbcCorp.Api.Messaging;

namespace AbcCorp.Jobs
{
    public sealed class ConsoleApplication: IHostedService
    {
        private readonly IReceiver<SubmissionNotification> _messageReceiver;
        private readonly MessageHandler _messageHandler;

        public ConsoleApplication(IReceiver<SubmissionNotification> messageReceiver, MessageHandler messageHandler)
        {
            _messageReceiver = messageReceiver;
            _messageHandler = messageHandler;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _messageReceiver.StartListening(_messageHandler.HandleMessage, _messageHandler.HandleException);
            return Task.Delay(Timeout.Infinite);
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _messageReceiver.Dispose();
            return Task.CompletedTask;
        }
    }
}


问:
Seaborn barplot label bars with 3rd variable
I am fairly new to Python visualization. I have data with 3 variables; month, frequency and word. I am trying to see which word appeared most in a month.

```<code>import pandas as pd
import seaborn as sns

test = pd.DataFrame({'month': ['2019-01','2019-02','2019-03','2019-04','2019-05'],
             'freq':[3,5,22,6,3],
             'word':['hello','world','seaborn','seaborn','python']})

sns.barplot(x = 'month', y = 'freq', data = test)
</code>```

So far, I have month on the x-axis, freq on the y-axis. But, I want to label bars with the words that appear in those months. For example "hello" should appear on Jan-2019 bar.

答:
Use plt.annotate to put the labels in the desired locations.

The ha and va keywords take care of proper (horizontal/vertical) alignment.

```<code>test = pd.DataFrame({'month': ['2019-01','2019-02','2019-03','2019-04','2019-05'],
             'freq':[3,5,22,6,3],
             'word':['hello','world','seaborn','seaborn','python']})

for i in test.index:
    word = test.loc[i, "word"]
    y = test.loc[i, "freq"]
    plt.annotate(word, (i, y), ha="center", va="bottom")

sns.barplot(x = 'month', y = 'freq', data = test);
</code>```

Body:
I am fairly new to Python visualization. I have data with 3 variables; month, frequency and word. I am trying to see which word appeared most in a month.

import pandas as pd
import seaborn as sns

test = pd.DataFrame({'month': ['2019-01','2019-02','2019-03','2019-04','2019-05'],
             'freq':[3,5,22,6,3],
             'word':['hello','world','seaborn','seaborn','python']})

sns.barplot(x = 'month', y = 'freq', data = test)

So far, I have month on the x-axis, freq on the y-axis. But, I want to label bars with the words that appear in those months. For example "hello" should appear on Jan-2019 bar.

Body:
Use plt.annotate to put the labels in the desired locations.

The ha and va keywords take care of proper (horizontal/vertical) alignment.

test = pd.DataFrame({'month': ['2019-01','2019-02','2019-03','2019-04','2019-05'],
             'freq':[3,5,22,6,3],
             'word':['hello','world','seaborn','seaborn','python']})

for i in test.index:
    word = test.loc[i, "word"]
    y = test.loc[i, "freq"]
    plt.annotate(word, (i, y), ha="center", va="bottom")

sns.barplot(x = 'month', y = 'freq', data = test);


问:
Why is the string 'andy' not printing please enter a new username?
```<code>current_users = ['Andy', 'Brett', 'Cassie', 'Derek', 'Eric']
new_users = ['eric', 'greg', 'hank', 'ian', 'john', 'andy', 'frank']
new_users.sort()

for current_user in current_users:
    current_user = current_user.lower()

for new_user in new_users:
    if new_user == current_user:
        print(f"\n{new_user}, Please enter a new username!")
    else:
        print(f"\n{new_user}, Username is available.")
</code>```

Andy is being printed as username is available.
Also please help me simplify as I am just learning python.

答:
a single equal mark is used to assign a value to a variable, whereas two consecutive equal marks is used to check whether 2 expressions give the same value .

= is an assignment operator

== is an equality operator

```<code>current_users = ['Andy', 'Brett', 'Cassie', 'Derek', 'Eric']
new_users = ['eric', 'greg', 'hank', 'ian', 'john', 'andy', 'frank']
new_users.sort()

for current_user in current_users:
    current_user == current_user.lower()

for new_user in new_users:
    if new_user == current_user:
        print(f"\n{new_user}, Please enter a new username!")
    else:
        print(f"\n{new_user}, Username is available.")
</code>```

Body:
current_users = ['Andy', 'Brett', 'Cassie', 'Derek', 'Eric']
new_users = ['eric', 'greg', 'hank', 'ian', 'john', 'andy', 'frank']
new_users.sort()

for current_user in current_users:
    current_user = current_user.lower()

for new_user in new_users:
    if new_user == current_user:
        print(f"\n{new_user}, Please enter a new username!")
    else:
        print(f"\n{new_user}, Username is available.")

Andy is being printed as username is available.
Also please help me simplify as I am just learning python.

Body:
a single equal mark is used to assign a value to a variable, whereas two consecutive equal marks is used to check whether 2 expressions give the same value .

= is an assignment operator

== is an equality operator

current_users = ['Andy', 'Brett', 'Cassie', 'Derek', 'Eric']
new_users = ['eric', 'greg', 'hank', 'ian', 'john', 'andy', 'frank']
new_users.sort()

for current_user in current_users:
    current_user == current_user.lower()

for new_user in new_users:
    if new_user == current_user:
        print(f"\n{new_user}, Please enter a new username!")
    else:
        print(f"\n{new_user}, Username is available.")


问:
Preserving inline styling inside PRE TAG container
I have a string like this

```<code><!DOCTYPE html><html> <head> <link rel="stylesheet" href="style.css"> <script src="script.js"></script> </head> <body> <h1>Hello Plunker!</h1> ```Some space then more text.``` </body></html>
</code>```

When i am rendering it inside angular, the text is rendering fine but inline style inside the span tag is missing.

how can i preserve inline style.

```<code><pre [innerHTML]="rawhtml">```
```

Please help.

答:
Due to security angular by default remove style or scripts tag present in string. To achieve this You have to use the DomSantizer provided by the angular. Just Inject the DomSantizer in your component then use the bypassSecurityTrustHtml method. You are good to go. For more details read the documentation.

```<code>htmlToRender = this.santizer.bypassSecurityTrustHtml(rawhtml);

<pre [innerHTML]="htmlToRender ">```
```

Let me know If you are facing any issue.

Body:
I have a string like this

<!DOCTYPE html>  <link rel="stylesheet" href="style.css">
Hello Plunker!

Some space then more text.

When i am rendering it inside angular, the text is rendering fine but inline style inside the span tag is missing.

how can i preserve inline style.

Please help.

Body:
Due to security angular by default remove style or scripts tag present in string. To achieve this You have to use the DomSantizer provided by the angular. Just Inject the DomSantizer in your component then use the bypassSecurityTrustHtml method. You are good to go. For more details read the documentation.

htmlToRender = this.santizer.bypassSecurityTrustHtml(rawhtml);

<pre [innerHTML]="htmlToRender "></pre>

Let me know If you are facing any issue.


问:
How can I check if a global variable that defined in Node.js if it's not changing after seconds
I wrote an app in nodejs but having logic problem with variable.
I'm looking for help with this issue.

Well, i have a global integer variable named "global_something"
I need a function that check if "global_something" not changing after 1000ms or 2000ms

How i can do that ?

Thanks!

答:
You have to make 2 variable for that </p>

```<code>var original_global = 'Test';
var copy_original_global; // save this field in database or json file for compare

setInterval(()=>{
  if(!copy_original_global){
      copy_original_global = original_global;
       return
 }
 if(original_global != copy_original_global){
  console.log('Changed')
 }
}, 3000);
</code>```

Body:
You have to make 2 variable for that

var original_global = 'Test';
var copy_original_global; // save this field in database or json file for compare

setInterval(()=>{
  if(!copy_original_global){
      copy_original_global = original_global;
       return
 }
 if(original_global != copy_original_global){
  console.log('Changed')
 }
}, 3000);


问:
Check is font monospace
I have a System.Drawing.Font object. How I can check is that font is monospace?
I tried something like font.FontFamily == FontFamily.GenericMonospace, but it's not properly working.

答:
In C# WPF an easy but a little bit expensive method goes like that:</p>

```<code>    private static char[] charSizes = new char[] { 'i', 'a', 'Z', '%', '#', 'a', 'B', 'l', 'm', ',', '.' };

    private bool IsMonospaced(FontFamily family)
    {
        foreach (Typeface typeface in family.GetTypefaces())
        {
            double firstWidth = 0d;

            foreach (char ch in charSizes)
            {
                FormattedText formattedText = new FormattedText(
                    ch.ToString(),
                    CultureInfo.CurrentCulture,
                    FlowDirection.LeftToRight,
                    typeface,
                    10d,
                    Brushes.Black,
                    new NumberSubstitution(),
                    1);
                if (ch == 'i')  // first char in list
                {
                    firstWidth = formattedText.Width;
                }
                else
                {
                    if (formattedText.Width != firstWidth)
                        return false;
                }
            }
        }

        return true;
    }
</code>```

Title: Check is font monospace

Body:
In C# WPF an easy but a little bit expensive method goes like that:

    private static char[] charSizes = new char[] { 'i', 'a', 'Z', '%', '#', 'a', 'B', 'l', 'm', ',', '.' };

    private bool IsMonospaced(FontFamily family)
    {
        foreach (Typeface typeface in family.GetTypefaces())
        {
            double firstWidth = 0d;

            foreach (char ch in charSizes)
            {
                FormattedText formattedText = new FormattedText(
                    ch.ToString(),
                    CultureInfo.CurrentCulture,
                    FlowDirection.LeftToRight,
                    typeface,
                    10d,
                    Brushes.Black,
                    new NumberSubstitution(),
                    1);
                if (ch == 'i')  // first char in list
                {
                    firstWidth = formattedText.Width;
                }
                else
                {
                    if (formattedText.Width != firstWidth)
                        return false;
                }
            }
        }

        return true;
    }


问:
Why can't I call a templated method from a derived class instance in C++?
Please consider these types:

```<code>struct X
{
    static std::string fullyQualifiedName();
};

struct A
{
    template <class T> void foo()
    {
        return foo(T::fullyQualifiedName());
    }

protected:
    virtual void foo(const std::string& name) = 0;
};

struct B : public A
{
protected:
    void foo(const std::string& name);
};
</code>```

I have a pointer to an instance of B, I'm trying to invoke the templated version of foo like so:

```<code>b->foo< X >();
</code>```

The compiler is complaining: 'X' : illegal use of this type as an expression.

On the other hand, this code's perfectly ok:

```<code>A* a = b;
a->foo< X >();
</code>```

Hence my question.

答:
The problem you are facing is called hiding. Basically the lookup rules in the language will start in the most derived type and work their way back up until it finds the appropriate symbol. In your case it will stop while looking at the B class as it finds void B::foo(const std::string& name). At that level, the only potential overload that it will consider is the one it is seeing.

To avoid hiding you can bring all the other overloads you can add a using declaration:

```<code>struct B : A{
   using A::foo;
   void foo( const std::string & name );
};
</code>```

The difference is that lookup will work up the hierarchy until it finds the first overload, which is again at B level, but because of the using directive, it will also consider any overload available in A.

Alternatively, you can leave the symbol hidden and force dispatch to the exact class by qualifying the call (note that this has the side effect of disabling dynamic dispatch, which is not a problem here, but could be if the overload to use is virtual):

```<code>b->A::foo<X>();
</code>```

Body:
Please consider these types:

struct X
{
    static std::string fullyQualifiedName();
};

struct A
{
    template <class T> void foo()
    {
        return foo(T::fullyQualifiedName());
    }

protected:
    virtual void foo(const std::string& name) = 0;
};

struct B : public A
{
protected:
    void foo(const std::string& name);
};

I have a pointer to an instance of B, I'm trying to invoke the templated version of foo like so:

b->foo< X >();

The compiler is complaining: 'X' : illegal use of this type as an expression.

On the other hand, this code's perfectly ok:

A* a = b;
a->foo< X >();

Hence my question.

Body:
The problem you are facing is called hiding. Basically the lookup rules in the language will start in the most derived type and work their way back up until it finds the appropriate symbol. In your case it will stop while looking at the B class as it finds void B::foo(const std::string& name). At that level, the only potential overload that it will consider is the one it is seeing.

To avoid hiding you can bring all the other overloads you can add a using declaration:

struct B : A{
   using A::foo;
   void foo( const std::string & name );
};

The difference is that lookup will work up the hierarchy until it finds the first overload, which is again at B level, but because of the using directive, it will also consider any overload available in A.

Alternatively, you can leave the symbol hidden and force dispatch to the exact class by qualifying the call (note that this has the side effect of disabling dynamic dispatch, which is not a problem here, but could be if the overload to use is virtual):

b->A::foo<X>();


答:
Well, you have to Parse Text of the TextBoxes and Add these values to DateTime.Today

```<code>if (int.TryParse(DayTextBox.Text, out int day) &&
    int.TryParse(MonthTextBox.Text, out int months) &&
    int.TryParse(YearTextBox.Text, out int years)) {
  DateTime result = DateTime.Today
    .AddDays(days)
    .AddMonths(months)
    .AddYears(years);

  //TODO: put relevant code here
}
else {
  //  Some of the text boxes has invalid value
}
</code>```

Please, note that order (.AddDays then .AddMonths or .AddMonths then .AddDays) matters:

```<code>30 Jan 2020 + 1 Day + 1 Month == 29 Feb 2020
30 Jan 2020 + 1 Month + 1 Day ==  1 Mar 2020
</code>```

Title: i have 3 text boxes for Day , Month and Year .From this need to calculate a date

Body:
I have 3 textboxes for Day, Month and Year. From this need to calculate a date. And need subtraction functionality also ( Calculation on Current date)

Eg: Current date = 20-02-2020 , Day -1 and Month - 1 and Year = 1 then the result = 21-03-2021

Body:
Well, you have to Parse Text of the TextBoxes and Add these values to DateTime.Today

if (int.TryParse(DayTextBox.Text, out int day) &&
    int.TryParse(MonthTextBox.Text, out int months) &&
    int.TryParse(YearTextBox.Text, out int years)) {
  DateTime result = DateTime.Today
    .AddDays(days)
    .AddMonths(months)
    .AddYears(years);

  //TODO: put relevant code here
}
else {
  //  Some of the text boxes has invalid value
}

Please, note that order (.AddDays then .AddMonths or .AddMonths then .AddDays) matters:

30 Jan 2020 + 1 Day + 1 Month == 29 Feb 2020
30 Jan 2020 + 1 Month + 1 Day ==  1 Mar 2020


问:
Implement kotlin copy function for properties declared in the class body
Is it possible in kotlin to write a copy function for properties declared in the class body rather than the primary constructor?

```<code>data class Person(val name: String) {
var age: Int = 0
}
</code>```

How can I write copy function for the age variable?

答:
why don't you just move the variable into constructor with default value like :

```<code>data class Person(val name: String, var age: Int = 0) {
}
</code>```

then you can use it like:

```<code>Person("Andy")
Person("Andy", 29)
</code>```

and copy will work fine as well:

```<code>val person = Person("Andy")
person.copy(age = 42)
</code>```

Body:
Is it possible in kotlin to write a copy function for properties declared in the class body rather than the primary constructor?

data class Person(val name: String) {
var age: Int = 0
}

How can I write copy function for the age variable?

Body:
why don't you just move the variable into constructor with default value like :

data class Person(val name: String, var age: Int = 0) {
}

then you can use it like:

Person("Andy")
Person("Andy", 29)

and copy will work fine as well:

val person = Person("Andy")
person.copy(age = 42)


问:
Populate Dropdown Box if 2 columns match with values from 3rd column
I am using Data Validation lists in Excel for something based on a data dictionary from a database. Setup is as follow:

```<code>    Sheet1
    column A - DB Table Name (repeats for as many rows as there are associated values in column B)
    Column B - List of all values associated with the DB table name in column A
</code>```

```<code>Example Sheet1
Column A  |  Column B
DB1       | ValueA1
DB1       | ValueA2
DB1       | ValueA3
DB2       | ValueB1
DB3       | ValueC1
DB3       | ValueC2
</code>```

On Sheet 2 I have a dropdown Data Validation in cell D1 that is populated from a table. All of the options in the table are the DB names in ColumnA of Sheet1. Based on the DB selection from the cell D1 on Sheet2 I want B1 of sheet2 to be a dropdown list of all of the matching values from Sheet1 column B where Sheet2 cell D1 matches Sheet1 columnA.

Example: Person selects DB3 in Sheet2 Cell D1. Then cell B1 in Sheet2 becomes a dropdown containing the values [ValueC1, ValueC2]. Those are the column B values from Sheet1 that name-match Sheet2 D1 and Sheet1 column A.

Tried numerous things with Index and vlookup but I am not getting multiple results so the data validation won't take the formula as it only returns a single result.

I hope that makes sense...

答:
1] In "sheet 1", Column C C2:C4 create a "UniqueList of data A"  : enter DB1,DB2 and DB3

2] In "sheet 2" D1 >> Data Validation >>

Allow : List

Source : =Sheet1!$C$2:$C$4

Select OK

3] In "sheet 2" B1 >> Data Validation >>

Allow : List

Source : =OFFSET(Sheet1!$B$1,MATCH($D1,Sheet1!$A$2:$A$7,0),0,COUNTIF(Sheet1!$A$2:$A$7,$D1))

Select OK

Body:
I am using Data Validation lists in Excel for something based on a data dictionary from a database. Setup is as follow:

    Sheet1
    column A - DB Table Name (repeats for as many rows as there are associated values in column B)
    Column B - List of all values associated with the DB table name in column A

Example Sheet1
Column A  |  Column B
DB1       | ValueA1
DB1       | ValueA2
DB1       | ValueA3
DB2       | ValueB1
DB3       | ValueC1
DB3       | ValueC2

On Sheet 2 I have a dropdown Data Validation in cell D1 that is populated from a table. All of the options in the table are the DB names in ColumnA of Sheet1. Based on the DB selection from the cell D1 on Sheet2 I want B1 of sheet2 to be a dropdown list of all of the matching values from Sheet1 column B where Sheet2 cell D1 matches Sheet1 columnA.

Example: Person selects DB3 in Sheet2 Cell D1. Then cell B1 in Sheet2 becomes a dropdown containing the values [ValueC1, ValueC2]. Those are the column B values from Sheet1 that name-match Sheet2 D1 and Sheet1 column A.

Tried numerous things with Index and vlookup but I am not getting multiple results so the data validation won't take the formula as it only returns a single result.

I hope that makes sense...


问:
where can I find Provisioning Profiles page in Certificates, Identifiers & Profiles?
I can't find page of Provisioning Profiles from Certificates, Identifiers & Profiles.
In googling, they all say " go Provisioning Profiles in Certificates, Identifiers & Profiles"
but my Page does'nt have that menu.
Do I need to more certification?
or something wrong with my ID?

this is my Page.

I think that left side is the place for Provisioning Profiles....
but there is not.

Thank you for reading, have a good day.

答:
All the answel I saw are past design of app developer site.
Now that image is recent design.
And we can not get app-id directly.
Make key or identifilers step can connect app-id.
I got helped this page.
https://learn.microsoft.com/ko-kr/azure/notification-hubs/notification-hubs-ios-apple-push-notification-apns-get-started</p>


问:
Get rid of client-config.wsdd in Axis
I am setting up my test environment and I need to programmatically register my handler/transport instead of using a client-config.wsdd:

```<code><?xml version="1.0" encoding="UTF-8"?>
<deployment xmlns="http://xml.apache.org/axis/wsdd/" xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">
 <handler name="MyClient" type="java:foo.bar.MyClient"/>
 <transport name="MyTransport" pivot="MyClient"/>
</deployment>
</code>```

Would you know if it's possible?

Thanks in advance.

答: in the other hand, you can add a new client-config.wsdd file to resource directory.</p>

Title: Get rid of client-config.wsdd in Axis

Body:
I am setting up my test environment and I need to programmatically register my handler/transport instead of using a client-config.wsdd:

<?xml version="1.0" encoding="UTF-8"?>
<deployment xmlns="http://xml.apache.org/axis/wsdd/" xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">
 <handler name="MyClient" type="java:foo.bar.MyClient"/>
 <transport name="MyTransport" pivot="MyClient"/>
</deployment>

Would you know if it's possible?

Thanks in advance.


问:
Trying to nest a dictionary from a previous dictionary
so I have the following scenario:

```<code>dictionary=[
{category1:clothes, category2:cheap, category3:10},
{category1:clothes, category2:normal, category3:20}]
</code>```

I need a dictionary that goes {clothes:{cheap:10, normal:20}}
All I have figured out is something that prints them individually

```<code>for i in range(len(dictionary)):
print({dictionary[i]['category1']:{dictionary[i][category2],dictionary[i][category3]}}
</code>```

But it prints them individually, and I can't figure out how to nest them together since this just gives me two dictionaries with the format I want, but the nested dictionary just has either the values from the first list or the second. I have also tried

```<code>[{item['category1']: {'Attribute': attr_key, 'Value': item[attr_key]}}
    for item in dictionary for attr_key in item if attr_key != 'category1']
</code>```

It is the same, it gives more lines whereas I just need one dictionary with cat1 and the other ones nested in its dictionary.

答:
```<code>raw = {}
for item in dictionary:
    value1 = item.get('category2')
    value2 = item.get('category3')
    raw.update({value1:value2})

data = {}
data[dictionary[0].get('category1')] = raw
</code>```

Output:

```<code>{'clothes': {'cheap': 10, 'normal': 20}}
</code>```

Body:
so I have the following scenario:

dictionary=[
{category1:clothes, category2:cheap, category3:10},
{category1:clothes, category2:normal, category3:20}]

I need a dictionary that goes {clothes:{cheap:10, normal:20}}
All I have figured out is something that prints them individually

for i in range(len(dictionary)):
print({dictionary[i]['category1']:{dictionary[i][category2],dictionary[i][category3]}}

But it prints them individually, and I can't figure out how to nest them together since this just gives me two dictionaries with the format I want, but the nested dictionary just has either the values from the first list or the second. I have also tried

[{item['category1']: {'Attribute': attr_key, 'Value': item[attr_key]}}
    for item in dictionary for attr_key in item if attr_key != 'category1']

It is the same, it gives more lines whereas I just need one dictionary with cat1 and the other ones nested in its dictionary.

Body:
raw = {}
for item in dictionary:
    value1 = item.get('category2')
    value2 = item.get('category3')
    raw.update({value1:value2})

data = {}
data[dictionary[0].get('category1')] = raw

Output:

{'clothes': {'cheap': 10, 'normal': 20}}


问:
Datagridview FirstDisplayedScrollingRowIndex not working at the bottom of the grid
For scrolling the datagrid, I use following code:

```<code>dataGridView1.FirstDisplayedScrollingRowIndex = currentRowIndexInGridView;
dataGridView1.Update();
</code>```

That works fine for rows not at the bottom of the grid.
If I use it for bottom rows, the setter doesnt set it to the value I wanted, when I inspect it during debugging.
E.g. I am setting FirstDisplayedScrollingRowIndex= 103, but after the assignment FirstDisplayedScrollingRowIndex has the value 90 and hence the desired row is not visible.
From a certain point it stops scrolling and I cant see the last 5 rows.
If I am adding new rows and setting them to be displayed, it scrolls by one, but I dont see the last 5 rows again.

I think it has something to do with the fact, the some of my rows have different height and some internal estiment of DisplayedRowCount fails  ???

Is there a way of detecting this situation and then forcing scrolling to the bottom of the datagrid?

EDIT:

The important part of the FirstDisplayedScrollingRowIndex setter looks like this in the Reflector:

```<code> if (value > this.displayedBandsInfo.FirstDisplayedScrollingRow)
        {
            int rows = this.Rows.GetRowCount(DataGridViewElementStates.Visible, this.displayedBandsInfo.FirstDisplayedScrollingRow, value);
            this.ScrollRowsByCount(rows, (rows > 1) ? ScrollEventType.LargeIncrement : ScrollEventType.SmallIncrement);
        }
        else
        {
            this.ScrollRowIntoView(-1, value, true, false);
        }
</code>```

There seems to be an error in computing the rows variable.

答:
I have similar issue but I found how to solved.
The problem seams to be that DataGridView required windows form refresh and only after that can be set FirstDisplayedScrollingRowIndex to the new index.
What I did?</p>

```<code>Timer refreshTimer = new Timer();
public void RefreshLog()
{
    dataGridViewVesselLog.DataSource = Log.Items;
    dataGridViewVesselLog.Update();
    dataGridViewVesselLog.Refresh();
    refreshTimer.Interval = 100;
    refreshTimer.Tick += (s, e) =>
    {
        if (dataGridViewVesselLog.Rows.Count > 0)
        {
            foreach (DataGridViewRow r in dataGridViewVesselLog.SelectedRows)
                r.Selected = false;
            dataGridViewVesselLog.Rows[dataGridViewVesselLog.Rows.Count - 1].Selected = true;
            dataGridViewVesselLog.FirstDisplayedScrollingRowIndex = (int)(dataGridViewVesselLog.Rows.Count - 1);

        }
        refreshTimer.Stop();
    }
    refreshTimer.Start();
}
</code>```

Body:
For scrolling the datagrid, I use following code:

dataGridView1.FirstDisplayedScrollingRowIndex = currentRowIndexInGridView;
dataGridView1.Update();

That works fine for rows not at the bottom of the grid.
If I use it for bottom rows, the setter doesnt set it to the value I wanted, when I inspect it during debugging.
E.g. I am setting FirstDisplayedScrollingRowIndex= 103, but after the assignment FirstDisplayedScrollingRowIndex has the value 90 and hence the desired row is not visible.
From a certain point it stops scrolling and I cant see the last 5 rows.
If I am adding new rows and setting them to be displayed, it scrolls by one, but I dont see the last 5 rows again.

I think it has something to do with the fact, the some of my rows have different height and some internal estiment of DisplayedRowCount fails  ???

Is there a way of detecting this situation and then forcing scrolling to the bottom of the datagrid?

EDIT:

The important part of the FirstDisplayedScrollingRowIndex setter looks like this in the Reflector:

 if (value > this.displayedBandsInfo.FirstDisplayedScrollingRow)
        {
            int rows = this.Rows.GetRowCount(DataGridViewElementStates.Visible, this.displayedBandsInfo.FirstDisplayedScrollingRow, value);
            this.ScrollRowsByCount(rows, (rows > 1) ? ScrollEventType.LargeIncrement : ScrollEventType.SmallIncrement);
        }
        else
        {
            this.ScrollRowIntoView(-1, value, true, false);
        }

There seems to be an error in computing the rows variable.

Body:
I have similar issue but I found how to solved.
The problem seams to be that DataGridView required windows form refresh and only after that can be set FirstDisplayedScrollingRowIndex to the new index.
What I did?

Timer refreshTimer = new Timer();
public void RefreshLog()
{
    dataGridViewVesselLog.DataSource = Log.Items;
    dataGridViewVesselLog.Update();
    dataGridViewVesselLog.Refresh();
    refreshTimer.Interval = 100;
    refreshTimer.Tick += (s, e) =>
    {
        if (dataGridViewVesselLog.Rows.Count > 0)
        {
            foreach (DataGridViewRow r in dataGridViewVesselLog.SelectedRows)
                r.Selected = false;
            dataGridViewVesselLog.Rows[dataGridViewVesselLog.Rows.Count - 1].Selected = true;
            dataGridViewVesselLog.FirstDisplayedScrollingRowIndex = (int)(dataGridViewVesselLog.Rows.Count - 1);

        }
        refreshTimer.Stop();
    }
    refreshTimer.Start();
}


问:
Finding if the current time is 72 hours more than the time that I get in a variable
I have a variable i with it's value as 2020-02-04 10:15:35

I want to check if the current datetime is at least 72 hours more than this given time stored in variable i

I tried with:

```<code>        now = datetime.datetime.now()
        if i > now - datetime.timedelta(hours=72):

            print(f"72 hours have passed")
</code>```

Code seems to be skipping the if condition But is shouldn't in this case.

Trying it for the first time. How to tackle this? Where am I messing up?

答:
You can do something like this,

Note: Ensure that i holds the datetime object

```<code>import datetime

i = datetime.datetime.strptime("2020-02-22 10:15:35", "%Y-%m-%d %H:%M:%S")
now = datetime.datetime.now()
if i <= now - datetime.timedelta(hours=72):
    print(f"72 hours have passed")
</code>```

Body:
I have a variable i with it's value as 2020-02-04 10:15:35

I want to check if the current datetime is at least 72 hours more than this given time stored in variable i

I tried with:

        now = datetime.datetime.now()
        if i > now - datetime.timedelta(hours=72):

            print(f"72 hours have passed")

Code seems to be skipping the if condition But is shouldn't in this case.

Trying it for the first time. How to tackle this? Where am I messing up?

Body:
You can do something like this,

Note: Ensure that i holds the datetime object

import datetime

i = datetime.datetime.strptime("2020-02-22 10:15:35", "%Y-%m-%d %H:%M:%S")
now = datetime.datetime.now()
if i <= now - datetime.timedelta(hours=72):
    print(f"72 hours have passed")


问:
Spring multithreading with hibernate
Some short version infos: Spring Boot 2.1 with Hibernate 5 and Java 8.

We try to do  a multithreaded processing step, in which we use spring services to work with hibernate entities. Basically it looks like the following snippet.

```<code>   ExecutorService executorService = Executors.newFixedThreadPool(4);

        List<Callable<String>> executions = new ArrayList<>();
        for (String partition : partitions) {
            Callable<String> partitionExecution = () -> {
                step.execute(partition);
                return partition;
            };
            executions.add(partitionExecution);
        }

        executorService.invokeAll(executions);
</code>```

Problem is that the hibernat session is somehow not available in the created threads. We get the following exception:

```<code>org.hibernate.LazyInitializationException:
failed to lazily initialize a collection of role: ..., could not initialize proxy - no Session
</code>```

If I remove to multithreading part (i.e. remove the executor service) everyhting works fine.

We already tried the following:

Use a spring managed ThreadPoolTaskExecutor

Put @Transactional at the top of the method/class (which is wired from another class and invoked there, so should basically work)

Any hints/suggestions appreciated :)

答:
In short, I'd strongly advise against passing Hibernate managed objects inside multiple threads as this can cause:

Lazy initialization problems (as you encountered)

Missing updates

Locking exceptions

For more details, this blog post explains why: https://xebia.com/blog/hibernate-and-multi-threading/

For a solution, I'd find a way to split the work so that each thread would get list of entity id's to work with, and they'd do their independent work inside thread (fetch the entities from database, do the actual work etc.).
This is briefly mentioned in the above blog post.

Title: Spring multithreading with hibernate

Body:
Some short version infos: Spring Boot 2.1 with Hibernate 5 and Java 8.

We try to do  a multithreaded processing step, in which we use spring services to work with hibernate entities. Basically it looks like the following snippet.

   ExecutorService executorService = Executors.newFixedThreadPool(4);

        List<Callable<String>> executions = new ArrayList<>();
        for (String partition : partitions) {
            Callable<String> partitionExecution = () -> {
                step.execute(partition);
                return partition;
            };
            executions.add(partitionExecution);
        }

        executorService.invokeAll(executions);

Problem is that the hibernat session is somehow not available in the created threads. We get the following exception:

org.hibernate.LazyInitializationException:
failed to lazily initialize a collection of role: ..., could not initialize proxy - no Session

If I remove to multithreading part (i.e. remove the executor service) everyhting works fine.

We already tried the following:

Use a spring managed ThreadPoolTaskExecutor

Put @Transactional at the top of the method/class (which is wired from another class and invoked there, so should basically work)

Any hints/suggestions appreciated :)


问:
Unable to use .find() to get value from table/form
Trying to wrap my head around this for a while now. Some guru needs to help me out, it would be greatly appreciated. I don't know why it is not working.

$(".form").on('submit', function(event) {
  event.preventDefault(); //prevent the forms default action
  var surname = $(this).find(".surname");
  console.log(surname);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <form class="form" method="post" action="nextpage.php">
    <tr>
      <td class="name">john</td>
      <td class="surname">smith</td>
      <td>british</td>
      <td><button type="submit" class="btn btn-info btn-sm">Submit</button></td>
    </tr>

  </form>

  <form class="form" method="post" action="nextpage.php">
    <tr>
      <td class="name">bob</td>
      <td class="surname">doe</td>
      <td>american</td>
      <td><button type="submit" class="btn btn-info btn-sm">Submit</button></td>
    </tr>
  </form>
</table></code>```

So if i click on the first submit button i should see john, and the second, bob.

答:
I fixed your code:

The <form> wraps around the

Catch the clicks on <buttons> and get the surname relatively to the clicked row (
)

$("button[type=submit]").on('click', function(event) {
  event.preventDefault(); //prevent the forms default action
  var surname = $(this).closest('tr').find(".surname");
  console.log(surname.text());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form" method="post" action="nextpage.php">
  <table>
    <tr>
      <td class="name">john</td>
      <td class="surname">smith</td>
      <td>british</td>
      <td><button type="submit" class="btn btn-info btn-sm">Submit</button></td>
    </tr>

    <tr>
      <td class="name">bob</td>
      <td class="surname">doe</td>
      <td>american</td>
      <td><button type="submit" class="btn btn-info btn-sm">Submit</button></td>
    </tr>
  </table>
</form></code>```

JSFiddle: https://jsfiddle.net/v9k3sL1f/

Body:
Trying to wrap my head around this for a while now. Some guru needs to help me out, it would be greatly appreciated. I don't know why it is not working.

$(".form").on('submit', function(event) {
  event.preventDefault(); //prevent the forms default action
  var surname = $(this).find(".surname");
  console.log(surname);
});

  <form class="form" method="post" action="nextpage.php">

      john
      smith
      british
      <button type="submit" class="btn btn-info btn-sm">Submit</button>

  </form>

  <form class="form" method="post" action="nextpage.php">

      bob
      doe
      american
      <button type="submit" class="btn btn-info btn-sm">Submit</button>

  </form>

So if i click on the first submit button i should see john, and the second, bob.

Body:
I fixed your code:

The <form> wraps around the <table>

Catch the clicks on <buttons> and get the surname relatively to the clicked row (<tr>)

$("button[type=submit]").on('click', function(event) {
  event.preventDefault(); //prevent the forms default action
  var surname = $(this).closest('tr').find(".surname");
  console.log(surname.text());
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form" method="post" action="nextpage.php">
  <table>
    <tr>
      <td class="name">john</td>
      <td class="surname">smith</td>
      <td>british</td>
      <td><button type="submit" class="btn btn-info btn-sm">Submit</button></td>
    </tr>

    <tr>
      <td class="name">bob</td>
      <td class="surname">doe</td>
      <td>american</td>
      <td><button type="submit" class="btn btn-info btn-sm">Submit</button></td>
    </tr>
  </table>
</form>

JSFiddle: https://jsfiddle.net/v9k3sL1f/


问:
How to fix error: "Google.Apis.Auth: At least one client secrets (Installed or Web) should be set " for YouTubeAPI
I have created an HTTP trigger azure function, which holds the code (below) to upload a video to YouTube automatically. Source: (https://developers.google.com/youtube/v3/docs/videos/insert).

When I try to run the app locally using visual studio, I am getting the following error:

Executed 'Function1' (Failed, Id=d601d64a-2f2c-4f8a-8053-a2f33ca21dbc)
  System.Private.CoreLib: Exception while executing function: Function1.
  Google.Apis.Auth: At least one client secrets (Installed or Web)
  should be set

It looks like a Google Authentication error, but I am unsure as to how to get this fixed and I see that YouTube API does not support Service account? How can this issue be fixed, is there a get around to this? Thanks in advance.

C# Code:

```<code>using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Upload;
using Google.Apis.YouTube.v3.Data;
using System.Reflection;
using Google.Apis.YouTube.v3;
using Google.Apis.Services;
using System.Threading;

namespace UploadVideo
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            log.LogInformation("YouTube Data API: Upload Video");
            log.LogInformation("==============================");

            try
            {
                await Run();
            }
            catch (AggregateException ex)
            {
                foreach (var e in ex.InnerExceptions)
                {
                    log.LogInformation("Error: " + e.Message);
                }
            }

            return new OkObjectResult($"Video Processed..");

        }

        private static async Task Run()
        {
            UserCredential credential;
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    // This OAuth 2.0 access scope allows an application to upload files to the
                    // authenticated user's YouTube channel, but doesn't allow other types of access.
                    new[] { YouTubeService.Scope.YoutubeUpload },
                    "user",
                    CancellationToken.None
                );
            }

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
            });

            var video = new Video();
            video.Snippet = new VideoSnippet();
            video.Snippet.Title = "Default Video Title";
            video.Snippet.Description = "Default Video Description";
            video.Snippet.Tags = new string[] { "tag1", "tag2" };
            video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
            video.Status = new VideoStatus();
            video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
            var filePath = @"C:\Users\Peter\Desktop\audio\test.mp4"; // Replace with path to actual movie file.

            using (var fileStream = new FileStream(filePath, FileMode.Open))
            {
                var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
                videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

                await videosInsertRequest.UploadAsync();
            }
        }

        private static void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
        {
            switch (progress.Status)
            {
                case UploadStatus.Uploading:
                    Console.WriteLine("{0} bytes sent.", progress.BytesSent);
                    break;

                case UploadStatus.Failed:
                    Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
                    break;
            }
        }

        private static void videosInsertRequest_ResponseReceived(Video video)
        {
            Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
        }
    }
}
</code>```

答:
It looks like you were trying to use the service account to do the OAuth2 web server flow, which wont work. The correct code form creating a service account credential is as follows.

```<code>GoogleCredential credential;
using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
              {
                    credential = GoogleCredential.FromStream(stream)
                         .CreateScoped(scopes);
                }
</code>```

Note

as i have mentioned in your other questions the YouTube API does NOT support service account authentication. You must use Oauth2 and i am not convinced this can be done inside of azure functions.  As there is no way to spawn the web browser window to request authorization of the user.

Body:
I have created an HTTP trigger azure function, which holds the code (below) to upload a video to YouTube automatically. Source: (https://developers.google.com/youtube/v3/docs/videos/insert).

When I try to run the app locally using visual studio, I am getting the following error:

Executed 'Function1' (Failed, Id=d601d64a-2f2c-4f8a-8053-a2f33ca21dbc)
  System.Private.CoreLib: Exception while executing function: Function1.
  Google.Apis.Auth: At least one client secrets (Installed or Web)
  should be set

It looks like a Google Authentication error, but I am unsure as to how to get this fixed and I see that YouTube API does not support Service account? How can this issue be fixed, is there a get around to this? Thanks in advance.

C# Code:

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Upload;
using Google.Apis.YouTube.v3.Data;
using System.Reflection;
using Google.Apis.YouTube.v3;
using Google.Apis.Services;
using System.Threading;

namespace UploadVideo
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            log.LogInformation("YouTube Data API: Upload Video");
            log.LogInformation("==============================");

            try
            {
                await Run();
            }
            catch (AggregateException ex)
            {
                foreach (var e in ex.InnerExceptions)
                {
                    log.LogInformation("Error: " + e.Message);
                }
            }

            return new OkObjectResult($"Video Processed..");

        }

        private static async Task Run()
        {
            UserCredential credential;
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    // This OAuth 2.0 access scope allows an application to upload files to the
                    // authenticated user's YouTube channel, but doesn't allow other types of access.
                    new[] { YouTubeService.Scope.YoutubeUpload },
                    "user",
                    CancellationToken.None
                );
            }

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
            });

            var video = new Video();
            video.Snippet = new VideoSnippet();
            video.Snippet.Title = "Default Video Title";
            video.Snippet.Description = "Default Video Description";
            video.Snippet.Tags = new string[] { "tag1", "tag2" };
            video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
            video.Status = new VideoStatus();
            video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
            var filePath = @"C:\Users\Peter\Desktop\audio\test.mp4"; // Replace with path to actual movie file.

            using (var fileStream = new FileStream(filePath, FileMode.Open))
            {
                var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
                videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

                await videosInsertRequest.UploadAsync();
            }
        }

        private static void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
        {
            switch (progress.Status)
            {
                case UploadStatus.Uploading:
                    Console.WriteLine("{0} bytes sent.", progress.BytesSent);
                    break;

                case UploadStatus.Failed:
                    Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
                    break;
            }
        }

        private static void videosInsertRequest_ResponseReceived(Video video)
        {
            Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
        }
    }
}

Body:
It looks like you were trying to use the service account to do the OAuth2 web server flow, which wont work. The correct code form creating a service account credential is as follows.

GoogleCredential credential;
using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
              {
                    credential = GoogleCredential.FromStream(stream)
                         .CreateScoped(scopes);
                }

Note

as i have mentioned in your other questions the YouTube API does NOT support service account authentication. You must use Oauth2 and i am not convinced this can be done inside of azure functions.  As there is no way to spawn the web browser window to request authorization of the user.


问:
Is it possible to match multiple keys of a Map instead of IF statements inside forEach?
I am trying to filter a Map and extract values by matching keys to strings. The map is  and values can either be string or List. Following is the code snippet-

```<code>container.forEach((k, v) -> {
            if (("userId").equals(k))
                registerContainer.setUserId(v.toString());
            if (("languageId").equals(k))
                registerContainer.setUserLanguage(v.toString());

            if (("formDetails").equals(k)) {

                registerContainer.setFields((ArrayList) v);
            }

            if (("value1").equals(k)) {
                HashMap fieldEntry = new LinkedHashMap<>();
                fieldEntry.put("fieldKey", k);
                fieldEntry.put("fieldValue", v.toString());
                masterParams.add(fieldEntry);
            }
            if (("value2").equals(k)) {
                HashMap fieldEntry = new LinkedHashMap<>();
                fieldEntry.put("fieldKey", k);
                fieldEntry.put("fieldValue", v.toString());
                masterParams.add(fieldEntry);
            }

                if (!CollectionUtils.isEmpty(params)) {

                    registerContainer.setFields(masterParams);
                }

        });
</code>```

My question is, is there a way to eliminate all the if statements and still be able to have the desired outcome?

Thanks in advance.

答:
You can simplify it by using the switch statement and squash code for value1 and value2 as both do the same things.
So sth like this:

```<code>container.forEach((k, v) -> {
            switch(k){
                case "userId":
                    registerContainer.setUserId(v.toString());
                    break;
                case "languageId":
                    registerContainer.setUserLanguage(v.toString());
                    break;
                case "formDetails":
                    registerContainer.setFields((ArrayList) v);
                    break;
                case "value1":
                case "value2":
                    HashMap fieldEntry = new LinkedHashMap<>();
                    fieldEntry.put("fieldKey", k);
                    fieldEntry.put("fieldValue", v.toString());
                    masterParams.add(fieldEntry);
                    break;
            }
        });
if (!CollectionUtils.isEmpty(params)) {
    registerContainer.setFields(masterParams);
}
</code>```

Body:
I am trying to filter a Map and extract values by matching keys to strings. The map is  and values can either be string or List. Following is the code snippet-

container.forEach((k, v) -> {
            if (("userId").equals(k))
                registerContainer.setUserId(v.toString());
            if (("languageId").equals(k))
                registerContainer.setUserLanguage(v.toString());

            if (("formDetails").equals(k)) {

                registerContainer.setFields((ArrayList) v);
            }

            if (("value1").equals(k)) {
                HashMap fieldEntry = new LinkedHashMap<>();
                fieldEntry.put("fieldKey", k);
                fieldEntry.put("fieldValue", v.toString());
                masterParams.add(fieldEntry);
            }
            if (("value2").equals(k)) {
                HashMap fieldEntry = new LinkedHashMap<>();
                fieldEntry.put("fieldKey", k);
                fieldEntry.put("fieldValue", v.toString());
                masterParams.add(fieldEntry);
            }

                if (!CollectionUtils.isEmpty(params)) {

                    registerContainer.setFields(masterParams);
                }

        });

My question is, is there a way to eliminate all the if statements and still be able to have the desired outcome?

Thanks in advance.

Body:
You can simplify it by using the switch statement and squash code for value1 and value2 as both do the same things.
So sth like this:

container.forEach((k, v) -> {
            switch(k){
                case "userId":
                    registerContainer.setUserId(v.toString());
                    break;
                case "languageId":
                    registerContainer.setUserLanguage(v.toString());
                    break;
                case "formDetails":
                    registerContainer.setFields((ArrayList) v);
                    break;
                case "value1":
                case "value2":
                    HashMap fieldEntry = new LinkedHashMap<>();
                    fieldEntry.put("fieldKey", k);
                    fieldEntry.put("fieldValue", v.toString());
                    masterParams.add(fieldEntry);
                    break;
            }
        });
if (!CollectionUtils.isEmpty(params)) {
    registerContainer.setFields(masterParams);
}


问:
Mongodb update array inside of an object
I can't write a query that would update a value of an array that is inside of an object:

Let's say I have a collection that has document entries with the structure like below (There are 2 entries in the example but actually there are a few thousand that I need to update in my db)

```<code>/* 1 */
{
    "name" : "Bob",
    "info" : {
        "species" : "human",
        "addresses" : [
            "one",
            "two"
        ]
    }
},
/* 2 */
{
    "name" : "John",
    "info" : {
        "species" : "human",
        "addresses" : [
            "two",
            "three"
        ]
    },
}
</code>```

How can I update all documents in this collection so that all addresses in info.addresses array with value one would be changed to have value four?

Examples in mongo db documentation solve such cases when arrays are not inside objects, but I can't make them work with arrays inside objects

Example - this query should update all info.addresses arrays for all documents and change the entry values from one to four

```<code>db.getCollection('test').update({"info.addresses": "one"},{ $set: { "info.addresses.$" : "four" } })
</code>```

答:
```<code>db.getCollection('test').update({"info.addresses": "one"},{ $set: { "info.addresses.$[]" : "four" } })</code>```

Notice how I added square brackets "[]" in the array specified in $set. It ($[]) is a positional operator in mongodb. You can read more about it in the Mongodb docs.

https://docs.mongodb.com/manual/reference/operator/update/positional-all/

Body:
I can't write a query that would update a value of an array that is inside of an object:

Let's say I have a collection that has document entries with the structure like below (There are 2 entries in the example but actually there are a few thousand that I need to update in my db)

/* 1 */
{
    "name" : "Bob",
    "info" : {
        "species" : "human",
        "addresses" : [
            "one",
            "two"
        ]
    }
},
/* 2 */
{
    "name" : "John",
    "info" : {
        "species" : "human",
        "addresses" : [
            "two",
            "three"
        ]
    },
}

How can I update all documents in this collection so that all addresses in info.addresses array with value one would be changed to have value four?

Examples in mongo db documentation solve such cases when arrays are not inside objects, but I can't make them work with arrays inside objects

Example - this query should update all info.addresses arrays for all documents and change the entry values from one to four

db.getCollection('test').update({"info.addresses": "one"},{ $set: { "info.addresses.$" : "four" } })

Body:
db.getCollection('test').update({"info.addresses": "one"},{ $set: { "info.addresses.$[]" : "four" } })

Notice how I added square brackets "[]" in the array specified in $set. It ($[]) is a positional operator in mongodb. You can read more about it in the Mongodb docs.

https://docs.mongodb.com/manual/reference/operator/update/positional-all/


问:
Batch update on object list using EntityFramework 6 and Linq
I want to create a function that accepts a list of objects with their properties already set and does a batch update or insert on them only making 1 call to the database.

(UPDATE) Here is the working version:

```<code>    public static void BatchInsertProducts(IList<Product> productList)
    {
        using (var context = new DbContext())
        {
            context.Products.AddRange(productList);
            context.SaveChanges();
        }
    }
</code>```

This is my attempt at doing either and update or an insert on several items based on the Id. I don't think I can use AddRange here so I tried it this way and I am getting an error:

```<code>    public static void SaveMultipleProducts(IList<Product> productList)
    {
        using (var context = new DbContext())
        {
            foreach (Account p in productList)
            {
                if (p.ID == 0)
                {
                    context.Entry(p).State = EntityState.Added;
                    p.InsertUserId = "jtunney";
                    p.InsertDate = DateTime.Now;
                }
                else
                {
                    context.Entry(p).State = EntityState.Modified;
                    p.UpdateUserId = "jtunney";
                    p.UpdateDate = DateTime.Now;
                }
            }
            context.SaveChanges();
        }
    }
</code>```

答:
This is bit different approach than other....

```<code>public static DbContext BatchInsertProducts(DbContext context,IList<Product> productList)
{
    context.Configuration.AutoDetectChangesEnabled = false;
    for (int i = 0; i < lobbies.Count; i += 100)
    {
        context.Set<Product>().AddRange(lobbies.GetRange(i, Math.Min(100, lobbies.Count - i)));
        context.Products.AddRange(productList);
        context.SaveChanges();

        //Dispose and create a context
        context.Dispose();
        context = new DbContext;
        context.Configuration.AutoDetectChangesEnabled = false;
    }

    return context;
}
</code>```

The above mentioned code snippet does some additional task inorder to improve the performance and also we can specify the number of records that need to included in each batch manipulation.

If we want to insert bulk records, creating new context for each batch
  and dispose then once task is done. very much improve the performance
  (from minutes to operation to seconds)

Body:
I want to create a function that accepts a list of objects with their properties already set and does a batch update or insert on them only making 1 call to the database.

(UPDATE) Here is the working version:

    public static void BatchInsertProducts(IList<Product> productList)
    {
        using (var context = new DbContext())
        {
            context.Products.AddRange(productList);
            context.SaveChanges();
        }
    }

This is my attempt at doing either and update or an insert on several items based on the Id. I don't think I can use AddRange here so I tried it this way and I am getting an error:

    public static void SaveMultipleProducts(IList<Product> productList)
    {
        using (var context = new DbContext())
        {
            foreach (Account p in productList)
            {
                if (p.ID == 0)
                {
                    context.Entry(p).State = EntityState.Added;
                    p.InsertUserId = "jtunney";
                    p.InsertDate = DateTime.Now;
                }
                else
                {
                    context.Entry(p).State = EntityState.Modified;
                    p.UpdateUserId = "jtunney";
                    p.UpdateDate = DateTime.Now;
                }
            }
            context.SaveChanges();
        }
    }

Body:
This is bit different approach than other....

public static DbContext BatchInsertProducts(DbContext context,IList<Product> productList)
{
    context.Configuration.AutoDetectChangesEnabled = false;
    for (int i = 0; i < lobbies.Count; i += 100)
    {
        context.Set<Product>().AddRange(lobbies.GetRange(i, Math.Min(100, lobbies.Count - i)));
        context.Products.AddRange(productList);
        context.SaveChanges();

        //Dispose and create a context
        context.Dispose();
        context = new DbContext;
        context.Configuration.AutoDetectChangesEnabled = false;
    }

    return context;
}

The above mentioned code snippet does some additional task inorder to improve the performance and also we can specify the number of records that need to included in each batch manipulation.

If we want to insert bulk records, creating new context for each batch
  and dispose then once task is done. very much improve the performance
  (from minutes to operation to seconds)


答:
This should do it.</p>

```<code>import collections

dictionary=[
    {'category1':'clothes', 'category2':'cheap', 'category3':10},
    {'category1':'clothes', 'category2':'normal', 'category3':20}
]

newdict = collections.defaultdict(dict)
for item in dictionary:
  newdict[item['category1']].update({item['category2']: item['category3']})
print(newdict)
</code>```

Title: Trying to nest a dictionary from a previous dictionary

Body:
so I have the following scenario:

dictionary=[
{category1:clothes, category2:cheap, category3:10},
{category1:clothes, category2:normal, category3:20}]

I need a dictionary that goes {clothes:{cheap:10, normal:20}}
All I have figured out is something that prints them individually

for i in range(len(dictionary)):
print({dictionary[i]['category1']:{dictionary[i][category2],dictionary[i][category3]}}

But it prints them individually, and I can't figure out how to nest them together since this just gives me two dictionaries with the format I want, but the nested dictionary just has either the values from the first list or the second. I have also tried

[{item['category1']: {'Attribute': attr_key, 'Value': item[attr_key]}}
    for item in dictionary for attr_key in item if attr_key != 'category1']

It is the same, it gives more lines whereas I just need one dictionary with cat1 and the other ones nested in its dictionary.

Body:
This should do it.

import collections

dictionary=[
    {'category1':'clothes', 'category2':'cheap', 'category3':10},
    {'category1':'clothes', 'category2':'normal', 'category3':20}
]

newdict = collections.defaultdict(dict)
for item in dictionary:
  newdict[item['category1']].update({item['category2']: item['category3']})
print(newdict)


问:
Regex recursion captured string
I have a problem with a regex that has to capture a substring that it's already captured...

I have this regex:

(?<domain>\w+\.\w+)($|\/|\.)

And I want to capture every subdomain recursively. For example, in this string:

test1.test2.abc.def

This expression captures test1.test2 and abc.def but I need to capture:
test1.test2
test2.abc
abc.def

Do you know if there is any option to do this recursively?

Thanks!

答:
Maybe the following:

```<code>(\.|^)(?=(\w+\.\w+))
</code>```

Go with capturing group 2

Title: Regex recursion captured string

Body:
Maybe the following:

(\.|^)(?=(\w+\.\w+))

Go with capturing group 2


问:
invalid entitlements 0xE8008016 when I add the entitlements file
I'm trying to do ad hoc distribution.  When I use XCode, the application installs fine on my phone.

In preparation for ad hoc distribution, I created the default entitlements file, unchecked the get-task-allow box, added the entitlements file name to the code signing entitlements line, and tried to install on my phone.

If I have the file in the entitlements in build settings, I get the (dreaded) error

The entitlements specified in your application's Code Signing Entitlements file do not match those specified in your provisioning profile.

(0xE8008016).

This ONLY happens if I have the entitlements file listed in the code signing section.

I created a brand new application to test this, to see what could have gone wrong and this happens with a completely new test application (so it doesn't seem like clean builds, opening and closing XCode, etc will help).

What am I missing?  I've read all of the other times this has occurred and nothing seems to apply.

答: Have you checked that the Code Signing Identity values under Project > Build Settings and Targets > Build Settings are correct?</p>