问:
I want to make a simple CalC in Angular Js
Here is My code...

```<code><html ng-app='CalC'>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
        <script >
            var app = angular.module('CalC',[]);
            app.controller('stoInt',function($scope){
                $scope.parseInt(txt1,10);
                $scope.parseInt(txt2,10);
            });
        </script>
    </head>
    <body  ng-controller="stoInt">
        <div class="panel panel-default" style="height: 200px;width : 200px;margin: 100px;">
            <div class="panel-body">
                <input type="text" class="form-control" placeholder="Enter 1st Number" ng-model="txt1" pattern="[0-9]*">
                <br>
                <input type="text" class="form-control" placeholder="Enter 2nd Number" ng-model="txt2" pattern="[0-9]">
            <br><br>
                 <p> Result :: {{txt1+txt2}} </p>
            </div>
        </div>

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

o/p Result :: {{txt1+txt2}}.

答:
Solution 1

There are few mistakes in your code, you need to make parseInt for the scope variable

```<code> parseInt($scope.txt1,10);
 parseInt($scope.txt2,10);
</code>```

you can define a function to calculate the sum and return it,

```<code>  $scope.add = function(){
      return parseInt($scope.txt1) + parseInt($scope.txt2);
  }
</code>```

DEMO

      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>

        <input type="text" class="form-control" placeholder="Enter 1st Number" ng-model="txt1" pattern="[0-9]*">

        <input type="text" class="form-control" placeholder="Enter 2nd Number" ng-model="txt2" pattern="[0-9]">

 Result :: {{add()}}

    ```
</div>
</div>
</p>

<p><strong>Solution 2</strong></p>

<p>Make the input type as <strong><code>number</code></strong>,</p>

```

 <input type="number" class="form-control" placeholder="Enter 1st Number" ng-model="txt1" pattern="[0-9]*">

 <input type="number" class="form-control" placeholder="Enter 2nd Number" ng-model="txt2" pattern="[0-9]">

```

<p><strong>DEMO</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html ng-app='CalC'>
     <head>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
      <script >
       var app = angular.module('CalC',[]);
       app.controller('stoInt',function($scope){
       });
      </script>
     </head>
     <body  ng-controller="stoInt">
      <div class="panel panel-default" style="height: 200px;width : 200px;margin: 100px;">
       <div class="panel-body">
        <input type="number" class="form-control" placeholder="Enter 1st Number" ng-model="txt1" pattern="[0-9]*">
        <br>
        <input type="number" class="form-control" placeholder="Enter 2nd Number" ng-model="txt2" pattern="[0-9]">
       <br><br>
         <p> Result :: {{txt1+txt2}} </p>
       </div>
      </div>

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

Body:
Here is My code...

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>

                <input type="text" class="form-control" placeholder="Enter 1st Number" ng-model="txt1" pattern="[0-9]*">

                <input type="text" class="form-control" placeholder="Enter 2nd Number" ng-model="txt2" pattern="[0-9]">

 Result :: {{txt1+txt2}}

o/p Result :: {{txt1+txt2}}.

Body:
Solution 1

There are few mistakes in your code, you need to make parseInt for the scope variable

 parseInt($scope.txt1,10);
 parseInt($scope.txt2,10);

you can define a function to calculate the sum and return it,

  $scope.add = function(){
      return parseInt($scope.txt1) + parseInt($scope.txt2);
  }

DEMO

    <html ng-app='CalC'>
     <head>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
      <script >
       var app = angular.module('CalC',[]);
       app.controller('stoInt',function($scope){
          $scope.add = function(){
               return parseInt($scope.txt1) + parseInt($scope.txt2);
             }
       });
      </script>
     </head>
     <body  ng-controller="stoInt">
      <div class="panel panel-default" style="height: 200px;width : 200px;margin: 100px;">
       <div class="panel-body">
        <input type="text" class="form-control" placeholder="Enter 1st Number" ng-model="txt1" pattern="[0-9]*">
        <br>
        <input type="text" class="form-control" placeholder="Enter 2nd Number" ng-model="txt2" pattern="[0-9]">
       <br><br>
         <p> Result :: {{add()}} </p>
       </div>
      </div>

     </body>
    </html>

Solution 2

Make the input type as number,

 <div class="panel-body">
 <input type="number" class="form-control" placeholder="Enter 1st Number" ng-model="txt1" pattern="[0-9]*">
 <br>
 <input type="number" class="form-control" placeholder="Enter 2nd Number" ng-model="txt2" pattern="[0-9]">
 <br><br>

DEMO

<html ng-app='CalC'>
     <head>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
      <script >
       var app = angular.module('CalC',[]);
       app.controller('stoInt',function($scope){
       });
      </script>
     </head>
     <body  ng-controller="stoInt">
      <div class="panel panel-default" style="height: 200px;width : 200px;margin: 100px;">
       <div class="panel-body">
        <input type="number" class="form-control" placeholder="Enter 1st Number" ng-model="txt1" pattern="[0-9]*">
        <br>
        <input type="number" class="form-control" placeholder="Enter 2nd Number" ng-model="txt2" pattern="[0-9]">
       <br><br>
         <p> Result :: {{txt1+txt2}} </p>
       </div>
      </div>

     </body>
    </html>


来源: stackexchange

问:
Replacing emoji within UILabel with NSTextAttachment - not able to set the plaintext representation back to regular emoji for copying/pasting
I'm replacing emoji within a UILabel/UITextView with my own custom emoji. This works fine, but what I'm struggling with is getting the original emoji to paste.

So for example where the UILabel may display "Hello ", with a custom emoji, copying then pasting that text, or calling the text property of the UILabel would display "Hello " with the standard emoji.

I'm implementing this using a subclass of NSTextAttachment which displays an image, and adding it as an NSAttributedString whenever the emoji is used:

```<code>class EmojiTextAttachment: NSTextAttachment {
    static let size = CGSize(width: 16, height: 16)

    let emoji: Emoji

    init(emoji: Emoji) {
        self.emoji = emoji

        super.init(data: emoji.rawValue.data(using: .utf8), ofType: "public.text")
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func image(forBounds imageBounds: CGRect, textContainer: NSTextContainer?, characterIndex charIndex: Int) -> UIImage? {
        return Emoji.generateConstrainedFaceImage(emoji: emoji, height: imageBounds.size.height)
    }
}

let emoji = Emoji(rawValue: emojiString)!
let emojiTextAttachment = EmojiTextAttachment(emoji: emoji)
emojiTextAttachment.bounds = CGRect(x: 0, y: self.font!.descender, width: self.font!.lineHeight, height: self.font!.lineHeight)
let attributedString = NSAttributedString(attachment: emojiTextAttachment)
</code>```

This appears correctly, but now if I call the text property of the UITextField, it doesn't include the NSTextAttachment as part of its' text. Additionally, copying the content copies the EmojiTextAttachment as data. Here, I've tried to set the data:ofType: to be a string (converted to data), but that didn't work, it just forms some data which is pated. And setting the image through emojiTextAttachment.image means it'd paste the image. Setting it through the imageForBounds:textContainer:characterIndex: function means the image itself doesn't get copied/pasted.

Is there a way that I can set the plaintext representation of an NSTextAttachment, or some other known way of making this work?

答:
Couldn't find a really clean way of doing it. Subclassing NSAttributedString isn't supported, so no way of overriding the string function.

Instead, I've added an extension of NSAttributedString with a plaintextRepresentation function, which enumerates through the attributes, replacing any EmojiTextAttachments with the emoji itself, then returns the string value of the attributed string.

ContentLicense: CC BY-SA 3.0

Body:
I'm replacing emoji within a UILabel/UITextView with my own custom emoji. This works fine, but what I'm struggling with is getting the original emoji to paste.

So for example where the UILabel may display "Hello ", with a custom emoji, copying then pasting that text, or calling the text property of the UILabel would display "Hello " with the standard emoji.

I'm implementing this using a subclass of NSTextAttachment which displays an image, and adding it as an NSAttributedString whenever the emoji is used:

class EmojiTextAttachment: NSTextAttachment {
    static let size = CGSize(width: 16, height: 16)

    let emoji: Emoji

