问:
listen EADDRINUSE: address already in use -> No matter what port I use?
NodeJS version: LTS 12.17 installed like this:

```<code>curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -
sudo apt install nodejs
</code>```

I have a pretty weird issue:

One of my NodeJS app suddenly reports: listen EADDRINUSE: address already in use and it doesn't help anything no matter what port # I try to change it to?

The full trace-stack looks like this:

```<code>Error: listen EADDRINUSE: address already in use 0.0.0.0:6080
    at Server.setupListenHandle [as _listen2] (net.js:1313:16)
    at listenInCluster (net.js:1361:12)
    at doListen (net.js:1498:7)
    at processTicksAndRejections (internal/process/task_queues.js:85:21)
</code>```

I'm listening like this (_wl = a Winston logger instance):

```<code>> _server.listen(_port, '0.0.0.0', function () { _wl.info('SERVER STARTED! (listening on port # ' + _port + ')')});
</code>```

I have just setup this AWS EC2 Ubuntu 20.04 instance - so I guess somehow it has something to do with this. It has been working for years on a lot of different instance earlier Windows (I guess I have never run it on Ubuntu earlier).

I  execute like like:

```<code>1. cd into folder
2. node ./server.js (I have also tried to use Sudo)
</code>```

Can it have something to do with permissions?

I have tried to allow all in /out going traffic in the server atteched Security Group.

I have check that the firewall in Ubuntu 20.04 is disabled as well.

Also, on the same server I'm running a Python app which exposes a web socket server and the NodeJS app has no issue to subscribe to this connection...

And yes - I have tried to check all ports in use at the server and only few ports are in use.
The NodeJS app also try to expose a websocket server at a given port - but no matter what port I try to use I get the error above.

答:
Sorry!

I use express in my NodeJS apps and most of my apps contain the following line:

```<code>app.listen(port); // In this case port # 6080
</code>```

Later on in the current app (in which I experience the issue described above) I initialize a web socket server as well like this:

```<code>const _server = require('http').createServer();
_server.on('request', app);
_server.listen(_port, '0.0.0.0', function () { _wl.info('WEB SOCKET SERVER STARTED! (listening on port # ' + _port + ')')});
</code>```

in the code above both port and _port used the same ENV variable/setting(6080). Do to my app/Express in this case actually didn't use the app.listen(port) to anything and that Windows just choose to overrule the port's use-case when the web socket server afterwards got initialized with the same port number --> is the reason why I never have experienced any issues on Windows. But Linux/Ubuntu is more sensitive in this regard.

Cheers! :-)

Body:
NodeJS version: LTS 12.17 installed like this:

curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -
sudo apt install nodejs

I have a pretty weird issue:

One of my NodeJS app suddenly reports: listen EADDRINUSE: address already in use and it doesn't help anything no matter what port # I try to change it to?

The full trace-stack looks like this:

Error: listen EADDRINUSE: address already in use 0.0.0.0:6080
    at Server.setupListenHandle [as _listen2] (net.js:1313:16)
    at listenInCluster (net.js:1361:12)
    at doListen (net.js:1498:7)
    at processTicksAndRejections (internal/process/task_queues.js:85:21)

I'm listening like this (_wl = a Winston logger instance):

> _server.listen(_port, '0.0.0.0', function () { _wl.info('SERVER STARTED! (listening on port # ' + _port + ')')});

I have just setup this AWS EC2 Ubuntu 20.04 instance - so I guess somehow it has something to do with this. It has been working for years on a lot of different instance earlier Windows (I guess I have never run it on Ubuntu earlier).

I  execute like like:

1. cd into folder
2. node ./server.js (I have also tried to use Sudo)

Can it have something to do with permissions?

I have tried to allow all in /out going traffic in the server atteched Security Group.

I have check that the firewall in Ubuntu 20.04 is disabled as well.

Also, on the same server I'm running a Python app which exposes a web socket server and the NodeJS app has no issue to subscribe to this connection...

And yes - I have tried to check all ports in use at the server and only few ports are in use.
The NodeJS app also try to expose a websocket server at a given port - but no matter what port I try to use I get the error above.

Body:
Sorry!

I use express in my NodeJS apps and most of my apps contain the following line:

app.listen(port); // In this case port # 6080

Later on in the current app (in which I experience the issue described above) I initialize a web socket server as well like this:

const _server = require('http').createServer();
_server.on('request', app);
_server.listen(_port, '0.0.0.0', function () { _wl.info('WEB SOCKET SERVER STARTED! (listening on port # ' + _port + ')')});

in the code above both port and _port used the same ENV variable/setting(6080). Do to my app/Express in this case actually didn't use the app.listen(port) to anything and that Windows just choose to overrule the port's use-case when the web socket server afterwards got initialized with the same port number --> is the reason why I never have experienced any issues on Windows. But Linux/Ubuntu is more sensitive in this regard.

Cheers! :-)


来源: stackexchange

问:
Problem In Route CodeIgniter when access file on public_html
I have problem when route my site.

```<code>$route['(:any)']        = 'salam/salam/$1';
</code>```

because of this route, i cant access my file on https://example.com/OneSignalSDKWorker.js, please give me a solution. thanks guys.

答:
It doesn't seem okay to redirect all of the queries to this page.

Anyway if you want to exclude something you can add it before that line with

```<code>$route['(admin|login|home|sign_up)'] = "$1";
</code>```

That are example urls, but you can add OneSignalSDKWorker.js as well. That would load them and everything else would be redirected to salam/salam

ContentLicense: CC BY-SA 4.0

Body:
I have problem when route my site.

$route['(:any)']        = 'salam/salam/$1';

because of this route, i cant access my file on https://example.com/OneSignalSDKWorker.js, please give me a solution. thanks guys.

Body:
It doesn't seem okay to redirect all of the queries to this page.

Anyway if you want to exclude something you can add it before that line with

$route['(admin|login|home|sign_up)'] = "$1";

That are example urls, but you can add OneSignalSDKWorker.js as well. That would load them and everything else would be redirected to salam/salam


问:
Is DbProviderFactories.GetFactory(string providerName) expensive?
I'm trying to figure out if DbProviderFactories.GetFactory(string providerName) is expensive, or if I can safely create a new instance every time I need one.

The reason for this is that I have a situation where the provider name can change and it would be more convenient just to recreate the factory every time if that's a cheap call.

答:
Expensive is a relative term.

Getting the Factory itself does not involve making a connection over the network, so from my vantage point it is inexpensive, even if there is a small amount of reflection behind the scenes.

ContentLicense: CC BY-SA 3.0


问:
Can't build an Android Cordova project (Ionic 5)
I'm making an app in Ionic 5 (with Angular as my framework of choice), which uses Cordova for compiling the final hybrid app.

As the final development period is coming, I'm trying to put some ads into the app. For that, I used the Cordova's plugin "AdMobFree", and integrated it with ionic-native/admob-free NPM package for using the plugin from my codebase.

Thing is, I'm not being able to compile anything. The error I'm getting seems to be related with the Google Play Services package. This error starts giving me the following warning:

```<code>WARNING in ./node_modules/parse/node_modules/crypto-js/core.js
Module not found: Error: Can't resolve 'crypto' in 'D:\Dev\bygymapp\node_modules\parse\node_modules\crypto-js'
</code>```

As it is only a warning, I don't give it too much credit, but I add it in case it's related. The big chunk of the problem seems to be here:

```<code>    BUILD FAILED in 14s
D:\Dev\bygymapp\platforms\android\gradlew: Command failed with exit code 1 Error output:
FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.
> In project 'app' a resolved Google Play services library dependency depends on another at an exact version (e.g. "[17.0.
  0]", but isn't being resolved to that version. Behavior exhibited by the library will be unknown.

  Dependency failing: com.google.android.gms:play-services-measurement-api:17.0.0 -> com.google.android.gms:play-services-
  measurement-sdk-api@[17.0.0], but play-services-measurement-sdk-api version was 17.1.0.

  The following dependencies are project dependencies that are direct or have transitive dependencies that lead to the art
  ifact with the issue.
  -- Project 'app' depends onto com.google.android.gms:play-services-ads@11.0.4
  -- Project 'app' depends onto com.google.android.gms:play-services-measurement-sdk@17.0.0
  -- Project 'app' depends onto com.google.android.gms:play-services-ads@19.0.1
  -- Project 'app' depends onto com.google.android.gms:play-services-gass@19.0.1
  -- Project 'app' depends onto com.google.firebase:firebase-core@17.0.0
  -- Project 'app' depends onto com.google.android.gms:play-services-ads@16.0.0
  -- Project 'app' depends onto com.google.android.gms:play-services-tagmanager-api@17.0.0
  -- Project 'app' depends onto com.google.firebase:firebase-analytics@17.0.0
  -- Project 'app' depends onto com.google.android.gms:play-services-tagmanager@17.0.0
  -- Project 'app' depends onto com.google.android.gms:play-services-measurement-api@17.0.0
  -- Project 'app' depends onto com.google.android.gms:play-services-measurement-sdk-api@17.1.0
  -- Project 'app' depends onto com.google.android.gms:play-services-ads-lite@19.0.1

  For extended debugging info execute Gradle from the command line with ./gradlew --info :app:assembleDebug to see the dep
  endency paths to the artifact. This error message came from the google-services Gradle plugin, report issues at https://
  github.com/google/play-services-plugins and disable by adding "googleServices { disableVersionCheck = false }" to your b
  uild.gradle file.
</code>```

I tried declaring different versions of the Google Play Service in my package.json, but I couldn't manage to get this error off. The app works well when I use it with ionic serve (even if the AdMobFree plugin doesn't work because it's on a browser instead of a mobile device), so I guess it's not a problem of my codebase nor the plugin itself, but rather, a problem with my Android SDK versions and so.

Anybody got any idea on how to fix this annoying error?

Thank you a lot!

edit: my environment looks like this:

```<code>Windows 10
Node Version: 14.1
Ionic Version: 5.4.14
Cordova Android: ^8.1.0
</code>```

This is my build.gradle:

