问:
How can I achieve one single form, pre-populated with data from two different Profile instances?
I have a model, Pair, and another model Profile.

An instance of the model Pair will be made with a form that draws from two different Profile instances. So, how do I pre-populate a single form with bits of information from two Profiles?

Two models: Profile & Pair:

```<code>class Profile(models.Model):
    ...
    favorites = models.CharField(max_length=150)

class Pair(models.Model):
    requester = models.ForeignKey(Profile)
    accepter = models.ForeignKey(Profile)
    requester_favorite = models.CharField(max_length=50)
    accepter_favorite = models.CharField(max_length=50)
</code>```

The form so far:

```<code>class PairRequestForm(forms.Form):
    your_favorites = forms.CharField(max_length=50)
    partners_favorites = forms.CharField(max_length=50)
</code>```

Code Explanation:  The way it works is, a user(requester) will request the initiation of a pair with the PairRequestForm to the potential accepter.

The form should be pre-populated with the "favorite" of each individual user.

I'm not sure how to wire up the views.py since I need to obtain two objects.

```<code>class PairRequestView(FormView):
    form_class = PairRequestForm
    template_name = 'profile/pair_request.html'
    success_url = "/"

    def is_valid(self, form):
        return
</code>```

note: The pair form must be pre-populated with current information from the Profile. However, the form will not update any old information(will not save() any Profiles)--it will simply create a new Pair instance.

答:
Assuming that the accepters page is visited at something like /profiles/2, you can capture the id of the accepter from the url, as you normally would.

Couple of things - you don't need to save the favourites into the Pair model, since for any use of the Pair model, you can just access them by doing

```<code>`p = Pair.objects.get(id=1) #or whatever query
 p.requester.favourites
 > Some of my favourites
 p.accepter.favourites
 > Some of your favourites.
</code>```

If you, the proposer, are id=1, and visiting mine, the accepter's page (id=2), then you can populate the form - (I've done this in a very long manner for clarity)

```<code>accepterobj = Profile.objects.get(id=id_from_url_for_page)
proposerobj = Profile.objects.get(id=request.user.id)

form = PairRequestForm(accepter=accepterobj,
                       proposer=proposerobj,
                       accepter_favourites=accepterobj.favourites,
                       proposerobj_favourites=proposerobj.favourites)
</code>```

in your CBV, you can do the queries above by overriding the get_initial method on your PairRequestView.

```<code>def get_initial(self):
    """
    Returns the initial data to use for forms on this view.
    """
    initial = super(PairRequestView, self).get_initial()

    initial['proposer'] = self.request.user
    ...etc
    return initial
</code>```

Body:
I have a model, Pair, and another model Profile.

An instance of the model Pair will be made with a form that draws from two different Profile instances. So, how do I pre-populate a single form with bits of information from two Profiles?

Two models: Profile & Pair:

class Profile(models.Model):
    ...
    favorites = models.CharField(max_length=150)

class Pair(models.Model):
    requester = models.ForeignKey(Profile)
    accepter = models.ForeignKey(Profile)
    requester_favorite = models.CharField(max_length=50)
    accepter_favorite = models.CharField(max_length=50)

The form so far:

class PairRequestForm(forms.Form):
    your_favorites = forms.CharField(max_length=50)
    partners_favorites = forms.CharField(max_length=50)

Code Explanation:  The way it works is, a user(requester) will request the initiation of a pair with the PairRequestForm to the potential accepter.

The form should be pre-populated with the "favorite" of each individual user.

I'm not sure how to wire up the views.py since I need to obtain two objects.

class PairRequestView(FormView):
    form_class = PairRequestForm
    template_name = 'profile/pair_request.html'
    success_url = "/"

    def is_valid(self, form):
        return

note: The pair form must be pre-populated with current information from the Profile. However, the form will not update any old information(will not save() any Profiles)--it will simply create a new Pair instance.

Body:
Assuming that the accepters page is visited at something like /profiles/2, you can capture the id of the accepter from the url, as you normally would.

Couple of things - you don't need to save the favourites into the Pair model, since for any use of the Pair model, you can just access them by doing

`p = Pair.objects.get(id=1) #or whatever query
 p.requester.favourites
 > Some of my favourites
 p.accepter.favourites
 > Some of your favourites.

If you, the proposer, are id=1, and visiting mine, the accepter's page (id=2), then you can populate the form - (I've done this in a very long manner for clarity)

accepterobj = Profile.objects.get(id=id_from_url_for_page)
proposerobj = Profile.objects.get(id=request.user.id)

form = PairRequestForm(accepter=accepterobj,
                       proposer=proposerobj,
                       accepter_favourites=accepterobj.favourites,
                       proposerobj_favourites=proposerobj.favourites)

in your CBV, you can do the queries above by overriding the get_initial method on your PairRequestView.

def get_initial(self):
    """
    Returns the initial data to use for forms on this view.
    """
    initial = super(PairRequestView, self).get_initial()

    initial['proposer'] = self.request.user
    ...etc
    return initial


来源: stackexchange

问:
Loading of windows form takes more time that usual?
I have created a windows form application in c# having two forms.
2nd form loads on click of each button on form1. I have six buttons on first form.2nd form contains textbox whose content is assigned at runtime. Now if I click on more than 3 buttons one after other the form is hanged nothing happen.Also for second click form2 takes tim to load. I am not getting the reason behind this. I have used following code for show hide.
{this.Hide();} to hide and  {this.ShowDialog();}to open form2.

答:
The dialogboxes are two types.

Model and Model less.

When you open other form through showdialog, we have to finish the work with that dialogbox then only we can able to go back.

The second form you can load by calling form2.Show()

ContentLicense: CC BY-SA 3.0


问:
$state.go with data not being passed to the view
I have a post controller that should send the response data to the view with $state.go but does not seem to work

My Controller with the post response

```<code> 'use strict';

angular.module('App.addresses', [])

.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
  $stateProvider
  .state('addresses', {
    url: '/addresses',
    views: {
      'addressesContent': {
        templateUrl: "addresses/addresses.html",
        controller: 'AddressCtrl as address'
      }
    }
  })
}])

.controller('AddressCtrl', ['$state', '$http', '$scope', function($state, $http, $scope){
    this.search = function() {

        var data = {
             "mobile":$scope.mobile,
             "userId":localStorage.getItem('userId'),
             "sessionToken":localStorage.getItem('sessionToken')
            };
        $http({
            method: 'POST',
            url: url + '/getAddresses',
            data: data,
            headers: header
        })
        .then(function(response) {
                if (response.data.code == 101) {
                 var error = response.data.message;
                 $state.go('auth');
                }else {
                  var data = response.data;
                  console.log(data)
                  $state.go('display', {'addresses': data});
                }
        })
    }
}])
</code>```

This is my view code where am supposed to display the data

```<code><table class="table">
    <thead>
        <tr>
            <th>Address Type</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="addess in addresses">
            <td>{{address.addressType}}</td>
        </tr>
    </tbody>
</table>
</code>```

What am I doing wrong. Been stuck on this for a while?

答: You need to $state.go to a state name like $state.go('addresses', {data:someStuff}) you also typically specify what arguments/parameters a state will take https://github.com/angular-ui/ui-router/wiki/URL-Routing#url-parameters</p>

Body:
I have a post controller that should send the response data to the view with $state.go but does not seem to work

My Controller with the post response

 'use strict';

angular.module('App.addresses', [])

.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
  $stateProvider
  .state('addresses', {
    url: '/addresses',
    views: {
      'addressesContent': {
        templateUrl: "addresses/addresses.html",
        controller: 'AddressCtrl as address'
      }
    }
  })
}])

.controller('AddressCtrl', ['$state', '$http', '$scope', function($state, $http, $scope){
    this.search = function() {

        var data = {
             "mobile":$scope.mobile,
             "userId":localStorage.getItem('userId'),
             "sessionToken":localStorage.getItem('sessionToken')
            };
        $http({
            method: 'POST',
            url: url + '/getAddresses',
            data: data,
            headers: header
        })
        .then(function(response) {
                if (response.data.code == 101) {
                 var error = response.data.message;
                 $state.go('auth');
                }else {
                  var data = response.data;
                  console.log(data)
                  $state.go('display', {'addresses': data});
                }
        })
    }
}])

This is my view code where am supposed to display the data

            Address Type

            {{address.addressType}}

What am I doing wrong. Been stuck on this for a while?


问:
How to uppercase first char in the C input?
My output doesn't uppercase next argument after space-character (' ').

```<code>int main(void)
{
    int i = 0;
    int flag = OUT;
    char name[100];
    int leng = strlen(name);

    printf("Value pls: \n");
    fgets(name, 100, stdin);
    printf("%c", toupper(name[0]));

    while(name[i])
    {
        printf("%c", name[i + 1]);
        if(i == ' ')
        {
            printf("%c", toupper(name[i + 1]));
        }
        i++;
    }
}
</code>```