    init(emoji: Emoji) {
        self.emoji = emoji

        super.init(data: emoji.rawValue.data(using: .utf8), ofType: "public.text")
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func image(forBounds imageBounds: CGRect, textContainer: NSTextContainer?, characterIndex charIndex: Int) -> UIImage? {
        return Emoji.generateConstrainedFaceImage(emoji: emoji, height: imageBounds.size.height)
    }
}

let emoji = Emoji(rawValue: emojiString)!
let emojiTextAttachment = EmojiTextAttachment(emoji: emoji)
emojiTextAttachment.bounds = CGRect(x: 0, y: self.font!.descender, width: self.font!.lineHeight, height: self.font!.lineHeight)
let attributedString = NSAttributedString(attachment: emojiTextAttachment)

This appears correctly, but now if I call the text property of the UITextField, it doesn't include the NSTextAttachment as part of its' text. Additionally, copying the content copies the EmojiTextAttachment as data. Here, I've tried to set the data:ofType: to be a string (converted to data), but that didn't work, it just forms some data which is pated. And setting the image through emojiTextAttachment.image means it'd paste the image. Setting it through the imageForBounds:textContainer:characterIndex: function means the image itself doesn't get copied/pasted.

Is there a way that I can set the plaintext representation of an NSTextAttachment, or some other known way of making this work?


问:
How to connect to MSSQL server in UWP (.NET universal App)
I Cannot connect to my OData Web Service at the moment in my universal App, so i want to ask if someone of you found a way to connect to a MSSQL Server?
As I know it is only possible to connect to a MySQL server right now, but that is not an option for me. </p>

答:
I just created my own WCF - Web Service to gather my informations from the SQL- Server to my UWP-App.

This video helped me alot to understand the basics of WCF.

And this to host it on an IIS.

This sample Project is also very useful to replicate it to UWP (universal apps).

I Hope that this informations can help someone here.


问:
How to get usage details of AWS EBS service?
My team got billing for AWS EBS and we have no idea what is it about.

Going to our console and try to open EBS section though we failed to get one as the snapshots below.

So my question is how to get breakdown details on AWS EBS usage billing?

p.s.

The EBS usage cost is viewed under EC2 section in billing tab in the management console

答:
For AWS billing you can use cost explorer for generating handsome reports.

Billing Break-Down:

In aws they have grouped multiple offerings under one service. For ex: EBS, ELB, EIP all grouped under EC2.

Same when they provide billing breakdown they provide it on service basis then region basis and then offering.

If you want better breakdown best way is to use cost tags and cost explorer.

Like in your case you can give your service_tag = ebs and application_tag = app1.

Then by using cost explorer :  filter_by = app_tag and region and etc. and group_by = service_tag. By performing multiple combinations you can get a clear view of your cost and usage.


问:
Relabeling in Prometheus

Setup

Prometheus node exporter is registered as a service with consul agent with various tags. Example service definition provided to consul agent:

```<code>{
  "service":{
      "id": "server-stats",
      "name": "server-stats",
      "tags": [
        "a=1_meow",
        "b=2_woof",
        "c=3_moo",
        "monkey"
      ],
      "port": 9100,
      "checks": [
        {
          "name": "Process #1",
          "script": "/path/to/healthcheck/script.sh",
          "interval": "5s"
        }
      ]
    }
}
</code>```

Prometheus is set to look for this server-stats service and use the configuration (host address and port) provided by Consul to scrape stats from servers. The above tags are available as a comma separated list in __meta_consul_tags that can be used for relabeling.

Prometheus relabeling configuration:

```<code>relabel_configs:
- source_labels: [__meta_consul_tags]
  separator:     ','
  #regex:         '(.+)=(.+)'
  regex:         '([a-z_]+)=([a-z_]+|\d+)'
  target_label:  ${1}
  replacement:   ${2}
</code>```

Issue

I am trying to expose tags to Prometheus so that we can get stats and graphs based on labels. Keeping the above service configuration in mind, I would like each metric to have following labels in addition to whatever Prometheus does internally:
a=1_meow, b=2_woof, c=3_moo and ignore monkey because it is just a string. I can remove monkey from my list of tags if there is a solution that requires = to be there. The relabel configuration written above is not leading to exposing any tag at all and seems to be getting ignored. Running Prometheus with log level set to debug is also not yielding anything.

Relevant docs

https://prometheus.io/docs/operating/configuration/#%3Crelabel_config%3E

https://www.robustperception.io/extracting-full-labels-from-consul-tags/

答:
Incorrect understanding

I think there was a mistake in my understanding of how labeling in prometheus works. My incorrect understanding was:

before applying regex, string would be first split on separator (otherwise what is its purpose?),

each substring has regex evaluated against it,

if match groups are declared and found, they will be available as indexed values available to use in target_label and replacement fields.

if regex does not match, then that substring will be ignored.

because regex is expected to be applied to each substring after the split, it will lead to multiple labels from multiple substrings.

Correct understanding

However, from brian-brazil's post linked in his answer and Prometheus's documentation, it seems the following happening:

All __meta tags are combined into one long separator separated line.

regex is applied on that line only once.

If regex matches and includes groups, they are indexed beginning from 1 and available for use in target_label and replacement.

separator seems to be getting ignored in this section even if you mention it.

Config from corrected understanding

From this idea and following from example in the question, I was able to make the following config that works

```<code>relabel_configs:
- source_labels: [__meta_consul_tags]
  regex:         '.*,a=([a-z0-9_]+),.+'
  target_label:  'a'
  replacement:   ${1}

- source_labels: [__meta_consul_tags]
  regex:         '.*,b=([a-z0-9_]+),.+'
  target_label:  'b'
  replacement:   ${1}

- source_labels: [__meta_consul_tags]
  regex:         '.*,c=([a-z0-9_]+),.+'
  target_label:  'c'
  replacement:   ${1}

- source_labels: [__meta_consul_tags]
  regex:         '.*,d=([a-z0-9_]+),.+'
  target_label:  'd'
  replacement:   ${1}
</code>```

Caveats

I believe both approaches (the approach brian-brazil wrote in his blogpost, and what I am using above) have caveats - we either need to know all the labels we want beforehand, or have a set number of them. This means if a developer wants to associate different, or more labels with his/her service, s/he would need to work with ops as general flow will not be able to handle it. I think it is a minor caveat that should be addressed.

Title: Relabeling in Prometheus

Body:
Setup

Prometheus node exporter is registered as a service with consul agent with various tags. Example service definition provided to consul agent:

{
  "service":{
      "id": "server-stats",
      "name": "server-stats",
      "tags": [
        "a=1_meow",
        "b=2_woof",
        "c=3_moo",
        "monkey"
      ],
      "port": 9100,
      "checks": [
        {
          "name": "Process #1",
          "script": "/path/to/healthcheck/script.sh",
          "interval": "5s"
        }
      ]
    }
}

Prometheus is set to look for this server-stats service and use the configuration (host address and port) provided by Consul to scrape stats from servers. The above tags are available as a comma separated list in __meta_consul_tags that can be used for relabeling.

Prometheus relabeling configuration:

relabel_configs:
- source_labels: [__meta_consul_tags]
  separator:     ','
  #regex:         '(.+)=(.+)'
  regex:         '([a-z_]+)=([a-z_]+|\d+)'
  target_label:  ${1}
  replacement:   ${2}

Issue

I am trying to expose tags to Prometheus so that we can get stats and graphs based on labels. Keeping the above service configuration in mind, I would like each metric to have following labels in addition to whatever Prometheus does internally:
a=1_meow, b=2_woof, c=3_moo and ignore monkey because it is just a string. I can remove monkey from my list of tags if there is a solution that requires = to be there. The relabel configuration written above is not leading to exposing any tag at all and seems to be getting ignored. Running Prometheus with log level set to debug is also not yielding anything.

Relevant docs

https://prometheus.io/docs/operating/configuration/#%3Crelabel_config%3E

https://www.robustperception.io/extracting-full-labels-from-consul-tags/

Body:
Incorrect understanding

I think there was a mistake in my understanding of how labeling in prometheus works. My incorrect understanding was:

before applying regex, string would be first split on separator (otherwise what is its purpose?),

each substring has regex evaluated against it,

if match groups are declared and found, they will be available as indexed values available to use in target_label and replacement fields.

if regex does not match, then that substring will be ignored.

because regex is expected to be applied to each substring after the split, it will lead to multiple labels from multiple substrings.

Correct understanding

However, from brian-brazil's post linked in his answer and Prometheus's documentation, it seems the following happening:

All __meta tags are combined into one long separator separated line.

regex is applied on that line only once.

If regex matches and includes groups, they are indexed beginning from 1 and available for use in target_label and replacement.

separator seems to be getting ignored in this section even if you mention it.

Config from corrected understanding

From this idea and following from example in the question, I was able to make the following config that works

relabel_configs:
- source_labels: [__meta_consul_tags]
  regex:         '.*,a=([a-z0-9_]+),.+'
  target_label:  'a'
  replacement:   ${1}

- source_labels: [__meta_consul_tags]
  regex:         '.*,b=([a-z0-9_]+),.+'
  target_label:  'b'
  replacement:   ${1}

- source_labels: [__meta_consul_tags]
  regex:         '.*,c=([a-z0-9_]+),.+'
  target_label:  'c'
  replacement:   ${1}

- source_labels: [__meta_consul_tags]
  regex:         '.*,d=([a-z0-9_]+),.+'
  target_label:  'd'
  replacement:   ${1}

Caveats

I believe both approaches (the approach brian-brazil wrote in his blogpost, and what I am using above) have caveats - we either need to know all the labels we want beforehand, or have a set number of them. This means if a developer wants to associate different, or more labels with his/her service, s/he would need to work with ops as general flow will not be able to handle it. I think it is a minor caveat that should be addressed.


问:
Wix Toolset - ComponentGroupRef works with external project file?
I have the following in my Product.wxs file.

```<code><Feature Id="PA5gFeature" ConfigurableDirectory="INSTALLLOCATION" Title="$(var.ApplicationName)" Level="1">
  <ComponentGroupRef Id="PA5GSite.Content" />
  <ComponentGroupRef Id="SiteBinaries" />
  <ComponentGroupRef Id="ShortcutGroup" />
  <ComponentGroupRef Id="ConfigApp" />
  <ComponentGroupRef Id="PA5GApp" />
  <ComponentGroupRef Id="ConfigSupportDlls" />
  <ComponentGroupRef Id="ConfigReports" />

  <ComponentRef Id="PersistWebSiteValues" />
  <!--<ComponentRef Id="ChangeLogFolder" />-->
  <ComponentRef Id="ConfigReportFolder" />
  <ComponentRef Id="PA5GRunFolder" />
</Feature>
</code>```

When I search with PA5GSite.Content in the entire project, I do not find it at all. On the other hand I see a project file of an outside project as a shortcut inside the installer project, like below screenshot:

If I delete this project shortcut file from installer project and try to build, it gives me error: error LGHT0094: Unresolved reference to symbol 'WixC
omponentGroup:PA5GSite.Content' in section 'Product:*'

The reference is definitely correct and linked, but I do not understand how this is done. If i try to add reference in the Wix project to that outside project, it adds a reference in the reference folder but do not add shortcut file like before and it do not fix the error again. My question is, what is going on in here and how it works? How can I do something like this myself because I have to replace the current project file with a new project file. But I do not find any option in Wix to do that. Where should I look into?

答: I think I solved that mystery. I found the clue in the Wix Installer project file itself. I unload the wix project and then edited it manually. There I found a Harvest block which references the csproj file and i replace that with new project file and it all worked in the same way when I reload the Wix project. I found the clue from Wix Cookbook where it mentioned about this.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have the following in my Product.wxs file.

<Feature Id="PA5gFeature" ConfigurableDirectory="INSTALLLOCATION" Title="$(var.ApplicationName)" Level="1">
  <ComponentGroupRef Id="PA5GSite.Content" />
  <ComponentGroupRef Id="SiteBinaries" />
  <ComponentGroupRef Id="ShortcutGroup" />
  <ComponentGroupRef Id="ConfigApp" />
  <ComponentGroupRef Id="PA5GApp" />
  <ComponentGroupRef Id="ConfigSupportDlls" />
  <ComponentGroupRef Id="ConfigReports" />

  <ComponentRef Id="PersistWebSiteValues" />