```<code>buildscript {
    repositories {
        google()
        jcenter()
    }

    dependencies {
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files

        classpath 'com.android.tools.build:gradle:3.3.0'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }

    //This replaces project.properties w.r.t. build settings
    project.ext {
      defaultBuildToolsVersion="28.0.3" //String
      defaultMinSdkVersion=19 //Integer - Minimum requirement is Android 4.4
      defaultTargetSdkVersion=28 //Integer - We ALWAYS target the latest by default
      defaultCompileSdkVersion=28 //Integer - We ALWAYS compile with the latest by default
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

edit 2:
After many attempts and two answers, this is still not working. I'm getting the same error over and over, with the mention to the Google Play Services dependency error, especially with the com.google.android.gms:play-services-measurement-api package.

This is getting out of hand since I already tried every solution and nothing seems to yield results. I can't stress enough how much I need help with this.

答:
I was able to reproduce similar issue creating an empty Ionic app and adding the following two plugins: cordova-plugin-firebase-analytics & cordova-plugin-admob-free. I had to register the test app at Admob & Firebase and download the Firebase config file. The same dependencies related error in the log. I followed the suggestions from this thread.

Here's what I did:

```<code>cordova plugin rm cordova-plugin-admob-free --variable ADMOB_APP_ID="xxx"
cordova plugin add cordova-admob-sdk
cordova plugin add cordova-plugin-admob-free --variable ADMOB_APP_ID="xxx"
</code>```

This has fixed the problem for me.

Body:
I'm making an app in Ionic 5 (with Angular as my framework of choice), which uses Cordova for compiling the final hybrid app.

As the final development period is coming, I'm trying to put some ads into the app. For that, I used the Cordova's plugin "AdMobFree", and integrated it with ionic-native/admob-free NPM package for using the plugin from my codebase.

Thing is, I'm not being able to compile anything. The error I'm getting seems to be related with the Google Play Services package. This error starts giving me the following warning:

WARNING in ./node_modules/parse/node_modules/crypto-js/core.js
Module not found: Error: Can't resolve 'crypto' in 'D:\Dev\bygymapp\node_modules\parse\node_modules\crypto-js'

As it is only a warning, I don't give it too much credit, but I add it in case it's related. The big chunk of the problem seems to be here:

    BUILD FAILED in 14s
D:\Dev\bygymapp\platforms\android\gradlew: Command failed with exit code 1 Error output:
FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.
> In project 'app' a resolved Google Play services library dependency depends on another at an exact version (e.g. "[17.0.
  0]", but isn't being resolved to that version. Behavior exhibited by the library will be unknown.

  Dependency failing: com.google.android.gms:play-services-measurement-api:17.0.0 -> com.google.android.gms:play-services-
  measurement-sdk-api@[17.0.0], but play-services-measurement-sdk-api version was 17.1.0.

  The following dependencies are project dependencies that are direct or have transitive dependencies that lead to the art
  ifact with the issue.
  -- Project 'app' depends onto com.google.android.gms:play-services-ads@11.0.4
  -- Project 'app' depends onto com.google.android.gms:play-services-measurement-sdk@17.0.0
  -- Project 'app' depends onto com.google.android.gms:play-services-ads@19.0.1
  -- Project 'app' depends onto com.google.android.gms:play-services-gass@19.0.1
  -- Project 'app' depends onto com.google.firebase:firebase-core@17.0.0
  -- Project 'app' depends onto com.google.android.gms:play-services-ads@16.0.0
  -- Project 'app' depends onto com.google.android.gms:play-services-tagmanager-api@17.0.0
  -- Project 'app' depends onto com.google.firebase:firebase-analytics@17.0.0
  -- Project 'app' depends onto com.google.android.gms:play-services-tagmanager@17.0.0
  -- Project 'app' depends onto com.google.android.gms:play-services-measurement-api@17.0.0
  -- Project 'app' depends onto com.google.android.gms:play-services-measurement-sdk-api@17.1.0
  -- Project 'app' depends onto com.google.android.gms:play-services-ads-lite@19.0.1

  For extended debugging info execute Gradle from the command line with ./gradlew --info :app:assembleDebug to see the dep
  endency paths to the artifact. This error message came from the google-services Gradle plugin, report issues at https://
  github.com/google/play-services-plugins and disable by adding "googleServices { disableVersionCheck = false }" to your b
  uild.gradle file.

I tried declaring different versions of the Google Play Service in my package.json, but I couldn't manage to get this error off. The app works well when I use it with ionic serve (even if the AdMobFree plugin doesn't work because it's on a browser instead of a mobile device), so I guess it's not a problem of my codebase nor the plugin itself, but rather, a problem with my Android SDK versions and so.

Anybody got any idea on how to fix this annoying error?

Thank you a lot!

edit: my environment looks like this:

Windows 10
Node Version: 14.1
Ionic Version: 5.4.14
Cordova Android: ^8.1.0

This is my build.gradle:

buildscript {
    repositories {
        google()
        jcenter()
    }

    dependencies {
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files

        classpath 'com.android.tools.build:gradle:3.3.0'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }

    //This replaces project.properties w.r.t. build settings
    project.ext {
      defaultBuildToolsVersion="28.0.3" //String
      defaultMinSdkVersion=19 //Integer - Minimum requirement is Android 4.4
      defaultTargetSdkVersion=28 //Integer - We ALWAYS target the latest by default
      defaultCompileSdkVersion=28 //Integer - We ALWAYS compile with the latest by default
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

edit 2:
After many attempts and two answers, this is still not working. I'm getting the same error over and over, with the mention to the Google Play Services dependency error, especially with the com.google.android.gms:play-services-measurement-api package.

This is getting out of hand since I already tried every solution and nothing seems to yield results. I can't stress enough how much I need help with this.

Body:
I was able to reproduce similar issue creating an empty Ionic app and adding the following two plugins: cordova-plugin-firebase-analytics & cordova-plugin-admob-free. I had to register the test app at Admob & Firebase and download the Firebase config file. The same dependencies related error in the log. I followed the suggestions from this thread.

Here's what I did:

cordova plugin rm cordova-plugin-admob-free --variable ADMOB_APP_ID="xxx"
cordova plugin add cordova-admob-sdk
cordova plugin add cordova-plugin-admob-free --variable ADMOB_APP_ID="xxx"

This has fixed the problem for me.


问:
I cant change text using javascript?
Im working on a simple commenting system for a website using the postmail API. The thing is that i want to give the user a better error when something goes wrong because postmail only changes the URL. For this is i check the URL of the page when the page loads and if that contains an error i want to change a element to that error. The only problem is that detecting it works fine and i can also create a alert with the error but the text wont change... Can anyone help me with this?

js:

```<code>    <script>
        function sending(){
            document.getElementById("submit_form").value = 'Sending...';
        };

        if (window.location.href.indexOf("err") != -1){
            alert("An error occured! Please make sure to check your input fields."); //this works fine
            document.getElementById("ertext").innerHTML = 'Error!'; //this doesnt
        };
    </script>
</code>```

HTML:

```<code>                <form action="https://postmail.invotes.com/send"
                    method="post" id="email_form">

                    <h2>Feedback</h2>
                    <h4>Your Email:</h4>
                    <input type="text" name="subject" placeholder="aa@aa.aa" style="width: 80%;"/><br>
                    <h6>Your Message:</h6>
                    <textarea name="text" placeholder="Give some feedback" style="resize: none; width: 80%;"></textarea>
                    <input type="hidden" name="access_token" value="--" />

                    <input type="hidden" name="success_url" value="./comments.html" />
                    <input type="hidden" name="error_url" value="./comments.html?err=1" /><br><br>

                    <input id="submit_form" type="submit" value="Send" onclick="sending();" />

                </form>
                <p id="ertext"></p>
                <br> <br>```
```

答:
It depends on where you put the script. If you put it before the DOM element, document.getElementById("ertext") wouldn't find the element.

the element

```

Title: I cant change text using javascript?

Body:
Im working on a simple commenting system for a website using the postmail API. The thing is that i want to give the user a better error when something goes wrong because postmail only changes the URL. For this is i check the URL of the page when the page loads and if that contains an error i want to change a element to that error. The only problem is that detecting it works fine and i can also create a alert with the error but the text wont change... Can anyone help me with this?

js:

HTML:

                <form action="https://postmail.invotes.com/send"
                    method="post" id="email_form">

Feedback

Your Email:

                    <input type="text" name="subject" placeholder="aa@aa.aa" style="width: 80%;"/>

Your Message:

                    <textarea name="text" placeholder="Give some feedback" style="resize: none; width: 80%;"></textarea>
                    <input type="hidden" name="access_token" value="--" />

                    <input type="hidden" name="success_url" value="./comments.html" />
                    <input type="hidden" name="error_url" value="./comments.html?err=1" />

                    <input id="submit_form" type="submit" value="Send" onclick="sending();" />

                </form>

```

Body:
It depends on where you put the script. If you put it before the DOM element, document.getElementById("ertext") wouldn't find the element.

<script>
  // before the DOM element

  // Below line would raise TypeError: Cannot set property 'innerHTML' of null
  document.getElementById('ertext').innerHTML = location.href;
</script>
<h1 id="ertext">the element</h1>
<script>
  // after the DOM element

  // You'd see `the element after` which indicates
  // the script that is after the DOM element can find the element.
  document.getElementById('ertext').innerHTML += ' after';
</script>


问:
What's the difference between .NET Core, .NET Framework, and Xamarin?
Microsoft now has .NET Core, .NET Framework and Xamarin (Mono) in its family.

It seems to be a lot of overlap here. What's the difference between these types of .NET Platforms? When should I choose to use .NET Core in my project, instead of .NET Framework or Xamarin?

答:
Xamarin is used for phone applications (both IOS/Android). The .NET Core is used for designing Web applications that can work on both Apache and IIS.

That is the difference in two sentences.


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

On a chef-client run, I see this:

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

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

Here is the relevant piece of the recipe:

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

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

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

Any ideas how to make this work?

答: Add lazy {} block around node.run_state where you are utilizing it. So in your directory and template resource. lazy {} ensures that the resource evaluates during the execution phase of a Chef Infra Client run (as opposed to during the compile phase). You can read more about lazy block here</p>

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

On a chef-client run, I see this:

       Compiling Cookbooks...
       {}

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

Here is the relevant piece of the recipe:

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

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

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

Any ideas how to make this work?


问:
Python Twisted Scrapy AttributeError: 'DefaultOpenSSLContextFactory' object has no attribute 'privateKey'
In this code, I am trying to use a certificate .key and .pem file for a private page which I am authorized to use.

