问:
How to loop through a object array in an Alexa Intent?
So the problem is I am not able to loop through the question's array in the loop in the quizIntent handler. Only the first question is shown and then it does not move any further. Rest of the code is working fine.
What I want to do is Keep on asking questions till the array runs out of them and break out of the loop when the user gives a wrong answer.

I am just a newbie to Alexa Programming. Please help.

Here is my array

```<code>    const got = [
    {
        question: "Grey Wind, Lady, Ghost, Shaggydog, Summer and the sixth direwolve's name is?",
        answer: 'nymeria',
    },
    {
        question: "What was the name of the sinister castle where Arya and Gendry were held prisoner in season two?",
        answer: 'harrenhal',
    },
    {
        question: "What is a person called that can enter the minds of animals?",
        answer: 'warg',
    },
    {
        question: "What was the name of the Stark ancestral sword that was melted down by Tywin Lannister?",
        answer: 'ice',
    }
];
</code>```

Here is my Alexa Intent

```<code>    var handlers = {
  "customIntent": function () {
           this.response.speak("Would you like to appear for a trial by combat");
      this.emit(":responseReady");
   },
   "quizIntent": function () {
       var mydecision = this.event.request.intent.slots.decision.value;
       if(mydecision=='no'||mydecision=='nope'||mydecision=='naah'){
        this.response.speak("A five year old has more courage than you.");
        this.emit(":responseReady");
       }

       for(var i = 0; i <got.length; i++){
            var myanswer = this.event.request.intent.slots.answer.value;
            var item = got[i].question;
            this.response.speak(item).listen();
            if(myanswer!=got[i].answer){
                this.response.speak("Wrong Answer. You are dead");
                this.emit(':responseReady');

            }
            if(i==got.length-1){
                this.response.speak("You won");
                this.emit(':responseReady');
            }

      }

   },
   "LaunchRequest": function () {
    this.response.speak("Valar Morghulis").listen("You are supposed to say Valar Dohareis");
    this.emit(":responseReady");
   }

};
</code>```

Here is my Intent Schema in case you wanna look at that too

```<code>{
  "languageModel": {
    "types": [
      {
        "name": "answerSlot",
        "values": [
          {
            "id": null,
            "name": {
              "value": "Nymeria",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Harrenhal",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Warg",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Ice",
              "synonyms": []
            }
          }
        ]
      },
      {
        "name": "decisionSlot",
        "values": [
          {
            "id": null,
            "name": {
              "value": "Yes",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "No",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Naah",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Yeah",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Yup",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Nope",
              "synonyms": []
            }
          }
        ]
      }
    ],
    "intents": [
      {
        "name": "AMAZON.CancelIntent",
        "samples": []
      },
      {
        "name": "AMAZON.HelpIntent",
        "samples": []
      },
      {
        "name": "AMAZON.StopIntent",
        "samples": []
      },
      {
        "name": "customIntent",
        "samples": [
          "Valar Dohareis",
          "hello",
          "hola"
        ],
        "slots": []
      },
      {
        "name": "quizIntent",
        "samples": [
          "{decision}",
          "The answer is {answer}"
        ],
        "slots": [
          {
            "name": "decision",
            "type": "decisionSlot"
          },
          {
            "name": "answer",
            "type": "answerSlot"
          }
        ]
      }
    ],
    "invocationName": "quiz game"
  }
}
</code>```

答:
for loop doesn't serve any purpose as intent is designed to give a single response on every single invocation. So though you're for loop would be running, it will not emit out the second response as execution after the listen method of the first iteration would be starting from the very start since it's a new invocation.

The purpose you want to attain can be successfully achieved by using Session attribute.

```<code>var iterations = 0; //defined globally

// Later on, for every iteration, you simply need to call
// into the attributes property of the alexa object to change the value.

this.attributes['iterations'] = iterations + 1;
</code>```

Body:
So the problem is I am not able to loop through the question's array in the loop in the quizIntent handler. Only the first question is shown and then it does not move any further. Rest of the code is working fine.
What I want to do is Keep on asking questions till the array runs out of them and break out of the loop when the user gives a wrong answer.

I am just a newbie to Alexa Programming. Please help.

Here is my array

    const got = [
    {
        question: "Grey Wind, Lady, Ghost, Shaggydog, Summer and the sixth direwolve's name is?",
        answer: 'nymeria',
    },
    {
        question: "What was the name of the sinister castle where Arya and Gendry were held prisoner in season two?",
        answer: 'harrenhal',
    },
    {
        question: "What is a person called that can enter the minds of animals?",
        answer: 'warg',
    },
    {
        question: "What was the name of the Stark ancestral sword that was melted down by Tywin Lannister?",
        answer: 'ice',
    }
];

Here is my Alexa Intent

    var handlers = {
  "customIntent": function () {
           this.response.speak("Would you like to appear for a trial by combat");
      this.emit(":responseReady");
   },
   "quizIntent": function () {
       var mydecision = this.event.request.intent.slots.decision.value;
       if(mydecision=='no'||mydecision=='nope'||mydecision=='naah'){
        this.response.speak("A five year old has more courage than you.");
        this.emit(":responseReady");
       }

       for(var i = 0; i <got.length; i++){
            var myanswer = this.event.request.intent.slots.answer.value;
            var item = got[i].question;
            this.response.speak(item).listen();
            if(myanswer!=got[i].answer){
                this.response.speak("Wrong Answer. You are dead");
                this.emit(':responseReady');

            }
            if(i==got.length-1){
                this.response.speak("You won");
                this.emit(':responseReady');
            }

      }

   },
   "LaunchRequest": function () {
    this.response.speak("Valar Morghulis").listen("You are supposed to say Valar Dohareis");
    this.emit(":responseReady");
   }

};

Here is my Intent Schema in case you wanna look at that too

{
  "languageModel": {
    "types": [
      {
        "name": "answerSlot",
        "values": [
          {
            "id": null,
            "name": {
              "value": "Nymeria",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Harrenhal",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Warg",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Ice",
              "synonyms": []
            }
          }
        ]
      },
      {
        "name": "decisionSlot",
        "values": [
          {
            "id": null,
            "name": {
              "value": "Yes",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "No",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Naah",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Yeah",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Yup",
              "synonyms": []
            }
          },
          {
            "id": null,
            "name": {
              "value": "Nope",
              "synonyms": []
            }
          }
        ]
      }
    ],
    "intents": [
      {
        "name": "AMAZON.CancelIntent",
        "samples": []
      },
      {
        "name": "AMAZON.HelpIntent",
        "samples": []
      },
      {
        "name": "AMAZON.StopIntent",
        "samples": []
      },
      {
        "name": "customIntent",
        "samples": [
          "Valar Dohareis",
          "hello",
          "hola"
        ],
        "slots": []
      },
      {
        "name": "quizIntent",
        "samples": [
          "{decision}",
          "The answer is {answer}"
        ],
        "slots": [
          {
            "name": "decision",
            "type": "decisionSlot"
          },
          {
            "name": "answer",
            "type": "answerSlot"
          }
        ]
      }
    ],
    "invocationName": "quiz game"
  }
}

Body:
for loop doesn't serve any purpose as intent is designed to give a single response on every single invocation. So though you're for loop would be running, it will not emit out the second response as execution after the listen method of the first iteration would be starting from the very start since it's a new invocation.

The purpose you want to attain can be successfully achieved by using Session attribute.

var iterations = 0; //defined globally

// Later on, for every iteration, you simply need to call
// into the attributes property of the alexa object to change the value.

this.attributes['iterations'] = iterations + 1;


来源: stackexchange

问:
SQL Row_Number() increase only when the value = 1 for a specific column
I am having some trouble generating row_number() in my SQL query as my expectation. I have this following output of my query-

Now, I want to add row number for all rows where row number will only increase when the value in C1 is = 1. Required output as below-

Any help will be appreciated. TIA

答:
Table Variable:

```<code>DECLARE @Table AS TABLE (C1 INT)
INSERT INTO @Table VALUES (1),(4),(1),(1),(4),(1),(3),(4)
</code>```

SQL 2008 Version

```<code>;WITH cteSimulateAnOriginalIdentityKey AS (
    SELECT
       C1
       ,OriginalOrder = ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
    FROM
       @Table
)

, cteC1RowNumber AS (
    SELECT
       *
       ,C1RowNumber = ROW_NUMBER() OVER (PARTITION BY C1 ORDER BY OriginalOrder)
    FROM
       cteSimulateAnOriginalIdentityKey
)

SELECT
    C1
    ,RN = ISNULL((SELECT MAX(C1RowNumber) FROM cteC1RowNumber r2 WHERE r2.C1 = 1 AND r2.OriginalOrder <= r1.OriginalOrder),1)
FROM
    cteC1RowNumber r1
ORDER BY
    OriginalOrder
</code>```

SQL 2012+ version

```<code>;WITH cteSimulateAnOriginalIdentityKey AS (
    SELECT
       C1
       ,OriginalOrder = ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
    FROM
       @Table
)

, cteC1RowNumber AS (
    SELECT
       *
       ,C1RowNumber = ROW_NUMBER() OVER (PARTITION BY C1 ORDER BY OriginalOrder)
    FROM
       cteSimulateAnOriginalIdentityKey
)

SELECT
    C1
   ,RN = ISNULL(MAX(CASE WHEN C1 = 1 THEN C1RowNumber END) OVER (ORDER BY OriginalOrder),1)
FROM
    cteC1RowNumber
ORDER BY
    OriginalOrder
</code>```

RESULT:

```<code>C1  RN
1   1
4   1
1   2
1   3
4   3
1   4
3   4
4   4
</code>```

If you in fact have another column by which to maintain the desired original order you don't need the first cte which is simply simulating that column

ContentLicense: CC BY-SA 3.0

Body:
Table Variable:

