问:
MySQL auto_increment getting crazy after massive INSERT
I have created a new table (my_new_table) with an auto increment PK.

```<code>SELECT `AUTO_INCREMENT`
FROM  INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'myschema'
AND   TABLE_NAME   = 'my_new_table';
</code>```

Result: 1, ok.

I INSERT into that table 871 values from another table. Then I make any of those two queries:

```<code>SELECT MAX(id) FROM my_new_table;
SELECT count(*) FROM my_new_table;
</code>```

Result: 871. ok.

But when I check the AUTO_INCREMENT again:

```<code>SELECT `AUTO_INCREMENT`
FROM  INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'myschema'
AND   TABLE_NAME   = 'my_new_table';
</code>```

Result: 1024.

Why the AUTO_INCREMENT value is 1024 and not 872?

Thanks in advance

答:
It may possible due to Mysql 2 variable auto_increment_increment and auto_increment_offset values of both these variables are 1 by default. you had made any change of the value.

So please make that value of both this variable auto_increment_increment
and auto_increment_offset by 1.

```<code>SET @@auto_increment_increment=1;
SET @@auto_increment_offset=1;
</code>```

Body:
I have created a new table (my_new_table) with an auto increment PK.

SELECT `AUTO_INCREMENT`
FROM  INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'myschema'
AND   TABLE_NAME   = 'my_new_table';

Result: 1, ok.

I INSERT into that table 871 values from another table. Then I make any of those two queries:

SELECT MAX(id) FROM my_new_table;
SELECT count(*) FROM my_new_table;

Result: 871. ok.

But when I check the AUTO_INCREMENT again:

SELECT `AUTO_INCREMENT`
FROM  INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'myschema'
AND   TABLE_NAME   = 'my_new_table';

Result: 1024.

Why the AUTO_INCREMENT value is 1024 and not 872?

Thanks in advance

Body:
It may possible due to Mysql 2 variable auto_increment_increment and auto_increment_offset values of both these variables are 1 by default. you had made any change of the value.

So please make that value of both this variable auto_increment_increment
and auto_increment_offset by 1.

SET @@auto_increment_increment=1;
SET @@auto_increment_offset=1;


来源: stackexchange

问:
Using Pact JUnit Rule versus Using the Pact DSL directly?
I want to understand why is the below scenario occurring?
Issue : The Junit test fails with HttpConnect exception if I use Pact Junit Rule. But the same test passes and pact file is generated if I use the Pact DSL Directly. Can someone enlighten me why and how to get going with the Pact Junit Rule?

Code using Pact Junit Rule :(This fails with HttpHostConnectException)

```<code>@Rule
     public PactProviderRule rule = new PactProviderRule("DrivePOC", PactSpecVersion.V2, this);

     /*Setting up what your expectations are*/
        @Pact(provider = "P1",consumer = "C1")
        public PactFragment createFragment(PactDslWithProvider builder)
        {

            PactFragment pactFragment = ConsumerPactBuilder
                    .consumer("C1")
                    .hasPactWith("P1")
                    .uponReceiving("load Files Data")
                        .path("/loadData")
                        .method("POST")
                        .body("{\"givefileId\": \"abc\"}")
                    .willRespondWith()
                        .status(200)
                        .body("{\"fileId\": \"abcfileId1234\"}")
                        .toFragment();
            return pactFragment;

        }

        /*Test similar to Junit, verifies if the test are ok and the responses are as per expectations set in the createFragment*/
        @Test
        @PactVerification(value = "P1")
        public void runTest() throws IOException
        {
            MockProviderConfig config = MockProviderConfig.createDefault();
            Map expectedResponse = new HashMap();
            expectedResponse.put("fileId", "abcfileId1234");
            try {
                Assert.assertEquals(new ProviderClient(config.url()).helloToDrive("{\"givefileId\": \"abc\"}"),
                        expectedResponse);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

              }
</code>```

Code using Pact DSL Directly(This Junit passes and generate Pact file successfully)

```<code>@Test
        public void testPact() {
            PactFragment pactFragment = ConsumerPactBuilder
                .consumer("C1")
                .hasPactWith("P1")
                .uponReceiving("load Files Data")
                    .path("/loadData")
                    .method("POST")
                    .body("{\"givefileId\": \"abc\"}")
                .willRespondWith()
                    .status(200)
                    .body("{\"fileId\": \"abcfileId1234\"}")
                    .toFragment();

            MockProviderConfig config = MockProviderConfig.createDefault();
            VerificationResult result = pactFragment.runConsumer(config, new TestRun() {
                public void run(MockProviderConfig config) throws Throwable {
                    Map expectedResponse = new HashMap();
                    expectedResponse.put("fileId", "abcfileId1234");
                    try {
                        Assert.assertEquals(new ProviderClient(config.url()).helloToHueDrive("{\"givefileId\": \"abc\"}"),
                                expectedResponse);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });

            if (result instanceof PactError) {
                throw new RuntimeException(((PactError)result).error());
            }

            Assert.assertEquals(ConsumerPactTest.PACT_VERIFIED, result);
    }
</code>```

答: I could make my annotations work, after changing Junit version from 4.8 to 4.9.</p>

ContentLicense: CC BY-SA 3.0

Body:
I want to understand why is the below scenario occurring?
Issue : The Junit test fails with HttpConnect exception if I use Pact Junit Rule. But the same test passes and pact file is generated if I use the Pact DSL Directly. Can someone enlighten me why and how to get going with the Pact Junit Rule?

Code using Pact Junit Rule :(This fails with HttpHostConnectException)