It's always shows somthing like this:
Value pls:
jon smith
Jon smith

Word "smith" is always lowercase.

答:
The idea to "fiddle" with the loop counter is often ill-adviced. It definitely is for the job you want to do here. The canonic approach is using a flag. Rough outline:

```<code>int wasspace = 1; // to capitalize the *first* character
for (i=0; name[i]; ++i)
{
    printf("%c", wasspace ? toupper((unsigned char)name[i]) : name[i]);
    wasspace = (name[i] == ' ');
    // maybe better: wasspace = isspace((unsigned char)name[i]);
    // so you handle tabs, newlines etc. as well
}
</code>```

On a side note, part of your problem was this line:

```<code>    if(i == ' ')
</code>```

i is your loop counter, not the i'th character in your name. Comparing it to a space doesn't make sense.

Body:
My output doesn't uppercase next argument after space-character (' ').

int main(void)
{
    int i = 0;
    int flag = OUT;
    char name[100];
    int leng = strlen(name);

    printf("Value pls: \n");
    fgets(name, 100, stdin);
    printf("%c", toupper(name[0]));

    while(name[i])
    {
        printf("%c", name[i + 1]);
        if(i == ' ')
        {
            printf("%c", toupper(name[i + 1]));
        }
        i++;
    }
}

It's always shows somthing like this:
Value pls:
jon smith
Jon smith

Word "smith" is always lowercase.

Body:
The idea to "fiddle" with the loop counter is often ill-adviced. It definitely is for the job you want to do here. The canonic approach is using a flag. Rough outline:

int wasspace = 1; // to capitalize the *first* character
for (i=0; name[i]; ++i)
{
    printf("%c", wasspace ? toupper((unsigned char)name[i]) : name[i]);
    wasspace = (name[i] == ' ');
    // maybe better: wasspace = isspace((unsigned char)name[i]);
    // so you handle tabs, newlines etc. as well
}

On a side note, part of your problem was this line:

    if(i == ' ')

i is your loop counter, not the i'th character in your name. Comparing it to a space doesn't make sense.


问:
Uses of javax.faces.PROJECT_STAGE
I wanted to understand impact of 'javax.faces.PROJECT_STAGE' property for a JSF application. A nice use case was presented in below links

https://dzone.com/articles/jsf-20-new-feature-preview-ser

http://www.java-tutorial.ch/java-server-faces/jsf-project-stage

Except presenting validation error messages, is there any other use case where this property really helps?  I understand that we can check this variable to identify the environment and change certain functionality, however is there anything else that JSF does automatically to help developers? Would be great if you can share the experiences from your project?

答: Another function of setting the PROJECT_STAGE as Development is that we will also be able to see our changes in .xhtml files without restarting the server.</p>

ContentLicense: CC BY-SA 4.0

Title: Uses of javax.faces.PROJECT_STAGE


问:
Maven pom.xml inheriting dependencies from spring-boot-starter-parent is not working
I have created a Spring boot application for learning purpose.

I had my configurations in default application.properties file.

src/main/resources/application.properties

```<code>server.port=8761
</code>```

This was working fine.

Later I decided to change configurations to application.yml file

src/main/resources/application.yml

```<code>server:
 port: 1112
</code>```

From Spring documentation:

Create a file called application.yml and stick it in the root of your
  classpath, and also add snakeyaml to your dependencies (Maven
  coordinates org.yaml:snakeyaml, already included if you use the
  spring-boot-starter).

My pom.xml is inheriting from parent spring-boot-starter as below.

```<code><parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
</code>```

Since parent pom.xml has org.yaml:snakeyaml depedencies, I have not included any dependency in pom and tried running application.

But now values from application.yml file is not taken in account, instead application is using default port.

When I added the snakeyaml dependency explicitly in pom.xml, application.yml values are considered.

Also I dont think parent pom is missing the dependency, because when I added snakeyaml explicitly I am getting below warning in eclipse

```<code>Overriding managed version 1.17 for snakeyaml
</code>```

Can anyone help me on this issue?

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>ServiceDiscovery</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>ServiceDiscovery</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
            <scope>test</scope>
        </dependency>
            <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.6.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.yaml/snakeyaml -->
<dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
    <version>1.19</version>
</dependency>

    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Camden.SR5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

答:
My org.yaml:snakeyaml comes from spring-boot-starter-web (mvn dependency:tree command)

```<code>[INFO] +- org.springframework.boot:spring-boot-starter-web:jar:1.5.1.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter:jar:1.5.1.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot:jar:1.5.1.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-autoconfigure:jar:1.5.1.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-starter-logging:jar:1.5.1.RELEASE:compile
[INFO] |  |  |  +- ch.qos.logback:logback-classic:jar:1.1.9:compile
[INFO] |  |  |  |  \- ch.qos.logback:logback-core:jar:1.1.9:compile
[INFO] |  |  |  +- org.slf4j:jul-to-slf4j:jar:1.7.22:compile
[INFO] |  |  |  \- org.slf4j:log4j-over-slf4j:jar:1.7.22:compile
[INFO] |  |  \- org.yaml:snakeyaml:jar:1.17:runtime
</code>```

here is the dependency

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>1.5.1.RELEASE</version>
</dependency>
</code>```

Presumably it is in other spring-boot-starter modules that include spring-boot-starter.

You do not need the

```<code><dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
    <version>1.19</version>
</dependency>
</code>```

Body:
I have created a Spring boot application for learning purpose.

I had my configurations in default application.properties file.

src/main/resources/application.properties

server.port=8761

This was working fine.

Later I decided to change configurations to application.yml file

src/main/resources/application.yml

server:
 port: 1112

From Spring documentation:

Create a file called application.yml and stick it in the root of your
  classpath, and also add snakeyaml to your dependencies (Maven
  coordinates org.yaml:snakeyaml, already included if you use the
  spring-boot-starter).

My pom.xml is inheriting from parent spring-boot-starter as below.

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath/>
    </parent>

Since parent pom.xml has org.yaml:snakeyaml depedencies, I have not included any dependency in pom and tried running application.

But now values from application.yml file is not taken in account, instead application is using default port.

When I added the snakeyaml dependency explicitly in pom.xml, application.yml values are considered.

Also I dont think parent pom is missing the dependency, because when I added snakeyaml explicitly I am getting below warning in eclipse

Overriding managed version 1.17 for snakeyaml

Can anyone help me on this issue?

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>ServiceDiscovery</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>ServiceDiscovery</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
            <scope>test</scope>
        </dependency>
            <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.6.4</version>
        </dependency>

<dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
    <version>1.19</version>
</dependency>

    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Camden.SR5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Body:
My org.yaml:snakeyaml comes from spring-boot-starter-web (mvn dependency:tree command)

[INFO] +- org.springframework.boot:spring-boot-starter-web:jar:1.5.1.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter:jar:1.5.1.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot:jar:1.5.1.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-autoconfigure:jar:1.5.1.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-starter-logging:jar:1.5.1.RELEASE:compile
[INFO] |  |  |  +- ch.qos.logback:logback-classic:jar:1.1.9:compile
[INFO] |  |  |  |  \- ch.qos.logback:logback-core:jar:1.1.9:compile
[INFO] |  |  |  +- org.slf4j:jul-to-slf4j:jar:1.7.22:compile
[INFO] |  |  |  \- org.slf4j:log4j-over-slf4j:jar:1.7.22:compile
[INFO] |  |  \- org.yaml:snakeyaml:jar:1.17:runtime

here is the dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>1.5.1.RELEASE</version>
</dependency>

Presumably it is in other spring-boot-starter modules that include spring-boot-starter.

You do not need the

<dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
    <version>1.19</version>
</dependency>


问:
Permissions for truncating a table
What permission do I need to GRANT a user, in MSSQL, in order to be able to truncate a table?

I'm trying to grant the minimal set of permissions, but I can't use DELETE, because the table is very large, and I want the operation to be quick.

答:
The minimum permission required is
  ALTER on table_name. TRUNCATE TABLE
  permissions default to the table
  owner, members of the sysadmin fixed
  server role, and the db_owner and
  db_ddladmin fixed database roles, and
  are not transferable. However, you can
  incorporate the TRUNCATE TABLE
  statement within a module, such as a
  stored procedure, and grant
  appropriate permissions to the module
  using the EXECUTE AS clause. For more
  information, see Using EXECUTE AS to
  Create Custom Permission Sets.

Source

ContentLicense: CC BY-SA 2.5

Title: Permissions for truncating a table


问:
How to set default font family in React Native?
Is there an equivalent to this CSS in React Native, so that the app uses the same  font everywhere ?

```<code>body {
  font-family: 'Open Sans';
}
</code>```

Applying it manually on every Text node seems overly complicated.

答:
You can override Text behaviour by adding this in any of your component using Text:

```<code>let oldRender = Text.prototype.render;
Text.prototype.render = function (...args) {
    let origin = oldRender.call(this, ...args);
    return React.cloneElement(origin, {
        style: [{color: 'red', fontFamily: 'Arial'}, origin.props.style]
    });
};
</code>```

Edit: since React Native 0.56, Text.prototypeis not working anymore. You need to remove the .prototype :

```<code>let oldRender = Text.render;
Text.render = function (...args) {
    let origin = oldRender.call(this, ...args);
    return React.cloneElement(origin, {
        style: [{color: 'red', fontFamily: 'Arial'}, origin.props.style]
    });
};
</code>```

Body:
Is there an equivalent to this CSS in React Native, so that the app uses the same  font everywhere ?

body {
  font-family: 'Open Sans';
}

Applying it manually on every Text node seems overly complicated.

Body:
You can override Text behaviour by adding this in any of your component using Text:

let oldRender = Text.prototype.render;
Text.prototype.render = function (...args) {
    let origin = oldRender.call(this, ...args);
    return React.cloneElement(origin, {
        style: [{color: 'red', fontFamily: 'Arial'}, origin.props.style]
    });
};

Edit: since React Native 0.56, Text.prototypeis not working anymore. You need to remove the .prototype :

let oldRender = Text.render;
Text.render = function (...args) {
    let origin = oldRender.call(this, ...args);
    return React.cloneElement(origin, {
        style: [{color: 'red', fontFamily: 'Arial'}, origin.props.style]
    });
};


问:
Is it possible to apply dynamic style as string in Angular?
I have a  that I want to apply dynamic style to.

Style is stored in a css-like string variable and can be arbitrary e.g.

myStyle = 'color: white; font-weight: bold;'

or

myStyle = 'background-color: red;'

I expected it to work like

but it didn't.

I tried different options but none seem to work for me for different reasons:

I can't put styles in a .css file and use class names because style is coming from server in the form of aforementioned string

Using [style.color] etc. doesn't suit me because I don't know what the style can be

Using [ngStyle] doesn't suit me because it expects object like {'color': 'red', 'font-weight': 'bold'} and I only have string

The reason I have a style stored in a string is because I need to apply it in HTML generated on the server where I simply pass that string to a placeholder variable in a velocity template.

I am almost confident that it can't be done the way I want but probably I am overlooking some solution.

答: I think I will go the way of converting the incoming css string into a style object and then applying it to  using [ngStyle]

Body: I think I will go the way of converting the incoming css string into a style object and then applying it to <span> using [ngStyle]


问:
C# Code closes without completing the code
That's the code. What happens is the console prints out

```<code>Enter a number(a) :