DECLARE @Table AS TABLE (C1 INT)
INSERT INTO @Table VALUES (1),(4),(1),(1),(4),(1),(3),(4)

SQL 2008 Version

;WITH cteSimulateAnOriginalIdentityKey AS (
    SELECT
       C1
       ,OriginalOrder = ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
    FROM
       @Table
)

, cteC1RowNumber AS (
    SELECT
       *
       ,C1RowNumber = ROW_NUMBER() OVER (PARTITION BY C1 ORDER BY OriginalOrder)
    FROM
       cteSimulateAnOriginalIdentityKey
)

SELECT
    C1
    ,RN = ISNULL((SELECT MAX(C1RowNumber) FROM cteC1RowNumber r2 WHERE r2.C1 = 1 AND r2.OriginalOrder <= r1.OriginalOrder),1)
FROM
    cteC1RowNumber r1
ORDER BY
    OriginalOrder

SQL 2012+ version

;WITH cteSimulateAnOriginalIdentityKey AS (
    SELECT
       C1
       ,OriginalOrder = ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
    FROM
       @Table
)

, cteC1RowNumber AS (
    SELECT
       *
       ,C1RowNumber = ROW_NUMBER() OVER (PARTITION BY C1 ORDER BY OriginalOrder)
    FROM
       cteSimulateAnOriginalIdentityKey
)

SELECT
    C1
   ,RN = ISNULL(MAX(CASE WHEN C1 = 1 THEN C1RowNumber END) OVER (ORDER BY OriginalOrder),1)
FROM
    cteC1RowNumber
ORDER BY
    OriginalOrder

RESULT:

C1  RN
1   1
4   1
1   2
1   3
4   3
1   4
3   4
4   4

If you in fact have another column by which to maintain the desired original order you don't need the first cte which is simply simulating that column


问:
How to fix this Wordpress Fatal error?
This error execute from functions.php

Fatal error: Cannot redeclare new_excerpt_more() (previously declared
  in
  C:\xampp\htdocs\odishaddugkyalumnai\wp-content\themes\odishaddugkyalumnai\functions.php:626)
  in
  C:\xampp\htdocs\odishaddugkyalumnai\wp-content\themes\odishaddugkyalumnai\functions.php
  on line 649

答:
open this file

```<code>C:\xampp\htdocs\odishaddugkyalumnai\wp-content\themes\odishaddugkyalumnai\functions.php
</code>```

and serch for "new_excerpt_more" function and delete it.

Title: How to fix this Wordpress Fatal error?

Body:
open this file

C:\xampp\htdocs\odishaddugkyalumnai\wp-content\themes\odishaddugkyalumnai\functions.php

and serch for "new_excerpt_more" function and delete it.


问:
on click event leads to chain of events after first click
Im trying to add and remove class followed by click events to perform ajax calls. later on success retrieve back the old class. Like Im changing a state of input field to enable, change text of edit button to save and adding class at the same time. when i click same button it has to send modified value in input field to api and restore back to original save button. This is happening for first time when I click edit button. After saving if I click the edit button its changing the state to save and edit back again.help needed.</p>

```<code>           $.each(data, function(key, value) {
            if (parseInt(cat_id[i].innerHTML) == value.category.id) {
                base_rate[i].value = value.base_rate;
                ast[i].innerHTML = value.service_type.name;
                airportEditId[i].setAttribute("id",value.id);
                newEvent = value.id;
                airportEditId[i].classList.add("fireevent"+value.id);
                j = true;
                base_rate[i].setAttribute("disabled",true);
                      $('.fireevent'+value.id).on('click',function(){
                        $(this).attr("id",value.id);
                        $(this).parents("tr").find("input").prop('disabled',false);
                        $(this).text("save");
                        $(this).removeClass().addClass("smokeevent"+value.id).addClass("btn btn-primary");
                        console.log(this);

                      $('.smokeevent'+value.id).on('click',function(){
                           var airport = {
                              "updated_by":{{user.id}},
                              "city":parseInt($('#city_list option:selected').val()),
                              "service_type":parseInt($('#select_service1 option:selected').val()),
                              "base_rate":parseInt($(this).parents("tr").find("input").val()),
                              "vehicle_varient":[1,2]
                           };

                           console.log(airport);
                         $.ajax({
                            url: '/rapido/api/update_airportratecard/'+value.id+'/',
                            method: 'PUT',
                            headers:{'X-CSRFToken':'{{ csrf_token }}'},
                            contentType : 'application/json',
                            context:this,
                            data: JSON.stringify(airport),
                            success:function(res){
                              console.log(this);
                              $(this).text("Edit");
                              $(this).parents("tr").find("input").prop('disabled',true);
                              $(this).removeClass().addClass("btn btn-success");
                            }
                         });
                      });
                    });
</code>```