@Rule
     public PactProviderRule rule = new PactProviderRule("DrivePOC", PactSpecVersion.V2, this);

     /*Setting up what your expectations are*/
        @Pact(provider = "P1",consumer = "C1")
        public PactFragment createFragment(PactDslWithProvider builder)
        {

            PactFragment pactFragment = ConsumerPactBuilder
                    .consumer("C1")
                    .hasPactWith("P1")
                    .uponReceiving("load Files Data")
                        .path("/loadData")
                        .method("POST")
                        .body("{\"givefileId\": \"abc\"}")
                    .willRespondWith()
                        .status(200)
                        .body("{\"fileId\": \"abcfileId1234\"}")
                        .toFragment();
            return pactFragment;

        }

        /*Test similar to Junit, verifies if the test are ok and the responses are as per expectations set in the createFragment*/
        @Test
        @PactVerification(value = "P1")
        public void runTest() throws IOException
        {
            MockProviderConfig config = MockProviderConfig.createDefault();
            Map expectedResponse = new HashMap();
            expectedResponse.put("fileId", "abcfileId1234");
            try {
                Assert.assertEquals(new ProviderClient(config.url()).helloToDrive("{\"givefileId\": \"abc\"}"),
                        expectedResponse);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

              }

Code using Pact DSL Directly(This Junit passes and generate Pact file successfully)

@Test
        public void testPact() {
            PactFragment pactFragment = ConsumerPactBuilder
                .consumer("C1")
                .hasPactWith("P1")
                .uponReceiving("load Files Data")
                    .path("/loadData")
                    .method("POST")
                    .body("{\"givefileId\": \"abc\"}")
                .willRespondWith()
                    .status(200)
                    .body("{\"fileId\": \"abcfileId1234\"}")
                    .toFragment();

            MockProviderConfig config = MockProviderConfig.createDefault();
            VerificationResult result = pactFragment.runConsumer(config, new TestRun() {
                public void run(MockProviderConfig config) throws Throwable {
                    Map expectedResponse = new HashMap();
                    expectedResponse.put("fileId", "abcfileId1234");
                    try {
                        Assert.assertEquals(new ProviderClient(config.url()).helloToHueDrive("{\"givefileId\": \"abc\"}"),
                                expectedResponse);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });

            if (result instanceof PactError) {
                throw new RuntimeException(((PactError)result).error());
            }

            Assert.assertEquals(ConsumerPactTest.PACT_VERIFIED, result);
    }


问:
Stylecop tells me to add this keyword, but it's redundant - any performance implications?
I use Stylecop for Resharper and whenever I call something in my class, Stylecop tells me to use the this keyword. But the IDE says this is redundant code (which it sure is), so why should I use the this keyword?

Does redundant code mean its not needed (obviously) and the compiler won't even do anything with the this keyword? So I assume the this keyword is just for clarity.

Also, with the CLR, do things like this fall consistently across languages? So if the answer is that the compiler doesn't even touch the this keyword and it is just for presentation and clarity, then the same is true for VB.NET? I assume it is all for clarity as stylecop keeps an eye on this and Fxcop (which I will use later on) keeps an eye on my code's quality from a technical point of view.

Thanks

答:
It is just for clarity, and one can argue about what is better. Python doesn't support omitting the "self" identifier at all.

Also, with the CLR, do things like this fall consistently across languages? So if the answer is that the compiler doesn't even touch the this keyword and it is just for presentation and clarity, then the same is true for VB.NET?

In JVM for sure (and also for CLR, I'm almost sure) the code for the "this" keyword is always generated, even if that is omitted from the source - so it's like if the this keyword is always added. So, I don't think that any .NET compiler could generate different output, so there can't be a performance penalty.

Then, it depends on the language. For instance JScript (and even JScript.NET) does not allow to omit "this", like Python, because there are functions (so "this.a()" is a method invocation, "a()" is a function invocation), and because the compiler does not know the members of any types - they're only known at runtime (well, this is not an impossible problem to solve indeed, the other issue is more relevant).

OwnerDisplayName: GSS

OwnerDisplayName: Blaisorblade

ContentLicense: CC BY-SA 2.5


问:
locating jar file in $PATH environment variable for java -jar command
I want to run a simple executable jar like this:

```<code>java -jar /path/to/my/jar/myjar.jar
</code>```

However, i have to put that absolute path every time I want to run it. Is there a way to tell the OS to look for the jar in $PATH environment variable?

答: You could use CLASSPATH environment variable instead</p>

Body:
I want to run a simple executable jar like this:

java -jar /path/to/my/jar/myjar.jar

However, i have to put that absolute path every time I want to run it. Is there a way to tell the OS to look for the jar in $PATH environment variable?


问:
RESTfully fetch a JSON list
I am writing a simple RESTful controller. So far, I am able to retrieve a single JSON object of type Employee by calling http://127.0.0.1:8080/api/employee/5. But I am NOT able to retrieve a collection of Employee objects when calling http://127.0.0.1:8080/api/employee/. This gets me the following error.

```<code><Error>
<Message>
No HTTP resource was found that matches the request URI 'http://127.0.0.1:8080/api/employee/'.
</Message>
<MessageDetail>
No type was found that matches the controller named 'employee'.
</MessageDetail>
</Error>
</code>```

Same thing happens when I am trying to save a new employee.

EmployeeApiController.cs

```<code>[RoutePrefix("api/employee")]
public class EmployeeApiController : ApiController
{

    readonly EmployeePersistence persistence;

    public EmployeeApiController()
    {
        persistence = new EmployeePersistence();
    }

    [HttpPost]
    public void Post([FromBody] Employee employee) // DOESN'T WORK
    {
        // saving id for the debugging purposes
        long id = persistence.SaveEmployee(employee);
    }

    [HttpGet]
    [Route("{id:long}")]
    public IHttpActionResult GetEmployee(long id) // WORKS
    {
        return Ok(
            new Employee("Bobby", "Smedley",
                         "London", "Teheran",
                         EmployeeGender.M,
                         DepartmentCode.D_21570,
                         "12345678901"));
    }

    [HttpGet]
    public IHttpActionResult ListEmployees() // DOESN'T WORK
    {
        return Ok(
            new List<Employee> {
                new Employee("Bobby", "Smedley",
                         "London", "Teheran",
                         EmployeeGender.M,
                         DepartmentCode.D_21570,
                         "12345678901"),

                new Employee("Robbie", "Medleigh",
                         "Liverpool", "Teheran",
                         EmployeeGender.M,
                         DepartmentCode.D_21570,
                         "12345678901")});
    }
}
</code>```

Any idea why get per ID works, but get a list, and post don't work here?

UPDATE
Adding Route above the ListEmployees led to the following issue:

```<code><Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace/>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Type 'MyWebService.Models.Employee' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. Alternatively, you can ensure that the type is public and has a parameterless constructor - all public members of the type will then be serialized, and no attributes will be required.
</ExceptionMessage>
<ExceptionType>
System.Runtime.Serialization.InvalidDataContractException
</ExceptionType>
</code>```

RouteConfig.cs

```<code>public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}
</code>```

答:
You can add attribute [Route] on ListEmployees action or check your route table

```<code>routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);
</code>```

Title: RESTfully fetch a JSON list

Body:
I am writing a simple RESTful controller. So far, I am able to retrieve a single JSON object of type Employee by calling http://127.0.0.1:8080/api/employee/5. But I am NOT able to retrieve a collection of Employee objects when calling http://127.0.0.1:8080/api/employee/. This gets me the following error.

<Error>
<Message>
No HTTP resource was found that matches the request URI 'http://127.0.0.1:8080/api/employee/'.
</Message>
<MessageDetail>
No type was found that matches the controller named 'employee'.
</MessageDetail>
</Error>

Same thing happens when I am trying to save a new employee.

EmployeeApiController.cs

[RoutePrefix("api/employee")]
public class EmployeeApiController : ApiController
{

    readonly EmployeePersistence persistence;

    public EmployeeApiController()
    {
        persistence = new EmployeePersistence();
    }

    [HttpPost]
    public void Post([FromBody] Employee employee) // DOESN'T WORK
    {
        // saving id for the debugging purposes
        long id = persistence.SaveEmployee(employee);
    }

    [HttpGet]
    [Route("{id:long}")]
    public IHttpActionResult GetEmployee(long id) // WORKS
    {
        return Ok(
            new Employee("Bobby", "Smedley",
                         "London", "Teheran",
                         EmployeeGender.M,
                         DepartmentCode.D_21570,
                         "12345678901"));
    }

    [HttpGet]
    public IHttpActionResult ListEmployees() // DOESN'T WORK
    {
        return Ok(
            new List<Employee> {
                new Employee("Bobby", "Smedley",
                         "London", "Teheran",
                         EmployeeGender.M,
                         DepartmentCode.D_21570,
                         "12345678901"),

                new Employee("Robbie", "Medleigh",
                         "Liverpool", "Teheran",
                         EmployeeGender.M,
                         DepartmentCode.D_21570,
                         "12345678901")});
    }
}

Any idea why get per ID works, but get a list, and post don't work here?

UPDATE
Adding Route above the ListEmployees led to the following issue:

<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace/>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Type 'MyWebService.Models.Employee' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. Alternatively, you can ensure that the type is public and has a parameterless constructor - all public members of the type will then be serialized, and no attributes will be required.
</ExceptionMessage>
<ExceptionType>
System.Runtime.Serialization.InvalidDataContractException
</ExceptionType>

RouteConfig.cs

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

Body:
You can add attribute [Route] on ListEmployees action or check your route table

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);


问:
Get property with highest value from key value pair
In MongoDB, I have documents with a structure like this:

```<code>{
    _id: "123456...", // an ObjectId
    name: "foobar",
    classification: {
        class_1: 0.45,
        class_2: 0.11,
        class_3: 0.44
    }
}
</code>```

Using the aggregation pipeline, is it possible to give me an object that contains the highest classification? So, given the above, I would like something like this as result:

```<code>{
    _id: "123456...", // an ObjectId
    name: "foobar",
    classification: "class_1"
}
</code>```

I thought I could use $unwind but the classification property is not an array.

For what it's worth: I know there will always be three properties in classification, so it's ok to hard-code the keys in the query.

答:
In the end, I went with a more simple solution, but not as generic as the other ones posted here. I used this a switch case statement:

```<code>{'$project': {'_id': 1, 'name': 1,
              'classification': {'$switch': {
                  'branches': [
                      {'case': {'$and': [{'$gt': ['$classification.class_1', '$classification.class_2']},
                                         {'$gt': ['$classification.class_1', '$classification.class_3']}]},
                           'then': "class1"},
                      {'case': {'$and': [{'$gt': ['$classification.class_2', '$classification.class_1']},
                                         {'$gt': ['$classification.class_2', '$classification.class_3']}]},
                           'then': "class_2"},
                      {'case': {'$and': [{'$gt': ['$classification.class_3', '$classification.class_1']},
                                         {'$gt': ['$classification.class_3', '$classification.class_2']}]},
                           'then': "class_3"}],
                      'default': ''}}
                  }}
</code>```

This works for me, but the other answers might be a better option, YMMV.

Body:
In MongoDB, I have documents with a structure like this:

{
    _id: "123456...", // an ObjectId
    name: "foobar",
    classification: {
        class_1: 0.45,
        class_2: 0.11,
        class_3: 0.44
    }
}

Using the aggregation pipeline, is it possible to give me an object that contains the highest classification? So, given the above, I would like something like this as result:

{
    _id: "123456...", // an ObjectId
    name: "foobar",
    classification: "class_1"
}

I thought I could use $unwind but the classification property is not an array.

For what it's worth: I know there will always be three properties in classification, so it's ok to hard-code the keys in the query.

Body:
In the end, I went with a more simple solution, but not as generic as the other ones posted here. I used this a switch case statement:

{'$project': {'_id': 1, 'name': 1,
              'classification': {'$switch': {
                  'branches': [
                      {'case': {'$and': [{'$gt': ['$classification.class_1', '$classification.class_2']},
                                         {'$gt': ['$classification.class_1', '$classification.class_3']}]},
                           'then': "class1"},
                      {'case': {'$and': [{'$gt': ['$classification.class_2', '$classification.class_1']},
                                         {'$gt': ['$classification.class_2', '$classification.class_3']}]},
                           'then': "class_2"},
                      {'case': {'$and': [{'$gt': ['$classification.class_3', '$classification.class_1']},
                                         {'$gt': ['$classification.class_3', '$classification.class_2']}]},
                           'then': "class_3"}],
                      'default': ''}}
                  }}

This works for me, but the other answers might be a better option, YMMV.


问:
Rails ajax submit fails to send params
View File

```<code><%= form_for(@task, url: task_path, method: :post, remote: true) do |f| %>
  <li><button class="bton" name="status" value="Pending">Complete</button></li>
<% end %>
</code>```

On clicking the Complete button the name and value is not received at the controller but things works fine if I remove remote:true

Am I missing anything?

答:
You can submit form using form object:

```<code><%= f.submit "Complete", class: "bton", name: "status"%>
</code>```

If you want to use plain HTML tag then:

```<code><button type="submit" class="bton" name="status" value="Pending">Complete</button>
</code>```

Title: Rails ajax submit fails to send params

Body:
View File

<%= form_for(@task, url: task_path, method: :post, remote: true) do |f| %>

<button class="bton" name="status" value="Pending">Complete</button>

<% end %>

On clicking the Complete button the name and value is not received at the controller but things works fine if I remove remote:true

Am I missing anything?

Body:
You can submit form using form object:

<%= f.submit "Complete", class: "bton", name: "status"%>

If you want to use plain HTML tag then:

<button type="submit" class="bton" name="status" value="Pending">Complete</button>


问:
Java-based workflow solutions
We currently use a sequential workflow to process documents. We have a total of 10 distinct workflow steps. We have re-analyzed the workflow and realized that we could restructure the workflow to process in parallel a number of the workflow steps. Basically we are able to process steps 1,2,3,4 in parallel, wait until steps 1-4 are completed and then process step 5, then process steps 6,7,8,9 in parallel wait until steps 6-9 are completed and then finally process step 10. If we were able to implement this new workflow we could boost our processing throughput dramatically.

My question is: What java-based open-source workflow projects would you recommend? Do they typically support what I outlined above?

Thanks for all the replies. After taking a quick look at the the websites you all have listed I think I have more than enough to chew on for a while.

答:
Spring batch is really nice

http://static.springsource.org/spring-batch/

You can define the jobs right in XML.  Has a fairly steep learning curve though, may be too much for a single process if you don't plan to do any more batch processing.

Title: Java-based workflow solutions


问:
Connect Java application using Tomcat to database
I follow this tutorial (https://netbeans.org/kb/docs/javaee/ecommerce/connect-db.html) but for a server it uses GlassFish while I am using Tomcat.
How do I connect my MySQL database to my java web application?
I mention that I use NetBeans 8.2 as IDE.</p>

答:
Generally is a good idea to create a connection pool and using it to access the database.

Using tomcat you can use the pool offered by tomcat, you can follow the official guide


问:
Event hub input size data is three time more in output size when reading using stream analytics
when i ingest 100 KB data file in event hub, when i read data from event hub using streaming analytic output file size is three times bigger than  input file.

Please confirm

答:
I had a same issue and as was investigating that, the input count (by byte and size) was multiplied by partition factors.
the partitions were created and mapped as inputs (we have only 2 inputs), but when you will see your job diagram - click ... and select expand partitions.
Per attached picture our IoT hub input is expanded to 20 partitions.


问:
Use external javaScript library in angular application
I have an angular 4 application and I have a javascript component that I created in a javascript file : timeline.js. The javascript component works well but I want to use it with angular 4. So, I put my js file in the folder assets/js/timeline.js.

In the file index.html, I call my js file with  and in app.component.ts, I have :

```<code>var timeline = new Timeline("timelineVisualization")
</code>```

So, normally, the timeline is created in the div which has id="timelineVisualization".

But it doesn't work  and I have an error on the new Timeline : Cannot find name Timeline.

So, do you know how I can do to call the Timeline constructor from timeline.js ?

答:
Try this:</p>

```<code>declare const Timeline;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an angular 4 application and I have a javascript component that I created in a javascript file : timeline.js. The javascript component works well but I want to use it with angular 4. So, I put my js file in the folder assets/js/timeline.js.

In the file index.html, I call my js file with  and in app.component.ts, I have :

var timeline = new Timeline("timelineVisualization")

So, normally, the timeline is created in the div which has id="timelineVisualization".

But it doesn't work  and I have an error on the new Timeline : Cannot find name Timeline.

So, do you know how I can do to call the Timeline constructor from timeline.js ?

Body:
Try this:

declare const Timeline;


问:
How to for loop in userDefaults swift
I am saving data into userDeafults using 2 textfield as String, String but I want to know how to retrieve all the data to display either using loop or function </p>

```<code>    let save = UserDefaults.standard

    let heading = headingText.text
    let description = desxriptionTexr.text
    save.set(description, forKey: heading!)
</code>```

答:
To get all keys and corresponding values in UserDefaults, you can use:

```<code>for (key, value) in UserDefaults.standard.dictionaryRepresentation() {
            print("\(key) = \(value) \n")
}
</code>```

In swift 3, you can store and retrieve using:

```<code>UserDefaults.standard.setValue(token, forKey: "user_auth_token")
print("\(UserDefaults.standard.value(forKey: "user_auth_token")!)")
</code>```

Title: How to for loop in userDefaults swift

Body:
I am saving data into userDeafults using 2 textfield as String, String but I want to know how to retrieve all the data to display either using loop or function

    let save = UserDefaults.standard

    let heading = headingText.text
    let description = desxriptionTexr.text
    save.set(description, forKey: heading!)

Body:
To get all keys and corresponding values in UserDefaults, you can use:

for (key, value) in UserDefaults.standard.dictionaryRepresentation() {
            print("\(key) = \(value) \n")
}

In swift 3, you can store and retrieve using:

UserDefaults.standard.setValue(token, forKey: "user_auth_token")
print("\(UserDefaults.standard.value(forKey: "user_auth_token")!)")


问:
Checking the value of the window's "WindowState" in a Trigger
In WPF, is there a way to check the window's "WindowState" property in a Trigger?  I've tried using the value of "0", "Minimized" and "WindowState.Minimized."

EXAMPLE:

<Window.Triggers>
    <Trigger Property="WindowState" Value="Minimized">
        <Setter Property="ShowInTaskBar" Value="False" />
    </Trigger>
</Window.Triggers>
```

答:
Or if you want a control other than the window to respond to the WindowState property you can use a DataTrigger instead:</p>

```<code><DataTrigger Binding="{Binding WindowState, RelativeSource={RelativeSource AncestorType=Window}}"
             Value="Normal">
   <Setter Property="Fill" Value="Green"/>
</DataTrigger>
</code>```

Body:
Or if you want a control other than the window to respond to the WindowState property you can use a DataTrigger instead:

<DataTrigger Binding="{Binding WindowState, RelativeSource={RelativeSource AncestorType=Window}}"
             Value="Normal">
   <Setter Property="Fill" Value="Green"/>
</DataTrigger>


问:
Why were Symfony 3 unit tests moved out of the actual bundle?
I never really write any tests because I usually have to work with low budgets. So I usually just delete the demo files.
However, I noticed that the test directory was moved from /src/MyBundle/Test in Symfony 2 to /tests in Symfony 3 and I wonder why?

Bundles are, or at least I thought they are, potentially "decoupable" components in an application. This means it's always possible to run/work with the same bundle in another Symfony "runtime" with little to no effort.

So, moving the tests directory out of its related bundle into the root directory doesn't make any sense for me. Making an independent piece of software dependent/incomplete for no reason.
It actually makes me feel like I completely misunderstood the concept of bundles in Symfony.

I also noticed that Symfony tutorials started a few years ago to force their users to move their templates into /app/Resources. When I learned it, they had the templates in their related bundles which seems much cleaner for me. Why should I ever move anything outside if I already have everything bundled (!) in a single directory. Maybe I have some problems with the translation, but in german, a "bundle" is 1 single unit. If you split a bundle, you get 2, but not a half.

I usually see Symfony as a configured runtime for my bundles, so I don't touch anything outside /src besides composer.json, AppKernel or config files.

Well, I may admit that the bundle may react different based on its environment - but unit tests shouldn't even rely on context if I got them right.

Even if you see the AppBundle as a special, context related one - it's still an inconsistent development style when some files can be found there, where others can be found in a completely different place. At least the AppBundle shouldn't be a bundle then.

答:
It's because in Symfony 3 there's a separation between application bundles and reusable bundles:

There are two types of bundles:

Application-specific bundles: only used to build your application;

Reusable bundles: meant to be shared across many projects.

This article is all about how to structure your reusable bundles so that
  they're easy to configure and extend. Many of these recommendations do
  not apply to application bundles because you'll want to keep those as
  simple as possible.

You can learn more in bundle best practices in Symfony.


问:
Delegate for Limitation of characters in Objective c
I have a form which have Delegate for field to limit to enter 4 digits in a field.Now i have another field i want to use another limitation on different field in same form which can limit the field to enter only seven values.How can i use two delegate in same form, if i use them they show error that its twice used. This is the delegate which i have use for the first field.

```<code>- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
</code>```

{

}

答:
To identify different textfield in same controller you can give tag to them. Now lets take an example you have two textfield and you give them tag as 100 and 200 respectively. Now you need to restrict the character that a user can enter to 4, in first textfield whose tag is 100, and 10 in second textfield whose tag is 200. So your code will go like follows:

```<code>- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    //To make sure no crashes occurs
    if(range.length + range.location > textField.text.length)
    {
        return NO;
    }

    NSUInteger textLength = [textField.text length] + [string length] - range.length;

    if (textField.tag == 100) {

        return textLength <= 4;

    }else if(textField.tag == 200){

        return textLength <= 10;

    }else{

        //Other textfields except the one with tag 100 and 200 would have no limits
        return YES;
    }

}
</code>```

I have demonstrated this example with an IF condition you can use Switch case or whatever you want to apply.

Hope this will help you :)

Body:
I have a form which have Delegate for field to limit to enter 4 digits in a field.Now i have another field i want to use another limitation on different field in same form which can limit the field to enter only seven values.How can i use two delegate in same form, if i use them they show error that its twice used. This is the delegate which i have use for the first field.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{

}

Body:
To identify different textfield in same controller you can give tag to them. Now lets take an example you have two textfield and you give them tag as 100 and 200 respectively. Now you need to restrict the character that a user can enter to 4, in first textfield whose tag is 100, and 10 in second textfield whose tag is 200. So your code will go like follows:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    //To make sure no crashes occurs
    if(range.length + range.location > textField.text.length)
    {
        return NO;
    }

    NSUInteger textLength = [textField.text length] + [string length] - range.length;

    if (textField.tag == 100) {

        return textLength <= 4;

    }else if(textField.tag == 200){

        return textLength <= 10;

    }else{

        //Other textfields except the one with tag 100 and 200 would have no limits
        return YES;
    }

}

I have demonstrated this example with an IF condition you can use Switch case or whatever you want to apply.

Hope this will help you :)


问:
Is it possible to handle click event and toggle separately for react treebeard
I want to collapse the tree on click of arrow icon, but it should not re-render the content of the tree. For example -

http://alexcurtis.github.io/react-treebeard/

As you can see collapsing the tree changing the right pane content of the tree. That I don't want.

I want onClick and onToggle to behave differently.

Clicking on the Arrow beside each folder should only expand the tree, not display it's contents on the right panel. Select a folder should display it's content on the right panel.

答:
If you don't want to collapse tree view, just don't update any data for Treebeard component and your state.

```<code>onToggle(){
    // TODO: your desired behavior goes here
    console.log(
      'You could see that message in console, but the tree was not collapsed'
    );
}

render(){
    return (
        <Treebeard
            data={data}
            onToggle={this.onToggle}
        />
    );
}
</code>```

React component rerendering when: you are updating Component state or Component receiving new props.

Body:
If you don't want to collapse tree view, just don't update any data for Treebeard component and your state.

onToggle(){
    // TODO: your desired behavior goes here
    console.log(
      'You could see that message in console, but the tree was not collapsed'
    );
}

render(){
    return (
        <Treebeard
            data={data}
            onToggle={this.onToggle}
        />
    );
}

React component rerendering when: you are updating Component state or Component receiving new props.


问:
Call and stop a rest service with an interval of time
I need to make a rest call every x interval seconds (3000 ms) to consult the status of a webservice until i have the wanted result or until 12 times (for example) or when I receive the status expected:

function myFunction() {
    var i=0;
    var _onSuccess = function(response) {
        if (response.status=== 'READY' || i >= 12) {
            clearInterval(x);
            if(response.status !== 'READY') {
                $location.path('/errorView');
            }
        }
    }
    var x = setInterval(function () {
       $rest.getSomething(_onSuccess)
    }, 3000);
}
```

<p>I have another function that calls myFunction with a timeout because if I dont receive the expected result after 32 seconds i want to cancel stop rest call and go to an error view.</p>

```function myFunction2() {
    myFunction();
    $timeout(function () {
        $location.path('/routeWhenStatusReady');
    }, 32000);
}
```

Is there any way to improve this? I want to finish timeout myFunction2 if the Ready status is ok in 16 seconds for example and not to wait 32 seconds...

Thank you!

答:
step 1 :

assign $interval to a variable

```<code> var timeHandler = $interval(() => {
                // your code
 }, 1000) };