  <ComponentRef Id="ConfigReportFolder" />
  <ComponentRef Id="PA5GRunFolder" />
</Feature>

When I search with PA5GSite.Content in the entire project, I do not find it at all. On the other hand I see a project file of an outside project as a shortcut inside the installer project, like below screenshot:

If I delete this project shortcut file from installer project and try to build, it gives me error: error LGHT0094: Unresolved reference to symbol 'WixC
omponentGroup:PA5GSite.Content' in section 'Product:*'

The reference is definitely correct and linked, but I do not understand how this is done. If i try to add reference in the Wix project to that outside project, it adds a reference in the reference folder but do not add shortcut file like before and it do not fix the error again. My question is, what is going on in here and how it works? How can I do something like this myself because I have to replace the current project file with a new project file. But I do not find any option in Wix to do that. Where should I look into?


问:
React js dynamic input field value to state
How to pass dynamic input field value to state as an array and update the value when user changes the input again?

Input field was generated by JSON data and in the state, we cannot define the initial value for all. Can anyone give some advice for this kind of problem?

```<code>this.state = {
file:[{value1,value2}]
};
</code>```

and input field is generated like

```<code>{this.state.language.map((item,index) =>
<div className="be-checkbox inline" key={index} >
 <input type="text"  onChange={this.handleChange.bind(this, index)} value={this.state.index} />
</div>
)}
</code>```

答:
Add onChange and value in every input like below.

```<code><input type="text" onChange={this.handleChange.bind(this, index)} value={this.state.index}/>
</code>```

Add the function to be called

```<code>handleChange(name, e){
    var change = {};
    change[name] = e.target.value;
    this.setState(change);
  }
</code>```

Body:
How to pass dynamic input field value to state as an array and update the value when user changes the input again?

Input field was generated by JSON data and in the state, we cannot define the initial value for all. Can anyone give some advice for this kind of problem?

this.state = {
file:[{value1,value2}]
};

and input field is generated like

{this.state.language.map((item,index) =>

 <input type="text"  onChange={this.handleChange.bind(this, index)} value={this.state.index} />

)}

Body:
Add onChange and value in every input like below.

<input type="text" onChange={this.handleChange.bind(this, index)} value={this.state.index}/>

Add the function to be called

handleChange(name, e){
    var change = {};
    change[name] = e.target.value;
    this.setState(change);
  }


问:
Python For i in range(len(str)): last iteration prints None
```<code>def fun(str):
    for i in range(len(str)):
        print(i)

string = 'abc'

print(fun(string))
</code>```

print results are

```<code>0
1
2
None
</code>```

if I change

```<code>for i in range(len(str)-1):
</code>```

the last result is still None

Why is this?
And how do I stop it?

答: this is because you use print(fun(string)) and you have a print statement inside your function. So it executes the print inside your function and another print with no return value from the function so None.</p>

Body:
def fun(str):
    for i in range(len(str)):
        print(i)

string = 'abc'

print(fun(string))

print results are

0
1
2
None

if I change

for i in range(len(str)-1):

the last result is still None

Why is this?
And how do I stop it?


问:
Open files app directly in mobile devices
In mobile devices, I know that I can open the camera app directly by using: <input type="file" accept="image/*" capture>. But I was wondering if we could open the files app directly too? Removing the capture attribute will prompt the user to take a new photo from the camera app or open an existing one in your local files. Though in my use case, I don't want to prompt for the camera app.

I tried researching on this but to no avail. Can anyone shed some light?

答:
With this input the file app opens and you get to choose any file that is an image:

<input type="file" accept="image/*" />```


问:
Retrieve the Organisation detail and email detail of a specified number from contact list of an android phone?
I have a phone number. I want to know the detail of that phone number from my phone contact . For that number i stored name, organisation, phone number(work), phone number(home), email(home), email(work), address.

I can get the Display name and ID of that number using the following code

```<code>Uri lookUpUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
            Uri.encode(incoming_number));
    Cursor cursor = getApplicationContext().getContentResolver().query(lookUpUri,null,null,null,null);
if(cursor.getCount() > 0){
        while(cursor.moveToFirst()){
            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}}
</code>```

But i do not know how to retrieve the other details .

Please help me out .
Thank you.

答:
It's a 2 step process:

Get the contact-id from the phone number

Get requested data types (emails, phones, etc.) from the contact-id

Notes:

* multiple contacts may have the same phone number, in this example, i'll just take the first contact-id returned, and ignore the rest

* make sure you import all the following classes from ContactsContract or ContactsContract.CommonDataKinds

```<code>// Step 1:
Uri lookUpUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(incoming_number));
String[] projection = new String[] { PhoneLookup.CONTACT_ID, PhoneLookup.DISPLAY_NAME }
Cursor cur = getContentResolver().query(lookUpUri,projection,null,null,null);
if (cur.moveToFirst()){
    long id = cur.getLong(0);
    String name = cur.getString(1);
    Log.d(TAG, "found contact: " + id + " - " + name);

    // Step 2:
    String selection = Data.CONTACT_ID + "=" + id + " AND " + Data.MIMETYPE + " IN ('" + Phone.CONTENT_ITEM_TYPE + "', '" + Email.CONTENT_ITEM_TYPE + "', '" + Organization.CONTENT_ITEM_TYPE + "')";
    String projection = new String[] { Data.MIMETYPE, Data.DATA1, Data.DATA2, Data.DATA3 };
    Cursor cur2 = getContentResolver().query(Data.CONTENT_URI, projection, selection, null, null);
    while (cur2 != null && cur2.moveToNext()) {
        String mime = cur2.getString(0); // email / phone / company
        String data = cur2.getString(1); // the actual info, e.g. +1-212-555-1234
        int type = cur2.getInt(2); // a numeric value representing type: e.g. home / office / personal
        String label = cur2.getString(3); // a custom label in case type is "TYPE_CUSTOM"

        String kind = "unknown";
        String labelStr = "";

        switch (mime) {
            case Phone.CONTENT_ITEM_TYPE:
                kind = "phone";
                labelStr = Phone.getTypeLabel(getResources(), type, label);
                break;
            case Email.CONTENT_ITEM_TYPE:
                kind = "email";
                labelStr = Email.getTypeLabel(getResources(), type, label);
                break;
            case Organization.CONTENT_ITEM_TYPE:
                kind = "company";
                labelStr = Organization.getTypeLabel(getResources(), type, label);
                break;
        }
        Log.d(TAG, "got " + kind + " - " + data + " (" + labelStr + ")");
    }
    if (cur2 != null) {
        cur2.close();
    }
} else {
    Log.d(TAG, "contact not found");
}
cur.close();
</code>```

Body:
I have a phone number. I want to know the detail of that phone number from my phone contact . For that number i stored name, organisation, phone number(work), phone number(home), email(home), email(work), address.

I can get the Display name and ID of that number using the following code

Uri lookUpUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
            Uri.encode(incoming_number));
    Cursor cursor = getApplicationContext().getContentResolver().query(lookUpUri,null,null,null,null);
if(cursor.getCount() > 0){
        while(cursor.moveToFirst()){
            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}}

But i do not know how to retrieve the other details .

Please help me out .
Thank you.

Body:
It's a 2 step process:

Get the contact-id from the phone number

Get requested data types (emails, phones, etc.) from the contact-id

Notes:

* multiple contacts may have the same phone number, in this example, i'll just take the first contact-id returned, and ignore the rest

* make sure you import all the following classes from ContactsContract or ContactsContract.CommonDataKinds

// Step 1:
Uri lookUpUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(incoming_number));
String[] projection = new String[] { PhoneLookup.CONTACT_ID, PhoneLookup.DISPLAY_NAME }
Cursor cur = getContentResolver().query(lookUpUri,projection,null,null,null);
if (cur.moveToFirst()){
    long id = cur.getLong(0);
    String name = cur.getString(1);
    Log.d(TAG, "found contact: " + id + " - " + name);

    // Step 2:
    String selection = Data.CONTACT_ID + "=" + id + " AND " + Data.MIMETYPE + " IN ('" + Phone.CONTENT_ITEM_TYPE + "', '" + Email.CONTENT_ITEM_TYPE + "', '" + Organization.CONTENT_ITEM_TYPE + "')";
    String projection = new String[] { Data.MIMETYPE, Data.DATA1, Data.DATA2, Data.DATA3 };
    Cursor cur2 = getContentResolver().query(Data.CONTENT_URI, projection, selection, null, null);
    while (cur2 != null && cur2.moveToNext()) {
        String mime = cur2.getString(0); // email / phone / company
        String data = cur2.getString(1); // the actual info, e.g. +1-212-555-1234
        int type = cur2.getInt(2); // a numeric value representing type: e.g. home / office / personal
        String label = cur2.getString(3); // a custom label in case type is "TYPE_CUSTOM"

        String kind = "unknown";
        String labelStr = "";

        switch (mime) {
            case Phone.CONTENT_ITEM_TYPE:
                kind = "phone";
                labelStr = Phone.getTypeLabel(getResources(), type, label);
                break;
            case Email.CONTENT_ITEM_TYPE:
                kind = "email";
                labelStr = Email.getTypeLabel(getResources(), type, label);
                break;
            case Organization.CONTENT_ITEM_TYPE:
                kind = "company";
                labelStr = Organization.getTypeLabel(getResources(), type, label);
                break;
        }
        Log.d(TAG, "got " + kind + " - " + data + " (" + labelStr + ")");
    }
    if (cur2 != null) {
        cur2.close();
    }
} else {
    Log.d(TAG, "contact not found");
}
cur.close();


答:
EBS is under EC2 in the AWS Management Console. If you look at the size of your volumes, the type of volumes and also the size of your snapshots that should help identify the cost.

E.g. faster volumes types, provisioned IOPS, large volumes/snapshots are more expensive.

You can put this information into the AWS Simple Montly Calculator to work out the cost https://calculator.s3.amazonaws.com/index.html

You can also look at the usage in CloudWatch, however it's under EBS there and shows per volume statistics.

Title: How to get usage details of AWS EBS service?

Body:
My team got billing for AWS EBS and we have no idea what is it about.

Going to our console and try to open EBS section though we failed to get one as the snapshots below.

So my question is how to get breakdown details on AWS EBS usage billing?

p.s.

The EBS usage cost is viewed under EC2 section in billing tab in the management console


问:
Can compilers optimize nested loops?
In some cases, the time it takes to assign a block of memory to a variable is too much and has to be reduced as much as possible for optimization reasons. This most frequently occours when many itterations of the same method have to be made, where memory gets assigned and freed every itteration. Let me explain on an example:

```<code>while(something){
   int i = 4;
   int b =i*100;
   //...
}
</code>```

Do compilers in this case assign memory before entering the loop as if the variables were declared before the loop, or do they compile assembly code without performing this step and basically compile something "as bad as you wrote it"?
And further, what about nested loops?

答:
In this specific case, the compiler might simply not assign any memory and consider 400 as a constant, depending on what the rest of the loop body is and depending on what compiler optimisation options you are using. You should  construct a simple runnable example, try out some optimisation flags and analyse the assembly code generated by your compiler.

You can also take a look at GCC's optimisation options. For instance flags such as -fgcse-lm and -fgcse-sm can enable some of the behaviour you have described.

Title: Can compilers optimize nested loops?

Body:
In some cases, the time it takes to assign a block of memory to a variable is too much and has to be reduced as much as possible for optimization reasons. This most frequently occours when many itterations of the same method have to be made, where memory gets assigned and freed every itteration. Let me explain on an example:

while(something){
   int i = 4;
   int b =i*100;
   //...
}

Do compilers in this case assign memory before entering the loop as if the variables were declared before the loop, or do they compile assembly code without performing this step and basically compile something "as bad as you wrote it"?
And further, what about nested loops?


问:
How can I create a dictionary within a function out of an argument from that function?
Here's what I've tried:

```<code>def CreateDict(BDF):
    with open('%sdata\\%s.csv' % (mainDir,BDF), mode='r') as infile:
        reader = csv.reader(infile)
        for row in reader:
            key = row[0]
            print("%s%s = %s" % (BDF,[key],row[1:]))

CreateDict(FileName)
</code>```

Print gives me the correct answer. However I want to put it inside a dictionary instead of just printing it out. And I want that dictionary to have the name of FileName).

答:
To create the dictionary:

```<code>def CreateDict(BDF):
    saved={}
    with open('%sdata\\%s.csv' % (mainDir,BDF), mode='r') as infile:
        reader = csv.reader(infile)
        for row in reader:
            key = row[0]
            saved[key]=row[1:]
    return saved