```<code>from OpenSSL import SSL
from twisted.internet import ssl

class BrowserLikeContextFactory(ScrapyClientContextFactory):

        def creatorForNetloc(self, hostname, port):

            certificate = ssl.DefaultOpenSSLContextFactory('path\\sample.key','path\\sample.pem')

            return optionsForClientTLS(hostname.decode("ascii"),
                trustRoot=platformTrust(),
                clientCertificate=certificate,
                extraCertificateOptions={
                'method': self._ssl_method,
                    })

</code>```

The two files exist in the path specified. I tried a fetch command in Scrapy and this was the first result.

However, after putting in the PEM pass phrase, this error was encountered? How do I resolve this?

答:
This is not exactly the answer to your question, but it's too long for a comment. I find it easier NOT dealing with one-off certificates like self signed certificates or certificates for local/private servers. I've had success with something like this (taken from a treq project but should work for scrapy too, with some tweaking):

import re

from twisted.internet import ssl
from twisted.web.iweb import IPolicyForHTTPS
from twisted.web.client import BrowserLikePolicyForHTTPS, Agent
from zope.interface import implementer

@implementer(IPolicyForHTTPS)
class RegexContextFactory:

    defaultPolicy = BrowserLikePolicyForHTTPS()

    def __init__(self, re_domains):
        self.re_domains = re.compile(re_domains)

    def creatorForNetloc(self, hostname, port):
        if self.re_domains.match(hostname) != None:
            return ssl.CertificateOptions(verify=False)
        return self.defaultPolicy.creatorForNetloc(hostname, port)

# Replace regex with one that will match your private domains
regex_factory = RegexContextFactory(b"^(dev|test|stage)-api\.private.net")
```

The RegexContextFactory accepts a regex (make sure it's bytes type) and ignores security measures for all TLS URLs that match the regex. All other URLs behave in the default manner.

Body:
In this code, I am trying to use a certificate .key and .pem file for a private page which I am authorized to use.

from OpenSSL import SSL
from twisted.internet import ssl

class BrowserLikeContextFactory(ScrapyClientContextFactory):

        def creatorForNetloc(self, hostname, port):

            certificate = ssl.DefaultOpenSSLContextFactory('path\\sample.key','path\\sample.pem')

            return optionsForClientTLS(hostname.decode("ascii"),
                trustRoot=platformTrust(),
                clientCertificate=certificate,
                extraCertificateOptions={
                'method': self._ssl_method,
                    })

The two files exist in the path specified. I tried a fetch command in Scrapy and this was the first result.

However, after putting in the PEM pass phrase, this error was encountered? How do I resolve this?

Body:
This is not exactly the answer to your question, but it's too long for a comment. I find it easier NOT dealing with one-off certificates like self signed certificates or certificates for local/private servers. I've had success with something like this (taken from a treq project but should work for scrapy too, with some tweaking):

import re

from twisted.internet import ssl
from twisted.web.iweb import IPolicyForHTTPS
from twisted.web.client import BrowserLikePolicyForHTTPS, Agent
from zope.interface import implementer

@implementer(IPolicyForHTTPS)
class RegexContextFactory:

    defaultPolicy = BrowserLikePolicyForHTTPS()

    def __init__(self, re_domains):
        self.re_domains = re.compile(re_domains)

    def creatorForNetloc(self, hostname, port):
        if self.re_domains.match(hostname) != None:
            return ssl.CertificateOptions(verify=False)
        return self.defaultPolicy.creatorForNetloc(hostname, port)

# Replace regex with one that will match your private domains
regex_factory = RegexContextFactory(b"^(dev|test|stage)-api\.private.net")

The RegexContextFactory accepts a regex (make sure it's bytes type) and ignores security measures for all TLS URLs that match the regex. All other URLs behave in the default manner.


问:
Passing a variable to setIntervall function
i am calling a jQuery plugin every 5 seconds with the following code

```<code>    var now = new Date();

    setInterval('$("#id").myplugin(now)', 1000);
</code>```

The Plugin looks like this so far:

```<code>    (function( $ ){
    $.fn.myplugin = function(now) {
        return this.each(function() {
            alert(now.getTime());
        });
    }
   })( jQuery );
</code>```

However I get the error:

Uncaught ReferenceError: now is not defined

  plugins.js:30 Uncaught TypeError: Cannot call method 'getTime' of undefined

So it looks as if the now time object doenst get passed to the plugin function and is not even defined in the setInterval method. I could probably call var now = new Date(); every time in the plugin function ... but I want to know, why it doenst work like that and how to make it work ;). thx alot.

答:
Use a function like this:

```<code>var now = new Date();

setInterval(function() {
    $("#id").myplugin(now);
}, 1000);
</code>```

This way, the so-called scope of now is set to the function in which you call setInterval. Otherwise, it is just the global object (window) you're referring to, which doesn't have a now.

Secondly, passing a string works like eval(), which is unsafe and slow: Why is eval unsafe in javascript?.

Body:
i am calling a jQuery plugin every 5 seconds with the following code

    var now = new Date();

    setInterval('$("#id").myplugin(now)', 1000);

The Plugin looks like this so far:

    (function( $ ){
    $.fn.myplugin = function(now) {
        return this.each(function() {
            alert(now.getTime());
        });
    }
   })( jQuery );

However I get the error:

Uncaught ReferenceError: now is not defined

  plugins.js:30 Uncaught TypeError: Cannot call method 'getTime' of undefined

So it looks as if the now time object doenst get passed to the plugin function and is not even defined in the setInterval method. I could probably call var now = new Date(); every time in the plugin function ... but I want to know, why it doenst work like that and how to make it work ;). thx alot.

Body:
Use a function like this:

var now = new Date();

setInterval(function() {
    $("#id").myplugin(now);
}, 1000);

This way, the so-called scope of now is set to the function in which you call setInterval. Otherwise, it is just the global object (window) you're referring to, which doesn't have a now.

Secondly, passing a string works like eval(), which is unsafe and slow: Why is eval unsafe in javascript?.


问:
Displaying employee record or manager record along with his employees in oracle apex report
I have created a report with a form in Oracle Apex where:

if normal employee logins in timesheet application, then the report should display only the employee record, but

if manager logs in then the report should display manager record along with all the employees working under him.

How to achieve this? can anyone guide me?

答:
How do you distinguish "normal employees" from "managers"? There should be some table which says so. As code you posted as comments (really, why did you do that? Couldn't you edit the question and post properly formatted code instead of this unreadable mess?) suggests that unique identifier is someone's e-mail address which is also used as username when logging to Apex, that table would have pairs [e-mail + role], e.g.

```<code>SQL> desc apex_roles
 Name                                      Null?    Type
 ----------------------------------------- -------- ------------------------
 E_MAIL                                             VARCHAR2(15)
 ROLE                                               CHAR(1)

SQL> select * from apex_roles;

E_MAIL          R
--------------- -
lf@gmail.com    M          --> M = manager
kamal@yahoo.com E

SQL>
</code>```

Now, create a function which says whether someone is a manager. Let it return 1 if it is, 0 if it is not (why not Boolean? You can't use it in select statements).

```<code>SQL> create or replace function f_is_manager(par_app_user in varchar2)
  2    return number
  3  is
  4    retval number := 0;
  5  begin
  6    select 1
  7      into retval
  8      from apex_roles
  9      where e_mail = par_app_user
 10        and role = 'M';
 11
 12    return retval;
 13  exception
 14    when no_data_found then
 15      -- user isn't a manager
 16      return retval;
 17  end;
 18  /

Function created.

SQL>
</code>```

Now use that function in where clause in report; suppose that this is table that contains data you'd like to display:

```<code>SQL> select * from my_data;

E_MAIL               JOB              SAL
-------------------- --------- ----------
CLARK@gmail.com      MANAGER         2450
KING@gmail.com       PRESIDENT       5000
MILLER@gmail.com     CLERK           1300
lf@gmail.com         MANAGER         2200        --> manager in APEX_ROLES table
kamal@yahoo.com      CLERK           1500
</code>```

What happens when kamal runs the report? That user sees only its own data:

```<code>SQL> select job, sal
  2  from my_data
  3  where e_mail = case when f_is_manager('&&APP_USER') = 1 then e_mail
  4                      else '&&APP_USER'
  5                 end;
Enter value for app_user: kamal@yahoo.com

JOB              SAL
--------- ----------
CLERK           1500
</code>```

But, if a manager runs it, it sees everyone's data:

```<code>SQL> select job, sal
  2  from my_data
  3  where e_mail = case when f_is_manager('&&APP_USER') = 1 then e_mail
  4                      else '&&APP_USER'
  5                 end;
Enter value for app_user: lf@gmail.com

JOB              SAL
--------- ----------
MANAGER         2450
PRESIDENT       5000
CLERK           1300
MANAGER         2200
CLERK           1500

SQL>
</code>```

As it is Apex, you'd actually use

```<code>select job, sal
from my_data
where e_mail = case when f_is_manager(:APP_USER) = 1 then e_mail
                    else ':APP_USER'
               end;