答:
Try this, In a loop, there are multiple events attached for the same click.
let go off the earlier event and attach again.
    $('.airportdata').off('click').on('click', ...</p>

Body:
Im trying to add and remove class followed by click events to perform ajax calls. later on success retrieve back the old class. Like Im changing a state of input field to enable, change text of edit button to save and adding class at the same time. when i click same button it has to send modified value in input field to api and restore back to original save button. This is happening for first time when I click edit button. After saving if I click the edit button its changing the state to save and edit back again.help needed.

           $.each(data, function(key, value) {
            if (parseInt(cat_id[i].innerHTML) == value.category.id) {
                base_rate[i].value = value.base_rate;
                ast[i].innerHTML = value.service_type.name;
                airportEditId[i].setAttribute("id",value.id);
                newEvent = value.id;
                airportEditId[i].classList.add("fireevent"+value.id);
                j = true;
                base_rate[i].setAttribute("disabled",true);
                      $('.fireevent'+value.id).on('click',function(){
                        $(this).attr("id",value.id);
                        $(this).parents("tr").find("input").prop('disabled',false);
                        $(this).text("save");
                        $(this).removeClass().addClass("smokeevent"+value.id).addClass("btn btn-primary");
                        console.log(this);

                      $('.smokeevent'+value.id).on('click',function(){
                           var airport = {
                              "updated_by":{{user.id}},
                              "city":parseInt($('#city_list option:selected').val()),
                              "service_type":parseInt($('#select_service1 option:selected').val()),
                              "base_rate":parseInt($(this).parents("tr").find("input").val()),
                              "vehicle_varient":[1,2]
                           };

                           console.log(airport);
                         $.ajax({
                            url: '/rapido/api/update_airportratecard/'+value.id+'/',
                            method: 'PUT',
                            headers:{'X-CSRFToken':'{{ csrf_token }}'},
                            contentType : 'application/json',
                            context:this,
                            data: JSON.stringify(airport),
                            success:function(res){
                              console.log(this);
                              $(this).text("Edit");
                              $(this).parents("tr").find("input").prop('disabled',true);
                              $(this).removeClass().addClass("btn btn-success");
                            }
                         });
                      });
                    });


问:
Hive query join with string as datatype
I have two tables in hive and trying to perform a join:

Table A:

```<code>id  ord_time
84  10:00:00
84  12:00:00
84  15:00:00
84  4:00:00
</code>```

Data types:

```<code>Id  : int
ord_time : String
</code>```

Table B:

```<code>id  time_desc   beg_tm        end_tm
84  Late Night  00:00:00      04:59:59
84  Break Fast  05:00:00      10:29:59
84  Dinner      16:00:00      20:59:59
84  Lunch       11:00:00      13:59:59
84  Snack       14:00:00      15:59:59
</code>```

Data types:

```<code>Id  : int
time_desc : String
beg_tm : String
end_tm : String
</code>```

Query :

```<code>Select a.ord_time,b.id,b.time_desc,b.beg_tm,b.end_tm
from Table A a,Table B b
where a.id = b.id
and a.ord_time between b.beg_tm and b.end_tm
</code>```

When I ran the above query Result was Null.

I want the output to be:

```<code>id  ord_time    time_desc
84  10:00:00    BreakFast
84  12:00:00    Lunch
84  15:00:00    Snack
84  04:00:00    Late Night
</code>```

答:
Between also didnt work for me. Then I thought

```<code>name between "a" and "b"
</code>```

is equivalent to

```<code>name >="a" and name <="b"
</code>```

So I tried this. And it worked for me. Try for your case. Hope it works for you.

Title: Hive query join with string as datatype

Body:
I have two tables in hive and trying to perform a join:

Table A:

id  ord_time
84  10:00:00
84  12:00:00
84  15:00:00
84  4:00:00

Data types:

Id  : int
ord_time : String

Table B:

id  time_desc   beg_tm        end_tm
84  Late Night  00:00:00      04:59:59
84  Break Fast  05:00:00      10:29:59
84  Dinner      16:00:00      20:59:59
84  Lunch       11:00:00      13:59:59
84  Snack       14:00:00      15:59:59

Data types:

Id  : int
time_desc : String
beg_tm : String
end_tm : String

Query :

Select a.ord_time,b.id,b.time_desc,b.beg_tm,b.end_tm
from Table A a,Table B b
where a.id = b.id
and a.ord_time between b.beg_tm and b.end_tm

When I ran the above query Result was Null.

I want the output to be:

id  ord_time    time_desc
84  10:00:00    BreakFast
84  12:00:00    Lunch
84  15:00:00    Snack
84  04:00:00    Late Night

Body:
Between also didnt work for me. Then I thought

name between "a" and "b"

is equivalent to

name >="a" and name <="b"

So I tried this. And it worked for me. Try for your case. Hope it works for you.


问:
Issue importing java.util.function using Java 9
I'm having an importing issue with:

```<code>import com.google.common.base.Function;
</code>```

When I run my test I receive an error that states:

```<code>Error:(31, 33) java: cannot access java.util.function.Supplier
class file for java.util.function.Supplier not found
Error:(34, 49) java: cannot access java.util.function.Function
class file for java.util.function.Function not found
</code>```

So far I've learned that Java 8 uses these as replacements. However adding the following imports did not work:

```<code>import java.util.function.Function;
import java.util.function.Supplier;
import java.util.function.*;
</code>```

They are underscored in red (Intelli-J) and I receive the following errors:

```<code>Error:(22, 26) java: package java.util.function does not exist
Error:(23, 26) java: package java.util.function does not exist
Error:(21, 1) java: package java.util.function does not exist
</code>```

Important things to note is that I'm using Java 9, I do not have any previous Java installed because this a new laptop. Also, this project was created using Java 8. I'm also using maven.

I'm guessing that I probably have to update my project some how maybe in the PomXML file to reflect what JDK I'm using.

I installed java using Homebrew and I'm not sure how to install previous version of java.

Any help is greatly appreciated!

example of specific code that requires this import:

```<code>private static WebElement webAction(final By locator) {
    Wait<WebDriver> wait = new FluentWait<WebDriver>(SharedSD.getDriver())
            .withTimeout(15, TimeUnit.SECONDS)
            .pollingEvery(1, TimeUnit.SECONDS)
            .ignoring(java.util.NoSuchElementException.class)
            .ignoring(StaleElementReferenceException.class)
            .ignoring(ElementNotFoundException.class)
            .withMessage(
                    "Web driver waited for 15 seconds but still could not find the element therefore Timeout Exception has been thrown");

    WebElement element = wait.until(new Function<WebDriver, WebElement>() {
        public WebElement apply(WebDriver driver) {
            return driver.findElement(locator);
        }
    });
</code>```

pom.xml content :

```<code><parent>
    <groupId>ru.yandex.qatools.allure</groupId>
    <artifactId>allure-examples-parent</artifactId>
    <version>1.0</version>
</parent>

<groupId>CucumberSample</groupId>
<artifactId>com.cucumber.sample</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <allure.version>1.4.23</allure.version>
    <aspectj.version>1.8.9</aspectj.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.11</version>
    </dependency>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.4.0</version>
    </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-core</artifactId>
        <version>1.2.4</version>
    </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>1.2.4</version>
    </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>1.2.4</version>
    </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-jvm-deps</artifactId>
        <version>1.0.5</version>
    </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-testng</artifactId>
        <version>1.2.4</version>
    </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-picocontainer</artifactId>
        <version>1.2.4</version>
    </dependency>
    <dependency>
        <groupId>net.masterthought</groupId>
        <artifactId>cucumber-reporting</artifactId>
        <version>2.1.0</version>
    </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>gherkin</artifactId>
        <version>2.12.2</version>
    </dependency>
    <dependency>
        <groupId>ru.yandex.qatools.allure</groupId>
        <artifactId>allure-cucumber-jvm-adaptor</artifactId>
        <version>1.5.1</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.18.1</version>
            <configuration>

                <testFailureIgnore>false</testFailureIgnore>
                <argLine>
                    -javaagent:${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar
                </argLine>
                <properties>
                    <property>
                        <name>listener</name>
                        <value>ru.yandex.qatools.allure.cucumberjvm.AllureRunListener</value>
                    </property>
                </properties>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.aspectj</groupId>
                    <artifactId>aspectjweaver</artifactId>
                    <version>${aspectj.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.apache.maven.surefire</groupId>
                    <artifactId>surefire-junit47</artifactId>
                    <version>2.13</version>
                </dependency>
            </dependencies>
        </plugin>

        <!--Needed only to show reports locally. Run jetty:run and
        open localhost:8080 to show the report-->
        <plugin>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-maven-plugin</artifactId>
            <version>9.2.10.v20150310</version>
            <configuration>
                <webAppSourceDirectory>${project.build.directory}/site/allure-maven-plugin</webAppSourceDirectory>
                <stopKey>stop</stopKey>
                <stopPort>1234</stopPort>
            </configuration>
        </plugin>
    </plugins>
</build>

<reporting>
    <excludeDefaults>true</excludeDefaults>
    <plugins>
        <plugin>
            <groupId>ru.yandex.qatools.allure</groupId>
            <artifactId>allure-maven-plugin</artifactId>
            <version>2.0</version>
        </plugin>
    </plugins>
</reporting>
</code>```

答:
Few things that can be improved in your pom.xml configuration definitely for Java9 compatibility includes:-

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.7.0</version>
    <configuration>
         <!-- specify current java version here: -->
         <source>9</source>
         <target>9</target> <!-- or edit these in your properties -->
    </configuration>
</plugin>
</code>```

and

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.20.1</version>
    <configuration> ... your configuration </configuration>
</plugin>
</code>```

You can also configure a toolchains.xml with JDK version 9 as well and then run your tests using the custom path to it.

Edit from the comments - Do make sure your IntelliJ version is also compatible with Java9. (if the errors you see are in IntelliJ execution)

Body:
I'm having an importing issue with:

import com.google.common.base.Function;

When I run my test I receive an error that states:

Error:(31, 33) java: cannot access java.util.function.Supplier
class file for java.util.function.Supplier not found
Error:(34, 49) java: cannot access java.util.function.Function
class file for java.util.function.Function not found

So far I've learned that Java 8 uses these as replacements. However adding the following imports did not work:

import java.util.function.Function;
import java.util.function.Supplier;
import java.util.function.*;

They are underscored in red (Intelli-J) and I receive the following errors:

Error:(22, 26) java: package java.util.function does not exist
Error:(23, 26) java: package java.util.function does not exist
Error:(21, 1) java: package java.util.function does not exist

Important things to note is that I'm using Java 9, I do not have any previous Java installed because this a new laptop. Also, this project was created using Java 8. I'm also using maven.

I'm guessing that I probably have to update my project some how maybe in the PomXML file to reflect what JDK I'm using.

I installed java using Homebrew and I'm not sure how to install previous version of java.

Any help is greatly appreciated!

example of specific code that requires this import:

private static WebElement webAction(final By locator) {
    Wait<WebDriver> wait = new FluentWait<WebDriver>(SharedSD.getDriver())
            .withTimeout(15, TimeUnit.SECONDS)
            .pollingEvery(1, TimeUnit.SECONDS)
            .ignoring(java.util.NoSuchElementException.class)
            .ignoring(StaleElementReferenceException.class)
            .ignoring(ElementNotFoundException.class)
            .withMessage(
                    "Web driver waited for 15 seconds but still could not find the element therefore Timeout Exception has been thrown");

    WebElement element = wait.until(new Function<WebDriver, WebElement>() {
        public WebElement apply(WebDriver driver) {
            return driver.findElement(locator);
        }
    });

pom.xml content :

<parent>
    <groupId>ru.yandex.qatools.allure</groupId>
    <artifactId>allure-examples-parent</artifactId>
    <version>1.0</version>
</parent>

<groupId>CucumberSample</groupId>
<artifactId>com.cucumber.sample</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <allure.version>1.4.23</allure.version>
    <aspectj.version>1.8.9</aspectj.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>6.11</version>
    </dependency>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.4.0</version>
    </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-core</artifactId>
        <version>1.2.4</version>
    </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>1.2.4</version>
    </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>1.2.4</version>
    </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-jvm-deps</artifactId>
        <version>1.0.5</version>
    </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-testng</artifactId>
        <version>1.2.4</version>
    </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-picocontainer</artifactId>
        <version>1.2.4</version>
    </dependency>
    <dependency>
        <groupId>net.masterthought</groupId>
        <artifactId>cucumber-reporting</artifactId>
        <version>2.1.0</version>
    </dependency>
    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>gherkin</artifactId>
        <version>2.12.2</version>
    </dependency>
    <dependency>
        <groupId>ru.yandex.qatools.allure</groupId>
        <artifactId>allure-cucumber-jvm-adaptor</artifactId>
        <version>1.5.1</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.18.1</version>
            <configuration>

                <testFailureIgnore>false</testFailureIgnore>
                <argLine>
                    -javaagent:${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar
                </argLine>
                <properties>
                    <property>
                        <name>listener</name>
                        <value>ru.yandex.qatools.allure.cucumberjvm.AllureRunListener</value>
                    </property>
                </properties>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.aspectj</groupId>
                    <artifactId>aspectjweaver</artifactId>
                    <version>${aspectj.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.apache.maven.surefire</groupId>
                    <artifactId>surefire-junit47</artifactId>
                    <version>2.13</version>
                </dependency>
            </dependencies>
        </plugin>

        <plugin>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-maven-plugin</artifactId>
            <version>9.2.10.v20150310</version>
            <configuration>
                <webAppSourceDirectory>${project.build.directory}/site/allure-maven-plugin</webAppSourceDirectory>
                <stopKey>stop</stopKey>
                <stopPort>1234</stopPort>
            </configuration>
        </plugin>
    </plugins>
</build>

<reporting>
    <excludeDefaults>true</excludeDefaults>
    <plugins>
        <plugin>
            <groupId>ru.yandex.qatools.allure</groupId>
            <artifactId>allure-maven-plugin</artifactId>
            <version>2.0</version>
        </plugin>
    </plugins>
</reporting>

Body:
Few things that can be improved in your pom.xml configuration definitely for Java9 compatibility includes:-

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.7.0</version>
    <configuration>
         <!-- specify current java version here: -->
         <source>9</source>
         <target>9</target> <!-- or edit these in your properties -->
    </configuration>
</plugin>

and

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.20.1</version>
    <configuration> ... your configuration </configuration>
</plugin>

You can also configure a toolchains.xml with JDK version 9 as well and then run your tests using the custom path to it.

Edit from the comments - Do make sure your IntelliJ version is also compatible with Java9. (if the errors you see are in IntelliJ execution)


问:
Snakemake on cluster, avoid submitting one rule as a job
I'm executing a snakemake pipeline using

```<code>snakemake --cluster ...
</code>```

It's working nicely right now. However for reasons I won't describe here I want one of my rules not to be submitted as a job, but to be executed in the machine/node where snakemake is running. Is it possible to make such an exception?

答: Yes, you can mark rules as local, see the docs: http://snakemake.readthedocs.io/en/stable/snakefiles/rules.html?highlight=Localrules#local-rules</p>

Body:
I'm executing a snakemake pipeline using

snakemake --cluster ...

It's working nicely right now. However for reasons I won't describe here I want one of my rules not to be submitted as a job, but to be executed in the machine/node where snakemake is running. Is it possible to make such an exception?


问:
Mongodb- using find() method on an Array of Objects only return first match instead of all
Unlike the other question someone asked where they wanted only one item returned. I HAVE one item returned and I need ALL of the matching objects in the array return. However the second object that matches my query is being completely ignored.

This is what one of the items in the item collection looks like:

```<code>     {
       name: "soda",
       cost: .50,
       inventory: [
             { flavor: "Grape",
               amount: 8 },
             { flavor: "Orange",
               amount: 4 },
             { flavor: "Root Beer",
               amount: 15 }
       ]
     }
</code>```

Here is the query I typed in to mongo shell:

```<code>    Items.find({"inventory.amount" : { $lte : 10} } , { name : 1,  "inventory.$.flavor" : 1})
</code>```

And here is the result:

```<code>    "_id" : ObjectId("59dbe33094b70e0b5851724c"),
    "name": "soda"
    "inventory" : [
           { "flavor" : "Grape",
             "amount" : 8,
           }
     ]
</code>```

And here is what I want it to return to me:

```<code>    "_id" : ObjectId("59dbe33094b70e0b5851724c"),
    "name": "soda"
    "inventory" : [
           { "flavor" : "Grape",
             "amount" : 8
           },
           { "flavor" : "Orange",
             "amount" : 4
           }
     ]
</code>```

I'm new to mongo and am dabbling to get familiar with it. I've read through the docs but couldn't find a solution to this though it's quite possible I overlooked it. I'd really love some help. Thanks in advance.

答:
first u can get your result by this query</p>

```<code>db.Items.find({"inventory.amount" : { $lte : 10} } , { name : 1,  "inventory.flavor" : 1 , "inventory.amount" : 1})
</code>```

Body:
Unlike the other question someone asked where they wanted only one item returned. I HAVE one item returned and I need ALL of the matching objects in the array return. However the second object that matches my query is being completely ignored.

This is what one of the items in the item collection looks like:

     {
       name: "soda",
       cost: .50,
       inventory: [
             { flavor: "Grape",
               amount: 8 },
             { flavor: "Orange",
               amount: 4 },
             { flavor: "Root Beer",
               amount: 15 }
       ]
     }

Here is the query I typed in to mongo shell:

    Items.find({"inventory.amount" : { $lte : 10} } , { name : 1,  "inventory.$.flavor" : 1})

And here is the result:

    "_id" : ObjectId("59dbe33094b70e0b5851724c"),
    "name": "soda"
    "inventory" : [
           { "flavor" : "Grape",
             "amount" : 8,
           }
     ]

And here is what I want it to return to me:

    "_id" : ObjectId("59dbe33094b70e0b5851724c"),
    "name": "soda"
    "inventory" : [
           { "flavor" : "Grape",
             "amount" : 8
           },
           { "flavor" : "Orange",
             "amount" : 4
           }
     ]

I'm new to mongo and am dabbling to get familiar with it. I've read through the docs but couldn't find a solution to this though it's quite possible I overlooked it. I'd really love some help. Thanks in advance.

Body:
first u can get your result by this query

db.Items.find({"inventory.amount" : { $lte : 10} } , { name : 1,  "inventory.flavor" : 1 , "inventory.amount" : 1})


问:
Coding Standard Wiki
At my place of work I've been put in charge of creating a coding standards document. Generally we follow what FxCop and StyleCop tools report to some degree but what we really require is document that will explain when to use a convention, why and maybe even a simple example.

This could be extended in the future for other purposes as well.

The first thing that came to my mind is to have an internal wiki site that we could build up and change easily over time but I've never used a wiki-based engine before and would like some recommendations.

If possible the engine should be in C# so we're able to tweak it to our needs if required.

If you think a wiki solution is the wrong way to go about this then please give an alternative :)

Update

I've just been informed, although we do have a php server it wont be staying, so I'm afraid php-based wiki ideas are off the table.

Update 2

Could you also (if possible) let me know if any of these solutions work with Active Directory?

Cheers
Tony

答:
Brad Abrams has published an online set of C# coding standrds:

http://blogs.msdn.com/brada/articles/361363.aspx

If you go to the starter kits section of the Microsoft ASP.NET site, you will find several wikis to download such as ScrewTurn and Flexwiki. A wiki would be ideal for your needs by the sound of it :-)

ContentLicense: CC BY-SA 2.5

Title: Coding Standard Wiki

OwnerDisplayName: IrishChieftain


问:
Overflow:hidden not working on any Android Device Mobile App
I am using CSS property overflow:hidden(overflow-y:hidden; / overflow-x:hidden;) to stop the body scrolling on mobile app. It's working on mobile Browser, but this code is not working on any Android Device.</p>

```<code>body {
overflow:hidden;
}
</code>```

答:
Try adding following line in your html</p>

```<code><meta name="viewport" content="width=device-width, height=device-height">
</code>```

Body:
I am using CSS property overflow:hidden(overflow-y:hidden; / overflow-x:hidden;) to stop the body scrolling on mobile app. It's working on mobile Browser, but this code is not working on any Android Device.

body {
overflow:hidden;
}

Body:
Try adding following line in your html

<meta name="viewport" content="width=device-width, height=device-height">


问:
SparkSQL+Hive+Hbase+HbaseIntegration doesn't work
I am getting error when I am trying to connect hive table (which is being
created through HbaseIntegration) in spark

Steps I followed :
Hive Table creation code :

```<code>CREATE TABLE test.sample(id string,name string)
STORED BY 'org.apache.hadoop.hive.hbase.HBaseStorageHandler' WITH
SERDEPROPERTIES ("hbase.columns.mapping" = ":key,details:name")
TBLPROPERTIES ("hbase.table.name" = "sample");
</code>```

DESCRIBE TEST ;

```<code> col_name data_type comment
 id string from deserializer
 name string from deserializer
</code>```

Starting Spark shell with this command:

```<code>spark-shell --master local[2] --driver-class-path /usr/local/hive/lib/hive-
hbase-handler-1.2.1.jar:
/usr/local/hbase/lib/hbase-server-0.98.9-
hadoop2.jar:/usr/local/hbase/lib/hbase-protocol-0.98.9-hadoo2.jar:
/usr/local/hbase/lib/hbase-hadoop2-compat-0.98.9-
hadoop2.jar:/usr/local/hbase/lib/hbase-hadoop-compat-0.98.9-hadoop2.jar:
/usr/local/hbase/lib/hbase-client-0.98.9-
hadoop2.jar:/usr/local/hbase/lib/hbase-common-0.98.9-hadoop2.jar:
/usr/local/hbase/lib/htrace-core-2.04.jar:/usr/local/hbase/lib/hbase-common-
0.98.9-hadoop2-tests.jar:
/usr/local/hbase/lib/hbase-server-0.98.9-hadoop2-
tests.jar:/usr/local/hive/lib/zookeeper-3.4.6.jar:/usr/local/hive/lib/guava-
14.0.1.jar
</code>```

In spark-shell:

```<code>val sqlContext=new org.apache.spark.sql.hive.HiveContext(sc)

sqlContext.sql(“select count(*) from test.sample”).collect()
</code>```

Stack Trace :

Stack SQL context available as sqlContext.

```<code>scala> sqlContext.sql("select count(*) from test.sample").collect()

16/09/02 04:49:28 INFO parse.ParseDriver: Parsing command: select count(*) from test.sample
16/09/02 04:49:35 INFO parse.ParseDriver: Parse Completed
16/09/02 04:49:40 INFO metastore.HiveMetaStore: 0: get_table : db=test tbl=sample
16/09/02 04:49:40 INFO HiveMetaStore.audit: ugi=hdfs    ip=unknown-ip-addr  cmd=get_table : db=test tbl=sample
java.lang.NoClassDefFoundError: org/apache/hadoop/hbase/util/Bytes
    at org.apache.hadoop.hive.hbase.HBaseSerDe.parseColumnsMapping(HBaseSerDe.java:184)
    at org.apache.hadoop.hive.hbase.HBaseSerDeParameters.<init>(HBaseSerDeParameters.java:73)
    at org.apache.hadoop.hive.hbase.HBaseSerDe.initialize(HBaseSerDe.java:117)
    at org.apache.hadoop.hive.serde2.AbstractSerDe.initialize(AbstractSerDe.java:53)
    at org.apache.hadoop.hive.serde2.SerDeUtils.initializeSerDe(SerDeUtils.java:521)
    at org.apache.hadoop.hive.metastore.MetaStoreUtils.getDeserializer(MetaStoreUtils.java:391)
    at org.apache.hadoop.hive.ql.metadata.Table.getDeserializerFromMetaStore(Table.java:276)
    at org.apache.hadoop.hive.ql.metadata.Table.getDeserializer(Table.java:258)
    at org.apache.hadoop.hive.ql.metadata.Table.getCols(Table.java:605)
    at org.apache.spark.sql.hive.client.ClientWrapper$$anonfun$getTableOption$1$$anonfun$3.apply(ClientWrapper.scala:331)
    at org.apache.spark.sql.hive.client.ClientWrapper$$anonfun$getTableOption$1$$anonfun$3.apply(ClientWrapper.scala:326)
    at scala.Option.map(Option.scala:145)
    at org.apache.spark.sql.hive.client.ClientWrapper$$anonfun$getTableOption$1.apply(ClientWrapper.scala:326)
    at org.apache.spark.sql.hive.client.ClientWrapper$$anonfun$getTableOption$1.apply(ClientWrapper.scala:321)
    at org.apache.spark.sql.hive.client.ClientWrapper$$anonfun$withHiveState$1.apply(ClientWrapper.scala:279)
    at org.apache.spark.sql.hive.client.ClientWrapper.liftedTree1$1(ClientWrapper.scala:226)
    at org.apache.spark.sql.hive.client.ClientWrapper.retryLocked(ClientWrapper.scala:225)
    at org.apache.spark.sql.hive.client.ClientWrapper.withHiveState(ClientWrapper.scala:268)
    at org.apache.spark.sql.hive.client.ClientWrapper.getTableOption(ClientWrapper.scala:321)
    at org.apache.spark.sql.hive.client.ClientInterface$class.getTable(ClientInterface.scala:122)
    at org.apache.spark.sql.hive.client.ClientWrapper.getTable(ClientWrapper.scala:60)
    at org.apache.spark.sql.hive.HiveMetastoreCatalog.lookupRelation(HiveMetastoreCatalog.scala:384)
    at org.apache.spark.sql.hive.HiveContext$$anon$2.org$apache$spark$sql$catalyst$analysis$OverrideCatalog$$super$lookupRelation(HiveContext.scala:457)
    at org.apache.spark.sql.catalyst.analysis.OverrideCatalog$class.lookupRelation(Catalog.scala:161)
    at org.apache.spark.sql.hive.HiveContext$$anon$2.lookupRelation(HiveContext.scala:457)
    at org.apache.spark.sql.catalyst.analysis.Analyzer$ResolveRelations$.getTable(Analyzer.scala:303)
</code>```

I am using hadoop 2.6.0, spark 1.6.0, hive 1.2.1, hbase 0.98.9

I added this setting in hadoop-env.sh as

```<code>export HADOOP_CLASSPATH=$HADOOP_CLASSPATH:$HBASE_HOME/lib/*
</code>```

Can some body please suggest any solution

答:
I got it working . You have to use below jars .

spark-shell   --master yarn-client --executor-cores 10 --executor-memory 20G --num-executors 15 --driver-memory 2G --driver-class-path /usr/hdp/current/hbase-client/lib/hbase-common.jar:/usr/hdp/current/hbase-client/lib/hbase-client.jar:/usr/hdp/current/hbase-client/lib/hbase-server.jar:/usr/hdp/current/hbase-client/lib/hbase-protocol.jar:/usr/hdp/current/hbase-client/lib/guava-12.0.1.jar:/usr/hdp/current/hbase-client/lib/htrace-core-3.1.0-incubating.jar --jars /usr/hdp/current/hbase-client/lib/hbase-client.jar,/usr/hdp/current/hbase-client/lib/hbase-common.jar,/usr/hdp/current/hbase-client/lib/hbase-server.jar,/usr/hdp/current/hbase-client/lib/guava-12.0.1.jar,/usr/hdp/current/hbase-client/lib/hbase-protocol.jar,/usr/hdp/current/hbase-client/lib/htrace-core-3.1.0-incubating.jar,/usr/hdp/current/hive-client/lib/hive-hbase-handler.jar --files /etc/spark/conf/hbase-site.xml

Body:
I am getting error when I am trying to connect hive table (which is being
created through HbaseIntegration) in spark

Steps I followed :
Hive Table creation code :

CREATE TABLE test.sample(id string,name string)
STORED BY 'org.apache.hadoop.hive.hbase.HBaseStorageHandler' WITH
SERDEPROPERTIES ("hbase.columns.mapping" = ":key,details:name")
TBLPROPERTIES ("hbase.table.name" = "sample");

DESCRIBE TEST ;

 col_name data_type comment
 id string from deserializer
 name string from deserializer

Starting Spark shell with this command:

spark-shell --master local[2] --driver-class-path /usr/local/hive/lib/hive-
hbase-handler-1.2.1.jar:
/usr/local/hbase/lib/hbase-server-0.98.9-
hadoop2.jar:/usr/local/hbase/lib/hbase-protocol-0.98.9-hadoo2.jar:
/usr/local/hbase/lib/hbase-hadoop2-compat-0.98.9-
hadoop2.jar:/usr/local/hbase/lib/hbase-hadoop-compat-0.98.9-hadoop2.jar:
/usr/local/hbase/lib/hbase-client-0.98.9-
hadoop2.jar:/usr/local/hbase/lib/hbase-common-0.98.9-hadoop2.jar:
/usr/local/hbase/lib/htrace-core-2.04.jar:/usr/local/hbase/lib/hbase-common-
0.98.9-hadoop2-tests.jar:
/usr/local/hbase/lib/hbase-server-0.98.9-hadoop2-
tests.jar:/usr/local/hive/lib/zookeeper-3.4.6.jar:/usr/local/hive/lib/guava-
14.0.1.jar

In spark-shell:

val sqlContext=new org.apache.spark.sql.hive.HiveContext(sc)

sqlContext.sql(“select count(*) from test.sample”).collect()

Stack Trace :

Stack SQL context available as sqlContext.

scala> sqlContext.sql("select count(*) from test.sample").collect()

16/09/02 04:49:28 INFO parse.ParseDriver: Parsing command: select count(*) from test.sample
16/09/02 04:49:35 INFO parse.ParseDriver: Parse Completed
16/09/02 04:49:40 INFO metastore.HiveMetaStore: 0: get_table : db=test tbl=sample
16/09/02 04:49:40 INFO HiveMetaStore.audit: ugi=hdfs    ip=unknown-ip-addr  cmd=get_table : db=test tbl=sample
java.lang.NoClassDefFoundError: org/apache/hadoop/hbase/util/Bytes
    at org.apache.hadoop.hive.hbase.HBaseSerDe.parseColumnsMapping(HBaseSerDe.java:184)
    at org.apache.hadoop.hive.hbase.HBaseSerDeParameters.<init>(HBaseSerDeParameters.java:73)
    at org.apache.hadoop.hive.hbase.HBaseSerDe.initialize(HBaseSerDe.java:117)
    at org.apache.hadoop.hive.serde2.AbstractSerDe.initialize(AbstractSerDe.java:53)
    at org.apache.hadoop.hive.serde2.SerDeUtils.initializeSerDe(SerDeUtils.java:521)
    at org.apache.hadoop.hive.metastore.MetaStoreUtils.getDeserializer(MetaStoreUtils.java:391)
    at org.apache.hadoop.hive.ql.metadata.Table.getDeserializerFromMetaStore(Table.java:276)
    at org.apache.hadoop.hive.ql.metadata.Table.getDeserializer(Table.java:258)
    at org.apache.hadoop.hive.ql.metadata.Table.getCols(Table.java:605)
    at org.apache.spark.sql.hive.client.ClientWrapper$$anonfun$getTableOption$1$$anonfun$3.apply(ClientWrapper.scala:331)
    at org.apache.spark.sql.hive.client.ClientWrapper$$anonfun$getTableOption$1$$anonfun$3.apply(ClientWrapper.scala:326)
    at scala.Option.map(Option.scala:145)
    at org.apache.spark.sql.hive.client.ClientWrapper$$anonfun$getTableOption$1.apply(ClientWrapper.scala:326)
    at org.apache.spark.sql.hive.client.ClientWrapper$$anonfun$getTableOption$1.apply(ClientWrapper.scala:321)
    at org.apache.spark.sql.hive.client.ClientWrapper$$anonfun$withHiveState$1.apply(ClientWrapper.scala:279)
    at org.apache.spark.sql.hive.client.ClientWrapper.liftedTree1$1(ClientWrapper.scala:226)
    at org.apache.spark.sql.hive.client.ClientWrapper.retryLocked(ClientWrapper.scala:225)
    at org.apache.spark.sql.hive.client.ClientWrapper.withHiveState(ClientWrapper.scala:268)
    at org.apache.spark.sql.hive.client.ClientWrapper.getTableOption(ClientWrapper.scala:321)
    at org.apache.spark.sql.hive.client.ClientInterface$class.getTable(ClientInterface.scala:122)
    at org.apache.spark.sql.hive.client.ClientWrapper.getTable(ClientWrapper.scala:60)
    at org.apache.spark.sql.hive.HiveMetastoreCatalog.lookupRelation(HiveMetastoreCatalog.scala:384)
    at org.apache.spark.sql.hive.HiveContext$$anon$2.org$apache$spark$sql$catalyst$analysis$OverrideCatalog$$super$lookupRelation(HiveContext.scala:457)
    at org.apache.spark.sql.catalyst.analysis.OverrideCatalog$class.lookupRelation(Catalog.scala:161)
    at org.apache.spark.sql.hive.HiveContext$$anon$2.lookupRelation(HiveContext.scala:457)
    at org.apache.spark.sql.catalyst.analysis.Analyzer$ResolveRelations$.getTable(Analyzer.scala:303)

I am using hadoop 2.6.0, spark 1.6.0, hive 1.2.1, hbase 0.98.9

I added this setting in hadoop-env.sh as

export HADOOP_CLASSPATH=$HADOOP_CLASSPATH:$HBASE_HOME/lib/*

Can some body please suggest any solution


问:
Call PageFactory.InitElements in parallel running tests
How do I call PageFactory.InitElements(driver, this) when running tests in parallel? Do I need to : Hooks in my Page classes? Should I be passing the driver to the Page in my test with something like:

```<code>    Login pgLogin = PageFactory.InitElements(driver, Login.class);
</code>```

I doubt that I am the first person to build a framework using Page Object Model + Page Factory + C# + NUnit3 for testing in Parallel on Selenium Grid.. but can't find many examples. Most are very simplistic, depicting driver-setup and a test in one method, but when adding complexity through multiple tests and referencing objects from a Page.cs, additional logic is needed that I just don't know.

Code below:

Login.cs

Test.cs

Base.cs

Hooks.cs

答:
You can pass the driver object to the page object class :

Test method look like :

```<code>WebDriver driver;
public void yourTest(){
  Login login = new Login(driver);
  your rest of the code ......
}
</code>```

Page object class :

```<code>class Login{
 WebDriver driver;
 public Login(WebDriver driver){
    this.driver = driver;
    PageFactory.InitElements( this.driver, this);
    ............... your code
  }
 // required page elements like txtEmail.
}
</code>```

Body:
How do I call PageFactory.InitElements(driver, this) when running tests in parallel? Do I need to : Hooks in my Page classes? Should I be passing the driver to the Page in my test with something like:

    Login pgLogin = PageFactory.InitElements(driver, Login.class);

I doubt that I am the first person to build a framework using Page Object Model + Page Factory + C# + NUnit3 for testing in Parallel on Selenium Grid.. but can't find many examples. Most are very simplistic, depicting driver-setup and a test in one method, but when adding complexity through multiple tests and referencing objects from a Page.cs, additional logic is needed that I just don't know.

Code below:

Login.cs

Test.cs

Base.cs

Hooks.cs

Body:
You can pass the driver object to the page object class :

Test method look like :

WebDriver driver;
public void yourTest(){
  Login login = new Login(driver);
  your rest of the code ......
}

Page object class :

class Login{
 WebDriver driver;
 public Login(WebDriver driver){
    this.driver = driver;
    PageFactory.InitElements( this.driver, this);
    ............... your code
  }
 // required page elements like txtEmail.
}


问:
printjs in angular having properties with json object inside one other json
I am using printJs library for printing in properties I added JSON object properties its working fine, but if that JSON object contains one more JSON object inside it is showing [object object]. Can anyone tell me the solution?

```<code> PrintJS({

  printable: printIndexes,
  properties: ['reporter', 'entryTime', 'exitTime', 'status'],

  type: 'json',
  gridHeaderStyle: 'color: red;  border: 2px solid #3971A5;',
  gridStyle: 'border: 2px solid #3971A5;',
  header: 'List of master index'
</code>```

Please see this image it is showing like [object object] there I want to display name.

答:
traverse the object inner deep
for example:

user:{
    name:'xxx',
    address:{
              building:{
                           no:64,
                           street:corinder
                        },
              city:'texas'
             }
       }```

You can traverse by user.address.building.no it will shown 64

Body:
I am using printJs library for printing in properties I added JSON object properties its working fine, but if that JSON object contains one more JSON object inside it is showing [object object]. Can anyone tell me the solution?

 PrintJS({

  printable: printIndexes,
  properties: ['reporter', 'entryTime', 'exitTime', 'status'],

  type: 'json',
  gridHeaderStyle: 'color: red;  border: 2px solid #3971A5;',
  gridStyle: 'border: 2px solid #3971A5;',
  header: 'List of master index'

Please see this image it is showing like [object object] there I want to display name.

Body:
traverse the object inner deep
for example:

user:{
    name:'xxx',
    address:{
              building:{
                           no:64,
                           street:corinder
                        },
              city:'texas'
             }
       }

You can traverse by user.address.building.no it will shown 64


问:
What's the best way to run a python script daily?
I have a python script that connects to Redshift, executes a series of SQL commands, and generates a new derived table.

But for the life of me, I can't figure out a way to have it automatically run every day.

I've tried AWS Data Pipeline but my shell script won't run the first copy statement.
I can't get Lambda or Glue to work because my company's IAM policies are restrictive.
Airflow seems like overkill to just run a single python script daily.

Any suggestions for services to look into?

答:
Cron job?

```<code>00 12 * * * /home/scottie/bin/my_python_script.py
</code>```

Run my_python_script.py at the top of the hour (0th minute), at noon, every day.

Body:
Cron job?

00 12 * * * /home/scottie/bin/my_python_script.py

Run my_python_script.py at the top of the hour (0th minute), at noon, every day.


问:
UITableViewCell : UIImageView in ContentView overlaps images in iPhone SDK.
In my iPhone app,  I am using a tableView and have added the imageView as ContentView in my tableViewcell.

At the click of button I am changing the tableView Contents. So every time I click a button it should show the corresponding image in tableViewCell.

Problem:

Suppose I am loading images 1.png, 2.png and 3.png in tableView on click of button A, B and C respectively.

Now let us consider that initially I clicked button A and 1.png appears. Now when I click the button B then 2.png appears but 1.png also remains in background. So basically it overlaps the tableViewCell with a new image.

Troubleshooting I already have done:

1) I tried releasing imageView and setting imageView.image = nil;

2) I tried reloading the table and empty out table before each button click.

3) Even I tried putting the whole code in if(cell==nil) clause of cellForRowAtIndexPath method

答:
It seems that you have set the image in the (cell==nil) block. If yes please comment that out.

Do it like:

```<code>if(cell ==nil){
//add image view here.
}

UIImageView *imgView = (UIImageView *)[cell.contentView viewWithTag:ImgViewTag];
if(condition)
   imgView.image = someImage;
else
   imgView.image = nil;
</code>```

Body:
It seems that you have set the image in the (cell==nil) block. If yes please comment that out.

Do it like:

if(cell ==nil){
//add image view here.
}

UIImageView *imgView = (UIImageView *)[cell.contentView viewWithTag:ImgViewTag];
if(condition)
   imgView.image = someImage;
else
   imgView.image = nil;


问:
bash: extract an attribute value between quotes using awk or sed(GNU grep is not an option)
I have a xml file with data like below

```<code><temp>
<a="something" total="50" b="something" total="0" c="something" total="20">
</temp>
</code>```

I need to get first value of total i.e, 50 but my sed solution is giving value of last occurrence of total i.e, 20

```<code>sed -n 's/.*total="\([^"]*\).*/\1/p' temp.xml
</code>```

output : 20

desired output: 50

I appreciate the help. Thank you

答:
sed does not support non greedy match. Excerpt from here:

The trick to get non greedy matching in sed is to match all characters excluding the one that terminates the match.

So your solution is becomes:

```<code>sed -n 's/.[^ ]* total="\([^"]*\).*/\1/p' temp.xml
</code>```

Body:
I have a xml file with data like below

<temp>

</temp>

I need to get first value of total i.e, 50 but my sed solution is giving value of last occurrence of total i.e, 20

sed -n 's/.*total="\([^"]*\).*/\1/p' temp.xml

output : 20

desired output: 50

I appreciate the help. Thank you

Body:
sed does not support non greedy match. Excerpt from here:

The trick to get non greedy matching in sed is to match all characters excluding the one that terminates the match.

So your solution is becomes:

sed -n 's/.[^ ]* total="\([^"]*\).*/\1/p' temp.xml


问:
How to add a border inside a uiview?
I am having a uiview and I would like to add a border iside this UIVIew approximately 75 % of UIView. Could any one help with this. I could get the solution to draw the border outside.</p>

答:
@aroragourav's answer for Swift 3+</p>

```<code>let borderWidth: CGFloat = 2

frame = frame.insetBy(dx: -borderWidth, dy: -borderWidth)
layer.borderColor = UIColor.yellow.cgColor
layer.borderWidth = borderWidth
</code>```

Title: How to add a border inside a uiview?

Body:
@aroragourav's answer for Swift 3+

let borderWidth: CGFloat = 2

frame = frame.insetBy(dx: -borderWidth, dy: -borderWidth)
layer.borderColor = UIColor.yellow.cgColor
layer.borderWidth = borderWidth

ContentLicense: CC BY-SA 4.0


问:
view pager load more than one fragment data once
i am working tabs in App but when fragment loaded it load the data for two fragment . how to rectify that when i clock a tab it loaded only this tab data how to do this

this is my code for view pager
     // for tab selected event

```<code>private TabLayout.OnTabSelectedListener onTabSelectedListener(final ViewPager viewPager) {

    return new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    };
}

private void setupViewPager(ViewPager viewPager) {
    //int numberOfPages = 0;

    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new Matches_Tab(), "Matches");
    adapter.addFragment(new NewMatches_Tab(), "New matches");
    adapter.addFragment(new Similar_Matchs_Tab(), "Similar Matches");
    adapter.addFragment(new ShortlistTab(), "ShortListed");
    adapter.addFragment(new Viewed_My_Profile(), "View My Profile");
    adapter.addFragment(new ShortListedMeTab(), "ShortListed Me");
    adapter.addFragment(new Photo_Request_Received(), "Photo Request Received");
    //viewPager.setOffscreenPageLimit(numberOfPages);
    viewPager.setAdapter(adapter);
    //viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    //onTabSelectedListener(viewPager);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    //Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

// view pager adapter
 class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}
</code>```

答:
You can use setUserVisibleHint:

```<code>@Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser){
            //You can do inside this method
        }
    }
}
</code>```

this will return true if this fragment is in front of screen then do whatever you want inside of it.

Body:
i am working tabs in App but when fragment loaded it load the data for two fragment . how to rectify that when i clock a tab it loaded only this tab data how to do this

this is my code for view pager
     // for tab selected event

private TabLayout.OnTabSelectedListener onTabSelectedListener(final ViewPager viewPager) {

    return new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    };
}

private void setupViewPager(ViewPager viewPager) {
    //int numberOfPages = 0;

    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new Matches_Tab(), "Matches");
    adapter.addFragment(new NewMatches_Tab(), "New matches");
    adapter.addFragment(new Similar_Matchs_Tab(), "Similar Matches");
    adapter.addFragment(new ShortlistTab(), "ShortListed");
    adapter.addFragment(new Viewed_My_Profile(), "View My Profile");
    adapter.addFragment(new ShortListedMeTab(), "ShortListed Me");
    adapter.addFragment(new Photo_Request_Received(), "Photo Request Received");
    //viewPager.setOffscreenPageLimit(numberOfPages);
    viewPager.setAdapter(adapter);
    //viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    //onTabSelectedListener(viewPager);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    //Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

// view pager adapter
 class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

Body:
You can use setUserVisibleHint:

@Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser){
            //You can do inside this method
        }
    }
}

this will return true if this fragment is in front of screen then do whatever you want inside of it.


问:
C++ printing a function's result?
why is that when I print a result from my function, it prints out 0? I tried using a prototype, and followed an example from my teacher, but no dice. Pretty lost here. </p>

```<code>#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