</code>```

I don't know how to give to the dict a specific name, if you need to save more than one CSV file you can use a dictionary where the keys are the fileNames:

```<code> fileNames=['test0', 'test1', 'test2']
 all_files={}
 for fileName in fileNames:
     all_files[fileName]=CreateDict(fileName)
</code>```

Body:
Here's what I've tried:

def CreateDict(BDF):
    with open('%sdata\\%s.csv' % (mainDir,BDF), mode='r') as infile:
        reader = csv.reader(infile)
        for row in reader:
            key = row[0]
            print("%s%s = %s" % (BDF,[key],row[1:]))

CreateDict(FileName)

Print gives me the correct answer. However I want to put it inside a dictionary instead of just printing it out. And I want that dictionary to have the name of FileName).

Body:
To create the dictionary:

def CreateDict(BDF):
    saved={}
    with open('%sdata\\%s.csv' % (mainDir,BDF), mode='r') as infile:
        reader = csv.reader(infile)
        for row in reader:
            key = row[0]
            saved[key]=row[1:]
    return saved

I don't know how to give to the dict a specific name, if you need to save more than one CSV file you can use a dictionary where the keys are the fileNames:

 fileNames=['test0', 'test1', 'test2']
 all_files={}
 for fileName in fileNames:
     all_files[fileName]=CreateDict(fileName)


问:
how to check if a string contains a substring from an array of strings in JavaScript
I'm still learning JavaScript but I just can't seem to find a way to see if a string contains a substring.

Basically I have some Titles of some individuals and I want to see if the Title contains strings like "President" or "Sr" in the title this is what i have so far but does not seem to be working.

```<code>var title = "President of Sales";
var arrayOfTitles = ["President","Chief","VP","SVP","Director","Manager","Mrg","Sr","Senior","Executive Assistant","Principle Architect","GM","Technical Advisor"];

var re = new RegExp(arrayOfTitles.join("|"),"i");

for(i = 0; i < arrayOfTitles.length; i++){
        if ( re.test(gr.title)){
            return;
                }
     }
</code>```

However this code will not work with String likes "Jr VP" or "President of Sales". Is there a way to build an array of Regex of these strings?

any help would be great thanks

答:
You can also use the includes() function, instead of indexOf().</p>

```<code>     var title = "President of Sales";
       var arrayOfTitles = ["President","Chief","VP","SVP","Director","Manager","Mrg","Sr","Senior","Executive Assistant","Principle Architect","GM","Technical Advisor"];
       var matches = (function() {
         for(var i=0; i < arrayOfTitles.length; i++) {
               if(title.includes(arrayOfTitles[i])) { return true; }
         }
         return false;
       }());
</code>```

Body:
I'm still learning JavaScript but I just can't seem to find a way to see if a string contains a substring.

Basically I have some Titles of some individuals and I want to see if the Title contains strings like "President" or "Sr" in the title this is what i have so far but does not seem to be working.

var title = "President of Sales";
var arrayOfTitles = ["President","Chief","VP","SVP","Director","Manager","Mrg","Sr","Senior","Executive Assistant","Principle Architect","GM","Technical Advisor"];

var re = new RegExp(arrayOfTitles.join("|"),"i");

for(i = 0; i < arrayOfTitles.length; i++){
        if ( re.test(gr.title)){
            return;
                }
     }

However this code will not work with String likes "Jr VP" or "President of Sales". Is there a way to build an array of Regex of these strings?

any help would be great thanks

Body:
You can also use the includes() function, instead of indexOf().

     var title = "President of Sales";
       var arrayOfTitles = ["President","Chief","VP","SVP","Director","Manager","Mrg","Sr","Senior","Executive Assistant","Principle Architect","GM","Technical Advisor"];
       var matches = (function() {
         for(var i=0; i < arrayOfTitles.length; i++) {
               if(title.includes(arrayOfTitles[i])) { return true; }
         }
         return false;
       }());


问:
How to define the id in Rails input
How can I define a specific Id into my Rails form ?

```<code><%= c.text_field :description, {placeholder: "New comment", class: 'form-control', id: 'comment_text_bar#{post.id}'} %>
</code>```

I've tried #{}, or <%=%> but it's not working in this case

答:
You should use double quotes(" ") for string interpolation. This should work

```<code><%= c.text_field :description, {placeholder: "New comment", class: 'form-control', id: "comment_text_bar#{post.id}"} %>
</code>```

Title: How to define the id in Rails input

Body:
How can I define a specific Id into my Rails form ?

<%= c.text_field :description, {placeholder: "New comment", class: 'form-control', id: 'comment_text_bar#{post.id}'} %>

I've tried #{}, or <%=%> but it's not working in this case

Body:
You should use double quotes(" ") for string interpolation. This should work

<%= c.text_field :description, {placeholder: "New comment", class: 'form-control', id: "comment_text_bar#{post.id}"} %>


问:
UICollectionView, full width cells, allow autolayout dynamic height?
Note For 2021!  See @Ely answer regarding UICollectionLayoutListConfiguration !!!!

In a vertical UICollectionView ,

Is it possible to have full-width cells, but, allow the dynamic height to be controlled by autolayout?

This strikes me as perhaps the "most important question in iOS with no really good answer."

Important:

Note that in 99% of cases, to achieve full width cells + autolayout dynamic height, simply use a table view. It's that easy.

So what's an example of where you need a collection view?

Collection views are far more powerful than table views.

One straightforward example where you must use a collection view with autolayout dynamic height:

If you animate between two layouts in a collection view. For example, between a 1 and 2 column layout, when the device rotates.

That's a common idiom in iOS. Unfortunately it can only be achieved by solving the problem posed in this QA.  :-/

答:
Problem

You are looking for automatic height and also want to have  full in width,
it is not possible to get both in using UICollectionViewFlowLayoutAutomaticSize.

You want to do using UICollectionView so below is the solution for you.

Solution

Step-I: Calculate the expected height of Cell

1. If you have only UILabel  in CollectionViewCell than set the numberOfLines=0 and that calculated the expected height of UIlable, pass the all three paramters

```<code>func heightForLable(text:String, font:UIFont, width:CGFloat) -> CGFloat {
    // pass string, font, LableWidth
    let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
     label.numberOfLines = 0
     label.lineBreakMode = NSLineBreakMode.byWordWrapping
     label.font = font
     label.text = text
     label.sizeToFit()

     return label.frame.height
}
</code>```

2. If your CollectionViewCell contains only UIImageView and if it's  is supposed to be dynamic in  Height than you need to get the height of UIImage  (your UIImageView must have AspectRatio constraints)

```<code>// this will give you the height of your Image
let heightInPoints = image.size.height
let heightInPixels = heightInPoints * image.scale
</code>```

3.  If it contains both than calculated their height and add them together.

STEP-II: Return the Size of CollectionViewCell

1. Add UICollectionViewDelegateFlowLayout delegate  in your viewController

2. Implement the delegate method

```<code>func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    // This is just for example, for the scenario Step-I -> 1
    let yourWidthOfLable=self.view.size.width
    let font = UIFont(name: "Helvetica", size: 20.0)

    var expectedHeight = heightForLable(array[indePath.row], font: font, width:yourWidthOfLable)

    return CGSize(width: view.frame.width, height: expectedHeight)
}
</code>```

I hope this will help you out.

Body:
Problem

You are looking for automatic height and also want to have  full in width,
it is not possible to get both in using UICollectionViewFlowLayoutAutomaticSize.

You want to do using UICollectionView so below is the solution for you.

Solution

Step-I: Calculate the expected height of Cell

1. If you have only UILabel  in CollectionViewCell than set the numberOfLines=0 and that calculated the expected height of UIlable, pass the all three paramters

func heightForLable(text:String, font:UIFont, width:CGFloat) -> CGFloat {
    // pass string, font, LableWidth
    let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
     label.numberOfLines = 0
     label.lineBreakMode = NSLineBreakMode.byWordWrapping
     label.font = font
     label.text = text
     label.sizeToFit()

     return label.frame.height
}

2. If your CollectionViewCell contains only UIImageView and if it's  is supposed to be dynamic in  Height than you need to get the height of UIImage  (your UIImageView must have AspectRatio constraints)

// this will give you the height of your Image
let heightInPoints = image.size.height
let heightInPixels = heightInPoints * image.scale

3.  If it contains both than calculated their height and add them together.

STEP-II: Return the Size of CollectionViewCell

1. Add UICollectionViewDelegateFlowLayout delegate  in your viewController

2. Implement the delegate method

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    // This is just for example, for the scenario Step-I -> 1
    let yourWidthOfLable=self.view.size.width
    let font = UIFont(name: "Helvetica", size: 20.0)

    var expectedHeight = heightForLable(array[indePath.row], font: font, width:yourWidthOfLable)

    return CGSize(width: view.frame.width, height: expectedHeight)
}

I hope this will help you out.


问:
VBA Select Case runs through without selection
I am really puzzled by this one. Searched the net already but did not find any answer related to my specific case. I have the following code:

```<code>Dim CE_res As Integer

For Index = 1 To 7

Status = ""
CE_res = CInt(Worksheets("werkblad").Range("CEres" & Index).Value)

If CE_res = 0 Then
' Everything ok
    Status = "Pass"

Else

    Select Case CE_res

        Case CE_res < -1500
            Status = "Invalid kV Value"

        Case CE_res < -999
            Status = "No kV Value"

        Case CE_res < -399
            Status = "kV too high"

        Case CE_res = 0
            Status = "kV too low"

        Case CE_res > 500
            Status = "Invalid mAs Value"

        Case CE_res > 49
            Status = "mAs Value missing"

        Case CE_res > 9 And CE_res < 50
            Status = "Adapt Target"

        Case CE_res > 200
            Status = "Adapt Filter"

        Case Else
            Status = "No Selection"

    End Select

End If
</code>```

The CE_res is set to 50. However, always Case Else is selected. Declared CE_res as integer, coverted Worksheets("werkblad").Range("CEres" & Index).Value to an integer, just to be sure.
However, it does not seem to execute the Select Case correctly. Tried it also with other values, even changed the case CE_res > 49 to CE_res = "50" but this also did not work.

Now, I am out of ideas what could be wrong.

答:
As mentioned by other members, due to your use of < > = comparitors you need to make sure you order them correctly or they will not work as intended.  With the very specific values you are using you would probably be better to use TO and be more specific with the values.

```<code>Select Case
  Case -1000 TO -1500
    'Do This
  Case -400 TO -999
    'Do That
  Case -1 TO -399
    'Do Something Else
End Select
</code>```

If you do this the there is no ambiguity as to what does what, it's easier to read and the operation order doesn't matter.

You also don't need to add the CE_res to each Case statement as you already specified the variable on the Select Case CE-res line.  The Correct syntax is

```<code>Select Case CE_res
  Case <-1500
    Status = "Invalid kV Value"
