问:
Angular 2: Duplicate Async Calls in Template Loop
I have a template with an ngFor that receives data via an async observable:

```<code><div *ngFor="let result of data.results">
  <div>
    <img [src]="parseSrc(result.src)" alt="{{ getCaption(result.id) | async }}" />
    {{ getCaption(result.id) | async }}
  </div>
</div>
</code>```

The getCaption method, as you can see, is called twice. The code for it is below:

```<code>public getCaption(id: string) {
  return this.data$.results
    .map(results => {
      let result = results.find(r => r.id === id);
      return result && result.caption || '';
    })
}
</code>```

Is calling it twice an okay way to do this? I feel like calling the function twice is redundant and memory-intensive. What are the other options? I was thinking something like creating a variable in the template would be good, but that's not a facility angular allows. Since this is an ngFor as a result of another async call, performing this logic in the controller code is less than desirable and I feel like there should be a relatively elegant way to perform these two identical calls in the template.

Note: this is a contrived example.

答:
You can wrap it in an ngIf and use the as syntax to bind it to a local value like so:

```<code><div *ngIf="getCaption(result.id) | async as caption">
    <img [src]="parseSrc(result.src)" alt="{{ caption }}" />
    {{ caption }}
</div>
</code>```

Body:
I have a template with an ngFor that receives data via an async observable:

    {{ getCaption(result.id) | async }}

The getCaption method, as you can see, is called twice. The code for it is below:

public getCaption(id: string) {
  return this.data$.results
    .map(results => {
      let result = results.find(r => r.id === id);
      return result && result.caption || '';
    })
}

Is calling it twice an okay way to do this? I feel like calling the function twice is redundant and memory-intensive. What are the other options? I was thinking something like creating a variable in the template would be good, but that's not a facility angular allows. Since this is an ngFor as a result of another async call, performing this logic in the controller code is less than desirable and I feel like there should be a relatively elegant way to perform these two identical calls in the template.

Note: this is a contrived example.

Body:
You can wrap it in an ngIf and use the as syntax to bind it to a local value like so:

<div *ngIf="getCaption(result.id) | async as caption">
    <img [src]="parseSrc(result.src)" alt="{{ caption }}" />
    {{ caption }}
</div>


来源: stackexchange

问:
Serving static files in Express with mustache templating
I'm trying to serve a folder of static mustache files from Express, but can't seem to figure out how to get it working. Say I just have an object of data like

```<code>{
  a: 'Hello :)'
  b: 'Goodbye :('
}
</code>```

And two files,

public/a.html

```<code><div>{{a}}</div>
</code>```

public/b.html

```<code><div>{{b}}</div>
</code>```

How could I get express setup to where it serves any arbitrary number of static html files and replaces the templated parts with just my one big object? Thanks!

答:
You can use mustachejs just like pug in express by setting mustache as view engine and defining its working like below code:

//required files
const fs = require("fs")
const mustache = require("mustache")

// To set functioning of mustachejs view engine
app.engine('html', function (filePath, options, callback) {
    fs.readFile(filePath, function (err, content) {
        if(err)
            return callback(err)
        var rendered = mustache.to_html(content.toString(),options);
        return callback(null, rendered)
    });
  });

// Setting mustachejs as view engine
app.set('views',path.join(__dirname,'views'));
app.set('view engine','html');

//rendering example for response
app.get('/',(req,res)=>{
    res.render('index',{data:'Sample Data'});
});```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to serve a folder of static mustache files from Express, but can't seem to figure out how to get it working. Say I just have an object of data like

{
  a: 'Hello :)'
  b: 'Goodbye :('
}

And two files,

public/a.html

{{a}}

public/b.html

{{b}}

How could I get express setup to where it serves any arbitrary number of static html files and replaces the templated parts with just my one big object? Thanks!


问:
RegEx to make sure that the string contains at least one lower case char, upper case char, digit and symbol
What is the regex to make sure that a given string contains at least one character from each of the following categories.

Lowercase character

Uppercase character

Digit

Symbol

I know the patterns for individual sets namely [a-z], [A-Z], \d and _|[^\w] (I got them correct, didn't I?).

But how do I combine them to make sure that the string contains all of these in any order?

答:
Bart Kiers, your regex has a couple issues. The best way to do that is this:

```<code>(.*[a-z].*)       // For lower cases
(.*[A-Z].*)       // For upper cases
(.*\d.*)          // For digits
(.*\W.*)          // For symbols (non-word characters)
</code>```

In this way you are searching no matter if at the beginning, at the end or at the middle. In your have I have a lot of troubles with complex passwords.

ContentLicense: CC BY-SA 2.5

Body:
Bart Kiers, your regex has a couple issues. The best way to do that is this:

(.*[a-z].*)       // For lower cases
(.*[A-Z].*)       // For upper cases
(.*\d.*)          // For digits
(.*\W.*)          // For symbols (non-word characters)

In this way you are searching no matter if at the beginning, at the end or at the middle. In your have I have a lot of troubles with complex passwords.

ContentLicense: CC BY-SA 4.0


问:
Safari won't play HTML5 video
I'm trying to create a HTML5 video background for a website but I cannot seem to get it to work on Safari. Does anyone have any ideas?

Here's the HTML video tags I'm using

```<code><video id="bgVideo" class="bg__video" autoplay loop>
  <source src="./vid/Sample_Vid.ogv" type="video/ogv">
  <source src="./vid/Sample_Vid.m4v" type="video/m4v">
  <source src="./vid/Sample_Vid.webm" type="video/webm">
</video>
</code>```

I've tried adding a script tag under it to start playing the video with JS but that's not helped either.

```<code>document.getElementById("bgVideo").play();
</code>```

When I inspect the page it looks like the video element is taking up space in the DOM but it's just invisible basically.

I've also tried opening the .m4v files directly in the browser & it plays it there so I assume the file isn't an issue. These were all generated from easyhtml5video.com

I also have the Modernizer script to detect if autoplay is enabled for the browser which I've had to alter based on a pull request in the github repo as it was always saying that Safari doesn't support autoplay otherwise.

The test site I've setup is http://treetopia.neilnand.co.uk/

答:
If video does not has sound - use

```<code>document.getElementById("bgVideo").volume = 0;
</code>```

Safari don't allow autoplay for videos with sound.

Title: Safari won't play HTML5 video

Body:
I'm trying to create a HTML5 video background for a website but I cannot seem to get it to work on Safari. Does anyone have any ideas?

Here's the HTML video tags I'm using

<video id="bgVideo" class="bg__video" autoplay loop>
  <source src="./vid/Sample_Vid.ogv" type="video/ogv">
  <source src="./vid/Sample_Vid.m4v" type="video/m4v">
  <source src="./vid/Sample_Vid.webm" type="video/webm">
</video>

I've tried adding a script tag under it to start playing the video with JS but that's not helped either.

document.getElementById("bgVideo").play();

When I inspect the page it looks like the video element is taking up space in the DOM but it's just invisible basically.

I've also tried opening the .m4v files directly in the browser & it plays it there so I assume the file isn't an issue. These were all generated from easyhtml5video.com

I also have the Modernizer script to detect if autoplay is enabled for the browser which I've had to alter based on a pull request in the github repo as it was always saying that Safari doesn't support autoplay otherwise.

The test site I've setup is http://treetopia.neilnand.co.uk/

Body:
If video does not has sound - use

document.getElementById("bgVideo").volume = 0;

Safari don't allow autoplay for videos with sound.


问:
Xero API invalid OrgId
Working with Xero API

Authorization callback returns org, which should correspond Organisation's ShortCode for which Xero user allowed access.

In callback org value is BFtWATeLda24OXh2Yv-FLG but Organisation's ShortCode is !hvw0y, which obviously does not match.

Other possible field that could be matched

OrganisationId - 29e0fd2c-15da-409e-8462-1ac28b9f8f55 no match

ApiKey - QIBVL4B2BBDNE5WBADGFHZEQYR6SXM no match

I wonder how can i link value org callback parameter to Organisation in Xero.

Using Xero API .NET Core client

答: Is it named the org_muid? If so, that value returned in the oauth call is actually a one way mapping of the OrganisationID. It's a legacy property from before the OrganisationID was returned from the organisation endpoint that is still returned as the removal of it could cause breaking changes for those who use it as the identifier in their token databases.</p>

Title: Xero API invalid OrgId


问:
What are the different versions of Selenium, and which one should I get?
I'm trying to get started with Selenium, but it's extremely confusing for anyone who still doesn't know the project.

If I go to the Selenium download page I get 7 download links for things with different names, and no description of what is each one. And then the Selenium 2 download link points to a page with another 8 files.

What does all of that mean? Which ones are deprecated? Which files should I get?

What are the differences between version 1 and 2? Is the version 1 deprecated, or do we still need to mix some modules from version 1 together with version 2?

And then, after searching on Google, I find Which Selenium Tool Should I Use?, but it's a very outdated page (last edited in 2007). It also talks about a limitation of the JavaScript testing interface: Same Origin Policy. Does this limitation still apply nowadays?

What are "Selenium Core", "Selenium Remote Control", "Selenium IDE"?

How about "Selenium (standalone) Server"? Is it the same thing as the Remote Control, or something different? What is the difference between Selenium Remote Control and Selenium Server?

And then I reach an official FAQ that is also confusing, and talks about a WebDriver thing that was going to be part of Selenium. Is it already inside Selenium? Is that FAQ up-to-date? How does it relate with other Selenium parts?

After all, another way to understand this question is: "I've never used Selenium before, I'm completely lost, and the documentation doesn't help." What I need is an introduction of what are all the parts of the project, which ones are old and deprecated, which ones are needed, which ones are interchangeable, which ones work with different browsers...

(maybe it would be a nice idea to have a community wiki answer that tries to be as accurate and detailed as possible)

答:
I'm not much experienced with Selenium, but recently I have started it to automate form submissions while unit testing. For starters, try Selenium IDE. It is a Firefox addon which will help you to record actions and modify/replay them.

Actually more than that. You can perform Accessor operations, which will perfom a series of recorded/configured actions and will store the end results for us to analyze later.

And then there is Assertions, which will actually check the end state of a series of actions with some pre-configured conditions.

One thing I can say you is that Selenium is very handy and easy to learn. You can write your own test cases using plain html!

Here is a great beginner video - http://wiki.openqa.org/download/attachments/400/Selenium+IDE.swf?version=1

After seeing that, read through this tutorial - http://jroller.com/selenium/

And after that, read this reference - http://release.seleniumhq.org/selenium-core/1.0/reference.html

It explains everything you need to know. If you are first to Selenium, you will be amazZzed to see what all things selenium can do.


问:
Retrofit Null Response onSuccess Method
I was following this tutorial in YouTube for Retrofit for sending objects in a post request but encounter an error on emulator with a null response onResponse method.

Problem:

Main Activity:

```<code>public class MainActivity extends AppCompatActivity {

private EditText mName, mEmail, mAge, mTopics;
private Button mButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mName = findViewById(R.id.editText);
    mEmail = findViewById(R.id.editText2);
    mAge = findViewById(R.id.editText3);
    mTopics = findViewById(R.id.editText4);
    mButton = findViewById(R.id.button);

    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            User user = new User(
                    mName.getText().toString(),
                    mEmail.getText().toString(),
                    Integer.parseInt(mAge.getText().toString()),
                    mTopics.getText().toString().split(",")
            );

            //Added proof its not a NPE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            Log.d("Main", mName.getText().toString() +
                            mName.getText().toString()+ Integer.parseInt(mAge.getText().toString()) +
                            Integer.parseInt(mAge.getText().toString()) +mTopics.getText().toString().split(","));

            sendNetworkRequest(user);
        }
    });

}