double energie_cinetique(double m, double v) {
    double resultat;
     resultat = 1 / 2 * m * (v * v);
    return resultat;
}

int main(void) {
    double reponse;
    reponse = energie_cinetique(10, 5);
    printf("Energie pour m=10 kg et v=5 m/s: %d", reponse);
    system("pause");
    return EXIT_SUCCESS;
}
</code>```

答:
There are two errors here:

First, 1 / 2 == 0, obviously because they are integers. Change to

```<code>1.0 / 2.0 * m *(v * v);
// OR
0.5 * m * (v * v);
</code>```

Second, %d is a format specifier for signed integers. Using it to print double precision FP is UB. Your compiler should have already warned about this. You should write

```<code>printf("... %lf ...", ...);
            ^~~
</code>```

Then the output should be correct.

Title: C++ printing a function's result?

Body:
why is that when I print a result from my function, it prints out 0? I tried using a prototype, and followed an example from my teacher, but no dice. Pretty lost here.

#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

double energie_cinetique(double m, double v) {
    double resultat;
     resultat = 1 / 2 * m * (v * v);
    return resultat;
}

int main(void) {
    double reponse;
    reponse = energie_cinetique(10, 5);
    printf("Energie pour m=10 kg et v=5 m/s: %d", reponse);
    system("pause");
    return EXIT_SUCCESS;
}

Body:
There are two errors here:

First, 1 / 2 == 0, obviously because they are integers. Change to

1.0 / 2.0 * m *(v * v);
// OR
0.5 * m * (v * v);

Second, %d is a format specifier for signed integers. Using it to print double precision FP is UB. Your compiler should have already warned about this. You should write

printf("... %lf ...", ...);
            ^~~

Then the output should be correct.


问:
How to Load WebView in Fragment class? How to load Webview in android?
I am trying to create a WebView in a Fragment which should be loaded. I added it already to my xml File. However, the findViewById method only works if I extend an Activity class. Is there anyway of which I can use it in Fragment as well?

I already tested the Solution from another Question, but it doesn't work.

```<code>public class OneFragment extends Fragment{

public WebView PlanWebView;

public OneFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    PlanWebView WebView = (PlanWebView) getView().findViewById(R.id.PlanWebView);
    // Unknown class: "PlanWebView";
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_one, container, false);
}

}
</code>```

答:
Try this please , This is the  OneFragment class , Webview needs a view which has to be inflated using xml

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view=inflater.inflate(R.layout. fragment_one, container, false);
    mWebView = (WebView) view.findViewById(R.id.webview);
    mWebView.loadUrl("https://google.com");

    // Enable Javascript
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    // Force links and redirects to open in the WebView instead of in a browser
    mWebView.setWebViewClient(new WebViewClient());

    return view;
}
</code>```