</code>```

step 2:

and cancel it when ever you want by passing variable in interval cancel function

```<code>$interval.cancel(timeHandler);
</code>```

Refrence : here

Body:
I need to make a rest call every x interval seconds (3000 ms) to consult the status of a webservice until i have the wanted result or until 12 times (for example) or when I receive the status expected:

function myFunction() {
    var i=0;
    var _onSuccess = function(response) {
        if (response.status=== 'READY' || i >= 12) {
            clearInterval(x);
            if(response.status !== 'READY') {
                $location.path('/errorView');
            }
        }
    }
    var x = setInterval(function () {
       $rest.getSomething(_onSuccess)
    }, 3000);
}

I have another function that calls myFunction with a timeout because if I dont receive the expected result after 32 seconds i want to cancel stop rest call and go to an error view.

function myFunction2() {
    myFunction();
    $timeout(function () {
        $location.path('/routeWhenStatusReady');
    }, 32000);
}

Is there any way to improve this? I want to finish timeout myFunction2 if the Ready status is ok in 16 seconds for example and not to wait 32 seconds...

Thank you!

Body:
step 1 :

assign $interval to a variable

 var timeHandler = $interval(() => {
                // your code
 }, 1000) };

step 2:

and cancel it when ever you want by passing variable in interval cancel function

$interval.cancel(timeHandler);

Refrence : here


问:
Regex match all strings between 2 characters
I tried a couple of other links like Regex Match all characters between two strings and Regex get all content between two characters
but they don't seem to fit this use case.

I want to get all the names, potato and tomato. Eg, from | to >.

```<code>text = "with <@U0D08NR3|potato> and <@U1698M96|tomato> please"
</code>```

text.scan((?<=|).*?(?=>)) doesnt seem to work either..

Please guide me regex gods.

答: Just escape the | : (?<=\|).*?(?=>). Without it, the positive lookbehind means match anything

Body:
I tried a couple of other links like Regex Match all characters between two strings and Regex get all content between two characters
but they don't seem to fit this use case.

I want to get all the names, potato and tomato. Eg, from | to >.

text = "with <@U0D08NR3|potato> and <@U1698M96|tomato> please"

text.scan((?<=|).*?(?=>)) doesnt seem to work either..

Please guide me regex gods.


问:
InstallShield: cannot extract icon with index 0 vb.net
Im trying to use installshield to mak an installer for my applicatoin but when I add my icon to it then when i try and build it i get the error message InstallShield: cannot extract icon with index 0

Any ideas?

答: The reason I get this message is usually because I have not selected the icon file on the Shortcuts/Folders dialogue:


问:
Calculating sum of children's balance for each parent
I have two tables having parent-child relationship

```<code>Table1
| Account_no | Main_account_no | bla bla
+------------+-----------------+----------
|     234    |        111      |
|     235    |        111      |
|     222    |        112      |
|     220    |        112      |
</code>```

The second:

```<code>Table2
| Account_no | Balance         | bla bla
+------------+-----------------+----------
|     234    |        10       |
|     235    |        15       |
|     222    |        55       |
|     220    |        45       |
</code>```

What I need is to calculate the sum of balance of child accounts for each parent account.
The expected result is

```<code>| Main_account_no | Balance |
+-----------------+---------+
| 111             |  35     |
| 112             |  100    |
</code>```

I am trying to use

```<code>SELECT MAIN_ACCOUNT_NO, SUM((SELECT BALANCE FROM TABLE2 WHERE ACCOUNT_NO = A.ACCOUNT_NO)) OVER (PARTITION BY MAIN_ACCOUNT_NO)
FROM TABLE1 A
GROUP BY MAIN_ACCOUNT_NO
</code>```

But I get the ORA-00979: not a GROUP BY expression

Where did I do wrong?

答:
Since this apparently isn't homework... :-)

First let's get the main_account_nos alongside the balances:

```<code>select
    Table1.Main_account_no,
    Table1.Account_no,
    Table2.Balance