private void sendNetworkRequest(User user) {
    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl("http://10.0.2.2:3000/api/users/")
            .addConverterFactory(GsonConverterFactory.create());

    Retrofit retrofit = builder.build();
    UserClient client = retrofit.create(UserClient.class);
    Call<User> call = client.createAccount(user);
    call.enqueue(new Callback<User>() {
        @Override
        public void onResponse(Call<User> call, Response<User> response) {
            Toast.makeText(MainActivity.this, "Success UserID = "+ response.body(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call<User> call, Throwable t) {
            Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_SHORT).show();
        }
    });

}
</code>```

}

Proof of NOT NPE:

UserClient:

```<code>public interface UserClient {

    @POST("api/users")
    Call<User> createAccount(@Body User user);
}
</code>```

User:

```<code>public class User {

private Integer id;
private int age;
private String name, email;
private String [] topics;

public Integer getId() {
    return id;
}

public User(String name, String email, int age,  String[] topics) {
    this.age = age;
    this.name = name;
    this.email = email;
    this.topics = topics;
}
</code>```

Node.JS

App.js

```<code>const express = require('express');
const bodyParser = require('body-parser');
const routes = require('./routes/api');
const mongoose = require('mongoose');

const app = express();

mongoose.connect('mongodb://localhost/user1',  { useMongoClient: true });
mongoose.Promise = global.Promise;

app.use(bodyParser.json());
app.use('/api', routes);

app.listen(process.env.port || 3000, function(){
    console.log('Using PORT 3000');
});
</code>```

Api.js:

```<code>const express = require('express');
const router = express.Router();
const User = require('../models/user');

router.get('/users', function(req, res, next){
    res.send({type: "GET"});
});

router.post('/users', function(req, res, err){
    User.create(req.body).then(function(user){
        res.send(user);
    });
});

module.exports = router;
</code>```

User.js

```<code>const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const UserSchema = new Schema({
    name: {
        type: String
    },
    email: {
        type: String
    },
    age: {
        type: Number
    },
    topics: {
        type: String
    }
});

const User = mongoose.model('user', UserSchema);

module.exports = User;
</code>```

What I have tried:

I have tried changing the BASE_URL the local ip address of my machine using 'ipconfig' on my terminal. = 'http://192.168.X.X:3000/api/users/'

Use Headers and FormURLEncoded in the UserClient = @Headers("Content-Type: application/json") | @FormUrlEncoded.

Used postman to check responses, which successfully happen.

Checked Robomongo for verification/

Postman:

Get Request

Post Request

Robomongo

答:
BaseURL should be:   baseUrl("http://10.0.2.2:3000/") because your UserClient interface has the path:

```<code>@POST("api/users")
Call<User> createAccount(@Body User user);
</code>```

UPDATE

Your Topic field should be String not String[]

Change this:

```<code>private String [] topics;
</code>```

To this:

```<code>private String topics;
</code>```

Title: Retrofit Null Response onSuccess Method

Body:
I was following this tutorial in YouTube for Retrofit for sending objects in a post request but encounter an error on emulator with a null response onResponse method.

Problem:

Main Activity:

public class MainActivity extends AppCompatActivity {

private EditText mName, mEmail, mAge, mTopics;
private Button mButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mName = findViewById(R.id.editText);
    mEmail = findViewById(R.id.editText2);
    mAge = findViewById(R.id.editText3);
    mTopics = findViewById(R.id.editText4);
    mButton = findViewById(R.id.button);

    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            User user = new User(
                    mName.getText().toString(),
                    mEmail.getText().toString(),
                    Integer.parseInt(mAge.getText().toString()),
                    mTopics.getText().toString().split(",")
            );

            //Added proof its not a NPE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            Log.d("Main", mName.getText().toString() +
                            mName.getText().toString()+ Integer.parseInt(mAge.getText().toString()) +
                            Integer.parseInt(mAge.getText().toString()) +mTopics.getText().toString().split(","));

            sendNetworkRequest(user);
        }
    });

}

private void sendNetworkRequest(User user) {
    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl("http://10.0.2.2:3000/api/users/")
            .addConverterFactory(GsonConverterFactory.create());

    Retrofit retrofit = builder.build();
    UserClient client = retrofit.create(UserClient.class);
    Call<User> call = client.createAccount(user);
    call.enqueue(new Callback<User>() {
        @Override
        public void onResponse(Call<User> call, Response<User> response) {
            Toast.makeText(MainActivity.this, "Success UserID = "+ response.body(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call<User> call, Throwable t) {
            Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_SHORT).show();
        }
    });

}

}

Proof of NOT NPE:

UserClient:

public interface UserClient {

    @POST("api/users")
    Call<User> createAccount(@Body User user);
}

User:

public class User {

private Integer id;
private int age;
private String name, email;
private String [] topics;

public Integer getId() {
    return id;
}

public User(String name, String email, int age,  String[] topics) {
    this.age = age;
    this.name = name;
    this.email = email;
    this.topics = topics;
}

Node.JS

App.js

const express = require('express');
const bodyParser = require('body-parser');
const routes = require('./routes/api');
const mongoose = require('mongoose');

const app = express();

mongoose.connect('mongodb://localhost/user1',  { useMongoClient: true });
mongoose.Promise = global.Promise;

app.use(bodyParser.json());
app.use('/api', routes);

app.listen(process.env.port || 3000, function(){
    console.log('Using PORT 3000');
});

Api.js:

const express = require('express');
const router = express.Router();
const User = require('../models/user');

router.get('/users', function(req, res, next){
    res.send({type: "GET"});
});

router.post('/users', function(req, res, err){
    User.create(req.body).then(function(user){
        res.send(user);
    });
});

module.exports = router;

User.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const UserSchema = new Schema({
    name: {
        type: String
    },
    email: {
        type: String
    },
    age: {
        type: Number
    },
    topics: {
        type: String
    }
});

const User = mongoose.model('user', UserSchema);

module.exports = User;

What I have tried:

I have tried changing the BASE_URL the local ip address of my machine using 'ipconfig' on my terminal. = 'http://192.168.X.X:3000/api/users/'

Use Headers and FormURLEncoded in the UserClient = @Headers("Content-Type: application/json") | @FormUrlEncoded.

Used postman to check responses, which successfully happen.

Checked Robomongo for verification/

Postman:

Get Request

Post Request

Robomongo

Body:
BaseURL should be:   baseUrl("http://10.0.2.2:3000/") because your UserClient interface has the path:

@POST("api/users")
Call<User> createAccount(@Body User user);

UPDATE

Your Topic field should be String not String[]

Change this:

private String [] topics;

To this:

private String topics;


问:
Duplicate a line of text and add right prefix in notepad++?
I have to duplicate each line but I have to mod second one also.
Ex:

My input data is:

C:\Dir\Dir2\Dir3

Final should look like this:

Source:C:\Dir\Dir2\Dir3 Destination:http://mymachine/se/docs/Dir1/Dir2/Dir3

I was managed to make:

Source:C:\Dir\Dir2\Dir3 Destination:C:\Dir\Dir2\Dir3

by

find "^.*$" replace with "Source:$0 Destination:$0"

I have to replace "C:\" with "http://mymachine/se/docs/" and "\" with "/".

How to do this?

答:
Code

See regex in use here

```<code>[^\\]+\\(.*)
</code>```

Replacement: Source:$0 Destination:http://mymachine/se/docs/$1

To fix the backslash issue, you'll need to run a second regex replace after the one above. See below:

```<code>\bDestination:[^\\\v]*\K\\
</code>```

Replacement: /

Results

Input

```<code>C:\Dir1
</code>```

Output

```<code>Source:C:\Dir1 Destination:http://mymachine/se/docs/Dir1
</code>```

Explanation

First pattern

[^\\]+ Match any character except backslash \ one or more times

\\ Match a literal backslash character \

(.*) Capture any character any number of times (greedy) into capture group 1 (everything after the first backslash in the string)

Second pattern

\b Assert position as a word boundary

Destination: Match this literally

[^\\\v]* Match any number of any character except backslash \ and vertical whitespace characters

\K Reset the pattern's match. Any previously consumed characters are no longer included in the final match

\\ Match a literal backslash

Body:
Code

See regex in use here

[^\\]+\\(.*)

Replacement: Source:$0 Destination:http://mymachine/se/docs/$1

To fix the backslash issue, you'll need to run a second regex replace after the one above. See below:

\bDestination:[^\\\v]*\K\\

Replacement: /

Results

Input

C:\Dir1

Output

Source:C:\Dir1 Destination:http://mymachine/se/docs/Dir1

Explanation

First pattern

[^\\]+ Match any character except backslash \ one or more times

\\ Match a literal backslash character \

(.*) Capture any character any number of times (greedy) into capture group 1 (everything after the first backslash in the string)

Second pattern

\b Assert position as a word boundary

Destination: Match this literally

[^\\\v]* Match any number of any character except backslash \ and vertical whitespace characters

\K Reset the pattern's match. Any previously consumed characters are no longer included in the final match

\\ Match a literal backslash


问:
How to use Matches() and Pattern correctley
I'm doing a assignment for school and need to build a Student class. The constructor will receive a String,"Student name". I need to verify that the given String from the user includes only letters from a-z, A-Z, and numbers 0-9.

From looking online this is what I found

```<code>boolean ans = true;
String str = ("Maor Rocky");
Pattern pattern = Pattern.compile("[A-Za-z0-9]\\w+");
Matcher matcher = pattern.matcher(str);
System.out.println(matcher.group());

if (!str.matches("[a-zA-Z0-9//s+]"))
    ans = false;

System.out.println(ans);
</code>```

I know it's missing something but I didn't grasp the idea of pattern and matcher yet.

答:
If you have variable student of type String that will hold student name, simple check goes like this (no need to use Pattern or Matcher classes here):

```<code>String student = scanner.next();
if (student.matches("[\\w]*"))
    //do something for valid username
else
    //do something for invalid username
</code>```

Or do it the same way every beginner would do it:

```<code>    String student = scanner.next();

    for (int i = 0; i < student.length(); i++) {
        if (!Character.isLetterOrDigit(student.charAt(i)))
            //do something for invalid username;
    }
</code>```

Body:
I'm doing a assignment for school and need to build a Student class. The constructor will receive a String,"Student name". I need to verify that the given String from the user includes only letters from a-z, A-Z, and numbers 0-9.

From looking online this is what I found

boolean ans = true;
String str = ("Maor Rocky");
Pattern pattern = Pattern.compile("[A-Za-z0-9]\\w+");
Matcher matcher = pattern.matcher(str);
System.out.println(matcher.group());

if (!str.matches("[a-zA-Z0-9//s+]"))
    ans = false;

System.out.println(ans);

I know it's missing something but I didn't grasp the idea of pattern and matcher yet.

Body:
If you have variable student of type String that will hold student name, simple check goes like this (no need to use Pattern or Matcher classes here):

String student = scanner.next();
if (student.matches("[\\w]*"))
    //do something for valid username
else
    //do something for invalid username

Or do it the same way every beginner would do it:

    String student = scanner.next();

    for (int i = 0; i < student.length(); i++) {
        if (!Character.isLetterOrDigit(student.charAt(i)))
            //do something for invalid username;
    }


问:
Ruby on Rails Bundler issues LoadError
I believe I am having some PATH issues for my gems.

I am using rvm (version 1.29.3) with ruby (version 2.4.1) and rails (version 5.1.4)

I tried to run rails new myapp to which I get the following LoadErrors:

```<code>remove  config/initializers/new_framework_defaults_5_1.rb
run  bundle install
   /Users/fabienbessez/.rvm/rubies/ruby-2.4.1/bin/ruby: No such file or directory
-- /Users/fabienbessez/.rvm/rubies/ruby-
   2.4.1/lib/ruby/gems/2.4.0/gems/bundler-1.16.0/exe/bundle (LoadError)
run  bundle exec spring binstub --all
   /Users/fabienbessez/.rvm/rubies/ruby-2.4.1/bin/ruby: No such file or directory
   -- /Users/fabienbessez/.rvm/rubies/ruby
   2.4.1/lib/ruby/gems/2.4.0/gems/bundler-1.16.0/exe/bundle (LoadError)
</code>```

I get the same error when I try to then run bundle install

I checked the contents of ~/.rvm/rubies/ruby-2.4.1/lib/ruby/gems/2.4.0/gems to which I found that bundler-1.15.4 but not bundler-1.16.0. I assume that that is the issue. But I can't figure out how to update those gems. gem install bundler says it has installed bundler 1.16.0 but this is not being updated.

Any ideas??

Thanks!

答: Have you tried to uninstall all old versions of bundler with gem uninstall bundler?

Title: Ruby on Rails Bundler issues LoadError

Body:
I believe I am having some PATH issues for my gems.

I am using rvm (version 1.29.3) with ruby (version 2.4.1) and rails (version 5.1.4)

I tried to run rails new myapp to which I get the following LoadErrors:

remove  config/initializers/new_framework_defaults_5_1.rb
run  bundle install
   /Users/fabienbessez/.rvm/rubies/ruby-2.4.1/bin/ruby: No such file or directory
-- /Users/fabienbessez/.rvm/rubies/ruby-
   2.4.1/lib/ruby/gems/2.4.0/gems/bundler-1.16.0/exe/bundle (LoadError)
run  bundle exec spring binstub --all
   /Users/fabienbessez/.rvm/rubies/ruby-2.4.1/bin/ruby: No such file or directory
   -- /Users/fabienbessez/.rvm/rubies/ruby
   2.4.1/lib/ruby/gems/2.4.0/gems/bundler-1.16.0/exe/bundle (LoadError)

I get the same error when I try to then run bundle install

I checked the contents of ~/.rvm/rubies/ruby-2.4.1/lib/ruby/gems/2.4.0/gems to which I found that bundler-1.15.4 but not bundler-1.16.0. I assume that that is the issue. But I can't figure out how to update those gems. gem install bundler says it has installed bundler 1.16.0 but this is not being updated.

Any ideas??

Thanks!


问:
What is the best way to find an element in a regex expression in R?
I have a list of strings in R like so:

```<code>"A(123:456)"
"B(23456:345)"
"C(3451:45600)"
</code>```

I want to parse out the first number and the second number in the parenthesis for all these items:

```<code>first   second
123     456
23456   345
3451    45600
</code>```

What is the best way to do this in a vectorized manner? I've thought of using substrings and index of, but then heard of regexes, but am wondering of the most "R" way to do this.

答:
You could use regexpr to match the pattern,
and regmatches to extract the matched patterns.

You could define the pattern to match (to be extracted) as \\d+, which means 1 or more digits.
This will match the first 3 digits that occur in each pattern.
And extract the matches with regmatches, like this:

```<code>v <- c("A(123:456)", "B(234:345)", "C(345:456)")
regmatches(v, regexpr('\\d+', v))
</code>```

The above will give a vector of values:

```<code>[1] "123" "234" "345"
</code>```

To get a data.frame with two columns of the numeric values,
you can use gregmatches instead of regmatches.
That returns a list of lists,
from which you can extract the values into vectors:

```<code>m <- regmatches(v, gregexpr('\\d+', v))
first <- sapply(m, function(x) x[[1]])
second <- sapply(m, function(x) x[[2]])
</code>```

Or as @RuiBarradas pointed out in a comment, you can simplify the sapply calls like this:

```<code>first <- sapply(m, '[[', 1)
second <- sapply(m, '[[', 2)
</code>```

Body:
I have a list of strings in R like so:

"A(123:456)"
"B(23456:345)"
"C(3451:45600)"

I want to parse out the first number and the second number in the parenthesis for all these items:

first   second
123     456
23456   345
3451    45600

What is the best way to do this in a vectorized manner? I've thought of using substrings and index of, but then heard of regexes, but am wondering of the most "R" way to do this.

Body:
You could use regexpr to match the pattern,
and regmatches to extract the matched patterns.

You could define the pattern to match (to be extracted) as \\d+, which means 1 or more digits.
This will match the first 3 digits that occur in each pattern.
And extract the matches with regmatches, like this:

v <- c("A(123:456)", "B(234:345)", "C(345:456)")
regmatches(v, regexpr('\\d+', v))

The above will give a vector of values:

[1] "123" "234" "345"

To get a data.frame with two columns of the numeric values,
you can use gregmatches instead of regmatches.
That returns a list of lists,
from which you can extract the values into vectors:

m <- regmatches(v, gregexpr('\\d+', v))
first <- sapply(m, function(x) x[[1]])
second <- sapply(m, function(x) x[[2]])

Or as @RuiBarradas pointed out in a comment, you can simplify the sapply calls like this:

first <- sapply(m, '[[', 1)
second <- sapply(m, '[[', 2)


答:
Here's one way with regex:</p>

```<code># Your data
df <- data.frame(obs=c("A(123:456)","B(234:345)","C(345:456)"))
# extraction:
df$first <- gsub(df$obs,pattern="^.*\\((.*)\\:.*$",replacement="\\1")
</code>```

Title: What is the best way to find an element in a regex expression in R?

Body:
Here's one way with regex:

# Your data
df <- data.frame(obs=c("A(123:456)","B(234:345)","C(345:456)"))
# extraction:
df$first <- gsub(df$obs,pattern="^.*\\((.*)\\:.*$",replacement="\\1")


答:
Here are two ways.

The first is the simplest and if your strings always have exactly two characters followed by the three digit number of interest, it will work.

The second uses regular expressions.

```<code>substr(x, 3, 5)
[1] "123" "234" "345"

sub("^.*\\(([[:digit:]]*).*", "\\1", x)
[1] "123" "234" "345"
</code>```

Then, if you want numeric results, use as.integer or as.numeric.

DATA.

```<code>x <- scan(what = character(), text = '
"A(123:456)"
"B(234:345)"
"C(345:456)"')
</code>```

EDIT.

After the question's edit by the OP, the solutions above are no longer valid. The following one is. Note that the regex has changed and that I now also use strsplit.

```<code>res <- do.call(rbind, strsplit(sub("^.*\\((.*)\\).*$", "\\1", x), ":"))
res <- as.data.frame(res, stringsAsFactors = FALSE)
names(res) <- c("first", "second")
res
#  first second
#1   123    456
#2   234    345
#3   345    456
</code>```

The columns of this dataframe are both of class character. In order to have numbers, coerce them with

```<code>res[] <- lapply(res, as.integer)
</code>```

Body:
Here are two ways.

The first is the simplest and if your strings always have exactly two characters followed by the three digit number of interest, it will work.

The second uses regular expressions.

substr(x, 3, 5)
[1] "123" "234" "345"

sub("^.*\\(([[:digit:]]*).*", "\\1", x)
[1] "123" "234" "345"

Then, if you want numeric results, use as.integer or as.numeric.

DATA.

x <- scan(what = character(), text = '
"A(123:456)"
"B(234:345)"
"C(345:456)"')

EDIT.

After the question's edit by the OP, the solutions above are no longer valid. The following one is. Note that the regex has changed and that I now also use strsplit.

res <- do.call(rbind, strsplit(sub("^.*\\((.*)\\).*$", "\\1", x), ":"))
res <- as.data.frame(res, stringsAsFactors = FALSE)
names(res) <- c("first", "second")
res
#  first second
#1   123    456
#2   234    345
#3   345    456

The columns of this dataframe are both of class character. In order to have numbers, coerce them with

res[] <- lapply(res, as.integer)


问:
Converting an array to object in JavaScript
I have a dynamically created array like this on the client side.

```<code>value = [
  [-88.17179185999998, 41.78264698400005],
  [-88.17193080699997, 41.782605419000056]
]
</code>```

and I need to store it in an object format in this order with adding new "spatialReference": {"wkid": 4326 }

```<code>   var params = [
     {
       "x": -88.17179185999998,
       "y": 41.78264698400005,
       "spatialReference": {"wkid": 4326 }
     },
     {
       "x": -88.17193080699997,
       "y": 41.782605419000056,
       "spatialReference": {"wkid": 4326 }
     }
   ];
</code>```

How can I do this?

答:
You can simply use .map():

const value = [
  [-88.17179185999998, 41.78264698400005],
  [-88.17193080699997, 41.782605419000056]
];

const objs = value.map(([x, y]) => ({ x, y, spatialReference: {wkid: 4326 } }));

console.log(objs);```

.map() just goes through each element, and runs some function against it, and uses the results of that to make a new array. Very easy for converting elements in an array from a to b.

Body:
I have a dynamically created array like this on the client side.

value = [
  [-88.17179185999998, 41.78264698400005],
  [-88.17193080699997, 41.782605419000056]
]

and I need to store it in an object format in this order with adding new "spatialReference": {"wkid": 4326 }

   var params = [
     {
       "x": -88.17179185999998,
       "y": 41.78264698400005,
       "spatialReference": {"wkid": 4326 }
     },
     {
       "x": -88.17193080699997,
       "y": 41.782605419000056,
       "spatialReference": {"wkid": 4326 }
     }
   ];

How can I do this?

Body:
You can simply use .map():

const value = [
  [-88.17179185999998, 41.78264698400005],
  [-88.17193080699997, 41.782605419000056]
];

const objs = value.map(([x, y]) => ({ x, y, spatialReference: {wkid: 4326 } }));

console.log(objs);

.map() just goes through each element, and runs some function against it, and uses the results of that to make a new array. Very easy for converting elements in an array from a to b.


问:
Passing a string literal as a type argument to a class template
I want to declare a class template in which one of the template parameters takes a string literal, e.g. my_class<"string">.

Can anyone give me some compilable code which declares a simple class template as described?

Note: The previous wording of this question was rather ambiguous as to what the asker was actually trying to accomplish, and should probably have been closed as insufficiently clear. However, since then this question became multiple times referred-to as the canonical ‘string literal type parameter’ question. As such, it has been re-worded to agree with that premise.

答:
You can have a const char* non-type template parameter, and pass it a const char[] variable with static linkage, which is not all that far from passing a string literal directly.

```<code>#include <iostream>

template<const char *str>
struct cts {
    void p() {std::cout << str;}
};

static const char teststr[] = "Hello world!";
int main() {
    cts<teststr> o;
    o.p();
}
</code>```

http://coliru.stacked-crooked.com/a/64cd254136dd0272

LastEditorDisplayName: anon

Body:
You can have a const char* non-type template parameter, and pass it a const char[] variable with static linkage, which is not all that far from passing a string literal directly.

#include <iostream>

template<const char *str>
struct cts {
    void p() {std::cout << str;}
};

static const char teststr[] = "Hello world!";
int main() {
    cts<teststr> o;
    o.p();
}

http://coliru.stacked-crooked.com/a/64cd254136dd0272


问:
HTTPS equivalent of Django's HttpResponse
For some reason I am in need of a views.py that returns only  some text. Normally, i'd use HttpResponse("text") for this. However, In this case I require the text to be send over https, to counter the inevitable mixed content warning.

What is the simplest way of sending pure text via django(1.7.11) over https?

答:
Django in the relevant docs of httprequest.build_absolute_uri reads:

Mixing HTTP and HTTPS on the same site is discouraged, therefore
  build_absolute_uri() will always generate an absolute URI with the
  same scheme the current request has. If you need to redirect users to
  HTTPS, it’s best to let your Web server redirect all HTTP traffic to
  HTTPS.

The docs make clear that

the method of communication is entirely the responsibility of the server

as Daniel Roseman commented.

My prefered choice is to force https throughout a site, however it is possible to do it only for a certain page.

The above can be achieved by either:

Upgrading to a secure and supported release of Django where the use of SECURE_SSL_REDIRECT and SecurityMiddleware will redirect all traffic to SSL

Asking your host provider an advice on how could this be implemented in their servers

Using the apache config files.

Using .htaccess to redirect a single page.

There are also other -off the road- hackish solutions like a snippet which can be used with a decorator in urls.py to force https, or a custom middleware that redirects certain urls to https.


问:
How do I formally document a C# Attribute in UML?
What is the proper way to document a C# Attribute on a class in a UML class diagram?</p>

答:
I don't know if this is "standard", except that it uses a standard feature from UML:

Sparx Enterprise Architect, when reverse-engineering, for instance, a unit test class, uses tagged values for the attributes. A tagged value "Attribute" on the class, has the name of the attribute as a value, for instance, "[TestClass]". Similarly, "Attribute = [TestMethod]" is placed on the methods. An example would be:

```<code>[TestClass]
public class MyTests
{
    [TestMethod]
    public void DoSomeTest()
    {
    }
}
</code>```

In this example, [TestClass] and [TestMethod] are .NET attributes (not UML attributes). They are short for [TestClassAttribute] and [TestMethodAttribute]. Both are classes deriving from the System.Attribute class.

An attribute simply adds metadata to the assembly. By itself, it has no runtime behavior.

Body:
I don't know if this is "standard", except that it uses a standard feature from UML:

Sparx Enterprise Architect, when reverse-engineering, for instance, a unit test class, uses tagged values for the attributes. A tagged value "Attribute" on the class, has the name of the attribute as a value, for instance, "[TestClass]". Similarly, "Attribute = [TestMethod]" is placed on the methods. An example would be:

[TestClass]
public class MyTests
{
    [TestMethod]
    public void DoSomeTest()
    {
    }
}

In this example, [TestClass] and [TestMethod] are .NET attributes (not UML attributes). They are short for [TestClassAttribute] and [TestMethodAttribute]. Both are classes deriving from the System.Attribute class.

An attribute simply adds metadata to the assembly. By itself, it has no runtime behavior.


问:
Finding equal variables in non solvable multi-variables linear equations
I am trying to find an algorithm to solve the current problem. I have multiple unknown variables (F1,F2,F3, ... Fx) and (R1,R2,R3 ... Rx) and multiple equations like this:

```<code>F1 + R1 = a
F1 + R2 = a
F2 + R1 = b
F3 + R2 = b
F2 + R3 = c
F3 + R4 = c
</code>```

where a, b and c are known numbers. I am trying to find all equal variables in such equations. For example in the above equation I could see that F2 and F3 are equal and R3 and R4 are equal.

First equations tells us that R1 and R2 are equal, and second tells us that F2 and F3 are equal, while the third tells us that R3 and R4 are equal.

For a more complex scenario, is there any known algorithm that can find all equal (F and R) variables????

(I will edit the question if it is not clear enough)

Thanks

答: For the general situation, row echelon is probably the way to go. If every equation has only two variables, then you can consider each variable to be in a partition. Every time two variables appear in an equation together, their partitions are joined. So to begin with each variable is in its own partition. After the first equation, there a partition that contains F1 and R1. After the second equation, that partition is replaced by a partition that contain F1, R1 and R2. You should have the variables in some sort of order, and when two partitions are joined, put all the variables except the first one in terms of the first one (it doesn't really matter how you order the variables, you just need some way of deciding which is the "first"). So for instance, after the first equation, you have R1 = a-F1. After the second equation, you have R1 = a-F1 and R2 = a-F1. Each variable can be represented by two numbers: some number times the first variable in their partition, plus a constant. Then at the end, you go through each partition, and look for variables that have the same two numbers representing them.

Body:
I am trying to find an algorithm to solve the current problem. I have multiple unknown variables (F1,F2,F3, ... Fx) and (R1,R2,R3 ... Rx) and multiple equations like this:

F1 + R1 = a
F1 + R2 = a
F2 + R1 = b
F3 + R2 = b
F2 + R3 = c
F3 + R4 = c

where a, b and c are known numbers. I am trying to find all equal variables in such equations. For example in the above equation I could see that F2 and F3 are equal and R3 and R4 are equal.

First equations tells us that R1 and R2 are equal, and second tells us that F2 and F3 are equal, while the third tells us that R3 and R4 are equal.

For a more complex scenario, is there any known algorithm that can find all equal (F and R) variables????

(I will edit the question if it is not clear enough)

Thanks


问:
Angular 4 routerLink loading wrong component
this is my app-routing.module.ts :

```<code>const appRoutes: Routes = [
  {path: '', component: MainComponent, children:[
    {path: '', component: AppComponent, children:[
      {path: 'home', component: HomeComponent},
      {path: 'register', component: RegisterComponent},
      {path: 'login', component: LoginComponent},
    ]},
    {path: 'patient', component: PatientComponent, children: [
        { path: 'patient/profile', component: PatientProfileComponent, outlet: 'patient-outl'},
        { path: 'patient/changepass', component: ChangePasswordComponent, outlet: 'patient-outl'}
        ],
        canActivate: [RoleGuard],
        data: { roles: ['PATIENT'] }
    },
    {path: 'admin', component: AdminComponent, canActivate: [RoleGuard], data: { roles: ['ADMIN'] }},
    {path: 'dentist', component: DentistComponent, canActivate: [RoleGuard], data: { roles: ['DENTIST'] }},
    {path: '**', component: HomeComponent}
  ]}
];
</code>```

I navigate from  click in patient component to changepass like so:

```<code><a routerLink="/patient/changepass" routerLinkActive="active">Change Password</a>
</code>```

but what actually opens up is HomeComponent and not ChangePasswordComponent. The url is correct - /patient/changepass, but the loaded component is wrong.. Any idea why so?

EDIT:

I also tried to navigate like so:

```<code><a (click)="editProfile()">Edit Profile</a>
</code>```

and:

```<code>   editProfile(){
     this.router.navigate(['/patient/profile']);
   }
</code>```

but with the same result - navigation to home component..

答:
Your child routes are wrong.
They should be relative to their parent route. Even so the named router outlet not works with non-empty paths. It seems that your issue is related with this one.

I prepared a working example here

I hope this will help.

Body:
this is my app-routing.module.ts :

const appRoutes: Routes = [
  {path: '', component: MainComponent, children:[
    {path: '', component: AppComponent, children:[
      {path: 'home', component: HomeComponent},
      {path: 'register', component: RegisterComponent},
      {path: 'login', component: LoginComponent},
    ]},
    {path: 'patient', component: PatientComponent, children: [
        { path: 'patient/profile', component: PatientProfileComponent, outlet: 'patient-outl'},
        { path: 'patient/changepass', component: ChangePasswordComponent, outlet: 'patient-outl'}
        ],
        canActivate: [RoleGuard],
        data: { roles: ['PATIENT'] }
    },
    {path: 'admin', component: AdminComponent, canActivate: [RoleGuard], data: { roles: ['ADMIN'] }},
    {path: 'dentist', component: DentistComponent, canActivate: [RoleGuard], data: { roles: ['DENTIST'] }},
    {path: '**', component: HomeComponent}
  ]}
];

I navigate from  click in patient component to changepass like so:

Change Password

but what actually opens up is HomeComponent and not ChangePasswordComponent. The url is correct - /patient/changepass, but the loaded component is wrong.. Any idea why so?

EDIT:

I also tried to navigate like so:

Edit Profile

and:

   editProfile(){
     this.router.navigate(['/patient/profile']);
   }

but with the same result - navigation to home component..


问:
The current identity has not been registered:
I have successfully issued, imported and pinged a card on Hyperledger composer 0.16.0. However, when I try to execute transactions with the created identity, I get the following errors

"Error trying invoke business network. Error: No valid responses from any peers.\nResponse from attempted peer comms was an error: Error: chaincode error (status: 500, message: Error: The current identity has not been registered: roger)\n"

I am not sure whether I should now 'bind' the identity to a participant as demonstrated here. I did try this but there is a required certificate file --certificateFile which I am not sure where to find. Preliminary checks on .composer folder in my home directory indicate that I have a xxxx-pub and xxxx-priv file on the card details in client-data subdirectory. Would this xxxx-pub act as the required certificate?

Anyway, that was just my attempt at finding the solution but I would really appreciate if anyone could help me resolve the The current identity has not been registered: roger error.

答: Ok. I tried with the xxxx-pub file and it worked. So use -e /path/to/file/xxxx-pub in the composer identity bind command.


问:
Get only JSON string as output without any html
I am developing a webiste in ASP.NET. On one of the pages page named menu.aspx, with the help of a certain login, I am getting the output in this format

foo({"1":"Jeff","2":"Mik","5":"Tom"});

I am using this code to get the output on the JSON form.

```<code>outputText += Convert.ToString(k.GetValue(0));
            for (Int32 i = 1; i < k.Length; i++)
            {
                outputText += "," + Convert.ToString(k.GetValue(i));
            }
            //
            outputText += "}" +");";
            Response.Clear();
            Response.Write(outputText);
            Response.ContentType = "application/json";
</code>```

However, I must get the output only in simple JSON on the page without any HTML.

For eg: Here's the screenshot showing the source of the output page. http://i.stack.imgur.com/faUtY.jpg

Notice that it has only the JSON string as the output.

And here's the screenshot showing the output page source (with HTML). http://i.stack.imgur.com/gIxzR.jpg  .This HTML is what I have to remove. How can do I do this?
The full code of menu.aspx.cs is putup here. http://pastebin.com/M14Srrgf

答: I would recommend switching to a web service, but for this try adding a response.end call after you write the string.</p>

Body:
I am developing a webiste in ASP.NET. On one of the pages page named menu.aspx, with the help of a certain login, I am getting the output in this format

foo({"1":"Jeff","2":"Mik","5":"Tom"});

I am using this code to get the output on the JSON form.

outputText += Convert.ToString(k.GetValue(0));
            for (Int32 i = 1; i < k.Length; i++)
            {
                outputText += "," + Convert.ToString(k.GetValue(i));
            }
            //
            outputText += "}" +");";
            Response.Clear();
            Response.Write(outputText);
            Response.ContentType = "application/json";

However, I must get the output only in simple JSON on the page without any HTML.

For eg: Here's the screenshot showing the source of the output page. http://i.stack.imgur.com/faUtY.jpg

Notice that it has only the JSON string as the output.

And here's the screenshot showing the output page source (with HTML). http://i.stack.imgur.com/gIxzR.jpg  .This HTML is what I have to remove. How can do I do this?
The full code of menu.aspx.cs is putup here. http://pastebin.com/M14Srrgf


问:
feed placeholder traceback in tensorflow: 'tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor
Why does the following piece of code throw an exception? I feed the placeholder via feed_dict= in the for loop, but when I print the values of x or y_tensor, I get the following error message:

'tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'input' with dtype float and shape [?,5]'.

Surprisingly, I don't get the error for a certain tensor when I print another one. For instance, when I only print y_tensor, I don't get the error message for the line where I declared x, and the opposite.  I use the range of 10 only for testing the issue. The main problem is that the optimization can't work under this condition. How do I fix this?

Here The Code:

```<code>x = tf.placeholder(tf.float32, [None, 5], name='input')

W = tf.Variable(tf.zeros([5,1]))
b = tf.Variable(tf.zeros([1]))

y = tf.nn.softmax(tf.matmul(x, W) + b)

y_tensor = tf.placeholder(tf.float32, [None, 1], name='output')
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_tensor * tf.log(y), reduction_indices=[1]))

optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

session = tf.Session()
init = tf.global_variables_initializer()
session.run(init)

for i in range(10):
  batch_xs = [dataA[i], dataB[i], dataC[i], dataD[i],
              dataE[i]]]
  batch_ys = [[dataG[i]]]
  session.run(optimizer ,feed_dict={x: batch_xs, y_tensor: batch_ys})

print(session.run(y))
</code>```

答:
Because y depends on x. Therefore you need to change the last line to:

```<code>print(session.run(y, ,feed_dict={x: xs_test}))
</code>```

where xs_test is your test data.

Body:
Why does the following piece of code throw an exception? I feed the placeholder via feed_dict= in the for loop, but when I print the values of x or y_tensor, I get the following error message:

'tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'input' with dtype float and shape [?,5]'.

Surprisingly, I don't get the error for a certain tensor when I print another one. For instance, when I only print y_tensor, I don't get the error message for the line where I declared x, and the opposite.  I use the range of 10 only for testing the issue. The main problem is that the optimization can't work under this condition. How do I fix this?

Here The Code:

x = tf.placeholder(tf.float32, [None, 5], name='input')

W = tf.Variable(tf.zeros([5,1]))
b = tf.Variable(tf.zeros([1]))

y = tf.nn.softmax(tf.matmul(x, W) + b)

y_tensor = tf.placeholder(tf.float32, [None, 1], name='output')
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_tensor * tf.log(y), reduction_indices=[1]))

optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

session = tf.Session()
init = tf.global_variables_initializer()
session.run(init)

for i in range(10):
  batch_xs = [dataA[i], dataB[i], dataC[i], dataD[i],
              dataE[i]]]
  batch_ys = [[dataG[i]]]
  session.run(optimizer ,feed_dict={x: batch_xs, y_tensor: batch_ys})

print(session.run(y))

Body:
Because y depends on x. Therefore you need to change the last line to:

print(session.run(y, ,feed_dict={x: xs_test}))

where xs_test is your test data.


问:
Updating the UISegmentControl programmatically does not update the font color of the unselected segment
I'm using a segmented control as sub tabs for a tab bar controller. I have a button on the main tab that's supposed to transition to the second tab (the one with the sub tabs) and programmatically switch the UISegmentedControl to the first tab (0 index).

Of course, tapping on the segmented control works fine. But, when I try to change the tab programmatically using selectedSegmentIndex, the tab that get's deselected does not update it's font color, which makes the label seem to disappear.

tab bar image

Every post I've read about how to change tabs programmatically indicates that I'm doing it the right way. Can anyone tell me what I'm doing wrong? Thank you for your help!

Here is the code:

```<code>class AdvertisingViewController: BaseViewController, TabbedController, ClientSelectorController {

  var clientSelectorView: ClientSelector?
  var tabControl: UISegmentedControl!
  var tabView: UIView!
  var nextTabIndex: Int? = nil
  var activeTab: AdvertisingTabContent? = nil
  var tabs: [AdvertisingTabContent]!
  let margin: CGFloat = 20

  override func viewDidLoad() {
    super.viewDidLoad()

    // Initialize the tab view.
    tabView = UIView()
    view.addSubview(tabView!)

    // Initialize the tab controls.
    tabControl = UISegmentedControl()
    tabControl.insertSegment(withTitle: "Calendar", at: 0, animated: false)
    tabControl.insertSegment(withTitle: "TV", at: 1, animated: false)
    tabControl.insertSegment(withTitle: "Radio", at: 2, animated: false)
    tabControl.insertSegment(withTitle: "Search", at: 3, animated: false)
    tabControl.insertSegment(withTitle: "Display", at: 4, animated: false)
    tabControl.selectedSegmentIndex = 0
    tabControl.addTarget(self, action: #selector(selectedTab(sender:)), for: .valueChanged)
    view.addSubview(tabControl!)

    // Tab control styles.
    let font = UIFont.systemFont(ofSize: 12)
    tabControl.setTitleTextAttributes([
      NSAttributedStringKey.font: font,
      NSAttributedStringKey.foregroundColor: Color.lightGrey
    ], for: .normal)
    tabControl.removeBorders()

    // Intialize the tabs.
    nextTabIndex = nil
    tabs = [
      CampaignsTab(view: tabView),
      TVTab(view: tabView),
      RadioTab(view: tabView),
      PaidSearchTab(view: tabView),
      DisplayTab(view: tabView),
    ]

    // Bind clientSelector button to clientSelectButtonPressed method.
    initializeClientSelector()

    // Set the background color.
    tabView.backgroundColor = Color.backgroundColor
  }

  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    // Update client selector title.
    layoutClientSelector()

    // Update tab view & segmented control
    let controlHeight: CGFloat = 35
    tabControl.frame = CGRect(x: margin, y: clientSelectorView!.frame.height, width: view.frame.width - (margin * 2), height: controlHeight)

    // Update the tab view.
    tabView.frame = CGRect(x: 0, y: clientSelectorView!.frame.height + controlHeight + margin, width: view.frame.width, height: view.frame.height - clientSelectorView!.frame.height - controlHeight - margin)

    // Build tab.
    buildTab()
  }

  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    // Update the tabControl.
    if let next = nextTabIndex {
      if next != tabControl.selectedSegmentIndex {
        tabControl.selectedSegmentIndex = next
      }
      nextTabIndex = nil
    }
  }

  func clientSelectorClicked(selectorModal: UIViewController) {
    present(selectorModal, animated: true, completion: nil)
  }

  // MARK: - Tabs Control

  /**
   The user selected a different tab.
   */
  @objc func selectedTab(sender: UIButton) {
    buildTab()
  }

  /**
   A tab was selected from another part of the app.
   (This is called before viewWillAppear from another tab)
   */
  func switchToTab(atIndex index: Int) {
    nextTabIndex = index
  }

  func buildTab() {

    // Clean up the old tab.
    activeTab?.cleanUp()
    activeTab = nil

    // Check next index.
    var index = tabControl.selectedSegmentIndex
    if let next = nextTabIndex {
      index = next
    }

    // Add/Build the new tab.
    if index >= 0 && tabs.count > index {
      activeTab = tabs[index]
      activeTab?.buildViews()
    }
  }
}
</code>```

Update:

Spent a couple more hours looking for a solution this morning. I also tried hacking it by finding the label in the subviews of the segmented control, and manually changing the font color. I could change the text of the label, but not the font color. Something is overriding it.

Is there some other way to programmatically change the selected index? Do I need to submit a ticket to apple? Is nobody else having this problem? Thanks in advance for any help you can provide.

答:
After much struggling, I finally found an answer. I'm removing the borders using the method from the following post:

Swift: How to remove border from segmented control

```<code>extension UISegmentedControl {
  func applyAppStyles() {
    setBackgroundImage(imageWithColor(color: Color.contentBackgroundColor), for: .normal, barMetrics: .default)
    setBackgroundImage(imageWithColor(color: Color.orange), for: .selected, barMetrics: .default)
    setDividerImage(imageWithColor(color: UIColor.clear), forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
  }

  // create a 1x1 image with this color
  private func imageWithColor(color: UIColor) -> UIImage {
    let rect = CGRect(x: 0.0, y: 0.0, width:  1.0, height: 1.0)
    UIGraphicsBeginImageContext(rect.size)
    let context = UIGraphicsGetCurrentContext()
    context!.setFillColor(color.cgColor);
    context!.fill(rect);
    let image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image!
  }
}
</code>```

My first call to setBackgroundImage is causing the issue; I'm not sure why. But the following code fixes it:

```<code>tabControl.setTitleTextAttributes([
  NSAttributedStringKey.foregroundColor: Color.darkGreyBlue
], for: .selected)
</code>```

Body:
I'm using a segmented control as sub tabs for a tab bar controller. I have a button on the main tab that's supposed to transition to the second tab (the one with the sub tabs) and programmatically switch the UISegmentedControl to the first tab (0 index).

Of course, tapping on the segmented control works fine. But, when I try to change the tab programmatically using selectedSegmentIndex, the tab that get's deselected does not update it's font color, which makes the label seem to disappear.

tab bar image

Every post I've read about how to change tabs programmatically indicates that I'm doing it the right way. Can anyone tell me what I'm doing wrong? Thank you for your help!

Here is the code:

class AdvertisingViewController: BaseViewController, TabbedController, ClientSelectorController {

  var clientSelectorView: ClientSelector?
  var tabControl: UISegmentedControl!
  var tabView: UIView!
  var nextTabIndex: Int? = nil
  var activeTab: AdvertisingTabContent? = nil
  var tabs: [AdvertisingTabContent]!
  let margin: CGFloat = 20

  override func viewDidLoad() {
    super.viewDidLoad()

    // Initialize the tab view.
    tabView = UIView()
    view.addSubview(tabView!)

    // Initialize the tab controls.
    tabControl = UISegmentedControl()
    tabControl.insertSegment(withTitle: "Calendar", at: 0, animated: false)
    tabControl.insertSegment(withTitle: "TV", at: 1, animated: false)
    tabControl.insertSegment(withTitle: "Radio", at: 2, animated: false)
    tabControl.insertSegment(withTitle: "Search", at: 3, animated: false)
    tabControl.insertSegment(withTitle: "Display", at: 4, animated: false)
    tabControl.selectedSegmentIndex = 0
    tabControl.addTarget(self, action: #selector(selectedTab(sender:)), for: .valueChanged)
    view.addSubview(tabControl!)

    // Tab control styles.
    let font = UIFont.systemFont(ofSize: 12)
    tabControl.setTitleTextAttributes([
      NSAttributedStringKey.font: font,
      NSAttributedStringKey.foregroundColor: Color.lightGrey
    ], for: .normal)
    tabControl.removeBorders()

    // Intialize the tabs.
    nextTabIndex = nil
    tabs = [
      CampaignsTab(view: tabView),
      TVTab(view: tabView),
      RadioTab(view: tabView),
      PaidSearchTab(view: tabView),
      DisplayTab(view: tabView),
    ]

    // Bind clientSelector button to clientSelectButtonPressed method.
    initializeClientSelector()

    // Set the background color.
    tabView.backgroundColor = Color.backgroundColor
  }

  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    // Update client selector title.
    layoutClientSelector()

    // Update tab view & segmented control
    let controlHeight: CGFloat = 35
    tabControl.frame = CGRect(x: margin, y: clientSelectorView!.frame.height, width: view.frame.width - (margin * 2), height: controlHeight)

    // Update the tab view.
    tabView.frame = CGRect(x: 0, y: clientSelectorView!.frame.height + controlHeight + margin, width: view.frame.width, height: view.frame.height - clientSelectorView!.frame.height - controlHeight - margin)

    // Build tab.
    buildTab()
  }

  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    // Update the tabControl.
    if let next = nextTabIndex {
      if next != tabControl.selectedSegmentIndex {
        tabControl.selectedSegmentIndex = next
      }
      nextTabIndex = nil
    }
  }

  func clientSelectorClicked(selectorModal: UIViewController) {
    present(selectorModal, animated: true, completion: nil)
  }

  // MARK: - Tabs Control

  /**
   The user selected a different tab.
   */
  @objc func selectedTab(sender: UIButton) {
    buildTab()
  }

  /**
   A tab was selected from another part of the app.
   (This is called before viewWillAppear from another tab)
   */
  func switchToTab(atIndex index: Int) {
    nextTabIndex = index
  }

  func buildTab() {

    // Clean up the old tab.
    activeTab?.cleanUp()
    activeTab = nil

    // Check next index.
    var index = tabControl.selectedSegmentIndex
    if let next = nextTabIndex {
      index = next
    }

    // Add/Build the new tab.
    if index >= 0 && tabs.count > index {
      activeTab = tabs[index]
      activeTab?.buildViews()
    }
  }
}