2

Enter a number(b) :

Enter a number(c) :

a + b + c =73

Press any key to continue...
</code>```

P.S - This is my solution to an exercise I had. The exercise tells me to enter 3 values from the console using integrals.

```<code>class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter a number(a) : ");
        int a = Console.Read();
        Console.WriteLine("Enter a number(b) : ");
        int b = Console.Read();
        Console.WriteLine("Enter a number(c) : ");
        int c = Console.Read();
        Console.WriteLine("a + b + c =" + (a + b + c));
    }
}
</code>```

答: After your program does the output Console.WriteLine("a + b + c =" + (a + b + c)); your program ends and the consolewindow will close. Yout can call Console.ReadKey(); at the end, so the programm waits for another input from the user before its ending and closing the window

Body:
That's the code. What happens is the console prints out

Enter a number(a) :

2

Enter a number(b) :

Enter a number(c) :

a + b + c =73

Press any key to continue...

P.S - This is my solution to an exercise I had. The exercise tells me to enter 3 values from the console using integrals.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter a number(a) : ");
        int a = Console.Read();
        Console.WriteLine("Enter a number(b) : ");
        int b = Console.Read();
        Console.WriteLine("Enter a number(c) : ");
        int c = Console.Read();
        Console.WriteLine("a + b + c =" + (a + b + c));
    }
}


问:
PowerApps: Lock dropdown options
I generated a PowerApps from an existing SharePoint list and I have a Choice column which has been automatically converted to a dropdown list on the app's Edit screen. The issue I'm having is that the app lets the user "edit" the dropdown list and they can type something else other than the premade choices.

Is it possible to make the dropdown read-only? I have several fields that rely on its selection for visibility. For some reason I couldn't find a property that lets me lock the choices. Am I missing something? Thanks for any help!

答:
You can make a PowerApps dorp down read only. To do so

Select the Edit Form in the screens side pane

Select the Data Source in the right panel

In the fields scroll to the field you want to make read only, and expand it

You  will get multiple options, select the view mode

Title: PowerApps: Lock dropdown options


问:
CSS not working when added to site.css file in ASP.NET Core project. But works when added as inline
I'm testing an svg animation example (taken from Live Example section from here) on an ASP.NET Core project.

Image displays ok. When I add the following css inline to a specific view, the animation works but animation does NOT work when I add the same css to the site.css file (located by default at myProject\wwwroot\cs\site.css). Why?

View [Animation works after I moved the related css inside the view]

```<code><div>
    <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
             width="340px" height="333px" viewBox="0 0 340 333" enable-background="new 0 0 340 333" xml:space="preserve">

        <path class="path" fill="#FFFFFF" stroke="#000000" stroke-width="4" stroke-miterlimit="10" d="M66.039,133.545c0,0-21-57,18-67s49-4,65,8
            s30,41,53,27s66,4,58,32s-5,44,18,57s22,46,0,45s-54-40-68-16s-40,88-83,48s11-61-11-80s-79-7-70-41
            C46.039,146.545,53.039,128.545,66.039,133.545z" />
    </svg>
</div>
@section css{
    <style>
        .path {
            stroke-dasharray: 1000;
            stroke-dashoffset: 1000;
            animation: dash 5s linear alternate infinite;
        }

        @@keyframes dash {
            from {
                stroke-dashoffset: 1000;
            }

            to {
                stroke-dashoffset: 0;
            }
        }
    </style>
}
</code>```

Snapshot of myProject\wwwroot\css\site.css file: [Animation did NOT work when the the above css was added to the end of following site.css file.

```<code>body {
    padding-top: 50px;
    padding-bottom: 20px;
}

/* Wrapping element */
/* Set some basic padding to keep content from hitting the edges */
.body-content {
    padding-left: 15px;
    padding-right: 15px;
}
...
...
}

/*I added for svg animation test*/
.path {
    stroke-dasharray: 1000;
    stroke-dashoffset: 1000;
    animation: dash 5s linear alternate infinite;
}

@keyframes dash {
    from {
        stroke-dashoffset: 1000;
    }

    to {
        stroke-dashoffset: 0;
    }
}
</code>```

答:
Check the link in your _Layout.cshtml file.  It sets the default to the site.min.css version of the CSS, not the site.css.

```<code><link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
</code>```

change it to your decompressed full css file, site.css

```<code><link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
</code>```

Body:
I'm testing an svg animation example (taken from Live Example section from here) on an ASP.NET Core project.

Image displays ok. When I add the following css inline to a specific view, the animation works but animation does NOT work when I add the same css to the site.css file (located by default at myProject\wwwroot\cs\site.css). Why?

View [Animation works after I moved the related css inside the view]

    <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
             width="340px" height="333px" viewBox="0 0 340 333" enable-background="new 0 0 340 333" xml:space="preserve">

        <path class="path" fill="#FFFFFF" stroke="#000000" stroke-width="4" stroke-miterlimit="10" d="M66.039,133.545c0,0-21-57,18-67s49-4,65,8
            s30,41,53,27s66,4,58,32s-5,44,18,57s22,46,0,45s-54-40-68-16s-40,88-83,48s11-61-11-80s-79-7-70-41
            C46.039,146.545,53.039,128.545,66.039,133.545z" />
    </svg>

@section css{

}

Snapshot of myProject\wwwroot\css\site.css file: [Animation did NOT work when the the above css was added to the end of following site.css file.

body {
    padding-top: 50px;
    padding-bottom: 20px;
}

/* Wrapping element */
/* Set some basic padding to keep content from hitting the edges */
.body-content {
    padding-left: 15px;
    padding-right: 15px;
}
...
...
}

/*I added for svg animation test*/
.path {
    stroke-dasharray: 1000;
    stroke-dashoffset: 1000;
    animation: dash 5s linear alternate infinite;
}

@keyframes dash {
    from {
        stroke-dashoffset: 1000;
    }

    to {
        stroke-dashoffset: 0;
    }
}

Body:
Check the link in your _Layout.cshtml file.  It sets the default to the site.min.css version of the CSS, not the site.css.

<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />

change it to your decompressed full css file, site.css

<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />


问:
Parsing through Retrofit and set Data to the Base Adapter
I am working with Retrofit (JSON Parsing Android) and I am new with this I am so confused to set the response with the Base Adapter.

This is my Example Class

```<code>public class Example {

@SerializedName("Totalrecord")
@Expose
private List<Totalrecord> totalrecord = null;
@SerializedName("Table1")
@Expose
private List<Table1> table1 = null;
@SerializedName("Table2")
@Expose
private List<Table2> table2 = null;

public List<Totalrecord> getTotalrecord() {
    return totalrecord;
}

public void setTotalrecord(List<Totalrecord> totalrecord) {
    this.totalrecord = totalrecord;
}

public List<Table1> getTable1() {
    return table1;
}

public void setTable1(List<Table1> table1) {
    this.table1 = table1;
}

public List<Table2> getTable2() {
    return table2;
}

public void setTable2(List<Table2> table2) {
    this.table2 = table2;
}
}
</code>```

Here I am trying to retrieve Response in ArrayList so that I can set it to Adapter

```<code>    ApiService api = RetroClient.getApiService();
            Call<Example> call = api.getMyJson(38, 109);
            call.enqueue(new Callback<Example>() {
                @Override
                public void onResponse(Call<Example> call, Response<Example> response) {
                    dialog.dismiss();
                    if (response.isSuccessful()) {
                   //     Response_list = response.body().get...
                        adapter_view = new Adapter_view(Response_list, MainActivity.this);
                        listView.setAdapter(adapter_view);
                    }
                }
                @Override
                public void onFailure(Call<Example> call, Throwable t) {
                    dialog.dismiss();
                    System.out.println("failed");
                }
            });