End Select
</code>```

Body:
I am really puzzled by this one. Searched the net already but did not find any answer related to my specific case. I have the following code:

Dim CE_res As Integer

For Index = 1 To 7

Status = ""
CE_res = CInt(Worksheets("werkblad").Range("CEres" & Index).Value)

If CE_res = 0 Then
' Everything ok
    Status = "Pass"

Else

    Select Case CE_res

        Case CE_res < -1500
            Status = "Invalid kV Value"

        Case CE_res < -999
            Status = "No kV Value"

        Case CE_res < -399
            Status = "kV too high"

        Case CE_res = 0
            Status = "kV too low"

        Case CE_res > 500
            Status = "Invalid mAs Value"

        Case CE_res > 49
            Status = "mAs Value missing"

        Case CE_res > 9 And CE_res < 50
            Status = "Adapt Target"

        Case CE_res > 200
            Status = "Adapt Filter"

        Case Else
            Status = "No Selection"

    End Select

End If

The CE_res is set to 50. However, always Case Else is selected. Declared CE_res as integer, coverted Worksheets("werkblad").Range("CEres" & Index).Value to an integer, just to be sure.
However, it does not seem to execute the Select Case correctly. Tried it also with other values, even changed the case CE_res > 49 to CE_res = "50" but this also did not work.

Now, I am out of ideas what could be wrong.

Body:
As mentioned by other members, due to your use of < > = comparitors you need to make sure you order them correctly or they will not work as intended.  With the very specific values you are using you would probably be better to use TO and be more specific with the values.

Select Case
  Case -1000 TO -1500
    'Do This
  Case -400 TO -999
    'Do That
  Case -1 TO -399
    'Do Something Else
End Select

If you do this the there is no ambiguity as to what does what, it's easier to read and the operation order doesn't matter.

You also don't need to add the CE_res to each Case statement as you already specified the variable on the Select Case CE-res line.  The Correct syntax is

Select Case CE_res
  Case <-1500
    Status = "Invalid kV Value"
End Select


问:
How to hide item in Ext menu base on condition when load
i am trying to hide an item in Ext.menu.Menu base on condition but, i cannot find the trigger load event of menu. Can you give me advice.

```<code>//var lala //= 1 2 or 3

var menu = Ext.create('Ext.menu.Menu', {
        id: 'mainMenu',
        items: [

            {
                text: 'I like Ext',
                checked: true,       // condition 1
                checkHandler: onItemCheck
            }, {
               text: 'Choose a Date',
               iconCls: 'calendar',
               menu: dateMenu // <-- condition 2
           },{
               text: 'Choose a Color',
               menu: colorMenu // <-- condition 3
           }
        ]
    });
</code>```

Example: only show checkbox in menu if lala = 1.
Thank you.

答:
From your code //var lala //= 1 2 or 3, I presume, you know the value of lala when creating the menu. All you need to do then is set the items of the menu, that you want.

Something along the lines of:

```<code>var menuItems = [];

if (lala === 1) {
    menuItems.push({
        text: 'I like Ext',
        checked: true,       // condition 1
        checkHandler: onItemCheck
    });
}
else if (lala === 2) {
    menuItems.push({
        text: 'Choose a Date',
        iconCls: 'calendar',
        menu: dateMenu // <-- condition 2
    });
}
else if (lala === 3) {
    menuItems.push({
        text: 'Choose a Color',
        menu: colorMenu // <-- condition 3
    })
}

var menu = Ext.create('Ext.menu.Menu', {
    id: 'mainMenu',
    items: menuItems
});
</code>```

You keep talking about 'load'. Your example menu does not have any store, so it does not actually load.

However, if you need to change the menu on the fly, when some store loads (or some other event is fired), you can do it like this:

```<code>// Set all menu items in menu
var menu = Ext.create('Ext.menu.Menu', {
    id: 'mainMenu',
    items: [
        {
            text: 'I like Ext',
            itemId: 'lala1', // Item ID to find the component on the fly
            hidden: lala !== 1, // if lala is already initialized
            //hidden: true, // if lala is not initialized
            checked: true,       // condition 1
            checkHandler: onItemCheck
        },
        {
            text: 'Choose a Date',
            itemId: 'lala2', // Item ID to find the component on the fly
            hidden: lala !== 2, // If lala is already initialized
            //hidden: true, // if lala is not initialized
            iconCls: 'calendar',
            menu: dateMenu // <-- condition 2
        },
        {
            text: 'Choose a Color',
            itemId: 'lala3', // Item ID to find the component on the fly
            hidden: lala !== 3, // If lala is already initialized
            //hidden: true, // if lala is not initialized
            menu: colorMenu // <-- condition 3
        }
    ]
});

// Your store load (or any other event of your choosing)
yourStore.on({
    load: function() {
        var newLala = getLalaSomehow(); // Get lala the way you do

        // Get menu items by the item IDs set previously
        var menuItemLala1 = menu.down('#lala1');
        var menuItemLala2 = menu.down('#lala2');
        var menuItemLala3 = menu.down('#lala3');

        // Show/hide menu items based on a condition
        menuItemLala1.setVisible(newLala === 1); // Only show when lala is 1
        menuItemLala2.setVisible(newLala === 2); // Only show when lala is 2
        menuItemLala3.setVisible(newLala === 3); // Only show when lala is 3
    }
});
</code>```

In the example above, I am using setVisible method, which shows the component when the passed argument is true and hides it, if it's false.

Body:
i am trying to hide an item in Ext.menu.Menu base on condition but, i cannot find the trigger load event of menu. Can you give me advice.

//var lala //= 1 2 or 3

var menu = Ext.create('Ext.menu.Menu', {
        id: 'mainMenu',
        items: [

            {
                text: 'I like Ext',
                checked: true,       // condition 1
                checkHandler: onItemCheck
            }, {
               text: 'Choose a Date',
               iconCls: 'calendar',
               menu: dateMenu // <-- condition 2
           },{
               text: 'Choose a Color',
               menu: colorMenu // <-- condition 3
           }
        ]
    });

Example: only show checkbox in menu if lala = 1.
Thank you.

Body:
From your code //var lala //= 1 2 or 3, I presume, you know the value of lala when creating the menu. All you need to do then is set the items of the menu, that you want.

Something along the lines of:

var menuItems = [];

if (lala === 1) {
    menuItems.push({
        text: 'I like Ext',
        checked: true,       // condition 1
        checkHandler: onItemCheck
    });
}
else if (lala === 2) {
    menuItems.push({
        text: 'Choose a Date',
        iconCls: 'calendar',
        menu: dateMenu // <-- condition 2
    });
}
else if (lala === 3) {
    menuItems.push({
        text: 'Choose a Color',
        menu: colorMenu // <-- condition 3
    })
}

var menu = Ext.create('Ext.menu.Menu', {
    id: 'mainMenu',
    items: menuItems
});

You keep talking about 'load'. Your example menu does not have any store, so it does not actually load.

However, if you need to change the menu on the fly, when some store loads (or some other event is fired), you can do it like this:

// Set all menu items in menu
var menu = Ext.create('Ext.menu.Menu', {
    id: 'mainMenu',
    items: [
        {
            text: 'I like Ext',
            itemId: 'lala1', // Item ID to find the component on the fly
            hidden: lala !== 1, // if lala is already initialized
            //hidden: true, // if lala is not initialized
            checked: true,       // condition 1
            checkHandler: onItemCheck
        },
        {
            text: 'Choose a Date',
            itemId: 'lala2', // Item ID to find the component on the fly
            hidden: lala !== 2, // If lala is already initialized
            //hidden: true, // if lala is not initialized
            iconCls: 'calendar',
            menu: dateMenu // <-- condition 2
        },
        {
            text: 'Choose a Color',
            itemId: 'lala3', // Item ID to find the component on the fly
            hidden: lala !== 3, // If lala is already initialized
            //hidden: true, // if lala is not initialized
            menu: colorMenu // <-- condition 3
        }
    ]
});

// Your store load (or any other event of your choosing)
yourStore.on({
    load: function() {
        var newLala = getLalaSomehow(); // Get lala the way you do

        // Get menu items by the item IDs set previously
        var menuItemLala1 = menu.down('#lala1');
        var menuItemLala2 = menu.down('#lala2');
        var menuItemLala3 = menu.down('#lala3');

        // Show/hide menu items based on a condition
        menuItemLala1.setVisible(newLala === 1); // Only show when lala is 1
        menuItemLala2.setVisible(newLala === 2); // Only show when lala is 2
        menuItemLala3.setVisible(newLala === 3); // Only show when lala is 3
    }
});

In the example above, I am using setVisible method, which shows the component when the passed argument is true and hides it, if it's false.


问:
How to check and convert image data types in OpenCV using Python
I'm using various methods in OpenCV to preprocess some images. I often get errors relating to the data type when passing objects been methods eg:

```<code>import cv2
import numpy as np

#import image and select ROI
image1 = cv2.imread('image.png')
roi_1 = cv2.selectROI(image1) # spacebar to confirm selection
cv2.waitKey(0)
cv2.destroyAllWindows()

# preprocesssing
imCrop_1 = image1[int(roi_1[1]):int(roi_1[1]+roi_1[3]), int(roi_1[0]):int(roi_1[0]+roi_1[2])]
grey1 = cv2.cvtColor(imCrop_1, cv2.COLOR_RGB2GRAY)
thresh, bw_1 = cv2.threshold(grey1, 200, 255, cv2.THRESH_OTSU)
canny_edge1 = cv2.Canny(bw_1, 50, 100)

#test=roi_1 # Doesn't work with error: /home/bprodz/opencv/modules/photo/src/denoising.cpp:182: error: (-5) Type of input image should be CV_8UC3 or CV_8UC4! in function fastNlMeansDenoisingColored
#test = imCrop_1 # works
#test = grey1 # doesn't work with error above
#test = bw_1 # doesn't work with error above
#test = canny_edge1 # doesn't work with error above

dst = cv2.fastNlMeansDenoisingColored(test,None,10,10,7,21)