</code>```

Body:
How do you distinguish "normal employees" from "managers"? There should be some table which says so. As code you posted as comments (really, why did you do that? Couldn't you edit the question and post properly formatted code instead of this unreadable mess?) suggests that unique identifier is someone's e-mail address which is also used as username when logging to Apex, that table would have pairs [e-mail + role], e.g.

SQL> desc apex_roles
 Name                                      Null?    Type
 ----------------------------------------- -------- ------------------------
 E_MAIL                                             VARCHAR2(15)
 ROLE                                               CHAR(1)

SQL> select * from apex_roles;

E_MAIL          R
--------------- -
lf@gmail.com    M          --> M = manager
kamal@yahoo.com E

SQL>

Now, create a function which says whether someone is a manager. Let it return 1 if it is, 0 if it is not (why not Boolean? You can't use it in select statements).

SQL> create or replace function f_is_manager(par_app_user in varchar2)
  2    return number
  3  is
  4    retval number := 0;
  5  begin
  6    select 1
  7      into retval
  8      from apex_roles
  9      where e_mail = par_app_user
 10        and role = 'M';
 11
 12    return retval;
 13  exception
 14    when no_data_found then
 15      -- user isn't a manager
 16      return retval;
 17  end;
 18  /

Function created.

SQL>

Now use that function in where clause in report; suppose that this is table that contains data you'd like to display:

SQL> select * from my_data;

E_MAIL               JOB              SAL
-------------------- --------- ----------
CLARK@gmail.com      MANAGER         2450
KING@gmail.com       PRESIDENT       5000
MILLER@gmail.com     CLERK           1300
lf@gmail.com         MANAGER         2200        --> manager in APEX_ROLES table
kamal@yahoo.com      CLERK           1500

What happens when kamal runs the report? That user sees only its own data:

SQL> select job, sal
  2  from my_data
  3  where e_mail = case when f_is_manager('&&APP_USER') = 1 then e_mail
  4                      else '&&APP_USER'
  5                 end;
Enter value for app_user: kamal@yahoo.com

JOB              SAL
--------- ----------
CLERK           1500

But, if a manager runs it, it sees everyone's data:

SQL> select job, sal
  2  from my_data
  3  where e_mail = case when f_is_manager('&&APP_USER') = 1 then e_mail
  4                      else '&&APP_USER'
  5                 end;
Enter value for app_user: lf@gmail.com

JOB              SAL
--------- ----------
MANAGER         2450
PRESIDENT       5000
CLERK           1300
MANAGER         2200
CLERK           1500

SQL>

As it is Apex, you'd actually use

select job, sal
from my_data
where e_mail = case when f_is_manager(:APP_USER) = 1 then e_mail
                    else ':APP_USER'
               end;


问:
counting some string values for each group of id numbers
I have data in this form:

```<code>import pandas as pd
people_num=[1,1,2,2,2]
visited_places=['school', 'restaurant', 'church', 'restaurant', 'church']

df= pd.DataFrame({'people_num':people_num, 'visited_places':visited_places})
</code>```

I want to add a new column that contains the counting number of strings for each people number.

To visualize, Original table is like,

```<code>+------------+----------------+
| people_num | visited_places |
+------------+----------------+
|          1 | school         |
|          1 | restaurant     |
|          2 | church         |
|          2 | restaurant     |
|          2 | church         |
+------------+----------------+
</code>```

And The new table I want to get from this :

```<code>+------------+------------------------------+
| people_num |       counts_of_places       |
+------------+------------------------------+
|          1 | {'school':1,'restaurant':1}  |
|          2 | {'church':2, 'restaurant':1} |
+------------+------------------------------+
</code>```

Thanks in advance.

答:
I don't think you should put dictionaries into DataFrame columns.

I propose the following alternative solution.

```<code>>>> df
   people_num visited_places
0           1         school
1           1     restaurant
2           2         church
3           2     restaurant
4           2         church
>>> df.groupby('people_num')['visited_places'].value_counts().unstack(fill_value=0)
visited_places  church  restaurant  school
people_num
1                    0           1       1
2                    2           1       0
</code>```

... but if you insist

```<code>>>> df.groupby('people_num')['visited_places'].agg(lambda g: g.value_counts().to_dict())
people_num
1    {'restaurant': 1, 'school': 1}
2    {'church': 2, 'restaurant': 1}
Name: visited_places, dtype: object
</code>```

Body:
I have data in this form:

import pandas as pd
people_num=[1,1,2,2,2]
visited_places=['school', 'restaurant', 'church', 'restaurant', 'church']

df= pd.DataFrame({'people_num':people_num, 'visited_places':visited_places})

I want to add a new column that contains the counting number of strings for each people number.

To visualize, Original table is like,

+------------+----------------+
| people_num | visited_places |
+------------+----------------+
|          1 | school         |
|          1 | restaurant     |
|          2 | church         |
|          2 | restaurant     |
|          2 | church         |
+------------+----------------+

And The new table I want to get from this :

+------------+------------------------------+
| people_num |       counts_of_places       |
+------------+------------------------------+
|          1 | {'school':1,'restaurant':1}  |
|          2 | {'church':2, 'restaurant':1} |
+------------+------------------------------+

Thanks in advance.

Body:
I don't think you should put dictionaries into DataFrame columns.

I propose the following alternative solution.

>>> df
   people_num visited_places
0           1         school
1           1     restaurant
2           2         church
3           2     restaurant
4           2         church
>>> df.groupby('people_num')['visited_places'].value_counts().unstack(fill_value=0)
visited_places  church  restaurant  school
people_num
1                    0           1       1
2                    2           1       0

... but if you insist

>>> df.groupby('people_num')['visited_places'].agg(lambda g: g.value_counts().to_dict())
people_num
1    {'restaurant': 1, 'school': 1}
2    {'church': 2, 'restaurant': 1}
Name: visited_places, dtype: object


问:
CNN model not working well on 4 species but works well with 2 species
I tried CNN model on two classes and got 80% but when i tried the same model with 4 classes i got very bad result. What is the reason pls help.
The model of CNN i used is:

```<code>model= Sequential()

model.add(Conv2D(64,(3,3),input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())

model.add(Dense(64))
model.add(Activation('relu'))

model.add(Dropout(0.5))

model.add(Dense(1))
model.add(Activation('sigmoid'))

#opt = SGD( lr=0.01)

model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

history = model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples//batch_size,
    epochs=epochs,
    validation_data = validation_generator,
    validation_steps = validation_generator.samples // batch_size,
)
</code>```

The result of 2 classes something like this i lost the actual result of it:

```<code>Epoch 29/35
46/46 [==============================] - 188s 4s/step - loss: 0.6511 - accuracy: 0.5880 - val_loss: 0.7534 - val_accuracy: 0.5175

</code>```

The result with 4 classes is:

```<code>46/46 [==============================] - 367s 8s/step - loss: -10550614391401.7266 - accuracy: 0.2541 - val_loss: -15023441182720.0000 - val_accuracy: 0.2354
</code>```

答:
Difference between Sigmoid and Softmax

Difference between Sigmoid and Softmax function in deep learning
Softmax function can be understood as a generalized version of a sigmoid function or an extension of a sigmoid function. Softmax function is usually used in the output layers of neural networks.

Following are some of the differences between Sigmoid and Softmax function:

1. The sigmoid function is used for the two-class (binary) classification problem, whereas the softmax function is used for the multi-class classification problem.

2. Sum of all softmax units are supposed to be 1. In sigmoid, it’s not really necessary. Sigmoid just makes output between 0 to 1. The softmax enforces that the sum of the probabilities of all the output classes are equal to one, so in order to increase the probability of a particular class, softmax must correspondingly decrease the probability of at least one of the other classes.

When you use a softmax, basically you get a probability of each class (join distribution and a multinomial likelihood) whose sum is bound to be one. In case, you use sigmoid for multi-class classification, it’d be like a marginal distribution and a Bernoulli likelihood.

3 Formular for SoftMax function

4 Formular for Sigmoid function

Let me illustrate the point 2 with an example here. Lets say, we have 6 inputs:

[1,2,3,4,5,6]

If we pass these inputs through the sigmoid function, we will get following output:

[0.5, 0.73, 0.88, 0.95, 0.98, 0.99]

Sum of the above output units is 5.03 which is greater than 1.

But in case of softmax, the sum of output units is always 1. Lets see how? Pass the same input to softmax function, and we get following output:

[0.001, 0.009, 0.03, 0.06, 0.1, 0.8] which sums up to 1.

5. Sigmoid is usually used as an activation function in hidden layers (but we use ReLU nowadays) while Softmax is used in output layers

A general rule of thumb is to use ReLU as an activation function in hidden layers and softmax in output layer in a neural networks.

for more details here

So you have to use softmax activation function and categorical cross-entropy as the loss function for multi-class classification cases.

Body:
I tried CNN model on two classes and got 80% but when i tried the same model with 4 classes i got very bad result. What is the reason pls help.
The model of CNN i used is:

model= Sequential()

model.add(Conv2D(64,(3,3),input_shape=input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Conv2D(64,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

model.add(Flatten())

model.add(Dense(64))
model.add(Activation('relu'))

model.add(Dropout(0.5))

model.add(Dense(1))
model.add(Activation('sigmoid'))

#opt = SGD( lr=0.01)

model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

history = model.fit_generator(
    train_generator,
    steps_per_epoch=nb_train_samples//batch_size,
    epochs=epochs,
    validation_data = validation_generator,
    validation_steps = validation_generator.samples // batch_size,
)

The result of 2 classes something like this i lost the actual result of it:

Epoch 29/35
46/46 [==============================] - 188s 4s/step - loss: 0.6511 - accuracy: 0.5880 - val_loss: 0.7534 - val_accuracy: 0.5175

The result with 4 classes is:

46/46 [==============================] - 367s 8s/step - loss: -10550614391401.7266 - accuracy: 0.2541 - val_loss: -15023441182720.0000 - val_accuracy: 0.2354


问:
Reusing content of Angular ngb-tabs in multiple tabs with ngTemplateOutlet or something else
I am using Angular ng-tabset to render some tabs. My ngb-tab looks somewhat like:

```<code><ngb-tab id="mytabs">
    <ng-template ngbTabTitle>
        <div data-locator="xxxe">yyy</div>
    </ng-template>
    <ng-template ngbTabContent>
        ...
        ...
        ...
    </ng-template>
</ngb-tab>
</code>```

which works fine. But I have a couple of other tabs also in this template where I want the same content rendered. so, for the purpose of re-usability, I was trying to move the contents of the tab separate and use it's reference in each tab where I want that rendered. I am not sure how to do it. I tried putting it inside a separate <ng-template> as:

```<code><ng-template #testing>
    <ng-template ngbTabTitle>
        <div data-locator="xxxe">yyy</div>
    </ng-template>
    <ng-template ngbTabContent>
        ...
        ...
        ...
    </ng-template>
<ng-template
</code>```

and under tab, where I need this rendered, I try to call it as:

```<code><ngb-tab id="mytabs">
    <ng-container *ngTemplateOutlet="testing"></ng-container>    // referring the #testing above
</ngb-tab>

OR:

<ngb-tab id="mytabs">
    <ng-template *ngTemplateOutlet="testing"></ng-template>
</ngb-tab>
</code>```

But my tabs are not rendered. Maybe its wrong approach or I am missing something. Is it possible to achieve what I am trying to achieve? If yes, how?

答:
I would suggest not nesting the ng-templates and use them with different ids, then inserting them under ngb-tab separately like this:</p>

```<code><ng-template ngbTabTitle #testTitle>
    <div data-locator="xxxe">yyy</div>