</code>```

But I am confused to set The type of ArrayList and also Type of Callback<> so that I can get the response properly and set ArrayList to the Adapter.

答:
try following if you want to set List<Totalrecord> in your adapter.

```<code>ApiService api = RetroClient.getApiService();
            Call<Example> call = api.getMyJson(38, 109);
            call.enqueue(new Callback<Example>() {
                @Override
                public void onResponse(Call<Example> call, Response<Example> response) {
                    dialog.dismiss();
                    if (response.isSuccessful()) {
                   Response_list.clear();
                   Response_list.addAll(call.getTotalrecord());
                        adapter_view = new Adapter_view(Response_list, MainActivity.this);
                        listView.setAdapter(adapter_view);
                    }
                }
                @Override
                public void onFailure(Call<Example> call, Throwable t) {
                    dialog.dismiss();
                    System.out.println("failed");
                }
            });
</code>```

Body:
I am working with Retrofit (JSON Parsing Android) and I am new with this I am so confused to set the response with the Base Adapter.

This is my Example Class

public class Example {

@SerializedName("Totalrecord")
@Expose
private List<Totalrecord> totalrecord = null;
@SerializedName("Table1")
@Expose
private List<Table1> table1 = null;
@SerializedName("Table2")
@Expose
private List<Table2> table2 = null;

public List<Totalrecord> getTotalrecord() {
    return totalrecord;
}

public void setTotalrecord(List<Totalrecord> totalrecord) {
    this.totalrecord = totalrecord;
}

public List<Table1> getTable1() {
    return table1;
}

public void setTable1(List<Table1> table1) {
    this.table1 = table1;
}

public List<Table2> getTable2() {
    return table2;
}

public void setTable2(List<Table2> table2) {
    this.table2 = table2;
}
}

Here I am trying to retrieve Response in ArrayList so that I can set it to Adapter

    ApiService api = RetroClient.getApiService();
            Call<Example> call = api.getMyJson(38, 109);
            call.enqueue(new Callback<Example>() {
                @Override
                public void onResponse(Call<Example> call, Response<Example> response) {
                    dialog.dismiss();
                    if (response.isSuccessful()) {
                   //     Response_list = response.body().get...
                        adapter_view = new Adapter_view(Response_list, MainActivity.this);
                        listView.setAdapter(adapter_view);
                    }
                }
                @Override
                public void onFailure(Call<Example> call, Throwable t) {
                    dialog.dismiss();
                    System.out.println("failed");
                }
            });

But I am confused to set The type of ArrayList and also Type of Callback<> so that I can get the response properly and set ArrayList to the Adapter.

Body:
try following if you want to set List<Totalrecord> in your adapter.

ApiService api = RetroClient.getApiService();
            Call<Example> call = api.getMyJson(38, 109);
            call.enqueue(new Callback<Example>() {
                @Override
                public void onResponse(Call<Example> call, Response<Example> response) {
                    dialog.dismiss();
                    if (response.isSuccessful()) {
                   Response_list.clear();
                   Response_list.addAll(call.getTotalrecord());
                        adapter_view = new Adapter_view(Response_list, MainActivity.this);
                        listView.setAdapter(adapter_view);
                    }
                }
                @Override
                public void onFailure(Call<Example> call, Throwable t) {
                    dialog.dismiss();
                    System.out.println("failed");
                }
            });


问:
Phone call button in Swift 3 doesn't work
I need my app make a phone call when user taps a button. I found some tutorials and people there say use this code

```<code>let numberUrl = URL(string: "tel://12345678")!
UIApplication.shared.open(numberUrl, options: [:], completionHandler: nil)
</code>```

But it just does not work. Was it change in Swift 3?

答:
Try this...

```<code>let url:URL = URL(string: "tel:\(phone_number)")!
    let application:UIApplication = UIApplication.shared
    if (application.canOpenURL(url)) {
        if #available(iOS 10, *) {
            application.open(url)
        } else {
            application.openURL(url)
        }
    }
</code>```

Body:
I need my app make a phone call when user taps a button. I found some tutorials and people there say use this code

let numberUrl = URL(string: "tel://12345678")!
UIApplication.shared.open(numberUrl, options: [:], completionHandler: nil)

But it just does not work. Was it change in Swift 3?

Body:
Try this...

let url:URL = URL(string: "tel:\(phone_number)")!
    let application:UIApplication = UIApplication.shared
    if (application.canOpenURL(url)) {
        if #available(iOS 10, *) {
            application.open(url)
        } else {
            application.openURL(url)
        }
    }


问:
PHP code not working on ipage hosting?
My code is working well on localhost and also on godaddy server.But on ipage I am getting "500 Internal Server error" with this code.
My local server has PHP Version 5.4.7  and my ipage hosting has PHP Version 5.3.13</p>

```<code>         public function cms($cid,$vars) {
   global $db;
    //fetch cms data from database

          $stmt = $db->prepare("SELECT * FROM cms");
          $stmt->execute();
          $row = $stmt->fetchAll(PDO::FETCH_ASSOC);

       return $row;

   if ($cid == ""){
            $stmt = $db->prepare("SELECT * FROM cms");
            $stmt->execute();
            $row = $stmt->fetchAll(PDO::FETCH_ASSOC);

           return $row;
      }

      else {
          $stmt = $db->prepare("SELECT * FROM cms WHERE id=? ");
          $stmt->execute(array($cid));
          $row = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if ($vars == "") {
    return $row;
        }
        else {
            $ret = [];
            foreach ($vars as $var) {
                $ret[] = [
                    $var => $row[0][$var]
                        ];
                }
            return $ret;
         }

        }
  }
</code>```

答:
if anyone facing internal server (500) error in ipage, you can chat or call them, then they will upgrade your version to 7 or above.
you can check your php version using this code.</p>

```<code><?php
phpinfo();
?>
</code>```

Title: PHP code not working on ipage hosting?

Body:
My code is working well on localhost and also on godaddy server.But on ipage I am getting "500 Internal Server error" with this code.
My local server has PHP Version 5.4.7  and my ipage hosting has PHP Version 5.3.13

         public function cms($cid,$vars) {
   global $db;
    //fetch cms data from database

          $stmt = $db->prepare("SELECT * FROM cms");
          $stmt->execute();
          $row = $stmt->fetchAll(PDO::FETCH_ASSOC);

       return $row;

   if ($cid == ""){
            $stmt = $db->prepare("SELECT * FROM cms");
            $stmt->execute();
            $row = $stmt->fetchAll(PDO::FETCH_ASSOC);

           return $row;
      }

      else {
          $stmt = $db->prepare("SELECT * FROM cms WHERE id=? ");
          $stmt->execute(array($cid));
          $row = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if ($vars == "") {
    return $row;
        }
        else {
            $ret = [];
            foreach ($vars as $var) {
                $ret[] = [
                    $var => $row[0][$var]
                        ];
                }
            return $ret;
         }

        }
  }

Body:
if anyone facing internal server (500) error in ipage, you can chat or call them, then they will upgrade your version to 7 or above.
you can check your php version using this code.

<?php
phpinfo();
?>


问:
Wordpress link and content
I'm creating a menu for wordpress, but when I click on the permalink the content stays the same. And my second dropdown does not work eather. The problem is that on my section where the content needs to be it not shows. The content just takes the last message and not the post i select on the menu. </p>

<p>https://i.gyazo.com/1698056c27baa40768659d2edab5e3d9.png
This is how it stays even if i click an other post. </p>

```<code>  <?php
  get_header();
  ?>
  <div class="menu">

    <div>
        <a href="<?php echo home_url(); ?>"><h1>Documentatie</h1></a>
    </div>

      <?php $cats = get_categories();

      foreach ($cats as $cat) {
        $cat_id= $cat->term_id;
        echo "<div class='dropdown'>";
        echo "<button onclick='myFunction()' class='dropbtn'>".$cat->name."</button>";
        echo "<div id='myDropdown' class='dropdown-content'>";

        query_posts("cat=$cat_id&post_per_page=100");

    if (have_posts()) : while (have_posts()) : the_post(); ?>

     <button class="dropbutton"><h2><a href="<?php the_permalink();?>"><?php the_title(); ?></a></h2></button>

  <?php endwhile;
?>
</div>
</div>
<?php
   else :
    echo "<p>Geen content gevonden</p>";
  endif;
   wp_reset_postdata();
 }