# Check object types
type(imCrop_1) # returns numpy.ndarray - would like to see ~ CV_8UC3 etc.
type(grey1) # returns numpy.ndarray
</code>```

Presently I just use trial and error, is a there a more methodical approach that I can use for checking and converting between different object types?

答:
You are probably using wrong method, for this purpose, you may also get a hint from the method name you are using, as per documentation of cv2. fastNlMeansDenoisingColored:

src – Input 8-bit 3-channel image.

dst – Output image with the same size and type as src .

So, if want to use cv2. fastNlMeansDenoisingColored then you need to convert the src mat to a 3-channel matrix which can be done as:

```<code>cv2.cvtColor(src, cv2.COLOR_GRAY2BGR)
</code>```

But if you have gray-scale image, then you may use cv2.fastNlMeansDenoising, which accepts the both single channel and three channel as source mats, and save the step for converting the image.

You can also use img.shape to check the number of channels for a given matrix. it would return (100, 100) for a gray-scale matrix, (100, 100, 3) for 3-channel matrix and (100, 100, 4) for 4-channel matrix. You can also get the type of matrix using img.dtype

Body:
I'm using various methods in OpenCV to preprocess some images. I often get errors relating to the data type when passing objects been methods eg:

import cv2
import numpy as np

#import image and select ROI
image1 = cv2.imread('image.png')
roi_1 = cv2.selectROI(image1) # spacebar to confirm selection
cv2.waitKey(0)
cv2.destroyAllWindows()

# preprocesssing
imCrop_1 = image1[int(roi_1[1]):int(roi_1[1]+roi_1[3]), int(roi_1[0]):int(roi_1[0]+roi_1[2])]
grey1 = cv2.cvtColor(imCrop_1, cv2.COLOR_RGB2GRAY)
thresh, bw_1 = cv2.threshold(grey1, 200, 255, cv2.THRESH_OTSU)
canny_edge1 = cv2.Canny(bw_1, 50, 100)

#test=roi_1 # Doesn't work with error: /home/bprodz/opencv/modules/photo/src/denoising.cpp:182: error: (-5) Type of input image should be CV_8UC3 or CV_8UC4! in function fastNlMeansDenoisingColored
#test = imCrop_1 # works
#test = grey1 # doesn't work with error above
#test = bw_1 # doesn't work with error above
#test = canny_edge1 # doesn't work with error above

dst = cv2.fastNlMeansDenoisingColored(test,None,10,10,7,21)

# Check object types
type(imCrop_1) # returns numpy.ndarray - would like to see ~ CV_8UC3 etc.
type(grey1) # returns numpy.ndarray

Presently I just use trial and error, is a there a more methodical approach that I can use for checking and converting between different object types?

Body:
You are probably using wrong method, for this purpose, you may also get a hint from the method name you are using, as per documentation of cv2. fastNlMeansDenoisingColored:

src – Input 8-bit 3-channel image.

dst – Output image with the same size and type as src .

So, if want to use cv2. fastNlMeansDenoisingColored then you need to convert the src mat to a 3-channel matrix which can be done as:

cv2.cvtColor(src, cv2.COLOR_GRAY2BGR)

But if you have gray-scale image, then you may use cv2.fastNlMeansDenoising, which accepts the both single channel and three channel as source mats, and save the step for converting the image.

You can also use img.shape to check the number of channels for a given matrix. it would return (100, 100) for a gray-scale matrix, (100, 100, 3) for 3-channel matrix and (100, 100, 4) for 4-channel matrix. You can also get the type of matrix using img.dtype


问:
Linear Regression Model missing an argument .fit
I am trying to write a linear regression model but I get a type error:

```<code>Traceback (most recent call last) <ipython-input-65-8a233a281e65> in <module>()
      2 y_val= df['GOOGL']
      3 body_reg =linear_model.LinearRegression
----> 4 body_reg.fit(x_val, y_val)

TypeError: fit() missing 1 required positional argument: 'y'
</code>```

This is the code I have so after importing sklearn, pandas, etc.

```<code>import pandas as pd
import matplotlib.pyplot as plt
% matplotlib inline
df = pd.read_csv(r'C:\Users\Brian\Desktop\GOOGTICKER.CSV')
df
times = pd.DatetimeIndex(df['Date'])
grouped= df.groupby([times.year]).mean()
from sklearn import linear_model
x_val= df['MSFT']
y_val= df['GOOGL']
body_reg =linear_model.LinearRegression
body_reg.fit(x_val, y_val)
</code>```

Am I missing an argument?

答:
You need to create an instance of the class:</p>

```<code>body_reg = linear_model.LinearRegression()
</code>```

Body:
I am trying to write a linear regression model but I get a type error:

Traceback (most recent call last) <ipython-input-65-8a233a281e65> in <module>()
      2 y_val= df['GOOGL']
      3 body_reg =linear_model.LinearRegression
----> 4 body_reg.fit(x_val, y_val)

TypeError: fit() missing 1 required positional argument: 'y'

This is the code I have so after importing sklearn, pandas, etc.

import pandas as pd
import matplotlib.pyplot as plt
% matplotlib inline
df = pd.read_csv(r'C:\Users\Brian\Desktop\GOOGTICKER.CSV')
df
times = pd.DatetimeIndex(df['Date'])
grouped= df.groupby([times.year]).mean()
from sklearn import linear_model
x_val= df['MSFT']
y_val= df['GOOGL']
body_reg =linear_model.LinearRegression
body_reg.fit(x_val, y_val)

Am I missing an argument?

Body:
You need to create an instance of the class:

body_reg = linear_model.LinearRegression()


问:
macOS Swift: How to properly add application as Login Item
I have spent about one day (maybe a little more) on trying to add my application to Login Item in the order it starts up at macOS launch (user login).

The first approach was the newest one; I check this tutorial on youtube:
https://www.youtube.com/watch?v=2mmWEHUgEBo&t=660s

So following this steps, I have done:

Add new project inside my main project that I have named  Launcher

I am using Automatic Signing (as version of my Xcode) is different

In Project Settings > Capabilities I toggled App Sandbox to ON.

In Build Phases I have added this:

My Launcher has Skip Install = YES

Code in my Launcher app looks like this (I have even previously use Swift to do the same)

```<code>  - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application

    NSArray *pathComponents = [[[NSBundle mainBundle] bundlePath] pathComponents];
    pathComponents = [pathComponents subarrayWithRange:NSMakeRange(0, [pathComponents count] - 4)];
    NSString *path = [NSString pathWithComponents:pathComponents];
    [[NSWorkspace sharedWorkspace] launchApplication:path];
    [NSApp terminate:nil];
}
</code>```

Finally, I have magic code in Main App to enable app as Login Item

```<code>  if(!SMLoginItemSetEnabled("click.remotely.Remotely-Click-Server-Launcher"
 as CFString, Bool(checkboxButton.state as NSNumber) ) ) {
            let alert: NSAlert = NSAlert()
            alert.messageText = "Remotely.Click Server - Error";
            alert.informativeText = "Application couldn't be added as
        Login Item to macOS System Preferences > Users & Groups.";
            alert.alertStyle = NSAlertStyle.warning;
            alert.addButton(withTitle:"OK");
            alert.runModal();
   }
</code>```

I have made Archive, and then have different options to Export:

I couldn't decide which one to choose, so I tried all of them.
"Save for Mac App Store Deployment" - made Installation package that has installed in /Applications/ directory but the app never runs.
"Developer-Id signed," "Development-signed" , "macOS App" all makes file in a directory that I exported to Applications directory, but no one works.

When I click the checkbox button, I could see some window blinking for a while on the screen (Launcher program). When I log out and log in the same window blinking effect appears but Launcher didn't start the Main application. When I click checkbox button again (and turn off Login Item) this blinking effect on user login (system startup) doesn't happen again. So it seems that this addition of Launcher program as Login Item works, but this Launcher couldn't start the Main app. Moreover when I go to /Applications/Main.app/Contents/Library/LoginItems/Launcher.app and click it manually then Launcher app launch Main application correctly (so the path was correct).

So what's going wrong?

Then I consider implementation of deprecated approach using
kLSSharedFileListSessionLoginItems

I have thought it must work it just add something in System Preferences this
 window below.

But it also could go wrong!

I have chosen implementation in Swift (all examples/tutorials I have found was in Objective-C) So I have written something like this:

```<code> class LoginItemsList : NSObject {

let loginItemsList : LSSharedFileList = LSSharedFileListCreate(nil, kLSSharedFileListSessionLoginItems.takeRetainedValue(), nil).takeRetainedValue();

func addLoginItem(_ path: CFURL) -> Bool {

    if(getLoginItem(path) != nil) {
        print("Login Item has already been added to the list.");
        return true;
    }

    var path : CFURL = CFURLCreateWithString(nil, "file:///Applications/Safari.app" as CFString, nil);
    print("Path adding to Login Item list is: ", path);

    // add new Login Item at the end of Login Items list
    if let loginItem = LSSharedFileListInsertItemURL(loginItemsList,
                                                      getLastLoginItemInList(),
                                                      nil, nil,
                                                      path,
                                                      nil, nil) {
        print("Added login item is: ", loginItem);
        return true;
    }

    return false;
}

func removeLoginItem(_ path: CFURL) -> Bool {

    // remove Login Item from the Login Items list
    if let oldLoginItem = getLoginItem(path) {
        print("Old login item is: ", oldLoginItem);
        if(LSSharedFileListItemRemove(loginItemsList, oldLoginItem) == noErr) {
            return true;
        }
        return false;
    }
    print("Login Item for given path not found in the list.");
    return true;
}

func getLoginItem(_ path : CFURL) -> LSSharedFileListItem! {

    var path : CFURL = CFURLCreateWithString(nil, "file:///Applications/Safari.app" as CFString, nil);

    // Copy all login items in the list
    let loginItems : NSArray = LSSharedFileListCopySnapshot(loginItemsList, nil).takeRetainedValue();

    var foundLoginItem : LSSharedFileListItem?;
    var nextItemUrl : Unmanaged<CFURL>?;

    // Iterate through login items to find one for given path
    print("App URL: ", path);
    for var i in (0..<loginItems.count)  // CFArrayGetCount(loginItems)
    {

        var nextLoginItem : LSSharedFileListItem = loginItems.object(at: i) as! LSSharedFileListItem; // CFArrayGetValueAtIndex(loginItems, i).;

        if(LSSharedFileListItemResolve(nextLoginItem, 0, &nextItemUrl, nil) == noErr) {

            print("Next login item URL: ", nextItemUrl!.takeUnretainedValue());
            // compare searched item URL passed in argument with next item URL
            if(nextItemUrl!.takeRetainedValue() == path) {
                foundLoginItem = nextLoginItem;
            }
        }
    }

    return foundLoginItem;
}

func getLastLoginItemInList() -> LSSharedFileListItem! {

    // Copy all login items in the list
    let loginItems : NSArray = LSSharedFileListCopySnapshot(loginItemsList, nil).takeRetainedValue() as NSArray;
    if(loginItems.count > 0) {
        let lastLoginItem = loginItems.lastObject as! LSSharedFileListItem;

        print("Last login item is: ", lastLoginItem);
        return lastLoginItem
    }

    return kLSSharedFileListItemBeforeFirst.takeRetainedValue();
}

func isLoginItemInList(_ path : CFURL) -> Bool {

    if(getLoginItem(path) != nil) {
        return true;
    }

    return false;
}

static func appPath() -> CFURL {

    return NSURL.fileURL(withPath: Bundle.main.bundlePath) as CFURL;
}

 }
</code>```

I have used this to turn on/off Login Item by clicking in the checkbox

```<code>  let loginItemsList = LoginItemsList();

    if( checkboxButton.state == 0) {
        if(!loginItemsList.removeLoginItem(LoginItemsList.appPath())) {
            print("Error while removing Login Item from the list.");
        }
    } else {
        if(!loginItemsList.addLoginItem(LoginItemsList.appPath())) {
            print("Error while adding Login Item to the list.");
        }
    }