</ng-template>
<ng-template ngbTabContent #testContent>
    ...
    ...
    ...
</ng-template>
<ngb-tab id="mytabs">
    <ng-container *ngTemplateOutlet="testTitle"></ng-container>
    <ng-container *ngTemplateOutlet="testContent"></ng-container>
</ngb-tab>
</code>```

Body:
I am using Angular ng-tabset to render some tabs. My ngb-tab looks somewhat like:

<ngb-tab id="mytabs">
    <ng-template ngbTabTitle>

yyy

    </ng-template>
    <ng-template ngbTabContent>
        ...
        ...
        ...
    </ng-template>
</ngb-tab>

which works fine. But I have a couple of other tabs also in this template where I want the same content rendered. so, for the purpose of re-usability, I was trying to move the contents of the tab separate and use it's reference in each tab where I want that rendered. I am not sure how to do it. I tried putting it inside a separate <ng-template> as:

<ng-template #testing>
    <ng-template ngbTabTitle>

yyy

    </ng-template>
    <ng-template ngbTabContent>
        ...
        ...
        ...
    </ng-template>
<ng-template

and under tab, where I need this rendered, I try to call it as:

<ngb-tab id="mytabs">
    <ng-container *ngTemplateOutlet="testing"></ng-container>    // referring the #testing above
</ngb-tab>

OR:

<ngb-tab id="mytabs">
    <ng-template *ngTemplateOutlet="testing"></ng-template>
</ngb-tab>

But my tabs are not rendered. Maybe its wrong approach or I am missing something. Is it possible to achieve what I am trying to achieve? If yes, how?

Body:
I would suggest not nesting the ng-templates and use them with different ids, then inserting them under ngb-tab separately like this:

<ng-template ngbTabTitle #testTitle>
    <div data-locator="xxxe">yyy</div>
</ng-template>
<ng-template ngbTabContent #testContent>
    ...
    ...
    ...
</ng-template>
<ngb-tab id="mytabs">
    <ng-container *ngTemplateOutlet="testTitle"></ng-container>
    <ng-container *ngTemplateOutlet="testContent"></ng-container>
</ngb-tab>


问:
Overwrite Paste Event for TextFormField
I have a TextFormField. Usually you can use the selection toolbar to copy/paste/select all and so on using long tap/double tap.

I want to overwrite the Paste Event. It shouldn't simple insert the current clipboard data but open a popup with several options to insert.

Is it possible to catch and overwrite the Paste event in any way? I saw something like handlePaste() for SelectionControls, but I don't know how to add this to my TextFormField.

Thanks in advance!

答:
AFAIK, you can't exactly 'intercept' the standard toolbar. However, what you can do is to prevent the standard toolbar and make your own.

You can use wrap the textfield/textformfield under IgnorePointer. It will hide any tap gestures on the text field. Below is the code snippet.

```<code>IgnorePointer(
    child: TextField(
        focusNode: _textfieldFocusNode,
        controller: _controller,
    ),
)
</code>```

Now,you can wrap this IgnorePointer under GestureDetector and show your own menu. Like this :

```<code>GestureDetector(
    behavior: HitTestBehavior.opaque,
    onTap: () {
        FocusScope.of(context).requestFocus(_textfieldFocusNode);
    },
    onLongPress: () {
        showMenu(____
    }
)
</code>```

This produces the result below and the sample implementation code is here

Title: Overwrite Paste Event for TextFormField

Body:
AFAIK, you can't exactly 'intercept' the standard toolbar. However, what you can do is to prevent the standard toolbar and make your own.

You can use wrap the textfield/textformfield under IgnorePointer. It will hide any tap gestures on the text field. Below is the code snippet.

IgnorePointer(
    child: TextField(
        focusNode: _textfieldFocusNode,
        controller: _controller,
    ),
)

Now,you can wrap this IgnorePointer under GestureDetector and show your own menu. Like this :

GestureDetector(
    behavior: HitTestBehavior.opaque,
    onTap: () {
        FocusScope.of(context).requestFocus(_textfieldFocusNode);
    },
    onLongPress: () {
        showMenu(____
    }
)

This produces the result below and the sample implementation code is here


问:
Jenkins pipeline for loop output returning as individual letters rather that items
In my Jenkins pipeline I have a property

```<code>SERVICES=[test, dev, perf, prod, uat]
</code>```

I want to use this property in a for loop

```<code>                for(int i=0; i<SERVICES.size(); i++) {
                    println(SERVICES[i])
                }
</code>```

However the for loop is treating the property with each each letter rather that each item so the out put is as follows:

```<code>[
t
e
s
t
,

d
e
v
...
</code>```

How can I get the get the for loop to treat each item as a whole rather than by letters?

答: you are using println which print each item in new line try to print new line outside of a loop</p>

Body:
In my Jenkins pipeline I have a property

SERVICES=[test, dev, perf, prod, uat]

I want to use this property in a for loop

                for(int i=0; i<SERVICES.size(); i++) {
                    println(SERVICES[i])
                }

However the for loop is treating the property with each each letter rather that each item so the out put is as follows:

[
t
e
s
t
,

d
e
v
...

How can I get the get the for loop to treat each item as a whole rather than by letters?


答:
I hope that I understand your question right.  For re-usability of templates you can create you own components. For re-usability of logic you can create services.</p>

```<code><ngb-tab id="mytabs">
    <ng-template ngbTabTitle>
        <my-xyz-comp data-locator="xxxe"></my-xyz-comp>
    </ng-template>
    <ng-template ngbTabContent>
        <my-xyz-comp data-locator="aaaa"></my-xyz-comp>
    </ng-template>
</ngb-tab>
</code>```

Title: Reusing content of Angular ngb-tabs in multiple tabs with ngTemplateOutlet or something else

Body:
I hope that I understand your question right.  For re-usability of templates you can create you own components. For re-usability of logic you can create services.

<ngb-tab id="mytabs">
    <ng-template ngbTabTitle>
        <my-xyz-comp data-locator="xxxe"></my-xyz-comp>
    </ng-template>
    <ng-template ngbTabContent>
        <my-xyz-comp data-locator="aaaa"></my-xyz-comp>
    </ng-template>
</ngb-tab>


问:
Replace data after angle brackets
UDP Image which need to be changedI have  udp , would like to change udp to tcp inside my config file , can someone please help me here.

sed 's/udp/tcp/'   /config path/

Regards
Dev

答:
Try this:

```<code>sed -i 's/udp/tcp/g' path/to/filename
</code>```

g for global

-i modify the file inplace

If you want to backup the original file:

```<code>sed -i.bak 's/udp/tcp/g' path/to/filename
</code>```

Title: Replace data after angle brackets

Body:
Try this:

sed -i 's/udp/tcp/g' path/to/filename

g for global

-i modify the file inplace

If you want to backup the original file:

sed -i.bak 's/udp/tcp/g' path/to/filename


问:
Sorting a list based off of values in another list
I have two lists; invoice_ordering_list and pdfs. I need to sort pdfs based on the order of invoice_ordering_list.

```<code>invoice_ordering_list = ['265189', '265195', '265114', '265166', '265165', '265115']

pdfs = [
    'Est. 57349 April Bill Inv 265115.pdf',
    'AH_202015_JUN_57768 265189.pdf',
    'AH_202015_MAY FEE_265195.pdf',
    'Est. 56534 April Bill Inv 265165.pdf',
    'Est. 57279 April Bill Inv 265166.pdf',
    'Est. 42477 April Bill Inv 265114.pdf',
]
</code>```

I've tried:

```<code>keydict = dict(zip(pdfs, invoice_ordering_list))
pdfs.sort(key=keydict.get)
</code>```

For some reason it almost gets the order right but 265189 ends up at the end. I must be misunderstanding what's going on here. this seems like such an easy task that I just can't figure out.

The output should be:

```<code>pdfs_new = [
    'AH_202015_JUN_57768 265189.pdf',
    'AH_202015_MAY FEE_265195.pdf',
    'Est. 42477 April Bill Inv 265114.pdf',
    'Est. 57279 April Bill Inv 265166.pdf',
    'Est. 56534 April Bill Inv 265165.pdf',
    'Est. 57349 April Bill Inv 265115.pdf',
]
</code>```

答:
Try this way:

Step 1: create a dictionary be getting key from the pdf's file name

In this,step I extract the digits only on the last string joined with .pdf

```<code>d={}
for p in pdfs:
 key = re.findall(r'\d+',p.split()[-1].rstrip('.pdf'))[0]
 d[key] =  p
</code>```

Step 2: creat a new list to store the file name according to the your invoice_ordering_list

```<code>new_pdf=[]
for k in invoice_ordering_list:
  new_pdf.append(d[k])
</code>```

Body:
I have two lists; invoice_ordering_list and pdfs. I need to sort pdfs based on the order of invoice_ordering_list.

invoice_ordering_list = ['265189', '265195', '265114', '265166', '265165', '265115']

pdfs = [
    'Est. 57349 April Bill Inv 265115.pdf',
    'AH_202015_JUN_57768 265189.pdf',
    'AH_202015_MAY FEE_265195.pdf',
    'Est. 56534 April Bill Inv 265165.pdf',
    'Est. 57279 April Bill Inv 265166.pdf',
    'Est. 42477 April Bill Inv 265114.pdf',
]

I've tried:

keydict = dict(zip(pdfs, invoice_ordering_list))
pdfs.sort(key=keydict.get)

For some reason it almost gets the order right but 265189 ends up at the end. I must be misunderstanding what's going on here. this seems like such an easy task that I just can't figure out.

The output should be:

pdfs_new = [
    'AH_202015_JUN_57768 265189.pdf',
    'AH_202015_MAY FEE_265195.pdf',
    'Est. 42477 April Bill Inv 265114.pdf',
    'Est. 57279 April Bill Inv 265166.pdf',
    'Est. 56534 April Bill Inv 265165.pdf',
    'Est. 57349 April Bill Inv 265115.pdf',
]

Body:
Try this way:

Step 1: create a dictionary be getting key from the pdf's file name

In this,step I extract the digits only on the last string joined with .pdf

d={}
for p in pdfs:
 key = re.findall(r'\d+',p.split()[-1].rstrip('.pdf'))[0]
 d[key] =  p

Step 2: creat a new list to store the file name according to the your invoice_ordering_list

new_pdf=[]
for k in invoice_ordering_list:
  new_pdf.append(d[k])


问:
Behave: Accessing context.config variables outside of step definitions
I am can't find out a way how to init my ApiClient with the value of context.config.userdata['url'] from behave.ini

behave.ini

```<code>[behave.userdata]
url=http://some.url
</code>```

steps.py

```<code>from behave import *
from client.api_client import ApiClient

# This is where i want to pass the config.userdata['url'] value
api_calls = ApiClient('???')

@given('I am logged as "{user}" "{password}"')
def login(context, user, password):
    context.auth_header = api_calls.auth(user, password)
</code>```

api_client.py

```<code>class ApiClient(object):

    def __init__(self, url):
        self.url = url

    def auth(self, email, password):
        auth_payload = {'email': email, 'password': password}
        auth_response = requests.post(self.url + '/api/auth/session', auth_payload)

        return auth_response.text
</code>```

答:
I know this is a super old question but the answer is not current. No spaces seem to be required in the current documentation and OP's issue is the header tag. It must be [behave]

https://behave.readthedocs.io/en/latest/behave.html

Body:
I am can't find out a way how to init my ApiClient with the value of context.config.userdata['url'] from behave.ini

behave.ini

[behave.userdata]
url=http://some.url

steps.py

from behave import *
from client.api_client import ApiClient

# This is where i want to pass the config.userdata['url'] value
api_calls = ApiClient('???')

@given('I am logged as "{user}" "{password}"')
def login(context, user, password):
    context.auth_header = api_calls.auth(user, password)

api_client.py

class ApiClient(object):

    def __init__(self, url):
        self.url = url

    def auth(self, email, password):
        auth_payload = {'email': email, 'password': password}
        auth_response = requests.post(self.url + '/api/auth/session', auth_payload)

        return auth_response.text


问:
Use float or decimal for accounting application dollar amount?
We are rewriting our legacy accounting system in VB.NET and SQL Server. We brought in a new team of .NET/ SQL Programmers to do the rewrite. Most of the system is already completed with the dollar amounts using floats. The legacy system language, I programmed in, did not have a float, so I probably would have used a decimal.

What is your recommendation?

Should the float or decimal data type be used for dollar amounts?

What are some of the pros and cons for either?

One con mentioned in our daily scrum was you have to be careful when you calculate an amount that returns a result that is over two decimal positions. It sounds like you will have to round the amount to two decimal positions.

Another con is all displays and printed amounts have to have a format statement that shows two decimal positions. I noticed a few times where this was not done and the amounts did not look correct.  (i.e. 10.2 or 10.2546)

A pro is the float-only approach takes up eight bytes on disk where the decimal would take up nine bytes (decimal 12,2).

答:
Floating points have unexpected irrational numbers.

For instance you can't store 1/3 as a decimal, it would be 0.3333333333... (and so on)

Floats are actually stored as a binary value and a power of 2 exponent.

So 1.5 is stored as 3 x 2 to the -1 (or 3/2)

Using these base-2 exponents create some odd irrational numbers, for instance:

Convert 1.1 to a float and then convert it back again, your result will be something like: 1.0999999999989

This is because the binary representation of 1.1 is actually 154811237190861 x 2^-47, more than a double can handle.

More about this issue on my blog, but basically, for storage, you're better off with decimals.

On Microsoft SQL server you have the money data type - this is usually best for financial storage. It is accurate to 4 decimal positions.

For calculations you have more of a problem - the inaccuracy is a tiny fraction, but put it into a power function and it quickly becomes significant.

However decimals aren't very good for any sort of maths - there's no native support for decimal powers, for instance.

OwnerDisplayName: Gerhard Weiss

LastEditorDisplayName: Gerhard Weiss

OwnerDisplayName: Keith

ContentLicense: CC BY-SA 2.5


问:
What is the "proper" tag prefix for the AjaxControlToolkit?
I've seen many examples where they just use the "asp" prefix.  Is this a good practice?

(The reason I'm asking is because the templates that create the default for a new website appear to be problematic.  There's an apparent naming collision on the BulletedList control.)

答:
I like the prefix act.

I would definitely recommend against using asp as the prefix for anything other than the base ASP.NET WebControls.

OwnerDisplayName: Larsenal

LastEditorDisplayName: Larsenal

OwnerDisplayName: Dave Ward


问:
How to add background image to Button from material-ui in react?
I want to add background image to Material-ui button in React and I don't know how to do this correctly. Here is my code. Any ideas how to make it work? I was trying to add backgroundImage to styles, but that didn't work.

```<code>      const useStyles = makeStyles(() => ({
            buttonStep: {
                width: '150px',
                height: '49px',
                background: '#5F8FE8',
                backgrounImage: 'url("../../assets/icons/arrowButton.svg")',
              },
        }))
        export default function StepNavigation(props) {
        const classes = useStyles()

        return (

                   <Button
                        className={classes.buttonStep}
                    >
                        Next
                    </Button>
         )}
</code>```

答:
The main problem I see in your code is just a typo. You are missing the "d" in "backgroundImage".

Here is a working example:

```<code>import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";

const useStyles = makeStyles({
  buttonStep: {
    width: "150px",
    height: "49px",
    backgroundImage: "linear-gradient(.25turn, #f00, #00f)"
  }
});

export default function App() {
  const classes = useStyles();
  return <Button className={classes.buttonStep}>Next</Button>;
}
</code>```

Body:
I want to add background image to Material-ui button in React and I don't know how to do this correctly. Here is my code. Any ideas how to make it work? I was trying to add backgroundImage to styles, but that didn't work.

      const useStyles = makeStyles(() => ({
            buttonStep: {
                width: '150px',
                height: '49px',
                background: '#5F8FE8',
                backgrounImage: 'url("../../assets/icons/arrowButton.svg")',
              },
        }))
        export default function StepNavigation(props) {
        const classes = useStyles()

        return (

                   <Button
                        className={classes.buttonStep}
                    >
                        Next
                    </Button>
         )}

Body:
The main problem I see in your code is just a typo. You are missing the "d" in "backgroundImage".

Here is a working example:

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";

const useStyles = makeStyles({
  buttonStep: {
    width: "150px",
    height: "49px",
    backgroundImage: "linear-gradient(.25turn, #f00, #00f)"
  }
});

export default function App() {
  const classes = useStyles();
  return <Button className={classes.buttonStep}>Next</Button>;
}


问:
Turning 3 SQL queries into 1
I am trying to get a list of calendars - some public some private. Access to the private calendars is managed through a bridging table that lists calendar id (ccalId) and user id (cuserId). I can achieve this but using 3 SQL queries.

Is it possible to achieve this using just one query? I have tried JOINs but it never seems to work.

```<code>    $calModel->where('calTeam',session()->get('teamId'));
    $calModel->where('calType','public');
    $calModel->where('calStatus','active');
    $data = $calModel->get()->getResultArray();

    $calUserModel->select('ccalId');
    $calUserModel->where('cuserId', session()->get('id'));
    $callist = $calUserModel->get()->getResultArray();
    $newarray = implode(", ", $callist);

    $calModel->where('calTeam',session()->get('teamId'));
    $calModel->whereiI('id', $newarray);
    $data2 = $calModel->get()->getResultArray();

    $data = array_unique(array_merge($data,$data2), SORT_REGULAR);
</code>```

答:
Not every time the codeigniter query builder is the best solution. In my opinion for more complex queries it is better to do direct query to the database, instead of using models.

You can easily do a query with 2 joins to get all the results without the useless data. That would work faster and would look cleaner in your code.

Title: Turning 3 SQL queries into 1

Body:
I am trying to get a list of calendars - some public some private. Access to the private calendars is managed through a bridging table that lists calendar id (ccalId) and user id (cuserId). I can achieve this but using 3 SQL queries.

Is it possible to achieve this using just one query? I have tried JOINs but it never seems to work.

    $calModel->where('calTeam',session()->get('teamId'));
    $calModel->where('calType','public');
    $calModel->where('calStatus','active');
    $data = $calModel->get()->getResultArray();

    $calUserModel->select('ccalId');
    $calUserModel->where('cuserId', session()->get('id'));
    $callist = $calUserModel->get()->getResultArray();
    $newarray = implode(", ", $callist);

    $calModel->where('calTeam',session()->get('teamId'));
    $calModel->whereiI('id', $newarray);
    $data2 = $calModel->get()->getResultArray();

    $data = array_unique(array_merge($data,$data2), SORT_REGULAR);


问:
Show all variations of a component on a single page in React Storybook but still have Knobs?
I have a button component that can be of different types eg primary, secondary, etc:

```<code>export const buttonTypes = [
  'primary',
  'secondary',
  'tertiary',
  'positive',
  'negative',
]

const Button = ({ text, type }) => {
    return(
        <button className={type}>{text}</button>
    )
}

Button.propTypes = {
    text: PropTypes.string,
    type: PropTypes.oneOf(buttonTypes),
}
</code>```

In my Storybook file I'm mapping through the options. This means you can see all the variants on a single page and if another string was added to the buttonTypes array it would automatically be added to the style guide:

```<code>import ButtonComponent, { buttonTypes } from './Button';

const Button = () => {
    return(
        <div>
            {
                buttonTypes.map(type=>(
                    <ButtonComponent key={type} text={type} type={type} />
                ))
            }
        </div>
    )
}

export default {
  title: 'Components',
  component: Button,
};
</code>```

The problem is that this doens't work with with many of the add-ons eg knobs. For knobs to work you need Button to be the actual component, not a wrapper as I did above.

```<code>import ButtonComponent, { buttonTypes } from './Button';

const Button = () => {
  return (
    <ButtonComponent
      type={select('type', buttonTypes, buttonTypes.primary)}
      text="Button"
    />
  );
};
</code>```

Is there a way to use knobs and show all the variations on a single page? Ideally without having to create each component manually as this is more work and then won't automatically update if a new string is added to buttonTypes.

答:
Use the grouping feature of knobs, that way each instance of your component will get its own knob instance instead of all the knob instances being shared between all of the component instances.  You can even mix grouped knobs with non-grouped nobs if you want certain things to be shared and other not to be.

In the following example, I have a <Button/> story where each instance has its own copy of the type and disabled properties, but the text is shared between them all.

Each button type gets its own panel where you can set its type and disabled.  The "Other" group contains any knobs that didn't have their group set (such as text).

src/Button/Button.component.jsx

```<code>import * as React from "react";

import "./Button.style.css";

export const Button = ({
    text,
    type,
    disabled,
    onClick
}) => (
    <button
        className={`button button--${type} ${disabled ? "button--disabled" : ""}`}
        disabled={disabled}
        onClick={onClick}
        children={text}
    />
);
</code>```

src/Button/Button.stories.jsx

```<code>import * as React from "react";
import {withKnobs, text, boolean, select} from "@storybook/addon-knobs";
import {action} from "@storybook/addon-actions";

import {Button, buttonTypes} from "./";

export default {
    title: "Button",
    component: Button,
    decorators: [withKnobs]
};

export const ButtonStory = () => {
    const buttontext = text("Text", "Click Me");

    return (
        <div>
            {buttonTypes.map(buttonType => (
                <div key={buttonType}>
                    <Button
                        type={select("Type", buttonTypes, buttonType, buttonType)}
                        disabled={boolean("Disabled", false, buttonType)}
                        onClick={action(`${buttonType} clicked`)}
                        text={buttontext}
                    />
                </div>
            ))}
        </div>
    );
};

ButtonStory.story = {
    name: "All"
}
</code>```

src/Button/Button.types.js

export const buttonTypes = [
    "primary",
    "secondary",
    "tertiary"
];
```

<p><strong>src/Button/Button.style.css</strong></p>

<pre class="lang-css prettyprint-override"><code>.button {
    padding: 0.5em;
    font-size: 1.25em;
    border-radius: 10px;
    border-width: 2px;
    border-style: solid;
    border-color: black;
}

.button--primary {
    background-color: rgb(132, 198, 106);
    color: black;
    border-color: black;
}

.button--secondary {
    background-color: rgb(194, 194, 194);
    color: black;
    border-color: black;
}

.button--tertiary {
    background-color: transparent;
    color: inherit;
    border-color: transparent;
}

.button--disabled {
    background-color: rgb(194, 194, 194);
    color: rgb(105, 102, 102);
    border-color: rgb(105, 102, 102);
}
</code>```

src/Button/index.js

export {Button} from "./Button.component";
export {buttonTypes} from "./Button.types";
```

Body:
I have a button component that can be of different types eg primary, secondary, etc:

export const buttonTypes = [
  'primary',
  'secondary',
  'tertiary',
  'positive',
  'negative',
]

const Button = ({ text, type }) => {
    return(
        <button className={type}>{text}</button>
    )
}

Button.propTypes = {
    text: PropTypes.string,
    type: PropTypes.oneOf(buttonTypes),
}

In my Storybook file I'm mapping through the options. This means you can see all the variants on a single page and if another string was added to the buttonTypes array it would automatically be added to the style guide:

import ButtonComponent, { buttonTypes } from './Button';

const Button = () => {
    return(

            {
                buttonTypes.map(type=>(
                    <ButtonComponent key={type} text={type} type={type} />
                ))
            }

    )
}

export default {
  title: 'Components',
  component: Button,
};

The problem is that this doens't work with with many of the add-ons eg knobs. For knobs to work you need Button to be the actual component, not a wrapper as I did above.

import ButtonComponent, { buttonTypes } from './Button';

const Button = () => {
  return (
    <ButtonComponent
      type={select('type', buttonTypes, buttonTypes.primary)}
      text="Button"
    />
  );
};

Is there a way to use knobs and show all the variations on a single page? Ideally without having to create each component manually as this is more work and then won't automatically update if a new string is added to buttonTypes.

Body:
Use the grouping feature of knobs, that way each instance of your component will get its own knob instance instead of all the knob instances being shared between all of the component instances.  You can even mix grouped knobs with non-grouped nobs if you want certain things to be shared and other not to be.

In the following example, I have a <Button/> story where each instance has its own copy of the type and disabled properties, but the text is shared between them all.

Each button type gets its own panel where you can set its type and disabled.  The "Other" group contains any knobs that didn't have their group set (such as text).

src/Button/Button.component.jsx

import * as React from "react";

import "./Button.style.css";

export const Button = ({
    text,
    type,
    disabled,
    onClick
}) => (
    <button
        className={`button button--${type} ${disabled ? "button--disabled" : ""}`}
        disabled={disabled}
        onClick={onClick}
        children={text}
    />
);

src/Button/Button.stories.jsx

import * as React from "react";
import {withKnobs, text, boolean, select} from "@storybook/addon-knobs";
import {action} from "@storybook/addon-actions";

import {Button, buttonTypes} from "./";

export default {
    title: "Button",
    component: Button,
    decorators: [withKnobs]
};

export const ButtonStory = () => {
    const buttontext = text("Text", "Click Me");

    return (
        <div>
            {buttonTypes.map(buttonType => (
                <div key={buttonType}>
                    <Button
                        type={select("Type", buttonTypes, buttonType, buttonType)}
                        disabled={boolean("Disabled", false, buttonType)}
                        onClick={action(`${buttonType} clicked`)}
                        text={buttontext}
                    />
                </div>
            ))}
        </div>
    );
};

ButtonStory.story = {
    name: "All"
}

src/Button/Button.types.js

export const buttonTypes = [
    "primary",
    "secondary",
    "tertiary"
];

src/Button/Button.style.css

.button {
    padding: 0.5em;
    font-size: 1.25em;
    border-radius: 10px;
    border-width: 2px;
    border-style: solid;
    border-color: black;
}

.button--primary {
    background-color: rgb(132, 198, 106);
    color: black;
    border-color: black;
}

.button--secondary {
    background-color: rgb(194, 194, 194);
    color: black;
    border-color: black;
}

.button--tertiary {
    background-color: transparent;
    color: inherit;
    border-color: transparent;
}

.button--disabled {
    background-color: rgb(194, 194, 194);
    color: rgb(105, 102, 102);
    border-color: rgb(105, 102, 102);
}

src/Button/index.js

export {Button} from "./Button.component";
export {buttonTypes} from "./Button.types";


问:
Unable to change the JAVA path to the Oracle JDK
I'm using RHEL8 which has default OpenJDK installed.
which java command points to /usr/bin/java.
java -version gives openjdk version "1.8.0_252"

Installed java in /u01/app/java/ location. Modified the .bashrc like below & sourced it.
export JAVA_HOME=/u01/app/java/jdk1.8.0_241/
PATH="$JAVA_HOME/bin/java:$HOME/.local/bin:$HOME/bin:$PATH"
export PATH

Now JAVA_HOME points to /u01/app/java/jdk1.8.0_241/ But which java or java -version still points to the OpenJDK.

Added the same in .bash_profile file & removed it from the .bashrc : Results are same

Deleted OpenJDK & made changes in .bash_profile. But by doing so ended up with "Command not found" error.

How can i fix it?

答:
It was Path issue.
I have given PATH="$JAVA_HOME/bin/java:$HOME/.local/bin:$HOME/bin:$PATH" for PATH. which should not be the case.
Modified my PATH to below. It worked.

PATH="$JAVA_HOME/bin:$HOME/.local/bin:$HOME/bin:$PATH"
export PATH


问:
How to convert string hhmm to time in python
How could I convert the below column Time 1 from string to time eg: Time2

Time1

438

448

1815

1758

Time2

04:38

04:48

18:15

17:58

答:
To start, some of your time1 cases are not in the hhmm format: there are only three digits in 438, but this can be incorporated nonetheless.

```<code>import datetime
def convert_string_to_time(str):
    if len(str) < 4:
        return datetime.time(hour=int(str[0]), minute=int(str[1:3]))
    else:
        return datetime.time(hour=int(str[0:2]), minute=int(str[2:4]))
</code>```

This will return a datetime.time object for each time string. If you want to have the time in the format hh:mm:ss use str(convert_string_to_time(your string here))

Body:
To start, some of your time1 cases are not in the hhmm format: there are only three digits in 438, but this can be incorporated nonetheless.

import datetime
def convert_string_to_time(str):
    if len(str) < 4:
        return datetime.time(hour=int(str[0]), minute=int(str[1:3]))
    else:
        return datetime.time(hour=int(str[0:2]), minute=int(str[2:4]))

This will return a datetime.time object for each time string. If you want to have the time in the format hh:mm:ss use str(convert_string_to_time(your string here))


问:
How to print a specific item from within a JSON file into python
I want to print a user from a JSON list into Python that I select however I can only print all the users. How do you print a specific user? At the moment I have this which prints all the users out in a ugly format

```<code>import json

with open('Admin_sample.json') as f:
    admin_json = json.load(f)

print(admin_json['staff'])
</code>```

The JSON file looks like this

```<code>{
"staff": [
    {
        "id": "DA7153",
        "name": [
            "Fran\u00c3\u00a7ois",
            "Ullman"
        ],
        "department": {
            "name": "Admin"
        },
        "server_admin": "true"
    },
    {
        "id": "DA7356",
        "name": [
            "Bob",
            "Johnson"
        ],
        "department": {
            "name": "Admin"
        },
        "server_admin": "false"
    },
],
"assets": [
    {
        "asset_name": "ENGAGED SLOTH",
        "asset_type": "File",
        "owner": "DA8333",
        "details": {
            "security": {
                "cia": [
                    "HIGH",
                    "INTERMEDIATE",
                    "LOW"
                ],
                "data_categories": {
                    "Personal": "true",
                    "Personal Sensitive": "true",
                    "Customer Sensitive": "true"
                }
            },
            "retention": 2
        },
        "file_type": "Document",
        "server": {
            "server_name": "ISOLATED UGUISU",
            "ip": [
                10,
                234,
                148,
                52
            ]
        }
    },
    {
        "asset_name": "ISOLATED VIPER",
        "asset_type": "File",
        "owner": "DA8262",
        "details": {
            "security": {
                "cia": [
                    "LOW",
                    "HIGH",
                    "LOW"
                ],
                "data_categories": {
                    "Personal": "false",
                    "Personal Sensitive": "false",
                    "Customer Sensitive": "true"
                }
            },
            "retention": 2
        },
    },
]
</code>```

I just can't work it out. Any help would be appreciated.

Thanks.

答:
You need to index into the staff list, e.g.:

print(admin_json['staff'][0])
```

<p><strong>I suggest reading up a bit on dictionaries in Python.</strong> Dictionary values can be set to any object: in this case, the value of the <code>staff</code> key is set to a list of dicts. Here's an example that will loop through all the staff members and print their names:</p>

<pre class="lang-py prettyprint-override"><code>staff_list = admin_json['staff']
for person in staff_list:
    name_parts = person['name']
    full_name = ' '.join(name_parts)  # combine name parts into a string
    print(full_name)
</code>```

Body:
I want to print a user from a JSON list into Python that I select however I can only print all the users. How do you print a specific user? At the moment I have this which prints all the users out in a ugly format

import json

with open('Admin_sample.json') as f:
    admin_json = json.load(f)

print(admin_json['staff'])

The JSON file looks like this

{
"staff": [
    {
        "id": "DA7153",
        "name": [
            "Fran\u00c3\u00a7ois",
            "Ullman"
        ],
        "department": {
            "name": "Admin"
        },
        "server_admin": "true"
    },
    {
        "id": "DA7356",
        "name": [
            "Bob",
            "Johnson"
        ],
        "department": {
            "name": "Admin"
        },
        "server_admin": "false"
    },
],
"assets": [
    {
        "asset_name": "ENGAGED SLOTH",
        "asset_type": "File",
        "owner": "DA8333",
        "details": {
            "security": {
                "cia": [
                    "HIGH",
                    "INTERMEDIATE",
                    "LOW"
                ],
                "data_categories": {
                    "Personal": "true",
                    "Personal Sensitive": "true",
                    "Customer Sensitive": "true"
                }
            },
            "retention": 2
        },
        "file_type": "Document",
        "server": {
            "server_name": "ISOLATED UGUISU",
            "ip": [
                10,
                234,
                148,
                52
            ]
        }
    },
    {
        "asset_name": "ISOLATED VIPER",
        "asset_type": "File",
        "owner": "DA8262",
        "details": {
            "security": {
                "cia": [
                    "LOW",
                    "HIGH",
                    "LOW"
                ],
                "data_categories": {
                    "Personal": "false",
                    "Personal Sensitive": "false",
                    "Customer Sensitive": "true"
                }
            },
            "retention": 2
        },
    },
]

I just can't work it out. Any help would be appreciated.

Thanks.

Body:
You need to index into the staff list, e.g.:

print(admin_json['staff'][0])

I suggest reading up a bit on dictionaries in Python. Dictionary values can be set to any object: in this case, the value of the staff key is set to a list of dicts. Here's an example that will loop through all the staff members and print their names:

staff_list = admin_json['staff']
for person in staff_list:
    name_parts = person['name']
    full_name = ' '.join(name_parts)  # combine name parts into a string
    print(full_name)


问:
DI for class not resolving in Function
I have set up DI for an Azure function but it will not resolve when I run the function. The code I have is:

StartUp:

```<code>[assembly: FunctionsStartup(typeof(OmegaConnector.StartUp))]
namespace OmegaConnector
{
    public class StartUp : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables()
                .Build();

            builder.Services.AddLogging();
            builder.Services.AddVehicleSearchCosmosDataProvider();
            builder.Services.AddScoped<IProcessSearchData, SearchProcessor>(); <- This one
        }
    }
</code>```

IProcessSearchData:

```<code>public interface IProcessSearchData
 {
    Task<bool> ProcessData(string campaign);
 }
</code>```

SearchProcessor:

```<code>public class SearchProcessor : IProcessSearchData
    {

        public async Task<bool> ProcessData(string campaign)
        {
            return true;
        }
    }
</code>```

Function:

```<code> public OmegaConnectorFunction(ILogger<OmegaConnectorFunction> logger, IProcessSearchData searchProcessor)
        {
</code>```

I get the error:

```<code> Executed 'CatchCampaign' (Failed, Id=daef3371-fa4d-4d1f-abad-7ad343537872)
[27/05/2020 12:17:27] Microsoft.Extensions.DependencyInjection.Abstractions: Unable to resolve service for type 'OmegaConnector.Interfaces.IProcessSearchData' while attempting to activate 'OmegaConnector.OmegaConnectorFunction'.
</code>```

Sorry if this is too simple but I just can't see what I have wrong here. I think I have this set up correctly but I obviously don't. Can anyone see what I need to do?

答:
See here: https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library

The Functions 3.x packages are built with .NET Core 3.1 in mind.

Try keeping these versions in sync so there are no dependency compatibility problems.

Title: DI for class not resolving in Function

Body:
I have set up DI for an Azure function but it will not resolve when I run the function. The code I have is:

StartUp:

[assembly: FunctionsStartup(typeof(OmegaConnector.StartUp))]
namespace OmegaConnector
{
    public class StartUp : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables()
                .Build();

            builder.Services.AddLogging();
            builder.Services.AddVehicleSearchCosmosDataProvider();
            builder.Services.AddScoped<IProcessSearchData, SearchProcessor>(); <- This one
        }
    }

IProcessSearchData:

public interface IProcessSearchData
 {
    Task<bool> ProcessData(string campaign);
 }

SearchProcessor:

public class SearchProcessor : IProcessSearchData
    {

        public async Task<bool> ProcessData(string campaign)
        {
            return true;
        }
    }

Function:

 public OmegaConnectorFunction(ILogger<OmegaConnectorFunction> logger, IProcessSearchData searchProcessor)
        {

I get the error:

 Executed 'CatchCampaign' (Failed, Id=daef3371-fa4d-4d1f-abad-7ad343537872)
[27/05/2020 12:17:27] Microsoft.Extensions.DependencyInjection.Abstractions: Unable to resolve service for type 'OmegaConnector.Interfaces.IProcessSearchData' while attempting to activate 'OmegaConnector.OmegaConnectorFunction'.

Sorry if this is too simple but I just can't see what I have wrong here. I think I have this set up correctly but I obviously don't. Can anyone see what I need to do?


问:
See commands of make and all called make files thereafter
I am trying to decompose a make build system of a very large code base however I am unable to see every command the make invokes because it calls various make files in numerous directories outside of the current directory. I followed this answer and various other ones Making make print commands before executing when NOT using CMake

Though the above yielded some advancement and was quite illuminating it was not the home run I need. It offers solutions to see the commands that make invokes. Which is better than great. However, the issue is the various sub make commands that are invoked thereafter. I only see those commands as printed with no additional information of what is occurring sub make. I tried to alias make such that

```<code>alias make='make SHELL='\''/bin/bash -x'\'''

# or

alias make='make -n'
</code>```

However the above fail to replace the invoked make commands with the alias. Is there another way I can dissect a large code base make build system out there?

```<code>> make
rmdir --ignore-fail-on-non-empty /somefolder* 2> /dev/null; true
cd /someotherfolder/; make cur-dir=somefolder dirs-to-build=somemorefolders/ env_variable another_variable someMakeRule # no output from this  make
make  TARGET=someTarget env_variable gdbinit source_dir someMakeRule; # no output from this  make
# ...
# output from first top makefile
# ...
make[1]: Nothing to be done for 'someMakeRule'.
</code>```

答:
You can easily trace execution with --trace option. Consider the following example where someone had an idea to show clean output only without any option for being verbose:

```<code>$ cat Makefile
all: foo
        @echo Done with $@

foo: bar
        @echo Done with $@

bar:
        @$(MAKE) -f Makefile2 bar

.SILENT:

$ cat Makefile2
bar: baz
        @echo Done with $@

baz:
        @echo Done with $@
</code>```

Regular build does not allow to check what's happening:

```<code>$ make
Done with baz
Done with bar
Done with foo
Done with all
</code>```

But --trace will show what is happening and why:

```<code>$ make --trace
Makefile:8: target 'bar' does not exist
make -f Makefile2 bar
Makefile2:5: target 'baz' does not exist
echo Done with baz
Done with baz
Makefile2:2: update target 'bar' due to: baz
echo Done with bar
Done with bar
Makefile:5: update target 'foo' due to: bar
echo Done with foo
Done with foo
Makefile:2: update target 'all' due to: foo
echo Done with all
Done with all
</code>```

Body:
I am trying to decompose a make build system of a very large code base however I am unable to see every command the make invokes because it calls various make files in numerous directories outside of the current directory. I followed this answer and various other ones Making make print commands before executing when NOT using CMake

Though the above yielded some advancement and was quite illuminating it was not the home run I need. It offers solutions to see the commands that make invokes. Which is better than great. However, the issue is the various sub make commands that are invoked thereafter. I only see those commands as printed with no additional information of what is occurring sub make. I tried to alias make such that

alias make='make SHELL='\''/bin/bash -x'\'''

# or

alias make='make -n'

However the above fail to replace the invoked make commands with the alias. Is there another way I can dissect a large code base make build system out there?

> make
rmdir --ignore-fail-on-non-empty /somefolder* 2> /dev/null; true
cd /someotherfolder/; make cur-dir=somefolder dirs-to-build=somemorefolders/ env_variable another_variable someMakeRule # no output from this  make
make  TARGET=someTarget env_variable gdbinit source_dir someMakeRule; # no output from this  make
# ...
# output from first top makefile
# ...
make[1]: Nothing to be done for 'someMakeRule'.

Body:
You can easily trace execution with --trace option. Consider the following example where someone had an idea to show clean output only without any option for being verbose:

$ cat Makefile
all: foo
        @echo Done with $@

foo: bar
        @echo Done with $@

bar:
        @$(MAKE) -f Makefile2 bar

.SILENT:

$ cat Makefile2
bar: baz
        @echo Done with $@

baz:
        @echo Done with $@

Regular build does not allow to check what's happening:

$ make
Done with baz
Done with bar
Done with foo
Done with all

But --trace will show what is happening and why:

$ make --trace
Makefile:8: target 'bar' does not exist
make -f Makefile2 bar
Makefile2:5: target 'baz' does not exist
echo Done with baz
Done with baz
Makefile2:2: update target 'bar' due to: baz
echo Done with bar
Done with bar
Makefile:5: update target 'foo' due to: bar
echo Done with foo
Done with foo
Makefile:2: update target 'all' due to: foo
echo Done with all
Done with all