and xml for fragment_one

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>
</code>```

Body:
I am trying to create a WebView in a Fragment which should be loaded. I added it already to my xml File. However, the findViewById method only works if I extend an Activity class. Is there anyway of which I can use it in Fragment as well?

I already tested the Solution from another Question, but it doesn't work.

public class OneFragment extends Fragment{

public WebView PlanWebView;

public OneFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    PlanWebView WebView = (PlanWebView) getView().findViewById(R.id.PlanWebView);
    // Unknown class: "PlanWebView";
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_one, container, false);
}

}

Body:
Try this please , This is the  OneFragment class , Webview needs a view which has to be inflated using xml

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view=inflater.inflate(R.layout. fragment_one, container, false);
    mWebView = (WebView) view.findViewById(R.id.webview);
    mWebView.loadUrl("https://google.com");

    // Enable Javascript
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    // Force links and redirects to open in the WebView instead of in a browser
    mWebView.setWebViewClient(new WebViewClient());

    return view;
}

and xml for fragment_one

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>


问:
How to decrease the size of the legend in a figure?
The following code plots a figure. The code should work on Matlab >= R2014b. I want to remove the space within the legend. How to do this?

```<code>x = 0:0.5:10;
figure; hold on;
plot(x,sin(x), 'Marker', 'o');
plot(x,cos(x), 'Marker', 's');
[leg, objs] = legend({'sin', 'cos'}, 'Location', 'SouthWest');
line_start_end = [0.01, 0.4];
line_text_step = 0.01;
% for each line, text object, adjust their position in legend
for i = 1:numel(objs)
  if strcmp(get(objs(i), 'Type'), 'line')
    % line object
    if 2 == numel(get(objs(i), 'XData')) % line
      set(objs(i), 'XData', line_start_end);
    else % marker on line
      set(objs(i), 'XData', sum(line_start_end)/2);
    end
  else
    %text object
    text_pos = get(objs(i), 'Position');
    text_pos(1) = line_start_end(2) + line_text_step;
    set(objs(i), 'Position', text_pos);
  end