</code>```

I have run it in Debug mode (Xcode Play button) and try to archive it and export to /Applications folder if it matters, but this approach also doesn't work.

Console-printed messaged. Error means that the function Inserting Login Item returns nil.

So after that I even try to implement this (from some stackoverflow example) using Objective-C (as there is many Unmanaged<> in Swift)
So I added new .m and .h file and Bridging-Header.h and then a code like this:

```<code>- (void)enableLoginItemWithURL:(NSURL *)itemURL
{
    LSSharedFileListRef loginListRef = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);

    if (loginListRef) {
        // Insert the item at the bottom of Login Items list.
        LSSharedFileListItemRef loginItemRef = LSSharedFileListInsertItemURL(loginListRef,
                                                                             kLSSharedFileListItemLast,
                                                                             NULL,
                                                                             NULL,
                                                                             (__bridge CFURLRef) itemURL,
                                                                             NULL,
                                                                             NULL);
        if (loginItemRef) {
            CFRelease(loginItemRef);
        }
        CFRelease(loginListRef);
    }
}
</code>```

Simple (just insertion) without any bells and whistles.
It also has the same issue that LSSharedFileListInsertItemURL returns nil and Login Item is not added to System Preferences > Users & Groups > Login Items.

So any idea why I cannot make this work?

UPDATE 1

I have tried to implement application using first approach (helper Launcher application inside Main application) on another computer iMac (MacOS Sierra and the newest XCode 8.3) and it seems to work there correctly so maybe there is something wrong with my OS or Xcode (provisioning profiles, signing of app or whatever) On MacBook Air where this approach doesn't work I am using OS X El Capitan 10.11.5 and Xcode 8.0.

Watch how it works here:
https://youtu.be/6fnLzkh5Rbs
and testing
https://www.youtube.com/watch?v=sUE7Estju0U

The second approach doesn't work also on my iMac returning the nil while doing LSSharedFileListInsertItemURL. So I don't know why that is happening.

Watch how it works here:
https://youtu.be/S_7ctQLkIuA

UPDATE 2

After upgrade to macOS Sierra 10.12.5 from El Capitan 10.11.5 and using Xcode 8.3.2 instead of Xcode 8.0.0 the second approach also happens to work correctly and is adding Login Items to System Preferences > Users & Groups > Login Items
IMPORTANT! To work this approach with LSSharedFileListInsertItemURL needs to disable App Sandboxing! Like in the video below:
https://youtu.be/UvDkby0t_WI

答: For the ServiceManagement approach, sometimes it doesn't work in your development machine because there is another copy of the app in your Xcode's DerivedData. The system don't know which app to launch. So go to ~/Library/Developer/Xcode/DerivedData and delete your development copy could help.</p>

Body:
I have spent about one day (maybe a little more) on trying to add my application to Login Item in the order it starts up at macOS launch (user login).

The first approach was the newest one; I check this tutorial on youtube:
https://www.youtube.com/watch?v=2mmWEHUgEBo&t=660s

So following this steps, I have done:

Add new project inside my main project that I have named  Launcher

I am using Automatic Signing (as version of my Xcode) is different

In Project Settings > Capabilities I toggled App Sandbox to ON.

In Build Phases I have added this:

My Launcher has Skip Install = YES

Code in my Launcher app looks like this (I have even previously use Swift to do the same)

  - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application

    NSArray *pathComponents = [[[NSBundle mainBundle] bundlePath] pathComponents];
    pathComponents = [pathComponents subarrayWithRange:NSMakeRange(0, [pathComponents count] - 4)];
    NSString *path = [NSString pathWithComponents:pathComponents];
    [[NSWorkspace sharedWorkspace] launchApplication:path];
    [NSApp terminate:nil];
}

Finally, I have magic code in Main App to enable app as Login Item

  if(!SMLoginItemSetEnabled("click.remotely.Remotely-Click-Server-Launcher"
 as CFString, Bool(checkboxButton.state as NSNumber) ) ) {
            let alert: NSAlert = NSAlert()
            alert.messageText = "Remotely.Click Server - Error";
            alert.informativeText = "Application couldn't be added as
        Login Item to macOS System Preferences > Users & Groups.";
            alert.alertStyle = NSAlertStyle.warning;
            alert.addButton(withTitle:"OK");
            alert.runModal();
   }

I have made Archive, and then have different options to Export:

I couldn't decide which one to choose, so I tried all of them.
"Save for Mac App Store Deployment" - made Installation package that has installed in /Applications/ directory but the app never runs.
"Developer-Id signed," "Development-signed" , "macOS App" all makes file in a directory that I exported to Applications directory, but no one works.

When I click the checkbox button, I could see some window blinking for a while on the screen (Launcher program). When I log out and log in the same window blinking effect appears but Launcher didn't start the Main application. When I click checkbox button again (and turn off Login Item) this blinking effect on user login (system startup) doesn't happen again. So it seems that this addition of Launcher program as Login Item works, but this Launcher couldn't start the Main app. Moreover when I go to /Applications/Main.app/Contents/Library/LoginItems/Launcher.app and click it manually then Launcher app launch Main application correctly (so the path was correct).

So what's going wrong?

Then I consider implementation of deprecated approach using
kLSSharedFileListSessionLoginItems

I have thought it must work it just add something in System Preferences this
 window below.

But it also could go wrong!

I have chosen implementation in Swift (all examples/tutorials I have found was in Objective-C) So I have written something like this:

 class LoginItemsList : NSObject {

let loginItemsList : LSSharedFileList = LSSharedFileListCreate(nil, kLSSharedFileListSessionLoginItems.takeRetainedValue(), nil).takeRetainedValue();

func addLoginItem(_ path: CFURL) -> Bool {

    if(getLoginItem(path) != nil) {
        print("Login Item has already been added to the list.");
        return true;
    }

    var path : CFURL = CFURLCreateWithString(nil, "file:///Applications/Safari.app" as CFString, nil);
    print("Path adding to Login Item list is: ", path);

    // add new Login Item at the end of Login Items list
    if let loginItem = LSSharedFileListInsertItemURL(loginItemsList,
                                                      getLastLoginItemInList(),
                                                      nil, nil,
                                                      path,
                                                      nil, nil) {
        print("Added login item is: ", loginItem);
        return true;
    }

    return false;
}

func removeLoginItem(_ path: CFURL) -> Bool {

    // remove Login Item from the Login Items list
    if let oldLoginItem = getLoginItem(path) {
        print("Old login item is: ", oldLoginItem);
        if(LSSharedFileListItemRemove(loginItemsList, oldLoginItem) == noErr) {
            return true;
        }
        return false;
    }
    print("Login Item for given path not found in the list.");
    return true;
}

func getLoginItem(_ path : CFURL) -> LSSharedFileListItem! {

    var path : CFURL = CFURLCreateWithString(nil, "file:///Applications/Safari.app" as CFString, nil);

    // Copy all login items in the list
    let loginItems : NSArray = LSSharedFileListCopySnapshot(loginItemsList, nil).takeRetainedValue();

    var foundLoginItem : LSSharedFileListItem?;
    var nextItemUrl : Unmanaged<CFURL>?;

    // Iterate through login items to find one for given path
    print("App URL: ", path);
    for var i in (0..<loginItems.count)  // CFArrayGetCount(loginItems)
    {

        var nextLoginItem : LSSharedFileListItem = loginItems.object(at: i) as! LSSharedFileListItem; // CFArrayGetValueAtIndex(loginItems, i).;

        if(LSSharedFileListItemResolve(nextLoginItem, 0, &nextItemUrl, nil) == noErr) {

            print("Next login item URL: ", nextItemUrl!.takeUnretainedValue());
            // compare searched item URL passed in argument with next item URL
            if(nextItemUrl!.takeRetainedValue() == path) {
                foundLoginItem = nextLoginItem;
            }
        }
    }

    return foundLoginItem;
}

func getLastLoginItemInList() -> LSSharedFileListItem! {

    // Copy all login items in the list
    let loginItems : NSArray = LSSharedFileListCopySnapshot(loginItemsList, nil).takeRetainedValue() as NSArray;
    if(loginItems.count > 0) {
        let lastLoginItem = loginItems.lastObject as! LSSharedFileListItem;

        print("Last login item is: ", lastLoginItem);
        return lastLoginItem
    }

    return kLSSharedFileListItemBeforeFirst.takeRetainedValue();
}

func isLoginItemInList(_ path : CFURL) -> Bool {

    if(getLoginItem(path) != nil) {
        return true;
    }

    return false;
}

static func appPath() -> CFURL {

    return NSURL.fileURL(withPath: Bundle.main.bundlePath) as CFURL;
}

 }

I have used this to turn on/off Login Item by clicking in the checkbox

  let loginItemsList = LoginItemsList();

    if( checkboxButton.state == 0) {
        if(!loginItemsList.removeLoginItem(LoginItemsList.appPath())) {
            print("Error while removing Login Item from the list.");
        }
    } else {
        if(!loginItemsList.addLoginItem(LoginItemsList.appPath())) {
            print("Error while adding Login Item to the list.");
        }
    }

I have run it in Debug mode (Xcode Play button) and try to archive it and export to /Applications folder if it matters, but this approach also doesn't work.

Console-printed messaged. Error means that the function Inserting Login Item returns nil.

So after that I even try to implement this (from some stackoverflow example) using Objective-C (as there is many Unmanaged<> in Swift)
So I added new .m and .h file and Bridging-Header.h and then a code like this:

- (void)enableLoginItemWithURL:(NSURL *)itemURL
{
    LSSharedFileListRef loginListRef = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);

    if (loginListRef) {
        // Insert the item at the bottom of Login Items list.
        LSSharedFileListItemRef loginItemRef = LSSharedFileListInsertItemURL(loginListRef,
                                                                             kLSSharedFileListItemLast,
                                                                             NULL,
                                                                             NULL,
                                                                             (__bridge CFURLRef) itemURL,
                                                                             NULL,
                                                                             NULL);
        if (loginItemRef) {
            CFRelease(loginItemRef);
        }
        CFRelease(loginListRef);
    }
}

Simple (just insertion) without any bells and whistles.
It also has the same issue that LSSharedFileListInsertItemURL returns nil and Login Item is not added to System Preferences > Users & Groups > Login Items.

So any idea why I cannot make this work?

UPDATE 1

I have tried to implement application using first approach (helper Launcher application inside Main application) on another computer iMac (MacOS Sierra and the newest XCode 8.3) and it seems to work there correctly so maybe there is something wrong with my OS or Xcode (provisioning profiles, signing of app or whatever) On MacBook Air where this approach doesn't work I am using OS X El Capitan 10.11.5 and Xcode 8.0.

Watch how it works here:
https://youtu.be/6fnLzkh5Rbs
and testing
https://www.youtube.com/watch?v=sUE7Estju0U

The second approach doesn't work also on my iMac returning the nil while doing LSSharedFileListInsertItemURL. So I don't know why that is happening.

Watch how it works here:
https://youtu.be/S_7ctQLkIuA

UPDATE 2

After upgrade to macOS Sierra 10.12.5 from El Capitan 10.11.5 and using Xcode 8.3.2 instead of Xcode 8.0.0 the second approach also happens to work correctly and is adding Login Items to System Preferences > Users & Groups > Login Items
IMPORTANT! To work this approach with LSSharedFileListInsertItemURL needs to disable App Sandboxing! Like in the video below:
https://youtu.be/UvDkby0t_WI


问:
JaxB : Define default @XmlElements for a specific data type
As shown below JaxB provides for children to be differentiated by the tag name.

```<code>@XmlElements({
    @XmlElement(name="horse", type=Horse.class),
    @XmlElement(name="cow", type=Cow.class)
})
private Animal animal;
</code>```

But how can I implement the desired functionality by default. Every Animal within the document should have the choice of Horse or Cow but I don't want to type the @XmlElements every time ?

答:
It seems the solution is @XmlSeeAlso

http://docs.oracle.com/javaee/6/api/javax/xml/bind/annotation/XmlSeeAlso.html

Body:
As shown below JaxB provides for children to be differentiated by the tag name.

@XmlElements({
    @XmlElement(name="horse", type=Horse.class),
    @XmlElement(name="cow", type=Cow.class)
})
private Animal animal;

But how can I implement the desired functionality by default. Every Animal within the document should have the choice of Horse or Cow but I don't want to type the @XmlElements every time ?


问:
Convert Angular Material File Input to base64 format
I am using angular 1.7 with material design for my project. i am using angular material file input for this but it gives me result in file format. what i need is to convert that file format into base64 format. i have tried some external libraries but it doesn't work for me. can anyone post code or make a codepen/jsfiddle.</p>

答:
You can try this solution (this is o copy of this post: How to convert file to base64 in JavaScript? ):</p>

```<code>function getBase64(file) {
   var reader = new FileReader();
   reader.readAsDataURL(file);
   reader.onload = function () {
     console.log(reader.result);
   };
   reader.onerror = function (error) {
     console.log('Error: ', error);
   };
}