Update:

Spent a couple more hours looking for a solution this morning. I also tried hacking it by finding the label in the subviews of the segmented control, and manually changing the font color. I could change the text of the label, but not the font color. Something is overriding it.

Is there some other way to programmatically change the selected index? Do I need to submit a ticket to apple? Is nobody else having this problem? Thanks in advance for any help you can provide.

Body:
After much struggling, I finally found an answer. I'm removing the borders using the method from the following post:

Swift: How to remove border from segmented control

extension UISegmentedControl {
  func applyAppStyles() {
    setBackgroundImage(imageWithColor(color: Color.contentBackgroundColor), for: .normal, barMetrics: .default)
    setBackgroundImage(imageWithColor(color: Color.orange), for: .selected, barMetrics: .default)
    setDividerImage(imageWithColor(color: UIColor.clear), forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
  }

  // create a 1x1 image with this color
  private func imageWithColor(color: UIColor) -> UIImage {
    let rect = CGRect(x: 0.0, y: 0.0, width:  1.0, height: 1.0)
    UIGraphicsBeginImageContext(rect.size)
    let context = UIGraphicsGetCurrentContext()
    context!.setFillColor(color.cgColor);
    context!.fill(rect);
    let image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image!
  }
}

My first call to setBackgroundImage is causing the issue; I'm not sure why. But the following code fixes it:

tabControl.setTitleTextAttributes([
  NSAttributedStringKey.foregroundColor: Color.darkGreyBlue
], for: .selected)


问:
angular - Angular Material 2 Stepper Controls
I set up a linear stepper using the Angular Material 2 Stepper.

I have forms in different components (component-a, component-b, component-c). In my main container component (container-component) I want to have linear stepper that 'steps' through each component when their form is valid.

Is there some sort of functionality to talk up to the stepControl in the stepper to make it properly work?

I have attached documentation for the stepper and a StackBlitz version of the application. Also, a link to the repo I have working as well.

Material Stepper Component: https://material.angular.io/components/stepper/overview

StackBlitz: https://stackblitz.com/edit/angular-material2-issue-mjmu9u?file=app/app.component.ts

Github: https://github.com/sam11385

答:
We had the exact same problem, and found a working solution after several days of trial and error. Basically since the steps are divided into several components that each define a form, and that their corresponding stepControl must be in the parent, the FormGroup in the child component must be sent to the parent component that defines the stepper. After creating the FormGroup, emit an event and have the parent listen to that event, and pass the FormGroup through that event. You can apply this for all children, creating a separate event for each and a separate listener in the parent for each emitter.

In the child component:

declare the event

```<code>@Output() notify: EventEmitter<FormGroup> = new EventEmitter<FormGroup>();
</code>```

emit the formGroup to the parent component

```<code>this.notify.emit(this.myFormGroup);
</code>```

In the parent component containing the mat-stepper's stepControl(s):

In the component(.ts), add a function that will receive and set the formgroup:

```<code>myFormGroup: FormGroup;
onNotify(formGroup: FormGroup): void {
  this.myFormGroup = formGroup;
}
</code>```

In the html, add the notification listener:

```<code><mat-step [completed]="false" [stepControl]="myFormGroup">
  <ng-template matStepLabel>Step 1</ng-template>
  <app-child (notify)='onNotify($event)'></app-child>
</mat-step>
</code>```

Nested components explanations: https://www.themarketingtechnologist.co/building-nested-components-in-angular-2/

Body:
We had the exact same problem, and found a working solution after several days of trial and error. Basically since the steps are divided into several components that each define a form, and that their corresponding stepControl must be in the parent, the FormGroup in the child component must be sent to the parent component that defines the stepper. After creating the FormGroup, emit an event and have the parent listen to that event, and pass the FormGroup through that event. You can apply this for all children, creating a separate event for each and a separate listener in the parent for each emitter.

In the child component:

declare the event

@Output() notify: EventEmitter<FormGroup> = new EventEmitter<FormGroup>();

emit the formGroup to the parent component

this.notify.emit(this.myFormGroup);

In the parent component containing the mat-stepper's stepControl(s):

In the component(.ts), add a function that will receive and set the formgroup:

myFormGroup: FormGroup;
onNotify(formGroup: FormGroup): void {
  this.myFormGroup = formGroup;
}

In the html, add the notification listener:

<mat-step [completed]="false" [stepControl]="myFormGroup">
  <ng-template matStepLabel>Step 1</ng-template>
  <app-child (notify)='onNotify($event)'></app-child>
</mat-step>

Nested components explanations: https://www.themarketingtechnologist.co/building-nested-components-in-angular-2/


问:
Inheritance problem. How to create multiple instances of a base class?
I have a base class (PrintProviderBase). It holds some states (PrinterUnavailable, NoPaper, ...).

Then I inherit from this class : ColorPrintProvider, BlackAndWhitePrintProvider ...

I was assumed that if the base class has a property like this:

```<code>private PrintStateEnum State { get; set; }
</code>```

Then each child class (different print providers) have it's own state (though nothing is static). It seems one instance of the base class is shared among them while I meant to have a copy of the base class in each child class so the common functionality and state can be encapsulate into base class.

Now if a print provider goes into NoPaper state, other ones stop printing due to incorrect state. How can I change this behavior ?

答:
In the code you posted, State is a private to PrintProviderBase and would not be visible to the derived types like ColorPrintProvider and so on.

Make State a public property and use Composition not inheritance. Keep a member of PrintProvider (change the name from PrintProviderBase) in ColorPrintProvider, BlackAndWhitePrintProvider and so on.

Sample code:

```<code>public class PrinterState
{
     public Boolean IsPaperTrayEmpty { get; set; }
     public Int32 CartridgeLevel { get; set; }
}

public class ColorPrintProvider
{
     public PrinterState CurrentState { get; private set; }

     private void UpdateCurrentState()
     {
         // update the current state
         // based on / after some events like RequestForPrint, PrintCompleted...
     }
}
</code>```

Body:
I have a base class (PrintProviderBase). It holds some states (PrinterUnavailable, NoPaper, ...).

Then I inherit from this class : ColorPrintProvider, BlackAndWhitePrintProvider ...

I was assumed that if the base class has a property like this:

private PrintStateEnum State { get; set; }

Then each child class (different print providers) have it's own state (though nothing is static). It seems one instance of the base class is shared among them while I meant to have a copy of the base class in each child class so the common functionality and state can be encapsulate into base class.

Now if a print provider goes into NoPaper state, other ones stop printing due to incorrect state. How can I change this behavior ?

Body:
In the code you posted, State is a private to PrintProviderBase and would not be visible to the derived types like ColorPrintProvider and so on.

Make State a public property and use Composition not inheritance. Keep a member of PrintProvider (change the name from PrintProviderBase) in ColorPrintProvider, BlackAndWhitePrintProvider and so on.

Sample code:

public class PrinterState
{
     public Boolean IsPaperTrayEmpty { get; set; }
     public Int32 CartridgeLevel { get; set; }
}

public class ColorPrintProvider
{
     public PrinterState CurrentState { get; private set; }