from
    Table1
    join Table2 on Table1.Account_no = Table2.Account_no
</code>```

Gives

```<code>| Main_account_no | Account_no | Balance         |
+-----------------+------------+-----------------+
|        111      |     234    |        10       |
|        111      |     235    |        15       |
|        112      |     222    |        55       |
|        112      |     220    |        45       |
</code>```

Now we can easily group as required:

```<code>select
    Table1.Main_account_no,
    sum(Table2.Balance) as total
from
    Table1
    join Table2 on Table1.Account_no = Table2.Account_no
group by
    Table1.Main_account_no
</code>```

Body:
I have two tables having parent-child relationship

Table1
| Account_no | Main_account_no | bla bla
+------------+-----------------+----------
|     234    |        111      |
|     235    |        111      |
|     222    |        112      |
|     220    |        112      |

The second:

Table2
| Account_no | Balance         | bla bla
+------------+-----------------+----------
|     234    |        10       |
|     235    |        15       |
|     222    |        55       |
|     220    |        45       |

What I need is to calculate the sum of balance of child accounts for each parent account.
The expected result is

| Main_account_no | Balance |
+-----------------+---------+
| 111             |  35     |
| 112             |  100    |

I am trying to use

SELECT MAIN_ACCOUNT_NO, SUM((SELECT BALANCE FROM TABLE2 WHERE ACCOUNT_NO = A.ACCOUNT_NO)) OVER (PARTITION BY MAIN_ACCOUNT_NO)
FROM TABLE1 A
GROUP BY MAIN_ACCOUNT_NO

But I get the ORA-00979: not a GROUP BY expression

Where did I do wrong?

Body:
Since this apparently isn't homework... :-)

First let's get the main_account_nos alongside the balances:

select
    Table1.Main_account_no,
    Table1.Account_no,
    Table2.Balance
from
    Table1
    join Table2 on Table1.Account_no = Table2.Account_no

Gives

| Main_account_no | Account_no | Balance         |
+-----------------+------------+-----------------+
|        111      |     234    |        10       |
|        111      |     235    |        15       |
|        112      |     222    |        55       |
|        112      |     220    |        45       |

Now we can easily group as required:

select
    Table1.Main_account_no,
    sum(Table2.Balance) as total
from
    Table1
    join Table2 on Table1.Account_no = Table2.Account_no
group by
    Table1.Main_account_no


问:
Passing props to a dynamically created component
I dynamically create a component and like to pass some props into it as the following

```<code>import ResouceUsageGadget from './ResouceUsage/ResouceUsageGadget'
  constructor() {
    ...
    this.gadgetStateMap = {
            "ResouceUsageGadget":{"name":"ResouceUsageGadget", "type":ResouceUsageGadget, "state":"normal"}
    }
  }
...
render(){
  let aa = this.gadgetStateMap["ResouceUsageGadget"].type
  return (
     <aa gadgets={this.props.gadgets}/>
  )
}

const DashboardContainer = connect(
          store => {
                return {
                    gadgets: store.DashboardReducer.gadgets
                };
              }
            )(_DashboardContainer);
export default DashboardContainer
</code>```

I got a warning:

Warning: Unknown prop gadgets on  tag. Remove this prop from the element.
    in aa (created by _DashboardContainer)
    in div (created by _DashboardContainer)
    in div (created by _DashboardContainer)
    in _DashboardContainer (created by Connect(_DashboardContainer))
    in Connect(_DashboardContainer) (created by _MainContainer)

And the component never shown up...

Anything wrong?

答:
Uhm, try doing this:

```<code>import ResouceUsageGadget from './ResouceUsage/ResouceUsageGadget'
  constructor() {
    ...
    this.gadgetStateMap = {
            "ResouceUsageGadget":{"name":"ResouceUsageGadget", "type":ResouceUsageGadget, "state":"normal"}
    }
  }
...
render(){
  let aa = React.createElement(this.gadgetStateMap["ResouceUsageGadget"].type,
                               {'gadgets': this.props.gadgets})
  return (
     {aa}
  )
}

const DashboardContainer = connect(
          store => {
                return {
                    gadgets: store.DashboardReducer.gadgets
                };
              }
            )(_DashboardContainer);