end
</code>```

See the following result:

What I want is :

答:
There is a submission named resizeLegend by David J. Mack on File Exchange that does exactly that.

You can replace your loop with just this line:

```<code>resizeLegend();
</code>```

which gives:

Body:
The following code plots a figure. The code should work on Matlab >= R2014b. I want to remove the space within the legend. How to do this?

x = 0:0.5:10;
figure; hold on;
plot(x,sin(x), 'Marker', 'o');
plot(x,cos(x), 'Marker', 's');
[leg, objs] = legend({'sin', 'cos'}, 'Location', 'SouthWest');
line_start_end = [0.01, 0.4];
line_text_step = 0.01;
% for each line, text object, adjust their position in legend
for i = 1:numel(objs)
  if strcmp(get(objs(i), 'Type'), 'line')
    % line object
    if 2 == numel(get(objs(i), 'XData')) % line
      set(objs(i), 'XData', line_start_end);
    else % marker on line
      set(objs(i), 'XData', sum(line_start_end)/2);
    end
  else
    %text object
    text_pos = get(objs(i), 'Position');
    text_pos(1) = line_start_end(2) + line_text_step;
    set(objs(i), 'Position', text_pos);
  end
end

See the following result:

What I want is :

Body:
There is a submission named resizeLegend by David J. Mack on File Exchange that does exactly that.

You can replace your loop with just this line:

resizeLegend();

which gives:


问:
ERR_CONTENT_LENGTH_MISMATCH while loading js files on tomcat server
Configuration:

OS: CntOS 6.5 minimal

Tomcat: 7.0.53

Deployed war file contains many
.js and .css files

Issue:
When the war file is deployed on tomcat, it gets exploded properly and the web portal works fine.
Machine is idle for over 12 hours.

I access tomcat page: works fine. Even the manager page opens fine.

I launch my webportal, it does not load. Error:
GET http://:8080/webportal/client/libs/jquery/jquery-ui-1.9.2.min.js net::ERR_CONTENT_LENGTH_MISMATCH 10.211.106.184/:63
I get this error for various other js files as well.

What i have tried:

Not an issue with memory since sufficient memory is available.

Tried to open the .js file in another tab, the page keeps loading for a long time and then stops loading. The file is not fully downloaded. Hence the content mismatch issue.

Access to the same url from the local CentOS box using wget works but access from browser on remote box does not

Once static file is accessed on appliance using vi editor (not saved only accessed), downloads from browser start working

Question:

What could possibly be an issue here? Is there any compatibility issue with tomcat and CentOS.

Note again that immediately after deployment everything works fine. Webportal does not work only after a few (>12 approx) hours of inactivity.

答: Try to deploy your webapp to Tomcat 6 or Tomcat 8, sometimes it works. I have solved such a issue but I don't know why. So you can have a try. Maybe it works. Good luck!</p>


问:
JOIN tables with condition to return different values in same column
I have the following tables and columns to join with:

```<code> 1. CUSTOMERS: customer_id,source_system

 2. ALERT_CASE_HEADER: customer_id,data_source_id

 3. DATA_SOURCE:id,name