     private void UpdateCurrentState()
     {
         // update the current state
         // based on / after some events like RequestForPrint, PrintCompleted...
     }
}


问:
Disk Utilization stats per POD in K8
I was looking for ways to get details on disk utilization (mainly writes and Delete's) on a per POD level. I did get google advice such as cAdvisor/heapster etc but none of them talk about disk usage profiling from POD perspective.

Any help on this is greatly appreciated.

TIA!

答:
Assuming the pods are running a linux variant you can do:

```<code>kubectl exec -it <pod> cat /proc/1/io
</code>```

Returns info on the main process' IO defined here

You could then write a script to run the above command (or use the kuberentes API) for each pod of interest.

Title: Disk Utilization stats per POD in K8

Body:
Assuming the pods are running a linux variant you can do:

kubectl exec -it <pod> cat /proc/1/io

Returns info on the main process' IO defined here

You could then write a script to run the above command (or use the kuberentes API) for each pod of interest.


问:
JavaScript reference to event, declared by addEventListener()
I am trying to implement a Web Application which is supposed to let you draw shapes over a grid of pixels. For this purpose, I need to add several event listeners to each table element of my grid.
This is what I did so far:

```<code>td.addEventListener("click", setpixel);
td.addEventListener("mousedown", function () {
    mousedown = true;
})
td.addEventListener("mouseup", function () {
    mousedown = false;
})
td.addEventListener("mousemove", function () {
    if (mousedown) {
        setpixel(?);
    }
});
</code>```

The setPixel() function needs an event passed as parameter:

```<code>function setpixel(event) {
    var oldColor = this.style.backgroundColor;
    var currentColor=document.getElementById("current-color").style.backgroundColor;
    if (brushwidth > 1 && brushwidth < 4) {
        brushpixel(this.id, offset, currentColor);
    }
    else if (brushwidth == 4) {
        document.body.style.cursor = "url('https://www.wired.com/wp-content/uploads/images_blogs/design/2013/04/Susan-Kare-fill-icon-660x660.jpg')";
        floodfill(this.id, currentColor, oldColor);
        preview();
    }
    else {
        this.style.backgroundColor = currentColor;
    }
    preview();
}
</code>```

Otherwise it cannot function properly.
Where do I get the referenced event from?

Linked thread does not work for me here, not sure why, but I tried it out.

答:
Register the click event to the table and make a condition to which your function will work exclusively with . Use e.target to determine which  was actually clicked. Read this article on Event Delegation. Started this answer before your edit so wasn't aware of new additions.

Demo

// Reference table#T
var T = document.querySelector('#T');

/* Register the click event on #T
|| setPixel() is the callback
*/
T.addEventListener("click", setPixel);

function setPixel(e) {
  /* e.target is the clicked element
  || If the clicked element is a ...
  */
  var tgt = e.target;
  if (tgt.tagName === "TD") {
    /* ...if the td does not have a red
    || background then make it red
    */
    if (tgt.style.background !== 'red') {
      e.target.style.background = 'red';
    } else {
      /* Otherwise make it black */
      e.target.style.background = 'black';
    }
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#T {
  width: 90%
}

table,
td {
  border: 2px solid tomato;
  cursor: pointer;
  background: black;
}</code>```

```

Body:
I am trying to implement a Web Application which is supposed to let you draw shapes over a grid of pixels. For this purpose, I need to add several event listeners to each table element of my grid.
This is what I did so far:

td.addEventListener("click", setpixel);
td.addEventListener("mousedown", function () {
    mousedown = true;
})
td.addEventListener("mouseup", function () {
    mousedown = false;
})
td.addEventListener("mousemove", function () {
    if (mousedown) {
        setpixel(?);
    }
});

The setPixel() function needs an event passed as parameter:

function setpixel(event) {
    var oldColor = this.style.backgroundColor;
    var currentColor=document.getElementById("current-color").style.backgroundColor;
    if (brushwidth > 1 && brushwidth < 4) {
        brushpixel(this.id, offset, currentColor);
    }
    else if (brushwidth == 4) {
        document.body.style.cursor = "url('https://www.wired.com/wp-content/uploads/images_blogs/design/2013/04/Susan-Kare-fill-icon-660x660.jpg')";
        floodfill(this.id, currentColor, oldColor);
        preview();
    }
    else {
        this.style.backgroundColor = currentColor;
    }
    preview();
}

Otherwise it cannot function properly.
Where do I get the referenced event from?

Linked thread does not work for me here, not sure why, but I tried it out.

Body:
Register the click event to the table and make a condition to which your function will work exclusively with <td>. Use e.target to determine which <td> was actually clicked. Read this article on Event Delegation. Started this answer before your edit so wasn't aware of new additions.

Demo

// Reference table#T
var T = document.querySelector('#T');

/* Register the click event on #T
|| setPixel() is the callback
*/
T.addEventListener("click", setPixel);

function setPixel(e) {
  /* e.target is the clicked element
  || If the clicked element is a <td>...
  */
  var tgt = e.target;
  if (tgt.tagName === "TD") {
    /* ...if the td does not have a red
    || background then make it red
    */
    if (tgt.style.background !== 'red') {
      e.target.style.background = 'red';
    } else {
      /* Otherwise make it black */
      e.target.style.background = 'black';
    }
  }
}

#T {
  width: 90%
}

table,
td {
  border: 2px solid tomato;
  cursor: pointer;
  background: black;
}

<table id='T'>
  <tbody>
    <tr>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
  </tbody>
</table>


答:
Use map to create array of objects:

var value = [
  [-88.17179185999998, 41.78264698400005],
  [-88.17193080699997, 41.782605419000056]
]

var data = value.map(function(elem) {
  return {
    x: elem[0],
    y: elem[1],
    spatialReference: {
      wkid: 4326
    }
  }
})

console.log(data)```
</div>
</div>
</p>

<p>Or using es6:</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-js lang-js prettyprint-override"><code>const value = [
  [-88.17179185999998, 41.78264698400005],
  [-88.17193080699997, 41.782605419000056]
]

let data = value.map(elem => ({
    x: elem[0],
    y: elem[1],
    spatialReference: {
      wkid: 4326
    }
}))

console.log(data)</code>```

Title: Converting an array to object in JavaScript

Body:
I have a dynamically created array like this on the client side.

value = [
  [-88.17179185999998, 41.78264698400005],
  [-88.17193080699997, 41.782605419000056]
]

and I need to store it in an object format in this order with adding new "spatialReference": {"wkid": 4326 }

   var params = [
     {
       "x": -88.17179185999998,
       "y": 41.78264698400005,
       "spatialReference": {"wkid": 4326 }
     },
     {
       "x": -88.17193080699997,
       "y": 41.782605419000056,
       "spatialReference": {"wkid": 4326 }
     }
   ];

How can I do this?

Body:
Use map to create array of objects:

var value = [
  [-88.17179185999998, 41.78264698400005],
  [-88.17193080699997, 41.782605419000056]
]

var data = value.map(function(elem) {
  return {
    x: elem[0],
    y: elem[1],
    spatialReference: {
      wkid: 4326
    }
  }
})

console.log(data)

Or using es6:

const value = [
  [-88.17179185999998, 41.78264698400005],
  [-88.17193080699997, 41.782605419000056]
]

let data = value.map(elem => ({
    x: elem[0],
    y: elem[1],
    spatialReference: {
      wkid: 4326
    }
}))

console.log(data)


问:
How to add aria-hidden property to span on focus change?
I have to change the span element aria-hidden value to "true" on focus change event. How can I do that?

Here is my span element declaration-

```<code><span id="jawshide">#someText</span>
</code>```

and here is javascript part-

```<code>document.getElementById('jawshide').innerHTML= "aria-hidden='true'";
</code>```

What is the correct way to add this property?

答:
Js:

```<code>document.getElementById('jawshide').setAttribute("aria-hidden", "true")
</code>```

JQuery:

```<code>$('#jawshide').attr("aria-hidden", "true")
</code>```

Body:
I have to change the span element aria-hidden value to "true" on focus change event. How can I do that?

Here is my span element declaration-

#someText

and here is javascript part-

document.getElementById('jawshide').innerHTML= "aria-hidden='true'";

What is the correct way to add this property?

Body:
Js:

document.getElementById('jawshide').setAttribute("aria-hidden", "true")

JQuery:

$('#jawshide').attr("aria-hidden", "true")


问:
Filter 8 days ago
I have a Tableau work sheet with a Measure called 'Cost' and a Dimension called 'Created_date'.

On Sheet 1, I have the 'Cost' filtered by 'Yesterday' which is an option in the filter.

I would like to have a second sheet which is filtered 8 days ago, so the same time the previous week?

答:
Create a calculated field using datemath to return a boolean testing if day of created_date = 8 days ago:

datediff('day',[Created_Date],today())=8

Drag this calculation to the filters shelf and filter on "True"

Title: Filter 8 days ago


问:
C# Serializing XmlElement with XmlText
I have this XML format I need to replicate:

```<code><item>
    <attribute1>1</attribute1>
    <attribute2 something="true">
        2
    </attribute2>
    <attribute3 something="false">
        3
    </attribute3>
    <!-- goes on until attribute25 -->
</item>
</code>```

I'm currently using something like this to achieve what I want:

Item.cs:

```<code>[XmlType(TypeName = "item")]
public class Item {

    [XmlElement("attribute1")]
    public CustomElement<string> Attribute1 { get; set; }

    [XmlElement("attribute2")]
    public CustomElement<string> Attribute2 { get; set; }

    [XmlElement("attribute3")]
    public CustomElement<string> Attribute3 { get; set; }

    // Etc Etc
}
</code>```

CustomElement.cs:

```<code>/// <summary>
///     Represents a CustomElement.
/// </summary>
/// <typeparam name="T">The type for the value of the element.</typeparam>

public class CustomElement<T>
{
    [XmlIgnore] public T Value;

    [XmlText]
    public T XmlValue => Value;

    public CustomElement()
    {
    }

    public CustomElement(T value)
    {
        Value = value;
    }

    [XmlIgnore]
    public bool? Something { get; set; }

    [XmlAttribute("something")]
    public bool XmlSomething
    {
        get => Something != null && Something.Value;
        set => Something = value;
    }

    public bool XmlSomethingSpecified => Something.HasValue;

    public static implicit operator CustomElement<T>(T x)
    {
        return new CustomElement<T>(x);
    }
}
</code>```

However, after serializing my Item I get:

```<code><item>
    <attribute1 />
    <attribute2 />
    <attribute3 />
</item>
</code>```

How do I fix my CustomElement class so the value doesn't get lost?

答:
You have several problems here:

You are trying to serialize the XmlValue member as the element value for the element generated for an instance of CustomElement<T>, but you have defined it as a read-only expression-bodied member:

```<code>public T XmlValue => Value;
</code>```

XmlSerializer will only serialize public read/write properties and fields, so you must add a setter as well as a getter:

```<code>[XmlText]
public T XmlValue { get => Value; set => Value = value; }
</code>```

Alternatively, to simplify your model you could eliminate XmlValue entirely and serialize Value directly by marking it with [XmlText].  XML serialization attributes can be applied to fields as well as properties.

You are trying to suppress serialization of the <something> element when the underlying value is null using the {propertyName}Specified pattern.  This pattern is primarily used for tracking whether or not an associated element is encountered, and so the xxxSpecified property must be marked with [XmlIgnore]:

```<code>[XmlIgnore]
public bool XmlSomethingSpecified => Something.HasValue;
</code>```

Or, since you don't actually need to track the presence of the <something> element, you could simplify your model by switching to the ShouldSerialize{PropertyName}() pattern:

```<code>public bool ShouldSerializeXmlSomething() => Something.HasValue;
</code>```

The differences between the two patterns are described in ShouldSerialize() vs Specified Conditional Serialization Pattern.

If your Item type is going to be the root element of your XML document, you must mark it with [XmlRoot("item")] to make the root element's name be <item>:

```<code>[XmlRoot("item")]
[XmlType(TypeName = "ci")]
public class Item
{
    // Etc Etc
}
</code>```

In your c# code you have marked the XmlSomething property with [XmlElement] but in your XML something is shown as an element: <something>true</something>.

If you really want it to be an element you must mark XmlSomething with [XmlElement]:

```<code>[XmlElement("something")]
public bool XmlSomething
{
    get => Something != null && Something.Value;
    set => Something = value;
}
</code>```

In your question, you show an example of a <something> element with a non-boolean textual value:

```<code><attribute3>
    3
    <something>text</something>
</attribute3>
</code>```

I reckon this is a typo in the question, but if not, you will need to redesign your CustomElement<T> type to make Something be a string.

Sample working Roslyn .Net fiddle, and a second with the suggested simplifications for CustomElement<T>, and a third where <something> appears as a child element.

The classes from the second fiddle look like:

```<code>public class CustomElement<T>
{
    [XmlText]
    public T Value;

    public CustomElement()
    {
    }

    public CustomElement(T value)
    {
        Value = value;
    }

    [XmlIgnore]
    public bool? Something { get; set; }

    [XmlAttribute("something")]
    public bool XmlSomething
    {
        get => Something != null && Something.Value;
        set => Something = value;
    }

    public bool ShouldSerializeXmlSomething() => Something.HasValue;

    public static implicit operator CustomElement<T>(T x)
    {
        return new CustomElement<T>(x);
    }
}

[XmlRoot("item")]
[XmlType(TypeName = "ci")]
public class Item
{
    [XmlElement("attribute1")]
    public CustomElement<string> Attribute1 { get; set; }

    [XmlElement("attribute2")]
    public CustomElement<string> Attribute2 { get; set; }

    [XmlElement("attribute3")]
    public CustomElement<string> Attribute3 { get; set; }

    // Etc Etc
}
</code>```

Title: C# Serializing XmlElement with XmlText

Body:
I have this XML format I need to replicate:

<item>
    <attribute1>1</attribute1>
    <attribute2 something="true">
        2
    </attribute2>
    <attribute3 something="false">
        3
    </attribute3>

</item>

I'm currently using something like this to achieve what I want:

Item.cs:

[XmlType(TypeName = "item")]
public class Item {

    [XmlElement("attribute1")]
    public CustomElement<string> Attribute1 { get; set; }

    [XmlElement("attribute2")]
    public CustomElement<string> Attribute2 { get; set; }

    [XmlElement("attribute3")]
    public CustomElement<string> Attribute3 { get; set; }

    // Etc Etc
}

CustomElement.cs:

///
///     Represents a CustomElement.
///
/// <typeparam name="T">The type for the value of the element.</typeparam>

public class CustomElement<T>
{
    [XmlIgnore] public T Value;

    [XmlText]
    public T XmlValue => Value;

    public CustomElement()
    {
    }

    public CustomElement(T value)
    {
        Value = value;
    }

    [XmlIgnore]
    public bool? Something { get; set; }

    [XmlAttribute("something")]
    public bool XmlSomething
    {
        get => Something != null && Something.Value;
        set => Something = value;
    }

    public bool XmlSomethingSpecified => Something.HasValue;

    public static implicit operator CustomElement<T>(T x)
    {
        return new CustomElement<T>(x);
    }
}

However, after serializing my Item I get:

<item>
    <attribute1 />
    <attribute2 />
    <attribute3 />
</item>

How do I fix my CustomElement class so the value doesn't get lost?

Body:
You have several problems here:

You are trying to serialize the XmlValue member as the element value for the element generated for an instance of CustomElement<T>, but you have defined it as a read-only expression-bodied member:

public T XmlValue => Value;

XmlSerializer will only serialize public read/write properties and fields, so you must add a setter as well as a getter:

[XmlText]
public T XmlValue { get => Value; set => Value = value; }

Alternatively, to simplify your model you could eliminate XmlValue entirely and serialize Value directly by marking it with [XmlText].  XML serialization attributes can be applied to fields as well as properties.

You are trying to suppress serialization of the <something> element when the underlying value is null using the {propertyName}Specified pattern.  This pattern is primarily used for tracking whether or not an associated element is encountered, and so the xxxSpecified property must be marked with [XmlIgnore]:

[XmlIgnore]
public bool XmlSomethingSpecified => Something.HasValue;

Or, since you don't actually need to track the presence of the <something> element, you could simplify your model by switching to the ShouldSerialize{PropertyName}() pattern:

public bool ShouldSerializeXmlSomething() => Something.HasValue;

The differences between the two patterns are described in ShouldSerialize() vs Specified Conditional Serialization Pattern.

If your Item type is going to be the root element of your XML document, you must mark it with [XmlRoot("item")] to make the root element's name be <item>:

[XmlRoot("item")]
[XmlType(TypeName = "ci")]
public class Item
{
    // Etc Etc
}

In your c# code you have marked the XmlSomething property with [XmlElement] but in your XML something is shown as an element: <something>true</something>.

If you really want it to be an element you must mark XmlSomething with [XmlElement]:

[XmlElement("something")]
public bool XmlSomething
{
    get => Something != null && Something.Value;
    set => Something = value;
}

In your question, you show an example of a <something> element with a non-boolean textual value:

<attribute3>
    3
    <something>text</something>
</attribute3>

I reckon this is a typo in the question, but if not, you will need to redesign your CustomElement<T> type to make Something be a string.

Sample working Roslyn .Net fiddle, and a second with the suggested simplifications for CustomElement<T>, and a third where <something> appears as a child element.

The classes from the second fiddle look like:

public class CustomElement<T>
{
    [XmlText]
    public T Value;

    public CustomElement()
    {
    }

    public CustomElement(T value)
    {
        Value = value;
    }

    [XmlIgnore]
    public bool? Something { get; set; }

    [XmlAttribute("something")]
    public bool XmlSomething
    {
        get => Something != null && Something.Value;
        set => Something = value;
    }

    public bool ShouldSerializeXmlSomething() => Something.HasValue;

    public static implicit operator CustomElement<T>(T x)
    {
        return new CustomElement<T>(x);
    }
}

[XmlRoot("item")]
[XmlType(TypeName = "ci")]
public class Item
{
    [XmlElement("attribute1")]
    public CustomElement<string> Attribute1 { get; set; }

    [XmlElement("attribute2")]
    public CustomElement<string> Attribute2 { get; set; }

    [XmlElement("attribute3")]
    public CustomElement<string> Attribute3 { get; set; }

    // Etc Etc
}


问:
Can you document the APIs which are developed by someone else using swagger?
I am a newbie to swagger.io. And i have a bunch of APIs that have been developed by a team which is no longer working with me. So these APIs aren't properly documented by them. So, i was thinking to use swagger and document them properly.

But the Question is, Is possible to document these APIs with swagger?

If yes, How?
If no, is there any other tool/framework for me to do it?

答:
Not swagger, but WireMock will let observe and record an API as a black box.

http://wiremock.org/docs/record-playback/