export default DashboardContainer
</code>```

the <aa/> component is actually an html tag just like <input/>, not the component you imported ResouceUsageGadget.

Body:
I dynamically create a component and like to pass some props into it as the following

import ResouceUsageGadget from './ResouceUsage/ResouceUsageGadget'
  constructor() {
    ...
    this.gadgetStateMap = {
            "ResouceUsageGadget":{"name":"ResouceUsageGadget", "type":ResouceUsageGadget, "state":"normal"}
    }
  }
...
render(){
  let aa = this.gadgetStateMap["ResouceUsageGadget"].type
  return (
     <aa gadgets={this.props.gadgets}/>
  )
}

const DashboardContainer = connect(
          store => {
                return {
                    gadgets: store.DashboardReducer.gadgets
                };
              }
            )(_DashboardContainer);
export default DashboardContainer

I got a warning:

Warning: Unknown prop gadgets on  tag. Remove this prop from the element.
    in aa (created by _DashboardContainer)
    in div (created by _DashboardContainer)
    in div (created by _DashboardContainer)
    in _DashboardContainer (created by Connect(_DashboardContainer))
    in Connect(_DashboardContainer) (created by _MainContainer)

And the component never shown up...

Anything wrong?

Body:
Uhm, try doing this:

import ResouceUsageGadget from './ResouceUsage/ResouceUsageGadget'
  constructor() {
    ...
    this.gadgetStateMap = {
            "ResouceUsageGadget":{"name":"ResouceUsageGadget", "type":ResouceUsageGadget, "state":"normal"}
    }
  }
...
render(){
  let aa = React.createElement(this.gadgetStateMap["ResouceUsageGadget"].type,
                               {'gadgets': this.props.gadgets})
  return (
     {aa}
  )
}

const DashboardContainer = connect(
          store => {
                return {
                    gadgets: store.DashboardReducer.gadgets
                };
              }
            )(_DashboardContainer);
export default DashboardContainer

the <aa/> component is actually an html tag just like <input/>, not the component you imported ResouceUsageGadget.


问:
Issues with WebRTC based application
I have developed a WebRTC based application along with Kurento-Media-Server.

Problems with this application is:

It works but only on open network (i.e. if run on a network without firewall).

When in firewall it runs sometimes (once out of 10 attempts).

I have tried several things with the firewall, I have disabled all kind of incoming/outgoing traffic. I have created a port-forwarding for my application as well as Kurento-media server.

I am not sure how much useful this information might be but I am deploying my
application on the same physical box along with Kurento-Media-Server. I have configured google's STUN server on my client.js, I have also configured same STUN servers on kurento using code. I haven't configured TURN server.

Just confirming this, signaling server can be behind firewall along with rest of the application, correct?

I am not sure what to look for now, any help in this area would be great.

EDIT-1
From this link I learned that my current network on which my isn't working it has issues with plain websocket connection, it doesn't allow it, it only allows secure Websocket connections.

EDIT-2

Image of netscan:

In my phone network where my app works fine I see all greens in Websocket's "plain" column.

EDIT-3 Solved
Finally found the problem, We were using a router for testing and development and I found that the router had issues, I used LAN cable on the same router and everything worked fine. Calls from application were working just fine. Firewall related details help in configuring the firewall later on.

答:
Based on your problem description it seems all the UDP traffic is not open in your firewall. WebRTC media run on UDP ports.As you mentioned it works one out of 10 times whch means only few UDP ports are open in your firewall.You are lucky when traffic comes via tose ports.You can open  port-range in your firewall and configure the same in kurento-media-server config.Your job should be done.

Even if you configure TURN server you need to open certain ports for outgoing and incoming UDP traffic.For TURN server default port is 3478 or 8443 for sending data towards it but for incoming traffic you need to configure port-range on your TURN server and open those ports in your firewall. Always remember TURN server is assured way to connect but it's always costly.

Title: Issues with WebRTC based application


问:
Automate Facebook sign up process using selenium using java, but not able to select radio button
I am unable to click on "Create an account" button on facebook login page. We cannot store the radio button into List as there is not separate web element as Gender. </p>

```<code>    public static void main(String[] args)     {

        WebDriver fb = new FirefoxDriver();

        fb.get("https://www.facebook.com/");
        fb.findElement(By.xpath("id('u_0_1')")).sendKeys("Tomprakash");
        fb.findElement(By.xpath("id('u_0_3')")).sendKeys("Sahu");
        fb.findElement(By.xpath("id('u_0_6')")).sendKeys("7869084527");
        fb.findElement(By.xpath("id('u_0_9')")).sendKeys("7869084527");
        fb.findElement(By.xpath("id('u_0_b')")).sendKeys("cs083595");
        Select date = new Select(fb.findElement(By.xpath("id('day')")));
        date.selectByVisibleText("24");
        Select month = new Select(fb.findElement(By.xpath("id('month')")));
        month.selectByVisibleText("Dec");
        Select year = new Select(fb.findElement(By.xpath("id('year')")));
        year.selectByVisibleText("1989");
        fb.findElement(By.className("_58mt")).click(); //this code is working for female
        //fb.findElement(By.className("_5k")).click(); //this code is not working for male
        fb.findElement(By.name("Create an account")).submit();
    }

}
</code>```

答:
Try with this code, it is working for me:</p>

```<code>driver.findElement(By.cssSelector("[id=u_0_j]")).click();
driver.findElement(By.cssSelector("[id=u_0_n]")).click();
</code>```

Body:
I am unable to click on "Create an account" button on facebook login page. We cannot store the radio button into List as there is not separate web element as Gender.

    public static void main(String[] args)     {

        WebDriver fb = new FirefoxDriver();

        fb.get("https://www.facebook.com/");
        fb.findElement(By.xpath("id('u_0_1')")).sendKeys("Tomprakash");
        fb.findElement(By.xpath("id('u_0_3')")).sendKeys("Sahu");
        fb.findElement(By.xpath("id('u_0_6')")).sendKeys("7869084527");
        fb.findElement(By.xpath("id('u_0_9')")).sendKeys("7869084527");
        fb.findElement(By.xpath("id('u_0_b')")).sendKeys("cs083595");
        Select date = new Select(fb.findElement(By.xpath("id('day')")));
        date.selectByVisibleText("24");
        Select month = new Select(fb.findElement(By.xpath("id('month')")));
        month.selectByVisibleText("Dec");
        Select year = new Select(fb.findElement(By.xpath("id('year')")));
        year.selectByVisibleText("1989");
        fb.findElement(By.className("_58mt")).click(); //this code is working for female
        //fb.findElement(By.className("_5k")).click(); //this code is not working for male
        fb.findElement(By.name("Create an account")).submit();
    }

}

Body:
Try with this code, it is working for me:

driver.findElement(By.cssSelector("[id=u_0_j]")).click();
driver.findElement(By.cssSelector("[id=u_0_n]")).click();


问:
Why is this Perl script using the File::Tail module not working?
I'm working on a simple Perl script to monitor a log file using the File::Tail module, but I can't seem to get the module working properly.

The idea is to use it over IRC, but this didn't seem to work so after tinkering with the interactive interpreter I've narrowed the problem down to File::Tail. I've cut it down the following basic example to monitor the file and nothing happens at all when new entries are appended to the file:

```<code>#!/usr/bin/perl -w

use strict;

use File::Tail;

my $file = File::Tail->new("/var/log/apache2/error.log");

while(defined(my $line = $file->read))
{
    print "$line\n";
}
</code>```

Can anyone suggest what the problem might be? I've gone through the perldoc entry and this is virtually copied from there so I can't really see that I've made any glaring errors. I'm running Ubuntu Lucid.

答:
If all else fails, implement it yourself!

```<code>use Fcntl qw(:seek);

while (1) {
    while (<$fh>) {
        ...
    }
    sleep(1);
    seek $fh, 0, SEEK_CUR;
}
</code>```

...Which I wouldn't have had to type if I had simply linked you here or here.

Body:
I'm working on a simple Perl script to monitor a log file using the File::Tail module, but I can't seem to get the module working properly.

The idea is to use it over IRC, but this didn't seem to work so after tinkering with the interactive interpreter I've narrowed the problem down to File::Tail. I've cut it down the following basic example to monitor the file and nothing happens at all when new entries are appended to the file:

#!/usr/bin/perl -w

use strict;

use File::Tail;

my $file = File::Tail->new("/var/log/apache2/error.log");

while(defined(my $line = $file->read))
{
    print "$line\n";
}

Can anyone suggest what the problem might be? I've gone through the perldoc entry and this is virtually copied from there so I can't really see that I've made any glaring errors. I'm running Ubuntu Lucid.

Body:
If all else fails, implement it yourself!

use Fcntl qw(:seek);

while (1) {
    while (<$fh>) {
        ...
    }
    sleep(1);
    seek $fh, 0, SEEK_CUR;
}

...Which I wouldn't have had to type if I had simply linked you here or here.


问:
Avoiding an incomplete pattern match
Consider the following code:

```<code>data A
data B

f :: A -> B
f = undefined

data T = TA A | TB B
data ListT = ListTA [A] | ListTB [B]