</code>```

The query is to retrieve CUSTOMERS.source_system, both customer_id in tables CUSTOMERS and ALERT_CASE_HEADER are linked.
However, if DATA_SOURCE.name='Interactive', the source system should defaulted as 'NIL', both columns data_source_id and id are linked.

I am thinking to join them up, but seem no relationship in between CUSTOMERS and DATA_SOURCE to determine whether it's 'Interactive' or not

```<code>SELECT SOURCE_SYSTEM FROM CUSTOMERS CUS INNER JOIN
ALERT_CASE_HEADER ACH ON ACH.CUSTOMER_ID = CUS.CUSTOMER_ID INNER JOIN
ALERT_CASE_HEADER ACH ON ACH.CUSTOMER_ID = CUS.CUSTOMER_ID WHERE
ACH.DATASOURCE_ID=(SELECT DS.ID FROM DATA_SOURCE DS WHERE
DS.NAME='Interactive');
</code>```

Above query has been fixed, so i put it as one of the subquery as below.This query return the count of each STATUSES.Name and group by CUSTOMERS.Source_System and ORGANIZATION_UNITS.ORGUNIT_CODE. The expected result is to display all the counts including DATA_SOURCE.Name='NA'.Due to subquery return more than one row, the query doesn't fit the purpose.

```<code>SELECT
 (SELECT CASE WHEN DS.NAME = 'Interactive' THEN 'NA' ELSE CUS.SOURCE_SYSTEM END AS SOURCE_SYSTEM
  FROM CUSTOMERS CUS
  INNER JOIN  ALERT_CASE_HEADER ACH ON ACH.CUSTOMER_ID = CUS.CUSTOMER_ID
  INNER JOIN DATA_SOURCE DS ON ACH.DATASOURCE_ID = DS.ID),
  ORG.ORGUNIT_CODE AS ORGANIZATION_UNITS,
 SUM(
  CASE
    WHEN S.NAME = 'Pending' THEN 1 ELSE 0
  END
  ) AS PENDING,
 SUM(
  CASE
    WHEN S.NAME = 'New' THEN 1 ELSE 0
  END
  ) AS NEW,
 SUM(
  CASE
    WHEN S.NAME = 'Investigation' THEN 1 ELSE 0
  END
) AS INVESTIGATION,
 SUM(
  CASE
     WHEN S.NAME = 'Escalated' THEN 1 ELSE 0
  END
) AS ESCALATED,
  SUM(
  CASE
     WHEN S.NAME = 'Recommend' THEN 1 ELSE 0
  END
) AS RECOMMEND,
  SUM(
  CASE
     WHEN S.NAME = 'Reopen' THEN 1 ELSE 0
  END
) AS REOPEN

 FROM