?>
</div>
  <div class="content">
   <h2><?php the_title(); ?></h2>
   <div class="wpcontent"><?php the_content(); ?> </div>
 </div>
<?php wp_footer(); ?>
<script>
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {

    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}
</script>
</code>```

答:
Have a look at my other 2 comments and proposed solution below, this is not a WP issue you're facing, it's JS/jQuery

```<code>    echo "<div class='dropdown'>";
    echo "<button onclick='myFunction(" . $cat->slug . ")' class='dropbtn btn-" . $cat->slug . "'>".$cat->name."</button>";
    echo "<div id='myDropdown' class='dropdown-content'>";
</code>```

And:

```<code>function myFunction(cat_slug) {
   $('.btn-' + cat_slug).show();
}
</code>```

Try that, should work :)

Title: Wordpress link and content

Body:
I'm creating a menu for wordpress, but when I click on the permalink the content stays the same. And my second dropdown does not work eather. The problem is that on my section where the content needs to be it not shows. The content just takes the last message and not the post i select on the menu.

https://i.gyazo.com/1698056c27baa40768659d2edab5e3d9.png
This is how it stays even if i click an other post.

  <?php
  get_header();
  ?>

        <a href="<?php echo home_url(); ?>">
Documentatie

      <?php $cats = get_categories();

      foreach ($cats as $cat) {
        $cat_id= $cat->term_id;
        echo "
";
        echo "<button onclick='myFunction()' class='dropbtn'>".$cat->name."</button>";
        echo "
";

        query_posts("cat=$cat_id&post_per_page=100");

    if (have_posts()) : while (have_posts()) : the_post(); ?>

     <button class="dropbutton">
<a href="<?php the_permalink();?>"><?php the_title(); ?>
</button>

  <?php endwhile;
?>

<?php
   else :
    echo "
Geen content gevonden
";
  endif;
   wp_reset_postdata();
 }
?>

<?php the_title(); ?>

<?php the_content(); ?>

<?php wp_footer(); ?>

Body:
Have a look at my other 2 comments and proposed solution below, this is not a WP issue you're facing, it's JS/jQuery

    echo "<div class='dropdown'>";
    echo "<button onclick='myFunction(" . $cat->slug . ")' class='dropbtn btn-" . $cat->slug . "'>".$cat->name."</button>";
    echo "<div id='myDropdown' class='dropdown-content'>";

And:

function myFunction(cat_slug) {
   $('.btn-' + cat_slug).show();
}

Try that, should work :)


问:
Where to find Kubernetes API credentials with AKS?
I'm trying to follow this guide to setting up a K8s cluster with external-dns' Azure DNS provider.
The guide states that:

When your Kubernetes cluster is created by ACS, a file named /etc/kubernetes/azure.json is created to store the Azure credentials for API access. Kubernetes uses this file for the Azure cloud provider.

When I create a cluster using aks (e.g. az aks create --resource-group myResourceGroup --name myK8sCluster --node-count 1 --generate-ssh-keys) this file doesn't exist.

Where do the API credentials get stored when using AKS?

Essentially I'm trying to work out where to point this command:

kubectl create secret generic azure-config-file --from-
file=/etc/kubernetes/azure.json

答:
Use this command to get credentials:

```<code>az aks get-credentials --resource-group myResourceGroup --name myK8sCluster
</code>```

Source:

https://learn.microsoft.com/en-us/azure/aks/kubernetes-walkthrough

Body:
Use this command to get credentials:

az aks get-credentials --resource-group myResourceGroup --name myK8sCluster

Source:

https://learn.microsoft.com/en-us/azure/aks/kubernetes-walkthrough


问:
The "XamlCTask" task failed unexpectedly. What to do?
I am getting this error:

The "XamlCTask" task failed unexpectedly.
  System.ArgumentException: An item with the same key has already been added.

```<code>Server stack trace:
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ParseXaml(RootNode rootNode, XmlReader reader)
   at Xamarin.Forms.Build.Tasks.XamlTask.ParseXaml(Stream stream, TypeReference typeReference)
   at Xamarin.Forms.Build.Tasks.XamlCTask.Execute(IList`1& thrownExceptions)
   at Xamarin.Forms.Build.Tasks.XamlTask.Execute()
   at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
   at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)

Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at Microsoft.Build.Framework.ITask.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext()
</code>```

I know that it is saying that the item is duplicated but I scanned whole project with Total Commander and I didn't find any duplicated file.

答: Usually happens when there is error in compiling of your xaml code. Check the code recently added.</p>

Body:
I am getting this error:

The "XamlCTask" task failed unexpectedly.
  System.ArgumentException: An item with the same key has already been added.

Server stack trace:
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ParseXaml(RootNode rootNode, XmlReader reader)
   at Xamarin.Forms.Build.Tasks.XamlTask.ParseXaml(Stream stream, TypeReference typeReference)
   at Xamarin.Forms.Build.Tasks.XamlCTask.Execute(IList`1& thrownExceptions)
   at Xamarin.Forms.Build.Tasks.XamlTask.Execute()
   at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
   at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)

Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at Microsoft.Build.Framework.ITask.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext()

I know that it is saying that the item is duplicated but I scanned whole project with Total Commander and I didn't find any duplicated file.


问:
Online code beautifier and formatter
What are the best online code beautifier and formatter out there? I'm not asking for highlighters. Any language will do.</p>

答:
CSS: code beautifier

HTML: HTML Tidy, CleanUp HTML or the general purpose Pretty Diff

Javascript: http://jsbeautifier.org/

PHP: http://beta.phpformatter.com/

SQL: http://dpriver.com/pp/sqlformat.htm

XML: http://chris.photobooks.com/xml/default.htm

Colour all: http://quickhighlighter.com/

OwnerDisplayName: Tim Boland

Title: Online code beautifier and formatter

LastEditorDisplayName: Tim Boland


答: You can use ctr+F5 to start without debugging, this will hold the screen. Alternatively you can add Console.ReadLine(); or Console.ReadKey(); at the very end of your code.</p>

Title: C# Code closes without completing the code


问:
htaccess FilesMatch regex with version
Need regex help in htaccess. I need to catch css and js file with version number before extension.

Files with 0 version has no cache.

Filename example:
example.0.js
example.0.css

Files with larger than 0 version has 1 year cache.

Filename example:
example.1.js
example.9999.css

```<code><FilesMatch "\.(css|js)$">
   ExpiresActive On
   ExpiresDefault "access plus 1 year"
   Header append Cache-Control "public"
</FilesMatch>
</code>```

This work for all js and css, but I need different cache for files *.0.js and *.0.css

答:
You can use another FilesMatch that ends with .0.css or .0.js with no-cache headers. Also change existing regex to disallow .0.(js|css):

```<code>ExpiresActive On

<FilesMatch "(?<!\.0)\.(css|js)$">
   ExpiresDefault "access plus 1 year"
   Header append Cache-Control "public"
</FilesMatch>

<FilesMatch "\.0\.(css|js)$">
   ExpiresDefault A0
   Header set Cache-Control "no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, no-transform"
   Header set Pragma "no-cache"
</FilesMatch>
</code>```

Based on your comments below here is a Apache 2.4 solution to enable caching for only [0-9]+.(css|js) excluding 0.:

```<code><If "'%{THE_REQUEST}' =~ /\.[0-9]+\.(css|js)/">
   ExpiresActive On
   ExpiresDefault "access plus 1 year"
   Header set Cache-Control "public"
</If>
<If "'%{THE_REQUEST}' =~ /\.0\.(css|js)/">
   ExpiresDefault A0
   Header set Cache-Control "no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, no-transform"
   Header set Pragma "no-cache"
</If>

RewriteEngine On
RewriteRule ^(.+)\.\d+\.(css|js)$ /$1.$2 [L,NC]
</code>```

Title: htaccess FilesMatch regex with version

Body:
Need regex help in htaccess. I need to catch css and js file with version number before extension.

Files with 0 version has no cache.

Filename example:
example.0.js
example.0.css

Files with larger than 0 version has 1 year cache.

Filename example:
example.1.js
example.9999.css

<FilesMatch "\.(css|js)$">
   ExpiresActive On
   ExpiresDefault "access plus 1 year"
   Header append Cache-Control "public"
</FilesMatch>

This work for all js and css, but I need different cache for files *.0.js and *.0.css

Body:
You can use another FilesMatch that ends with .0.css or .0.js with no-cache headers. Also change existing regex to disallow .0.(js|css):

ExpiresActive On

<FilesMatch "(?<!\.0)\.(css|js)$">
   ExpiresDefault "access plus 1 year"
   Header append Cache-Control "public"
</FilesMatch>

<FilesMatch "\.0\.(css|js)$">
   ExpiresDefault A0
   Header set Cache-Control "no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, no-transform"
   Header set Pragma "no-cache"
</FilesMatch>

Based on your comments below here is a Apache 2.4 solution to enable caching for only [0-9]+.(css|js) excluding 0.:

<If "'%{THE_REQUEST}' =~ /\.[0-9]+\.(css|js)/">
   ExpiresActive On
   ExpiresDefault "access plus 1 year"
   Header set Cache-Control "public"
</If>
<If "'%{THE_REQUEST}' =~ /\.0\.(css|js)/">
   ExpiresDefault A0
   Header set Cache-Control "no-cache, no-store, must-revalidate, max-age=0, proxy-revalidate, no-transform"
   Header set Pragma "no-cache"
</If>

RewriteEngine On
RewriteRule ^(.+)\.\d+\.(css|js)$ /$1.$2 [L,NC]


问:
bootstrap active class background color
I have this HTML for navbar and I need to change the background color for the .active class.

```<code><nav class="navbar navbar-inverse">
  <div class="container-fluid">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" id="white" href="#">TableMailerMM</a>
    </div>
    <div class="collapse navbar-collapse" id="myNavbar">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Projects</a></li>
        <li><a href="#">Contact</a></li>
      </ul>
      <!--<ul class="nav navbar-nav navbar-right">
        <li><a href="#"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
      </ul>-->
    </div>
  </div>
</nav>
</code>```

What I have tried is,

```<code>.nav.navbar-nav li:active{
   background-color: #ff812c;
}
</code>```

but it doesn't work, any ideas?

答:
https://jsfiddle.net/94yqf9sa/4/

:active is about state of element.

.active is about class of element.

Title: bootstrap active class background color

Body:
I have this HTML for navbar and I need to change the background color for the .active class.

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

      </button>
      TableMailerMM

Home

About

Projects

Contact

What I have tried is,

.nav.navbar-nav li:active{
   background-color: #ff812c;
}

but it doesn't work, any ideas?


问:
Convert Binary BIT to an Index Number for Array - Swift
I need a way of determining or mapping a Binary BIT when set to an Index number for an array in Swift.

For example, I have have a uInt64 that has a BIT set 0b0010 0000 0000 ..., I would like to translate it in terms of an Index number for an array that ranges  from 0 to 39.

So the msb would be 0 and the lsb would be 39

Also, I need a way of identifying the most recent bit that has been switched.

For example, say the first is: 0b0010 0000 0000 .... and the second is 0x0010 0010 0000 .... until the integer is at its highest value i.e. 0xFFFFFFFF..

UPDATE:

After much helpful feedback, I have another problem which is identifying as to whether a variable has changed in Swift:

```<code>var changedValue: UInt64? {
                        willSet(newValue : UInt64) {
                            guard let oldValue = value, new = newValue else { return }
                            if oldValue != new { oldValue ^ newValue }
                            }
                        }
</code>```

It doesn't work with UInt64

答:
The XOR operator can be used to identify which bits have changed:

```<code>let oldValue: UInt64 = 0b0010_0000_0000
let newValue: UInt64 = 0b0010_0010_0000

let diff = oldValue ^ newValue
</code>```

and the ffsll() ("find first set, long long") function computes the position of the least significant bit which is set in the difference:

```<code>let bitpos = Int(ffsll(Int64(bitPattern: diff)))
print(bitpos) // 6
</code>```

If a change in the least significant bit corresponds to index 39
in your array then compute

```<code>let index = 40 - bitpos
</code>```

Body:
I need a way of determining or mapping a Binary BIT when set to an Index number for an array in Swift.

For example, I have have a uInt64 that has a BIT set 0b0010 0000 0000 ..., I would like to translate it in terms of an Index number for an array that ranges  from 0 to 39.

So the msb would be 0 and the lsb would be 39

Also, I need a way of identifying the most recent bit that has been switched.

For example, say the first is: 0b0010 0000 0000 .... and the second is 0x0010 0010 0000 .... until the integer is at its highest value i.e. 0xFFFFFFFF..

UPDATE:

After much helpful feedback, I have another problem which is identifying as to whether a variable has changed in Swift:

var changedValue: UInt64? {
                        willSet(newValue : UInt64) {
                            guard let oldValue = value, new = newValue else { return }
                            if oldValue != new { oldValue ^ newValue }
                            }
                        }

It doesn't work with UInt64

Body:
The XOR operator can be used to identify which bits have changed:

let oldValue: UInt64 = 0b0010_0000_0000
let newValue: UInt64 = 0b0010_0010_0000

let diff = oldValue ^ newValue

and the ffsll() ("find first set, long long") function computes the position of the least significant bit which is set in the difference:

let bitpos = Int(ffsll(Int64(bitPattern: diff)))
print(bitpos) // 6

If a change in the least significant bit corresponds to index 39
in your array then compute

let index = 40 - bitpos


问:
SSRS selecting results based on comma delimited list with like statement
Based on my question SSRS selecting results based on comma delimited list

Is it possible to do this, but instead of doing this as a an EQUALS, can it be done as below?

      WHERE value like 'abc%','def%'

One thing to note is that the % is not included in the list.

答:
One option is to split the passed in SSRS variable (CSV) into a table and join on that

```<code>DECLARE @tab TABLE (Col1 NVARCHAR(200))
INSERT INTO @tab (Col1)
VALUES (N'abc'),(N'def'),(N'xyz'),(N'nop'),(N'ghi'),(N'lmn')

DECLARE @substrings NVARCHAR(200) = 'abc,def,ghi'

;WITH cteX
AS(   --dynamically split the string
    SELECT Strings = y.i.value('(./text())[1]', 'nvarchar(4000)')
    FROM
    (
    SELECT x = CONVERT(XML, '<i>'
        + REPLACE(@substrings, ',', '</i><i>')
        + '</i>').query('.')
    ) AS a CROSS APPLY x.nodes('i') AS y(i)
)
SELECT
    T.*
FROM @tab   T
INNER JOIN cteX X ON X.Strings = T.Col1
</code>```

gives the following result

Body:
One option is to split the passed in SSRS variable (CSV) into a table and join on that

DECLARE @tab TABLE (Col1 NVARCHAR(200))
INSERT INTO @tab (Col1)
VALUES (N'abc'),(N'def'),(N'xyz'),(N'nop'),(N'ghi'),(N'lmn')

DECLARE @substrings NVARCHAR(200) = 'abc,def,ghi'

;WITH cteX
AS(   --dynamically split the string
    SELECT Strings = y.i.value('(./text())[1]', 'nvarchar(4000)')
    FROM
    (
    SELECT x = CONVERT(XML, '<i>'
        + REPLACE(@substrings, ',', '</i><i>')
        + '</i>').query('.')
    ) AS a CROSS APPLY x.nodes('i') AS y(i)
)
SELECT
    T.*
FROM @tab   T
INNER JOIN cteX X ON X.Strings = T.Col1

gives the following result


问:
Is checking for true explicity bad by design?
Is it considered bad to explicitly check for the boolean true. Would it be better to do a simple if(success) ?

I've seen various jokes made about how if (someBoolean === true) is horrible code in a strongly typed language but is it also considered bad in weakly typed languages?

This would apply for any weakly typed language that does type coercion on an if statement.

A specific example would be :

```<code>var onSuccess = function (JSONfromServer) {
    // explicitly check for the boolean value `true`
    if (JSONfromServer === true) {
         // do some things
    }
}

// pass it to an ajax as a callback
doSomeAjax(onSuccess);
</code>```

[Edit]

In this particular case the success variable is any valid JSON returned from a server. So it could be anything. if its the boolean true then a success happened. If it's some error handling object then it will be handled. If it's something else then it will probably be handled quietly.

The question was is getting the server to return true as JSON and checking for a good way to handle the case where the action succeeded.

I wanted to avoid being specific to JavaScript & AJAX though.

答:
With Javascript its worth knowing that beyond boolean true and false, values can be truthy and falsy.

Consider:

```<code>if (false)     // evaluates to false.
if (0)         // evaluates to false, 0 is falsy.
if ("")        // evaluates to false, empty strings are falsy.
if (null)      // evaluates to false, null values are falsy.
if (undefined) // evaluates to false, undefined values are falsy.
if (NaN)       // evaluates to false, NaN is falsy.
</code>```

All other values for objects are truthy.

If truthy and falsy values are leading to errors in your logic, you should consider explicitly using === and !== operators to ensure objects are compared by type and value.

Body:
Is it considered bad to explicitly check for the boolean true. Would it be better to do a simple if(success) ?

I've seen various jokes made about how if (someBoolean === true) is horrible code in a strongly typed language but is it also considered bad in weakly typed languages?

This would apply for any weakly typed language that does type coercion on an if statement.

A specific example would be :

var onSuccess = function (JSONfromServer) {
    // explicitly check for the boolean value `true`
    if (JSONfromServer === true) {
         // do some things
    }
}

// pass it to an ajax as a callback
doSomeAjax(onSuccess);

[Edit]

In this particular case the success variable is any valid JSON returned from a server. So it could be anything. if its the boolean true then a success happened. If it's some error handling object then it will be handled. If it's something else then it will probably be handled quietly.

The question was is getting the server to return true as JSON and checking for a good way to handle the case where the action succeeded.

I wanted to avoid being specific to JavaScript & AJAX though.

Body:
With Javascript its worth knowing that beyond boolean true and false, values can be truthy and falsy.

Consider:

if (false)     // evaluates to false.
if (0)         // evaluates to false, 0 is falsy.
if ("")        // evaluates to false, empty strings are falsy.
if (null)      // evaluates to false, null values are falsy.
if (undefined) // evaluates to false, undefined values are falsy.
if (NaN)       // evaluates to false, NaN is falsy.

All other values for objects are truthy.

If truthy and falsy values are leading to errors in your logic, you should consider explicitly using === and !== operators to ensure objects are compared by type and value.


问:
Way to execute Google Standalone Script directly from Drive
Well, I've been reading the documentation for a long time but, as per usual, it's really unclear...

I'm developing a Google Script with the Script Editor that is already working as expected (it have nothing to see with any G suite program but with Drive).

By now, the only way to execute it is opening the script editor and press on the "play" button or the "execute" bar and press on the function.

Obviously this is not a solution since anyone from the bussines could modify/see the code.

So the question is this: how can I make from this script something like an "exe" that I just have to double ckick (its obviously located at Drive) and it executes the script?

I saw this but seems it says no way to do it except from opening the code and execute from the google app script editor...

答:
From what I understand of your requirements the only way would be to deploy your script as a web app with a minimal user interface, just a short message to confirm proper execution for example.

You will never have a "local" executable file since everything in Apps Script is done on google's servers, not in our computers. Instead you will have an url... (with the advantage that it is completely OS independent ! )

The script will remain private unless you share it and you'll be able to choose who can use that url.


问:
Java ANTLR 4 Listener enter-methods don't get called
I'm shamelessly stealing the (slightly edited) title of another question as I'm having the same problem, and said question hasn't been answered yet (it's almost a year old).

Summary: the enter*** methods of my listener doesn't work. I'm able to increment a counter with the visitTerminal method, and I've tested enterEveryRule (as in the other question) which also works. But enterVariableDeclaration isn't doing anything, and even enterInit isn't called.

For clarity: init is my grammar's top rule. I'm able to get a graphical representation of this tree/rule when using TestRig.

The code for my listener:

```<code>class MyListener extends MyGrammarBaseListener {

    private int terminalCounter = 0;
    private List<String> variables = new ArrayList<>();

    @Override
    public void visitTerminal(TerminalNode node) {
        terminalCounter++;
    }

    @Override
    public void enterVariableDeclaration(MyGrammarParser.VariableDeclarationContext ctx) {
        variables.add(ctx.getText());
    }

    @Override
    public void enterInit(JavaExamGrammarParser.InitContext ctx) {
        System.out.println("init");
    }

    int getTerminalNodeCount() {
        return terminalCounter;
    }

    List<String> getVariables() {
        return variables;
    }

}
</code>```

The output is simply:

```<code>143
0
</code>```

where 143 is the number of terminal nodes and 0 is the size of variables; "init" isn't printed, even if that node/rule is definitely visited.

And for the tree in question, there should be at least a handful of declarations (can verify this by looking at the graphical tree).

Any help or tips?

Thanks in advance!

答:
In some ways, just posting to StackOverflow helps, even if no answer is provided.

Especially when the problem is your own doing...

There was nothing wrong with Antlr (I'm using 4.7, btw) there was nothing wrong with the grammar, and there was nothing wrong with the listener. It turns out that the project has two very similar grammars with two very similar names; I was using the wrong match-up of grammars and listeners.

Body:
I'm shamelessly stealing the (slightly edited) title of another question as I'm having the same problem, and said question hasn't been answered yet (it's almost a year old).

Summary: the enter*** methods of my listener doesn't work. I'm able to increment a counter with the visitTerminal method, and I've tested enterEveryRule (as in the other question) which also works. But enterVariableDeclaration isn't doing anything, and even enterInit isn't called.

For clarity: init is my grammar's top rule. I'm able to get a graphical representation of this tree/rule when using TestRig.

The code for my listener:

class MyListener extends MyGrammarBaseListener {

    private int terminalCounter = 0;
    private List<String> variables = new ArrayList<>();

    @Override
    public void visitTerminal(TerminalNode node) {
        terminalCounter++;
    }

    @Override
    public void enterVariableDeclaration(MyGrammarParser.VariableDeclarationContext ctx) {
        variables.add(ctx.getText());
    }

    @Override
    public void enterInit(JavaExamGrammarParser.InitContext ctx) {
        System.out.println("init");
    }

    int getTerminalNodeCount() {
        return terminalCounter;
    }

    List<String> getVariables() {
        return variables;
    }

}

The output is simply:

143
0

where 143 is the number of terminal nodes and 0 is the size of variables; "init" isn't printed, even if that node/rule is definitely visited.

And for the tree in question, there should be at least a handful of declarations (can verify this by looking at the graphical tree).

Any help or tips?

Thanks in advance!


问:
How to get full value of number input in Firefox with zeros
Firefox shows just 1 when I type 1,00 in the input. All other browsers I tested are showing 1,00. How can I read the full value of the input in Firefox with the zeros after the comma? The type of the input has to be number and can't be text.

$("#input").keyup(function() {
  $("#output").text($("#input").val());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="input" min="0.00" step="0.01" max="999.99">
<p id="output"></p></code>```

Edit: For me it doesn't matter if decimal mark is a comma or a period.
See the Screenshot of the difference between Chrome and Firefox.

答:
let output = document.getElementById('output');

document.getElementById('input').addEventListener('input', function (e) {
  output.innerText = e.currentTarget.value.replace('.', ',');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" id="input" min="0.00" step="0.01" max="999.99">
<p id="output"></p></code>```

Body:
Firefox shows just 1 when I type 1,00 in the input. All other browsers I tested are showing 1,00. How can I read the full value of the input in Firefox with the zeros after the comma? The type of the input has to be number and can't be text.

$("#input").keyup(function() {
  $("#output").text($("#input").val());
});

<input type="number" id="input" min="0.00" step="0.01" max="999.99">

Edit: For me it doesn't matter if decimal mark is a comma or a period.
See the Screenshot of the difference between Chrome and Firefox.

Body:
let output = document.getElementById('output');

document.getElementById('input').addEventListener('input', function (e) {
  output.innerText = e.currentTarget.value.replace('.', ',');
});

<input type="number" id="input" min="0.00" step="0.01" max="999.99">
<p id="output"></p>


问:
How to transfer databases and site contents
I own a website with 20 GB data on it Now I decided to change the Hosting compnay .
I'm Moving to Russian VPS so is there a way to transfer the contents of my website to the Russian VPS without uploading them again .

Is there a service that does this.
I heard that there is a way to do this using shell access (BUT what is shell access and how it works)
thanx in advance guys

答:
If your current provider supports FTP, you can issue FTP commands from your new VPS to the current FTP site. If your data is in DB - backup and transfer backup.

You can't avoid 40Gb of transfer (20 out from old site and 20 in new one).

This is one of the reasons that makes Amazon S3 a good thing.

OwnerDisplayName: umtoz

OwnerDisplayName: dmajkic


问:
Problem with validates_uniqueness_of
I'm using rails 2.3.5 and Authlogic in our website, and I have been getting errors on the database through hoptoad of users with duplicated emails trying to be saved. The problem is, obviously I have the validates_uniqueness_of :email on the model.

On my tests here in development I get the expected validation error and the user is not saved, but in production, I keep getting this errors on the DB layer.

I've tested with case sensitive emails and it also validated correctly.

I've checked and the class and there is no attr_accessor or any other attribute override, and I don't think Authlogic would do it in a wrong way...

What could be happening in production? Are there any cases where rails validates doesn't work?

答: Just a guess but could it be that your email column allows null, validates_uniqueness_of is ignoring nil (or blank) values and that your users are trying to register without specifying their email addresses?</p>

Title: Problem with validates_uniqueness_of


问:
react-select-fast-filter-options filter does not work
I have been trying to use react-select-fast-filter-options by passing props.options, but the filtering does not happen. All the options are getting rendered but the filter doesn't work.

I am also getting a warning:
Warning: getDefaultProps is only used on classic React.createClass definitions. Use a static property named defaultProps instead.

This is how I am trying to use the fast-filter:

```<code>import React, { Component } from 'react';
import VirtualizedSelect, { Value } from 'react-virtualized-select';
import createFilterOptions from 'react-select-fast-filter-options';
import 'react-select/dist/react-select.css';
import styles from './CategoryDropdown.less';
import CategoryDropdownOption from './CategoryDropdownOption';
import CategoryDropdownValue from './CategoryDropdownValue';

class CategoryDropdown extends Component {

  constructor(props, context) {
    super(props, context);
    **const filterOptions = createFilterOptions({
      labelKey: 'code',
      options: props.options
    });**
    this.sortOptions = this.sortOptions.bind(this);
    this.setValue = this.setValue.bind(this);
    this.clearValue = this.clearValue.bind(this);
    const dValue = props.defaultValue ? props.defaultValue : {};
    this.state = { value: dValue, options: [], selectedOption:{}, filterOptions };
  }

  componentDidMount() {
    this.sortOptions(this.props.options);
    this.setValue('');
  }

  componentWillReceiveProps(nextProps) {
    this.sortOptions(nextProps.options);
  }

  clearValue() {
    this.setState({ value: '' });
    this.setState({selectedOption:{}});
  }

    return (
      <div
        key={key}
        className={classNames.join(' ')}
        onClick={() => {
          focusOption(option);
          selectValue(option);
        }}
        onMouseDown={(e) => {
          e.preventDefault();
          e.stopPropagation();
          focusOption(option);
          selectValue(option);
        }}
        onMouseEnter={() => { focusOption(option); }}
        style={style}
        title={option.label}>
        <div className="categoryOptionType">
          <span className={option.categoryName}>{option.categoryDisplayName}</span>
        </div>
        <div className="optionLabelContainer">
          <span className="optionLabel">{value}</span>
        </div>
      </div>
    );
  }

  render() {
    const {filterOptions} = this.state;
    return (
      <VirtualizedSelect
        simpleValue
        clearable={true}
        label='code'
        name="form-field-name"
        multi={this.props.multi}
        optionHeight={20}
        onChange={this.setValue}
        **filterOptions={filterOptions}**
        options={this.state.options}
        searchable={true}
        value={this.state.selectedOption}
        optionRenderer={this.virtualOptionRenderer}
        valueComponent={this.props.emptyValueComponent ? Value : CategoryDropdownValue}
        className={this.props.className || 'categoryDropdown'}
        optionClassName={this.props.optionClassName || 'categoryOption'}
        placeholder={this.props.placeholder || 'Start typing to search'}
        autosize={this.props.autosize !== false}
        //matchProp="label"
      />

    );
  }
}

export default CategoryDropdown;
</code>```

答:
I am not sure about your ** tag, seems it is used to comment the code.

However, if we skip that ** tag then your code is good, except you are filtering your filterOptions: filterOptions = createFilterOptions({ ... }) within the constructor which is ONLY executed ONCE when the component is initialized.

Put this block on componentWillReceiveProps should fix your problem.

```<code>componentWillReceiveProps(nextProps) {
  const filterOptions = createFilterOptions({
    labelKey: 'code',
    options: nextProps.options
  });
  this.setState({filterOptions});
  this.sortOptions(nextProps.options);
}
</code>```

Body:
I have been trying to use react-select-fast-filter-options by passing props.options, but the filtering does not happen. All the options are getting rendered but the filter doesn't work.

I am also getting a warning:
Warning: getDefaultProps is only used on classic React.createClass definitions. Use a static property named defaultProps instead.

This is how I am trying to use the fast-filter:

import React, { Component } from 'react';
import VirtualizedSelect, { Value } from 'react-virtualized-select';
import createFilterOptions from 'react-select-fast-filter-options';
import 'react-select/dist/react-select.css';
import styles from './CategoryDropdown.less';
import CategoryDropdownOption from './CategoryDropdownOption';
import CategoryDropdownValue from './CategoryDropdownValue';

class CategoryDropdown extends Component {

  constructor(props, context) {
    super(props, context);
    **const filterOptions = createFilterOptions({
      labelKey: 'code',
      options: props.options
    });**
    this.sortOptions = this.sortOptions.bind(this);
    this.setValue = this.setValue.bind(this);
    this.clearValue = this.clearValue.bind(this);
    const dValue = props.defaultValue ? props.defaultValue : {};
    this.state = { value: dValue, options: [], selectedOption:{}, filterOptions };
  }

  componentDidMount() {
    this.sortOptions(this.props.options);
    this.setValue('');
  }

  componentWillReceiveProps(nextProps) {
    this.sortOptions(nextProps.options);
  }

  clearValue() {
    this.setState({ value: '' });
    this.setState({selectedOption:{}});
  }

    return (

 {
          focusOption(option);
          selectValue(option);
        }}
        onMouseDown={(e) => {
          e.preventDefault();
          e.stopPropagation();
          focusOption(option);
          selectValue(option);
        }}
        onMouseEnter={() => { focusOption(option); }}
        style={style}
        title={option.label}>

          {option.categoryDisplayName}

          {value}

    );
  }

  render() {
    const {filterOptions} = this.state;
    return (
      <VirtualizedSelect
        simpleValue
        clearable={true}
        label='code'
        name="form-field-name"
        multi={this.props.multi}
        optionHeight={20}
        onChange={this.setValue}
        **filterOptions={filterOptions}**
        options={this.state.options}
        searchable={true}
        value={this.state.selectedOption}
        optionRenderer={this.virtualOptionRenderer}
        valueComponent={this.props.emptyValueComponent ? Value : CategoryDropdownValue}
        className={this.props.className || 'categoryDropdown'}
        optionClassName={this.props.optionClassName || 'categoryOption'}
        placeholder={this.props.placeholder || 'Start typing to search'}
        autosize={this.props.autosize !== false}
        //matchProp="label"
      />

    );
  }
}

export default CategoryDropdown;

Body:
I am not sure about your ** tag, seems it is used to comment the code.

However, if we skip that ** tag then your code is good, except you are filtering your filterOptions: filterOptions = createFilterOptions({ ... }) within the constructor which is ONLY executed ONCE when the component is initialized.

Put this block on componentWillReceiveProps should fix your problem.

componentWillReceiveProps(nextProps) {
  const filterOptions = createFilterOptions({
    labelKey: 'code',
    options: nextProps.options
  });
  this.setState({filterOptions});
  this.sortOptions(nextProps.options);
}


问:
Join two Collections with LINQ with Contains operator
I have following two classes

```<code>Class C
{
public Guid Id{get;set;}
public string Type{get;set;}
}

Class D
{
  public List<Guid> CIds {get;set;}
  public string Type {get;set;}
}

 var D_Collection = new List<D>();
 var C_Collection = new List<C>();

 // SET The C_Collection.Type On the Basis of D_Collection
 // If C.Id exist in D.CIds then C.Type = D.Type
</code>```

I want to Set C.Type bases on the Criteria Given above in Comments

I tried following but it's not working

```<code> var temp = (from x in D_Collection
                        from y in C_Collection
                        where x.CIds.Contains(y.Id)
                        select new {
                               Id = y.Id,
                               Type = x.Type
                }).ToList();
</code>```

答:
I think it would be simpler to do this:

var c_comparisons = D_Collection.SelectMany(x => x.CIds.Select(y => new C { Id = y, Type = x.Type }));

foreach (var comparison in c_comparisons)
{
    var c = C_Collection.FirstOrDefault(x => x.Id == comparison.Id);

    if (c != null)
    {
        c.Type = comparison.Type;
    }
}
```

Body:
I have following two classes

Class C
{
public Guid Id{get;set;}
public string Type{get;set;}
}

Class D
{
  public List<Guid> CIds {get;set;}
  public string Type {get;set;}
}

 var D_Collection = new List<D>();
 var C_Collection = new List<C>();

 // SET The C_Collection.Type On the Basis of D_Collection
 // If C.Id exist in D.CIds then C.Type = D.Type

I want to Set C.Type bases on the Criteria Given above in Comments

I tried following but it's not working

 var temp = (from x in D_Collection
                        from y in C_Collection
                        where x.CIds.Contains(y.Id)
                        select new {
                               Id = y.Id,
                               Type = x.Type
                }).ToList();