g :: [T] -> ListT
g l =
  let
    f' :: T -> B
    f' (TA x) = f x
    f' (TB x) = x
    isA :: T -> Bool
    isA TA{} = True
    isA TB{} = False
  in
    case (all isA l) of
      True -> ListTA (map (\(TA x) -> x) l)
      False -> ListTB (map f' l)

main = pure ()
</code>```

The idea behind this is I've got a list of either As or Bs mixed together. I can convert A -> B but not the other way around. Based on this list, I want to make either a list of As or list of Bs, the former if all my original list elements are As, the latter if at least one is a B.

The above code compiles (and I'm guessing will work) but the incomplete pattern match in the map (\(TA x) -> x) l makes me just a little uncomfortable. Is such an incomplete match just a necessity of what I'm doing here? Also, am I reinventing the wheel, is there something that generalises what I'm doing here?

答:
The only way I can think of is something like

```<code>tryA :: [T] -> Maybe [A]
tryA [] = []
tryA (t:ts) =
  case t of
    TA x -> do xs <- tryA ts; return (x:xs)
    TB _ -> Nothing
</code>```

If tryA returns nothing, then do map f' l as before.

This way you're doing the all isA l and the map in a single pass, and it avoids an incomplete pattern.

Title: Avoiding an incomplete pattern match

Body:
Consider the following code:

data A
data B

f :: A -> B
f = undefined

data T = TA A | TB B
data ListT = ListTA [A] | ListTB [B]

g :: [T] -> ListT
g l =
  let
    f' :: T -> B
    f' (TA x) = f x
    f' (TB x) = x
    isA :: T -> Bool
    isA TA{} = True
    isA TB{} = False
  in
    case (all isA l) of
      True -> ListTA (map (\(TA x) -> x) l)
      False -> ListTB (map f' l)

main = pure ()

The idea behind this is I've got a list of either As or Bs mixed together. I can convert A -> B but not the other way around. Based on this list, I want to make either a list of As or list of Bs, the former if all my original list elements are As, the latter if at least one is a B.

The above code compiles (and I'm guessing will work) but the incomplete pattern match in the map (\(TA x) -> x) l makes me just a little uncomfortable. Is such an incomplete match just a necessity of what I'm doing here? Also, am I reinventing the wheel, is there something that generalises what I'm doing here?

Body:
The only way I can think of is something like

tryA :: [T] -> Maybe [A]
tryA [] = []
tryA (t:ts) =
  case t of
    TA x -> do xs <- tryA ts; return (x:xs)
    TB _ -> Nothing

If tryA returns nothing, then do map f' l as before.

This way you're doing the all isA l and the map in a single pass, and it avoids an incomplete pattern.


问:
accessing returned data from a states resolve function
I am using an AngularJS module ui-router and using the resolve property to fetch the id of an item.

In a separate file I have the component, patent for a state patents.patent, which has the function that returns the id. I need to access the returned id from the controller so I can then gather the correct data related to the selected item.

How do I access the resolve function returned value from the controller?

```<code>var app = angular.module('myApp', ['ui.router', 'chart.js']);

app.config(['$stateProvider', function($stateProvider) {

    $stateProvider
    .state('patents', {
        url: '/patents',
        component: 'patents',
        resolve: {
            patents: function(patentsService) {
                return patentsService.fetchAllPatents();
            },
            graphs: function(patentsService) {
                return  patentsService.fetchGraphData();
            }

        }
    })
    .state('patents.patent', {
        url: '/{patentId}',
        component: 'patent',
        resolve: {
            patent: function(patents, $stateParams) {
                return patents.find(function(patent){
                    return patent.id == $stateParams.patentId;
                })
            },
            graph: function(graphs, $stateParams) {
                return graphs.dataset.find(function(graph){
                    return graph.id == $stateParams.patentId; //NEED THIS VALUE
                })
            }
        }
    })

}]);
</code>```

```<code>angular.module('myApp').component('patent', {
    bindings: {
        patent: '=' ,
    },
    templateUrl: '../templates/patents/list/patent-item.htm',
    controller: function() {
        var vm = this;

        //WHERE I NEED TO ACCESS THE RETURNED VALUE

    }
});
</code>```

答:
As Vivz pointed out, injection into the controller should work, but you need to ensure to guard against minification issues:</p>

```<code>angular.module('myApp').component('patent', {
  bindings: {
    patent: '=' ,
  },
  templateUrl: '../templates/patents/list/patent-item.htm',
  controller: ['graph', function(graph) {
    var vm = this;

    //WHERE I NEED TO ACCESS THE RETURNED VALUE

  }]
});
</code>```

Body:
I am using an AngularJS module ui-router and using the resolve property to fetch the id of an item.

In a separate file I have the component, patent for a state patents.patent, which has the function that returns the id. I need to access the returned id from the controller so I can then gather the correct data related to the selected item.

How do I access the resolve function returned value from the controller?

var app = angular.module('myApp', ['ui.router', 'chart.js']);

app.config(['$stateProvider', function($stateProvider) {

    $stateProvider
    .state('patents', {
        url: '/patents',
        component: 'patents',
        resolve: {
            patents: function(patentsService) {
                return patentsService.fetchAllPatents();
            },
            graphs: function(patentsService) {
                return  patentsService.fetchGraphData();
            }

        }
    })
    .state('patents.patent', {
        url: '/{patentId}',
        component: 'patent',
        resolve: {
            patent: function(patents, $stateParams) {
                return patents.find(function(patent){
                    return patent.id == $stateParams.patentId;
                })
            },
            graph: function(graphs, $stateParams) {
                return graphs.dataset.find(function(graph){
                    return graph.id == $stateParams.patentId; //NEED THIS VALUE
                })
            }
        }
    })

}]);

angular.module('myApp').component('patent', {
    bindings: {
        patent: '=' ,
    },
    templateUrl: '../templates/patents/list/patent-item.htm',
    controller: function() {
        var vm = this;

        //WHERE I NEED TO ACCESS THE RETURNED VALUE

    }
});

Body:
As Vivz pointed out, injection into the controller should work, but you need to ensure to guard against minification issues:

angular.module('myApp').component('patent', {
  bindings: {
    patent: '=' ,
  },
  templateUrl: '../templates/patents/list/patent-item.htm',
  controller: ['graph', function(graph) {
    var vm = this;

    //WHERE I NEED TO ACCESS THE RETURNED VALUE

  }]
});


问:
WPF Log File Viewer Component
I am looking for a WPF component to load log files and show them in my application. It should at least provide some sort of filtering, a search and color coding.

The only thing I found that looked promising was Orc.LogViewer. I was however unable to simply use this as a viewer for existing log files, as there seems to be no functionality to load files. It only works with active log listeners.

答: You could look into the LogViewer app created by the same company. See https://github.com/wildgums/logviewer</p>

Title: WPF Log File Viewer Component


问:
Enable ckeditor keyboard shortcut for headings?
I want my editors to be able to use keyboard shortcuts for applying headings.

I've been experimenting with the "keystrokes" approach on the ckeditor site. It works for some things, but not the headings. For instance, the following applies an additional mapping for 'bold' using Ctrl + Shift + u:

```<code>config.keystrokes = [
    [ CKEDITOR.CTRL + CKEDITOR.SHIFT + 85 /*U*/, 'bold' ],
];
</code>```

Why can't I enable the headings?

Right now this is what my config.js looks like:

```<code>CKEDITOR.editorConfig = function( config ) {
    // Define changes to default configuration here.
    // For complete reference see:
    // http://docs.ckeditor.com/#!/api/CKEDITOR.config

    // The toolbar groups arrangement, optimized for two toolbar rows.
    config.toolbarGroups = [
        { name: 'styles', groups: [ 'styles' ] },
        { name: 'paragraph',   groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] },
        { name: 'editing',     groups: [ 'find', 'selection', 'spellchecker' ] },
        { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
        { name: 'clipboard',   groups: [ 'clipboard', 'undo' ] },
        { name: 'document',    groups: [ 'mode', 'document', 'doctools' ] },
        { name: 'others' },
        { name: 'forms' },
        { name: 'tools' }
    ];

    // Remove some buttons provided by the standard plugins, which are
    // not needed in the Standard(s) toolbar.
    config.removeButtons = 'Underline,Styles,Strike,Image,Outdent,Indent,Blockquote,Cut,Copy,Paste,PasteFromWord,Undo,Redo';

    // Set the most common block elements.
    config.format_tags = 'p;h1;h2;h3;h4';

    // Simplify the dialog windows.
    config.removeDialogTabs = 'image:advanced;link:advanced';

    // Whether to escape basic HTML entities in the document, including:
    // (nbsp,gt,lt,amp)
    config.basicEntities = false;
    config.entities_additional = 'lt,gt,amp,quot'
    config.entities_latin = false;
    config.entities_greek = false;
    config.disableNativeSpellChecker = false;
    config.removePlugins = 'wsc,scayt';
    config.scayt_autoStartup = false;
    config.height = 1000;

    config.keystrokes =
        [
            [ CKEDITOR.CTRL + CKEDITOR.SHIFT + 85 /*U*/, 'bold' ],
            [ CKEDITOR.CTRL + CKEDITOR.SHIFT + 73 /*I*/, 'h1' ],
        ];
};
</code>```

I'm hoping to keep my changes restricted to the ckeditor directory (ideally only inside config.js).

答:
You have to create a new command in your HTML page for each of the headings you want to apply. For
:

```<code>var editor1 = CKEDITOR.replace( 'editor1' );
editor1.on( 'instanceReady', function( evt ) {
    evt.editor.addCommand( 'h1' , new CKEDITOR.styleCommand( new CKEDITOR.style({ element: 'h1' } )) );
    // other commands for 'h2', 'h3' etc
    evt.editor.setKeystroke( CKEDITOR.CTRL + CKEDITOR.SHIFT + 85 /*U*/, 'h1');
    // other keystrokes for 'h2', 'h3', etc
});
</code>```

Body:
I want my editors to be able to use keyboard shortcuts for applying headings.

I've been experimenting with the "keystrokes" approach on the ckeditor site. It works for some things, but not the headings. For instance, the following applies an additional mapping for 'bold' using Ctrl + Shift + u:

config.keystrokes = [
    [ CKEDITOR.CTRL + CKEDITOR.SHIFT + 85 /*U*/, 'bold' ],
];

Why can't I enable the headings?

Right now this is what my config.js looks like:

CKEDITOR.editorConfig = function( config ) {
    // Define changes to default configuration here.
    // For complete reference see:
    // http://docs.ckeditor.com/#!/api/CKEDITOR.config

    // The toolbar groups arrangement, optimized for two toolbar rows.
    config.toolbarGroups = [
        { name: 'styles', groups: [ 'styles' ] },
        { name: 'paragraph',   groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] },
        { name: 'editing',     groups: [ 'find', 'selection', 'spellchecker' ] },
        { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
        { name: 'clipboard',   groups: [ 'clipboard', 'undo' ] },
        { name: 'document',    groups: [ 'mode', 'document', 'doctools' ] },
        { name: 'others' },
        { name: 'forms' },
        { name: 'tools' }
    ];

    // Remove some buttons provided by the standard plugins, which are
    // not needed in the Standard(s) toolbar.
    config.removeButtons = 'Underline,Styles,Strike,Image,Outdent,Indent,Blockquote,Cut,Copy,Paste,PasteFromWord,Undo,Redo';

    // Set the most common block elements.
    config.format_tags = 'p;h1;h2;h3;h4';

    // Simplify the dialog windows.
    config.removeDialogTabs = 'image:advanced;link:advanced';

    // Whether to escape basic HTML entities in the document, including:
    // (nbsp,gt,lt,amp)
    config.basicEntities = false;
    config.entities_additional = 'lt,gt,amp,quot'
    config.entities_latin = false;
    config.entities_greek = false;
    config.disableNativeSpellChecker = false;
    config.removePlugins = 'wsc,scayt';
    config.scayt_autoStartup = false;
    config.height = 1000;

    config.keystrokes =
        [
            [ CKEDITOR.CTRL + CKEDITOR.SHIFT + 85 /*U*/, 'bold' ],
            [ CKEDITOR.CTRL + CKEDITOR.SHIFT + 73 /*I*/, 'h1' ],
        ];
};

I'm hoping to keep my changes restricted to the ckeditor directory (ideally only inside config.js).

Body:
You have to create a new command in your HTML page for each of the headings you want to apply. For <h1>:

var editor1 = CKEDITOR.replace( 'editor1' );
editor1.on( 'instanceReady', function( evt ) {
    evt.editor.addCommand( 'h1' , new CKEDITOR.styleCommand( new CKEDITOR.style({ element: 'h1' } )) );
    // other commands for 'h2', 'h3' etc
    evt.editor.setKeystroke( CKEDITOR.CTRL + CKEDITOR.SHIFT + 85 /*U*/, 'h1');
    // other keystrokes for 'h2', 'h3', etc
});


问:
How to Convert colors from Hex to RGB
I have color in the String.xml file like this  <color name="ItemColor1">#ffff992b</color>
how can i convert is into four variables

```<code>float Red;
float Green;
float Blue;
float Alfa;
</code>```

in Java Code? any one can help

答:
Updated with ContextCompat as getColor is Deprecated.

```<code>int color = ContextCompat.getColor(mContext, R.color.colorAccent);
float red = (color >> 16) & 0xFF;
float green = (color >> 8) & 0xFF;
float blue = (color) & 0xFF;
float alpha = (color >> 24) & 0xFF;
</code>```

Hope it will useful.

Title: How to Convert colors from Hex to RGB

Body:
I have color in the String.xml file like this  <color name="ItemColor1">#ffff992b</color>
how can i convert is into four variables

float Red;
float Green;
float Blue;
float Alfa;

in Java Code? any one can help

Body:
Updated with ContextCompat as getColor is Deprecated.

int color = ContextCompat.getColor(mContext, R.color.colorAccent);
float red = (color >> 16) & 0xFF;
float green = (color >> 8) & 0xFF;
float blue = (color) & 0xFF;
float alpha = (color >> 24) & 0xFF;

Hope it will useful.


问:
Use external javaScript library in angular application
I have an angular 4 application and I have a javascript component that I created in a javascript file : timeline.js. The javascript component works well but I want to use it with angular 4. So, I put my js file in the folder assets/js/timeline.js.

In the file index.html, I call my js file with  and in app.component.ts, I have :

```<code>var timeline = new Timeline("timelineVisualization")
</code>```

So, normally, the timeline is created in the div which has id="timelineVisualization".

But it doesn't work  and I have an error on the new Timeline : Cannot find name Timeline.

So, do you know how I can do to call the Timeline constructor from timeline.js ?

答:
You can try to find your type definitions from :

Definitly Typed Github Page

If you cannot find your library, you can write your interfaces yourself (and try to pull request it to the github page for other developers) and this interface will act like a .ts file.

Here is a start

```<code>declare global {
    interface Window {
        Timeline: any
    }
}
</code>```

Body:
I have an angular 4 application and I have a javascript component that I created in a javascript file : timeline.js. The javascript component works well but I want to use it with angular 4. So, I put my js file in the folder assets/js/timeline.js.

In the file index.html, I call my js file with  and in app.component.ts, I have :

var timeline = new Timeline("timelineVisualization")

So, normally, the timeline is created in the div which has id="timelineVisualization".

But it doesn't work  and I have an error on the new Timeline : Cannot find name Timeline.

So, do you know how I can do to call the Timeline constructor from timeline.js ?

Body:
You can try to find your type definitions from :

Definitly Typed Github Page

If you cannot find your library, you can write your interfaces yourself (and try to pull request it to the github page for other developers) and this interface will act like a .ts file.

Here is a start

declare global {
    interface Window {
        Timeline: any
    }
}


问:
elastic search not found error in ruby on rails
I'm going to do elastic search on DoctorProfile and Subspeciality table. The error that I'm dealing with is that it gives the not found result. It takes a list of ids from doctor table but it doesn't gives desire result which is the doctor and with subspeciality.
this is what everything that i did:
I used these gems:

```<code>gem 'elasticsearch-model', git: 'git://github.com/elasticsearch/elasticsearch-rails.git'
gem 'elasticsearch-rails', git: 'git://github.com/elasticsearch/elasticsearch-rails.git'
gem 'elasticsearch-extensions', git: 'git://github.com/elasticsearch/elasticsearch-ruby.git'
</code>```

my search method:

```<code> def search
    query = params[:query]
    #query.encode("UTF-8")
    if query.nil?
      render json: { message: "no query is provided" }, status: :unprocessable_entity
      return
    end
    profiles = DoctorProfile.search(query).results.map { |r| r._source.id }
    subspecialties = Subspecialty.search(query).results.map { |r| r._source.title }
    subspecialties.uniq!
    profiles = profiles + DoctorProfile.where("subspeciality in (?)", subspecialties).ids
    profiles.uniq!
    logger.info "################  The profile is #{profiles} ########################"
    @doctors = DoctorProfile.find(profiles)
    @cleaned_doctors = @doctors.select { |u| !u.user.nil? }

    render json: @cleaned_doctors
  end
</code>```

in the doctor model:

```<code>  after_commit on: [:create] do
    __elasticsearch__.index_document if self.enabled?
  end

  after_commit on: [:update] do
    __elasticsearch__.update_document if self.enabled?
  end

  after_commit on: [:destroy] do
    __elasticsearch__.delete_document
  end

  settings index: {
    number_of_shards: 1,
    number_of_replicas: 0,
    analysis: {
      filter: {
        autocomplete_filter: {
          type: "edge_ngram",
          min_gram: 1,
          max_gram: 20
        }
      },
      analyzer: {
        autocomplete: {
          type: "custom",
          tokenizer: "standard",
          filter: [
            "lowercase",
            "autocomplete_filter"
          ]
        }
      }
    }
  }

  mappings dynamic: 'false' do
    indexes :first_name, type: "string"
    indexes :last_name, type: "string"
    indexes :medical_code, type: "string"
    indexes :expertise, type: "string", analyzer: "autocomplete", search_analyzer: "standard"
    indexes :subspeciality, type: "string", analyzer: "autocomplete", search_analyzer: "standard"
  end

  def self.search(query)
    __elasticsearch__.search(
      {
        query: {
          multi_match: {
            query: query,
            fields: ['medical_code^10', 'subspeciality^5', 'expertise^2', 'first_name', 'last_name']
          }
        }
      }
    )
</code>```

and in subspeciality model:

```<code> after_commit on: [:create] do
    self.services = self.services.each {|str| str.force_encoding("UTF-8")}
    __elasticsearch__.index_document if self.enabled?
  end

  after_commit on: [:update] do
    self.services = self.services.each {|str| str.force_encoding("UTF-8")}
    __elasticsearch__.update_document if self.enabled?
  end

  after_commit on: [:destroy] do
    __elasticsearch__.delete_document
  end

 settings index: {
    number_of_shards: 1,
    number_of_replicas: 0,
    analysis: {
      filter: {
        autocomplete_filter: {
          type: "edge_ngram",
          min_gram: 1,
          max_gram: 20
        }
      },
      analyzer: {
        autocomplete: {
          type: "custom",
          tokenizer: "standard",
          filter: [
            "lowercase",
            "autocomplete_filter"
          ]
        }
      }
    }
  }

  mappings dynamic: 'false' do
    indexes :description, type: "string", analyzer: "autocomplete", search_analyzer: "standard"
    indexes :services, type: "string"
  end

  def self.search(query)
    __elasticsearch__.search(
      {
        query: {
          multi_match: {
            query: query,
            fields: ['description', 'services']
          }
        }
      }
    )
  end
</code>```

and this is my error in log :

```<code>Couldn't find all DoctorProfiles with 'id': (031addd8-9df8-4a53-974d-da0067302ad0, ff890720-4bfb-47d8-bdb8-3dc712b27f29, 869b28e1-cdd7-4bb6-b1d0-c7296e4b0637, 6dd6a784-c54b-4bb7-a0e1-337474ec4114, 234ccc87-f0c7-42f7-b96f-cf8d85487929, 543b621d-87aa-4a34-b6d6-62144c6a387e, 77e35144-9b93-48a0-a5bb-7b3addb99dff, d368f1df-3d1a-49ce-b6f5-f791df3294b1, d3dca8de-3143-4b03-90ec-e73a27c88960, 24abb0b3-2d11-457b-b95d-972462c4a37f) (found 2 results, but was looking for 10
</code>```

i changed this line of code

```<code>@doctors = DoctorProfile.find(profiles)
</code>```

to

```<code>@doctors = DoctorProfile.where("id in (?)",profiles)
</code>```

and remove this line:

@cleaned_doctors = @doctors.select { |u| !u.user.nil? }

now i want to know what does this method do eactly.

```<code>@cleaned_doctors = @doctors.select { |u| !u.user.nil? }
</code>```

to be mention, i have a table named user that doctorProfile has reference to it

答:
Your code doesn't say much, but it seems that you have a boolean enabled on your model, which tells whether the record is to be indexed or not.

The issue is with the update callback, because if you change your model from enabled to not enabled, instead of removing it from the index, it just don't update existing information.

The correct callback would be

```<code>  after_commit on: [:update] do
    if enabled?
      if previous_changes['enabled'] &&
         !previous_changes['enabled'].first
        # previously not enabled, we need to index it
        __elasticsearch__.index_document
      else
        # previously enabled, we need to update it
        __elasticsearch__.update_document
      end
    else
      # not enabled
      if previous_changes['enabled'] &&
         previous_changes['enabled'].first
        # previously enabled, delete
        __elasticsearch__.delete_document
      end
      # if it wasn't enabled before, it's not in the index anyway.
      # do nothing
    end
  end
</code>```

The previous_changes hash stores the attributes that did change when saving the model, so you can check the previous value of the enabled attribute. See http://api.rubyonrails.org/classes/ActiveModel/Dirty.html#method-i-previous_changes

Once you have the new callback in place, rebuild the indexes to remove the bogus data in production if needed:

```<code>DoctorProfile.where(enabled: true).find_each { |dp| dp.__elasticsearch__.index_document }
Subspecialty.where(enabled: true).find_each { |dp| dp.__elasticsearch__.index_document }
</code>```

Body:
I'm going to do elastic search on DoctorProfile and Subspeciality table. The error that I'm dealing with is that it gives the not found result. It takes a list of ids from doctor table but it doesn't gives desire result which is the doctor and with subspeciality.
this is what everything that i did:
I used these gems:

gem 'elasticsearch-model', git: 'git://github.com/elasticsearch/elasticsearch-rails.git'
gem 'elasticsearch-rails', git: 'git://github.com/elasticsearch/elasticsearch-rails.git'
gem 'elasticsearch-extensions', git: 'git://github.com/elasticsearch/elasticsearch-ruby.git'

my search method:

 def search
    query = params[:query]
    #query.encode("UTF-8")
    if query.nil?
      render json: { message: "no query is provided" }, status: :unprocessable_entity
      return
    end
    profiles = DoctorProfile.search(query).results.map { |r| r._source.id }
    subspecialties = Subspecialty.search(query).results.map { |r| r._source.title }
    subspecialties.uniq!
    profiles = profiles + DoctorProfile.where("subspeciality in (?)", subspecialties).ids
    profiles.uniq!
    logger.info "################  The profile is #{profiles} ########################"
    @doctors = DoctorProfile.find(profiles)
    @cleaned_doctors = @doctors.select { |u| !u.user.nil? }

    render json: @cleaned_doctors
  end

in the doctor model:

  after_commit on: [:create] do
    __elasticsearch__.index_document if self.enabled?
  end

  after_commit on: [:update] do
    __elasticsearch__.update_document if self.enabled?
  end

  after_commit on: [:destroy] do
    __elasticsearch__.delete_document
  end

  settings index: {
    number_of_shards: 1,
    number_of_replicas: 0,
    analysis: {
      filter: {
        autocomplete_filter: {
          type: "edge_ngram",
          min_gram: 1,
          max_gram: 20
        }
      },
      analyzer: {
        autocomplete: {
          type: "custom",
          tokenizer: "standard",
          filter: [
            "lowercase",
            "autocomplete_filter"
          ]
        }
      }
    }
  }

  mappings dynamic: 'false' do
    indexes :first_name, type: "string"
    indexes :last_name, type: "string"
    indexes :medical_code, type: "string"
    indexes :expertise, type: "string", analyzer: "autocomplete", search_analyzer: "standard"
    indexes :subspeciality, type: "string", analyzer: "autocomplete", search_analyzer: "standard"
  end

  def self.search(query)
    __elasticsearch__.search(
      {
        query: {
          multi_match: {
            query: query,
            fields: ['medical_code^10', 'subspeciality^5', 'expertise^2', 'first_name', 'last_name']
          }
        }
      }
    )

and in subspeciality model:

 after_commit on: [:create] do
    self.services = self.services.each {|str| str.force_encoding("UTF-8")}
    __elasticsearch__.index_document if self.enabled?
  end

  after_commit on: [:update] do
    self.services = self.services.each {|str| str.force_encoding("UTF-8")}
    __elasticsearch__.update_document if self.enabled?
  end

  after_commit on: [:destroy] do
    __elasticsearch__.delete_document
  end

 settings index: {
    number_of_shards: 1,
    number_of_replicas: 0,
    analysis: {
      filter: {
        autocomplete_filter: {
          type: "edge_ngram",
          min_gram: 1,
          max_gram: 20
        }
      },
      analyzer: {
        autocomplete: {
          type: "custom",
          tokenizer: "standard",
          filter: [
            "lowercase",
            "autocomplete_filter"
          ]
        }
      }
    }
  }

  mappings dynamic: 'false' do
    indexes :description, type: "string", analyzer: "autocomplete", search_analyzer: "standard"
    indexes :services, type: "string"
  end

  def self.search(query)
    __elasticsearch__.search(
      {
        query: {
          multi_match: {
            query: query,
            fields: ['description', 'services']
          }
        }
      }
    )
  end

and this is my error in log :

Couldn't find all DoctorProfiles with 'id': (031addd8-9df8-4a53-974d-da0067302ad0, ff890720-4bfb-47d8-bdb8-3dc712b27f29, 869b28e1-cdd7-4bb6-b1d0-c7296e4b0637, 6dd6a784-c54b-4bb7-a0e1-337474ec4114, 234ccc87-f0c7-42f7-b96f-cf8d85487929, 543b621d-87aa-4a34-b6d6-62144c6a387e, 77e35144-9b93-48a0-a5bb-7b3addb99dff, d368f1df-3d1a-49ce-b6f5-f791df3294b1, d3dca8de-3143-4b03-90ec-e73a27c88960, 24abb0b3-2d11-457b-b95d-972462c4a37f) (found 2 results, but was looking for 10

i changed this line of code

@doctors = DoctorProfile.find(profiles)

to

@doctors = DoctorProfile.where("id in (?)",profiles)

and remove this line:

@cleaned_doctors = @doctors.select { |u| !u.user.nil? }

now i want to know what does this method do eactly.

@cleaned_doctors = @doctors.select { |u| !u.user.nil? }

to be mention, i have a table named user that doctorProfile has reference to it

Body:
Your code doesn't say much, but it seems that you have a boolean enabled on your model, which tells whether the record is to be indexed or not.

The issue is with the update callback, because if you change your model from enabled to not enabled, instead of removing it from the index, it just don't update existing information.

The correct callback would be

  after_commit on: [:update] do
    if enabled?
      if previous_changes['enabled'] &&
         !previous_changes['enabled'].first
        # previously not enabled, we need to index it
        __elasticsearch__.index_document
      else
        # previously enabled, we need to update it
        __elasticsearch__.update_document
      end
    else
      # not enabled
      if previous_changes['enabled'] &&
         previous_changes['enabled'].first
        # previously enabled, delete
        __elasticsearch__.delete_document
      end
      # if it wasn't enabled before, it's not in the index anyway.
      # do nothing
    end
  end

The previous_changes hash stores the attributes that did change when saving the model, so you can check the previous value of the enabled attribute. See http://api.rubyonrails.org/classes/ActiveModel/Dirty.html#method-i-previous_changes

Once you have the new callback in place, rebuild the indexes to remove the bogus data in production if needed:

DoctorProfile.where(enabled: true).find_each { |dp| dp.__elasticsearch__.index_document }
Subspecialty.where(enabled: true).find_each { |dp| dp.__elasticsearch__.index_document }


问:
mercurial log of changests on merged named branches, but not unmerged
I want to be able to get a "hg log" of every changeset that appears in the graph between
changeset1 and changeset2.  I cannot find a way to do it without either
a) omitting nodes on named branches that ARE merged between changeset1:changset2
or b) including nodes on named branches that ARE NOT ancestors of changeset2

Here's a "hg glog" of a simple example with 2 named branches plus the default branch. One named branch gets merged and so its nodes are relevant, the other is irrelevant:

```<code>@    changeset:   5:e384fe418e9b
|\   tag:         tip
| |  parent:      2:7dc7af503071
| |  parent:      3:0a9be59d576e
| |  summary:     merge somefeature branch into default
| |
| | o  changeset:   4:4e8c9ca127c9
| | |  branch:      unmerged_feature
| | |  parent:      1:ef98ad136fa8
| | |  summary:     change that is not merged into ending changeset
| | |
| o |  changeset:   3:0a9be59d576e
| |/   branch:      somefeature
| |    parent:      1:ef98ad136fa8
| |    summary:     changed b.txt
| |
o |  changeset:   2:7dc7af503071
|    summary:     changed a.txt
|
o  changeset:   1:ef98ad136fa8
|  summary:     added b.txt
|
o  changeset:   0:271b22b4ad30
   summary:     added a.txt
</code>```

I want a log command that will give me all the nodes that are descendent of rev 0 and ancestors of rev 5.  This is everything except rev 4.

I can get too much info:

```<code>hg log -r 0:5 --template "{rev}:branch={branches},desc={desc}\n"
</code>```

This gives me a log entry for rev 4, which is not an ancestor of rev 5:

```<code>0:branch=,desc=added a.txt
1:branch=,desc=added b.txt
2:branch=,desc=changed a.txt
3:branch=somefeature,desc=changed b.txt
4:branch=unmerged_feature,desc=change that is not merged into ending changeset
5:branch=,desc=merge somefeature branch into default
</code>```

I can get too little info:

```<code>hg log -b default -r 0:5 --template "{rev}:branch={branches},desc={desc}\n"
</code>```

omits rev 3, which is a descendent of rev 0 and ancestor of rev 5

```<code>0:branch=,desc=added a.txt
1:branch=,desc=added b.txt
2:branch=,desc=changed a.txt
5:branch=,desc=merge somefeature branch into default
</code>```

答:
If you're using a newer version of Mercurial (1.6.0 or higher), you can use the revsets feature.  In this case, you need the ancestors() operator:

```<code>hg log --rev ancestors(5)
</code>```

See hg help revsets for more information.

Body:
I want to be able to get a "hg log" of every changeset that appears in the graph between
changeset1 and changeset2.  I cannot find a way to do it without either
a) omitting nodes on named branches that ARE merged between changeset1:changset2
or b) including nodes on named branches that ARE NOT ancestors of changeset2

Here's a "hg glog" of a simple example with 2 named branches plus the default branch. One named branch gets merged and so its nodes are relevant, the other is irrelevant:

@    changeset:   5:e384fe418e9b
|\   tag:         tip
| |  parent:      2:7dc7af503071
| |  parent:      3:0a9be59d576e
| |  summary:     merge somefeature branch into default
| |
| | o  changeset:   4:4e8c9ca127c9
| | |  branch:      unmerged_feature
| | |  parent:      1:ef98ad136fa8
| | |  summary:     change that is not merged into ending changeset
| | |
| o |  changeset:   3:0a9be59d576e
| |/   branch:      somefeature
| |    parent:      1:ef98ad136fa8
| |    summary:     changed b.txt
| |
o |  changeset:   2:7dc7af503071
|    summary:     changed a.txt
|
o  changeset:   1:ef98ad136fa8
|  summary:     added b.txt
|
o  changeset:   0:271b22b4ad30
   summary:     added a.txt

I want a log command that will give me all the nodes that are descendent of rev 0 and ancestors of rev 5.  This is everything except rev 4.

I can get too much info:

hg log -r 0:5 --template "{rev}:branch={branches},desc={desc}\n"

This gives me a log entry for rev 4, which is not an ancestor of rev 5:

0:branch=,desc=added a.txt
1:branch=,desc=added b.txt
2:branch=,desc=changed a.txt
3:branch=somefeature,desc=changed b.txt
4:branch=unmerged_feature,desc=change that is not merged into ending changeset
5:branch=,desc=merge somefeature branch into default

I can get too little info:

hg log -b default -r 0:5 --template "{rev}:branch={branches},desc={desc}\n"

omits rev 3, which is a descendent of rev 0 and ancestor of rev 5

0:branch=,desc=added a.txt
1:branch=,desc=added b.txt
2:branch=,desc=changed a.txt
5:branch=,desc=merge somefeature branch into default

Body:
If you're using a newer version of Mercurial (1.6.0 or higher), you can use the revsets feature.  In this case, you need the ancestors() operator:

hg log --rev ancestors(5)

See hg help revsets for more information.