STATUSES S
JOIN ALERT_ITEM AI ON S.ID = AI.STATUS_ID
JOIN ALERT_CASE_HEADER ACH ON AI.ENTITY_KEY = ACH.ALERT_KEY
INNER JOIN ORGANIZATION_UNITS ORG ON ORG.ID = ACH.CUSTOMER_ORGUNIT_ID
INNER JOIN CUSTOMERS CUS ON CUS.CUSTOMER_ID = ACH.CUSTOMER_ID
WHERE AI.ENTITY_NAME = 'Active Alert'
GROUP BY ORG.ORGUNIT_CODE,CUS.SOURCE_SYSTEM;
</code>```

答:
I think you can just do a straight series of joins, and then use a CASE expression to render the final value of the source system:

```<code>SELECT
    CASE WHEN ds.NAME = 'Interactive' THEN 'NIL' ELSE c.SOURCE_SYSTEM END AS SOURCE_SYSTEM
FROM CUSTOMERS c
INNER JOIN ALERT_CASE_HEADER ach
    ON ach.CUSTOMER_ID = c.CUSTOMER_ID
INNER JOIN DATA_SOURCE ds
    ON ach.DATASOURCE_ID = ds.ID
</code>```

As a note, you might want to make one or both of the above joins LEFT JOIN if you suspect that records might be filtered off due to not matching the other table.  Also, in your original query you were joining twice to ALERT_CASE_HEADER, which is unnecessary.

Body:
I have the following tables and columns to join with:

 1. CUSTOMERS: customer_id,source_system

 2. ALERT_CASE_HEADER: customer_id,data_source_id

 3. DATA_SOURCE:id,name

The query is to retrieve CUSTOMERS.source_system, both customer_id in tables CUSTOMERS and ALERT_CASE_HEADER are linked.
However, if DATA_SOURCE.name='Interactive', the source system should defaulted as 'NIL', both columns data_source_id and id are linked.

I am thinking to join them up, but seem no relationship in between CUSTOMERS and DATA_SOURCE to determine whether it's 'Interactive' or not

SELECT SOURCE_SYSTEM FROM CUSTOMERS CUS INNER JOIN
ALERT_CASE_HEADER ACH ON ACH.CUSTOMER_ID = CUS.CUSTOMER_ID INNER JOIN
ALERT_CASE_HEADER ACH ON ACH.CUSTOMER_ID = CUS.CUSTOMER_ID WHERE
ACH.DATASOURCE_ID=(SELECT DS.ID FROM DATA_SOURCE DS WHERE
DS.NAME='Interactive');

Above query has been fixed, so i put it as one of the subquery as below.This query return the count of each STATUSES.Name and group by CUSTOMERS.Source_System and ORGANIZATION_UNITS.ORGUNIT_CODE. The expected result is to display all the counts including DATA_SOURCE.Name='NA'.Due to subquery return more than one row, the query doesn't fit the purpose.

SELECT
 (SELECT CASE WHEN DS.NAME = 'Interactive' THEN 'NA' ELSE CUS.SOURCE_SYSTEM END AS SOURCE_SYSTEM
  FROM CUSTOMERS CUS
  INNER JOIN  ALERT_CASE_HEADER ACH ON ACH.CUSTOMER_ID = CUS.CUSTOMER_ID
  INNER JOIN DATA_SOURCE DS ON ACH.DATASOURCE_ID = DS.ID),
  ORG.ORGUNIT_CODE AS ORGANIZATION_UNITS,
 SUM(
  CASE
    WHEN S.NAME = 'Pending' THEN 1 ELSE 0
  END
  ) AS PENDING,
 SUM(
  CASE
    WHEN S.NAME = 'New' THEN 1 ELSE 0
  END
  ) AS NEW,
 SUM(
  CASE
    WHEN S.NAME = 'Investigation' THEN 1 ELSE 0
  END
) AS INVESTIGATION,
 SUM(
  CASE
     WHEN S.NAME = 'Escalated' THEN 1 ELSE 0
  END
) AS ESCALATED,
  SUM(
  CASE
     WHEN S.NAME = 'Recommend' THEN 1 ELSE 0
  END
) AS RECOMMEND,
  SUM(
  CASE
     WHEN S.NAME = 'Reopen' THEN 1 ELSE 0
  END
) AS REOPEN

 FROM
STATUSES S
JOIN ALERT_ITEM AI ON S.ID = AI.STATUS_ID
JOIN ALERT_CASE_HEADER ACH ON AI.ENTITY_KEY = ACH.ALERT_KEY
INNER JOIN ORGANIZATION_UNITS ORG ON ORG.ID = ACH.CUSTOMER_ORGUNIT_ID
INNER JOIN CUSTOMERS CUS ON CUS.CUSTOMER_ID = ACH.CUSTOMER_ID
WHERE AI.ENTITY_NAME = 'Active Alert'
GROUP BY ORG.ORGUNIT_CODE,CUS.SOURCE_SYSTEM;

Body:
I think you can just do a straight series of joins, and then use a CASE expression to render the final value of the source system:

SELECT
    CASE WHEN ds.NAME = 'Interactive' THEN 'NIL' ELSE c.SOURCE_SYSTEM END AS SOURCE_SYSTEM
FROM CUSTOMERS c
INNER JOIN ALERT_CASE_HEADER ach
    ON ach.CUSTOMER_ID = c.CUSTOMER_ID
INNER JOIN DATA_SOURCE ds
    ON ach.DATASOURCE_ID = ds.ID

As a note, you might want to make one or both of the above joins LEFT JOIN if you suspect that records might be filtered off due to not matching the other table.  Also, in your original query you were joining twice to ALERT_CASE_HEADER, which is unnecessary.


问:
With Appium how to click the "home" button or launch the home screen in ios simulator?
I am trying to launch the "home" screen in ios simulator with Appium, but failed to find any api to do that .

Any suggestions would be of great help .

答:
During in test your app , you can run your app  in background an get back.

to do this you have to add

protected IOSDriver iosDriver;

after definition

```<code>@Test
@Description("Some Description")
public void testSearchZeroResultAndHomeBack(){

   // run app in background for 5 seconds
    iosDriver.runAppInBackground(5);

    Assert.assertTrue(isTextDisplayedOnPage("0 ilan"));
}
</code>```

// run app in background for 5 seconds

```<code>    iosDriver.runAppInBackground(5);
</code>```

Body:
During in test your app , you can run your app  in background an get back.

to do this you have to add

protected IOSDriver iosDriver;

after definition

@Test
@Description("Some Description")
public void testSearchZeroResultAndHomeBack(){

   // run app in background for 5 seconds
    iosDriver.runAppInBackground(5);

    Assert.assertTrue(isTextDisplayedOnPage("0 ilan"));
}

// run app in background for 5 seconds

    iosDriver.runAppInBackground(5);


问:
Async storage returning null value
I am saving a value in async storage react native. But when I try to get the value it returns null. Below is my code . Any help would be appreciated. Value printed in console is fine but async storage returns null.</p>

```<code> var userID = responseJson[0].UserId;
 console.log("User id"+userID +userID.toString())
 AsyncStorage.setItem("UserId",userID.toString());
 AsyncStorage.getItem("UserId", (UserId) => {
   console.log("get user details"+UserId )
 });
</code>```

答:
The data in the Asyncstorage should be stored in string format. You can do that as:

```<code>var userID = responseJson[0].UserId;
        console.log("User id"+userID +userID.toString())
        AsyncStorage.setItem("UserId",JSON.stringify(userID));
        AsyncStorage.getItem("UserId", (err, result) => {
          console.log("get user details"+ result)}
</code>```

Note that the result(data) will be in string format only(irrespective of whether its a variable or an object). In order to use it as object, you need to parse it as object.
You can do that using JSON.parse(result).

Title: Async storage returning null value

Body:
I am saving a value in async storage react native. But when I try to get the value it returns null. Below is my code . Any help would be appreciated. Value printed in console is fine but async storage returns null.

 var userID = responseJson[0].UserId;
 console.log("User id"+userID +userID.toString())
 AsyncStorage.setItem("UserId",userID.toString());
 AsyncStorage.getItem("UserId", (UserId) => {
   console.log("get user details"+UserId )
 });

Body:
The data in the Asyncstorage should be stored in string format. You can do that as:

var userID = responseJson[0].UserId;
        console.log("User id"+userID +userID.toString())
        AsyncStorage.setItem("UserId",JSON.stringify(userID));
        AsyncStorage.getItem("UserId", (err, result) => {
          console.log("get user details"+ result)}

Note that the result(data) will be in string format only(irrespective of whether its a variable or an object). In order to use it as object, you need to parse it as object.
You can do that using JSON.parse(result).