var file = /*Your file goes here*/
getBase64(file); // prints the base64 string
</code>```

Body:
You can try this solution (this is o copy of this post: How to convert file to base64 in JavaScript? ):

function getBase64(file) {
   var reader = new FileReader();
   reader.readAsDataURL(file);
   reader.onload = function () {
     console.log(reader.result);
   };
   reader.onerror = function (error) {
     console.log('Error: ', error);
   };
}

var file = /*Your file goes here*/
getBase64(file); // prints the base64 string


问:
Is there a way to get a 32bit C++ compiler to follow 16bit integer promotion rules?
With the following code:

```<code>#include <stdint.h>

uint16_t test() {
    uint16_t a = 1000;
    uint16_t b = 1000;
    uint16_t c = 100;
    return (a * b) / c;
}
</code>```

A compiler targeting a 32bit machine will return 10000, but one targeting a 16 bit machine will return 169. The behavior is explained by C's integer promotion rules.

This is a problem when unit testing firmware for a 8 or 16 bit machine on a desktop PC.

Right now, either casting every multiplication or putting it inside a function returning the same type are the only options I can think of. Ideally some compiler switch would exist, but I haven't seen one.

Happy with a solution for either GCC, Clang or MSVC.

答:
This could be an XY problem. Depends on your specific work.

While unit testing on a desktop machine for a different architecture could help, I doubt this is the way. Even if you found some switches in the compiler to simulate on x86 some rules for other architecture, you can never be sure that the simulated behavior will be the same as in the real environment. Furthermore there certainly will be other differences (some you can predict, some you cannot) on behavior between the target architecture and the testing architecture.

So in conclusion, testing on an architecture and expecting it to work on another is not reliable, not in a real way anyway. So the solution should be to test on the target architecture. Get an emulator, or a VM, or a remote device on which you can unit test on the real environment.

If that is not a viable option, instead of trying to make unit testing match the real environment from a pc environment, you could just live with these differences, take into account that unit tests are not very reliable and use them just for limited testing, and rely more on integration testing, which should be on the target architecture.

Body:
With the following code:

#include <stdint.h>

uint16_t test() {
    uint16_t a = 1000;
    uint16_t b = 1000;
    uint16_t c = 100;
    return (a * b) / c;
}

A compiler targeting a 32bit machine will return 10000, but one targeting a 16 bit machine will return 169. The behavior is explained by C's integer promotion rules.

This is a problem when unit testing firmware for a 8 or 16 bit machine on a desktop PC.

Right now, either casting every multiplication or putting it inside a function returning the same type are the only options I can think of. Ideally some compiler switch would exist, but I haven't seen one.

Happy with a solution for either GCC, Clang or MSVC.


答:
Why would it be 12?

```<code>x+1-x=y
</code>```

y can't possibly be 12, be this pointer arithmetic or integer.

ContentLicense: CC BY-SA 2.5

Title: How to understand the output?

Body:
int a[2][3];
cout << a+1 << " " << a << " " << (a+1) - a << endl;

Output:

0029FAC0 0029FAB4 1

Shouldn't (a+1)-a be 0029FAC0-0029FAB4=12 ?

Body:
Why would it be 12?

x+1-x=y

y can't possibly be 12, be this pointer arithmetic or integer.


问:
How do I in-place modify each element of a 1D Array?
I have a 1D eigen array (Eigen::Array<double,Dynamic,Dynamic>) of doubles, and I want to modify each element in the array in place. However, I'm not really sure how to do this. I'm considering this:

```<code>Eigen::Array<double,Eigen::Dynamic,Eigen::Dynamic> arr1D;
// ...

// Threshold function:
arr1D.unaryExpr([](double& elem)
{
    elem = elem < 0.0 ? 0.0 : 1.0;
}
);
</code>```

But this seems like a bit of a hack because the Eigen Reference examples only give examples of .unaryExpr where it is used with a functor that returns a value (and then the whole method just returns a different array). In my case, I was hoping to avoid the need for creating a new array.

I'm new to Eigen so I thought I might be missing something here, input is appreciated.

EDIT: I understand that I can replace the above simply with arr1D = arr1D >= 0.0, but please note that this is just an example

答:
Evgeny's answer is by far the best if your value types are relatively simple.

However, if you want to recreate real() and complex() (accessing portions of the Scalars structure), you can use const_cast<> to hack it all away, which is what real/complex() actually do (as of v3.3.3):
(note: This code was only tested in C++1y, but could be simplified.)

```<code>struct Value {
  double a{1.5};
  int b{2};
};

// Savage. Use aforemention hack from scalar_real_ref_op.
struct get_mutable_a_direct {
  double& operator()(const Value& v) const {
    return const_cast<Value&>(v).a;
  }
};
// ...
MatrixX<Value> X(2, 2);
auto X_am_direct = CwiseUnaryView<get_mutable_a_direct, MatrixX<Value>>(
    X, get_mutable_a_direct());
X_am_direct.setConstant(20);
</code>```

I've also tested out a quick wrapper, to reduce the above to something like:

```<code>struct get_a_flex {
  double& operator()(Value& v) const {
    return v.a;
  }
  const double& operator()(const Value& v) const {
    return v.a;
  }
};
// Less? savage.
auto X_am = unaryExprFlex(X, get_a_flex());
X_am *= 10;
cout << X_ac << endl;

// Works.
const auto& Xc = X;
auto Xc_am = unaryExprFlex(Xc, get_a_flex());
// Xc_am.setConstant(20);  // Fails as desired.
cout << Xc_am << endl;
</code>```

You can see the code snippet here: unary_view_mutable.cc

NOTE: If you want to use labmda, be sure you indicate returning a reference via auto&:

```<code>auto X_bm = unaryExprFlex(X, [](Value& v) -> auto& { return v.b; });
cout << X_bm << endl;
X_bm.setConstant(10);
cout << X_bm << endl;
</code>```

Body:
I have a 1D eigen array (Eigen::Array<double,Dynamic,Dynamic>) of doubles, and I want to modify each element in the array in place. However, I'm not really sure how to do this. I'm considering this:

Eigen::Array<double,Eigen::Dynamic,Eigen::Dynamic> arr1D;
// ...

// Threshold function:
arr1D.unaryExpr([](double& elem)
{
    elem = elem < 0.0 ? 0.0 : 1.0;
}
);

But this seems like a bit of a hack because the Eigen Reference examples only give examples of .unaryExpr where it is used with a functor that returns a value (and then the whole method just returns a different array). In my case, I was hoping to avoid the need for creating a new array.

I'm new to Eigen so I thought I might be missing something here, input is appreciated.

EDIT: I understand that I can replace the above simply with arr1D = arr1D >= 0.0, but please note that this is just an example

Body:
Evgeny's answer is by far the best if your value types are relatively simple.

However, if you want to recreate real() and complex() (accessing portions of the Scalars structure), you can use const_cast<> to hack it all away, which is what real/complex() actually do (as of v3.3.3):
(note: This code was only tested in C++1y, but could be simplified.)

struct Value {
  double a{1.5};
  int b{2};
};

// Savage. Use aforemention hack from scalar_real_ref_op.
struct get_mutable_a_direct {
  double& operator()(const Value& v) const {
    return const_cast<Value&>(v).a;
  }
};
// ...
MatrixX<Value> X(2, 2);
auto X_am_direct = CwiseUnaryView<get_mutable_a_direct, MatrixX<Value>>(
    X, get_mutable_a_direct());
X_am_direct.setConstant(20);

I've also tested out a quick wrapper, to reduce the above to something like:

struct get_a_flex {
  double& operator()(Value& v) const {
    return v.a;
  }
  const double& operator()(const Value& v) const {
    return v.a;
  }
};
// Less? savage.
auto X_am = unaryExprFlex(X, get_a_flex());
X_am *= 10;
cout << X_ac << endl;

// Works.
const auto& Xc = X;
auto Xc_am = unaryExprFlex(Xc, get_a_flex());
// Xc_am.setConstant(20);  // Fails as desired.
cout << Xc_am << endl;

You can see the code snippet here: unary_view_mutable.cc

NOTE: If you want to use labmda, be sure you indicate returning a reference via auto&:

auto X_bm = unaryExprFlex(X, [](Value& v) -> auto& { return v.b; });
cout << X_bm << endl;
X_bm.setConstant(10);
cout << X_bm << endl;


问:
SSH button in Google Compute Engine
Clicking on the SSH button in Google Compute Engine immediately closes the window after opening the window for a moment.
Having the issue in Latest Chrome and Edge on Windows 10.
Any help, please..
Thank you.</p>

答:
I'm not able to reproduce your issue, Have you tried to reproduce using Incognito window?
If you still observe issues, try capturing HAR while SSHing into instance and upload the HAR to check browser interaction with the GCP site. Instructions on how to capture HAR is documented here</p>

Title: SSH button in Google Compute Engine