问:
How to Pass the features folder dynamically to a Jenkins->Maven->Testng Runner File
In my jenkins pipeline I am invoking my test like

```<code>"mvn test -Drun_location=US"
</code>```

And my pom.xml file looks like this

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.16</version>
    <configuration>
        <systemPropertyVariables>
            <run.location>${run_location}</run.location>
        </systemPropertyVariables>
        <suiteXmlFiles>
            <suiteXmlFile>${basedir}/testng.xml</suiteXmlFile>
        </suiteXmlFiles>
        <skipTests>false</skipTests>
        <testFailureIgnore>false</testFailureIgnore>
    </configuration>
</plugin>
</code>```

And my testng.xml file looks like this

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite>
  <test>
  <parameter name="location" value="${run_location}"/>
   <classes>
      <class name="com.test.Runner_Jenkins"/>
    </classes>
  </test>
</suite>
</code>```

I need to pass this parameter to my runner file to set the feature directory dynamically. How do I accomplish this.

```<code>@CucumberOptions (
features = {"features/${run_location}"},
glue = "StepDefinitions"
)
</code>```

答:
There are two ways of achieving your requirement.

You could use the build parameters of Jenkins and pass your run_location. Then using the Execute Shell script option that runs before the maven build, you could use the sed command to add this parameter to your pom.xml file, feature file, and testng.xml file. sed command replaces the existing text with new text. You could search google about the usage of sed command.

The second option is to pass the run-location as a Jenkins build parameter. Then receive the build parameter inside your java code. Then add this run-location as a parameter to your testng xml file dynamically. This is called programmatic execution of testng. The below code will do this. The below code reads an existing testng XML file and adds a parameter based on your Jenkins input. In this way, you could receive this value inside any of your tests using the code mentioned below.

But this approach will not modify your pom.xml file and feature file. During the execution you have to figure out way to get this value to your code using java.

Programmatic execution of testng with dynamic jenkins parameter:

```<code>    String run_location = System.getProperty("run_location");

    TestNG tng = new TestNG();
    File initialFile = new File("testng.xml");
    InputStream inputStream = FileUtils.openInputStream(initialFile);
    Parser p = new Parser(inputStream);
    List<XmlSuite> suites = p.parseToList();
    List<XmlSuite> modifiedSuites = new ArrayList<>();
    for (XmlSuite suite : suites) {
        XmlSuite modifiedSuite = new XmlSuite();
        modifiedSuite.setParallel(suite.getParallel());
        modifiedSuite.setThreadCount(deviceNames.size());
        modifiedSuite.setName(suite.getName());
        modifiedSuite.setListeners(suite.getListeners());
        List<XmlTest> tests = suite.getTests();
        for (XmlTest test : tests) {
            for (int i = 0; i < deviceNames.size(); i++) {
                XmlTest modifedtest = new XmlTest(modifiedSuite);
                HashMap<String, String> parametersMap = new HashMap<>();
                parametersMap.put("run_location", run_location);

                modifedtest.setParameters(parametersMap);
                modifedtest.setXmlClasses(test.getXmlClasses());
            }
        }
        modifiedSuites.add(modifiedSuite);
    }
    inputStream.close();
    tng.setXmlSuites(modifiedSuites);
    tng.run();
</code>```

Accessing the Parameter value inside your tests

```<code>   @Test
   @Parameters(value={"run_location"})
   public void executeBeforeTest(String runlocation){
    /**Your code goes her**/
   }
</code>```

Body:
In my jenkins pipeline I am invoking my test like

"mvn test -Drun_location=US"

And my pom.xml file looks like this

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.16</version>
    <configuration>
        <systemPropertyVariables>
            <run.location>${run_location}</run.location>
        </systemPropertyVariables>
        <suiteXmlFiles>
            <suiteXmlFile>${basedir}/testng.xml</suiteXmlFile>
        </suiteXmlFiles>
        <skipTests>false</skipTests>
        <testFailureIgnore>false</testFailureIgnore>
    </configuration>
</plugin>

And my testng.xml file looks like this

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite>
  <test>
  <parameter name="location" value="${run_location}"/>
   <classes>
      <class name="com.test.Runner_Jenkins"/>
    </classes>
  </test>
</suite>

I need to pass this parameter to my runner file to set the feature directory dynamically. How do I accomplish this.

@CucumberOptions (
features = {"features/${run_location}"},
glue = "StepDefinitions"
)

Body:
There are two ways of achieving your requirement.

You could use the build parameters of Jenkins and pass your run_location. Then using the Execute Shell script option that runs before the maven build, you could use the sed command to add this parameter to your pom.xml file, feature file, and testng.xml file. sed command replaces the existing text with new text. You could search google about the usage of sed command.

The second option is to pass the run-location as a Jenkins build parameter. Then receive the build parameter inside your java code. Then add this run-location as a parameter to your testng xml file dynamically. This is called programmatic execution of testng. The below code will do this. The below code reads an existing testng XML file and adds a parameter based on your Jenkins input. In this way, you could receive this value inside any of your tests using the code mentioned below.

But this approach will not modify your pom.xml file and feature file. During the execution you have to figure out way to get this value to your code using java.

Programmatic execution of testng with dynamic jenkins parameter:

    String run_location = System.getProperty("run_location");

    TestNG tng = new TestNG();
    File initialFile = new File("testng.xml");
    InputStream inputStream = FileUtils.openInputStream(initialFile);
    Parser p = new Parser(inputStream);
    List<XmlSuite> suites = p.parseToList();
    List<XmlSuite> modifiedSuites = new ArrayList<>();
    for (XmlSuite suite : suites) {
        XmlSuite modifiedSuite = new XmlSuite();
        modifiedSuite.setParallel(suite.getParallel());
        modifiedSuite.setThreadCount(deviceNames.size());
        modifiedSuite.setName(suite.getName());
        modifiedSuite.setListeners(suite.getListeners());
        List<XmlTest> tests = suite.getTests();
        for (XmlTest test : tests) {
            for (int i = 0; i < deviceNames.size(); i++) {
                XmlTest modifedtest = new XmlTest(modifiedSuite);
                HashMap<String, String> parametersMap = new HashMap<>();
                parametersMap.put("run_location", run_location);

                modifedtest.setParameters(parametersMap);
                modifedtest.setXmlClasses(test.getXmlClasses());
            }
        }
        modifiedSuites.add(modifiedSuite);
    }
    inputStream.close();
    tng.setXmlSuites(modifiedSuites);
    tng.run();

Accessing the Parameter value inside your tests

   @Test
   @Parameters(value={"run_location"})
   public void executeBeforeTest(String runlocation){
    /**Your code goes her**/
   }


来源: stackexchange

问:
picking dropdown option with selenium
I went through a number very useful resources on Selenium parsing here, e.g. https://sqa.stackexchange.com/questions/12029/how-do-i-work-with-dropdowns-in-selenium-webdriver but could make my code work, so thought I would ask..

I'd like to pick up a dropdown option for example from ebay.com:

if I go to www.ebay.com and type "Minolta Rokkor", there will be a drop down menu, from which I want to pick, say, "minolta rokkor 40mm f/2".

I'm able to type in the query, but even getting the list of options isn't working for me. Would appreciate any help. Here's my code:

```<code>browser.get("https://www.ebay.com")
time.sleep(6)
e = browser.find_elements_by_class_name("gh-tb")
e[0].send_keys("Minolta Rokkor")
time.sleep(5)
dropdown_web_element = browser.find_element_by_id("gh-ac")
select_box = Select(dropdown_web_element)
time.sleep(1)
for o in select_box.options:
    print o.text
</code>```

答:
The problem is the "dropdown" is not actually a "select field". It may look like one. It may sort of function like one, but it isn't one.

The options are part of a ul that are styled to look like a select field.

You can use the following to obtain all options in the dropdown

```<code>browser.find_elements_by_xpath("//ul[contains(@class, 'ui-autocomplete')]//li/a")
</code>```

To click an option is a bit more tricky because the text isn't just inside the a tag, some of the text is surrounded by b tags, so doing so with xpath can be annoying. Here's what I came up with

browser.get("https://www.ebay.com")
time.sleep(6)
e = browser.find_elements_by_class_name("gh-tb")
e[0].send_keys("Minolta Rokkor")
time.sleep(5)
dropdown_web_element = browser.find_element_by_id("gh-ac")
select_options = browser.find_elements_by_xpath("//ul[contains(@class, 'ui-autocomplete')]//li/a")
time.sleep(1)
for ele in select_options:
    if ele.text == 'minolta rokkor 40mm f/2':
        click_id = ele.get_attribute('id')

browser.find_element_by_id(click_id).click()
```

ContentLicense: CC BY-SA 4.0

Title: picking dropdown option with selenium

Body:
I went through a number very useful resources on Selenium parsing here, e.g. https://sqa.stackexchange.com/questions/12029/how-do-i-work-with-dropdowns-in-selenium-webdriver but could make my code work, so thought I would ask..

I'd like to pick up a dropdown option for example from ebay.com:

if I go to www.ebay.com and type "Minolta Rokkor", there will be a drop down menu, from which I want to pick, say, "minolta rokkor 40mm f/2".

I'm able to type in the query, but even getting the list of options isn't working for me. Would appreciate any help. Here's my code:

browser.get("https://www.ebay.com")
time.sleep(6)
e = browser.find_elements_by_class_name("gh-tb")
e[0].send_keys("Minolta Rokkor")
time.sleep(5)
dropdown_web_element = browser.find_element_by_id("gh-ac")
select_box = Select(dropdown_web_element)
time.sleep(1)
for o in select_box.options:
    print o.text

Body:
The problem is the "dropdown" is not actually a "select field". It may look like one. It may sort of function like one, but it isn't one.

The options are part of a ul that are styled to look like a select field.

You can use the following to obtain all options in the dropdown

browser.find_elements_by_xpath("//ul[contains(@class, 'ui-autocomplete')]//li/a")

To click an option is a bit more tricky because the text isn't just inside the a tag, some of the text is surrounded by b tags, so doing so with xpath can be annoying. Here's what I came up with

browser.get("https://www.ebay.com")
time.sleep(6)
e = browser.find_elements_by_class_name("gh-tb")
e[0].send_keys("Minolta Rokkor")
time.sleep(5)
dropdown_web_element = browser.find_element_by_id("gh-ac")
select_options = browser.find_elements_by_xpath("//ul[contains(@class, 'ui-autocomplete')]//li/a")
time.sleep(1)
for ele in select_options:
    if ele.text == 'minolta rokkor 40mm f/2':
        click_id = ele.get_attribute('id')

browser.find_element_by_id(click_id).click()


问:
set parameter which is null in @NamedQuery (JPA QL 1.0)
I am writing a JPA QL named query that would search for documents. This should be done in only one query and I cannot switch to native SQL (that's non functional requirement).
The query I wrote looks as follows:

```<code>query = "select doc from Doc doc " +
" join doc.Csts cst " +
" where cst.cstFrstNm like :FrstNm " +
" and cst.cstLastNm like :LastNm " +
" and doc.resId = :id ";
</code>```

This query is parametrized using following instructions:

```<code>query.setParameter("FrstNm ", firstName + '%');
query.setParameter("LastNm ", lastName + '%');
query.setParameter("id", resId);
</code>```

firstName, lastName, resId in the above code are my search criteria and they are all Strings and they can be null. When one of them is null, it shouldn't be taken into consideration when the query is invoked.

For instance:

Let's say that: firstName = "John", lastName = "Doe" and resId is null, then the query should return all the entries from Doc table that are for user John Doe, no matter what is their resId.

I was trying to put additional OR and AND conditions into query that'd check if resId is null but it didn't work. I'm testing it on HSQLDB.

Is it any way to modify this JPA query to handle null values?

答:
Two solutions:

First one, don't use a named query and craft a new query for each request:

```<code>boolean first = true;
query = query = "select doc from Doc doc " +
" join doc.Csts cst " +
if (firstName != null) {
    query += (first ? " where " : " and ");
    query += " cst.cstFrstNm like :FrstNm ";
    first = false;
}
query += ";";
// ...
</code>```

Second solution, you are using wildcard. If your parameter is empty, just put a '%' in your query, which will match all corresponding strings:

```<code>query.setParameter("FrstNm ", (firstName != null ? firstName : "") + '%');
query.setParameter("LastNm ", (lastName != null ? lastName : "") + '%');
</code>```

If firstName is empty, your query will look like:

```<code>... cst.cstFrstNm like '%' ...
</code>```

and will match all the values. It will result in the parameter not filtering any result, with a behaviour similar as if it wasn't present.

ContentLicense: CC BY-SA 3.0

Body:
I am writing a JPA QL named query that would search for documents. This should be done in only one query and I cannot switch to native SQL (that's non functional requirement).
The query I wrote looks as follows:

query = "select doc from Doc doc " +
" join doc.Csts cst " +
" where cst.cstFrstNm like :FrstNm " +
" and cst.cstLastNm like :LastNm " +
" and doc.resId = :id ";

This query is parametrized using following instructions:

query.setParameter("FrstNm ", firstName + '%');
query.setParameter("LastNm ", lastName + '%');
query.setParameter("id", resId);

firstName, lastName, resId in the above code are my search criteria and they are all Strings and they can be null. When one of them is null, it shouldn't be taken into consideration when the query is invoked.

For instance:

Let's say that: firstName = "John", lastName = "Doe" and resId is null, then the query should return all the entries from Doc table that are for user John Doe, no matter what is their resId.

I was trying to put additional OR and AND conditions into query that'd check if resId is null but it didn't work. I'm testing it on HSQLDB.

Is it any way to modify this JPA query to handle null values?

Body:
Two solutions:

First one, don't use a named query and craft a new query for each request:

boolean first = true;
query = query = "select doc from Doc doc " +
" join doc.Csts cst " +
if (firstName != null) {
    query += (first ? " where " : " and ");
    query += " cst.cstFrstNm like :FrstNm ";
    first = false;
}
query += ";";
// ...

Second solution, you are using wildcard. If your parameter is empty, just put a '%' in your query, which will match all corresponding strings:

query.setParameter("FrstNm ", (firstName != null ? firstName : "") + '%');
query.setParameter("LastNm ", (lastName != null ? lastName : "") + '%');

If firstName is empty, your query will look like:

... cst.cstFrstNm like '%' ...

and will match all the values. It will result in the parameter not filtering any result, with a behaviour similar as if it wasn't present.


问:
Android Studio "No tests were found"
Has anyone been able to get tests to run in Android Studio (from the GUI and not terminal), I have been unable to run tests from the GUI.

Everytime I try to run tests through the GUI I just get the following message:

I am able to run the tests from terminal using the following command:

```<code>./gradlew connectedAndroidTest
</code>```

I am running Android Studio 0.5.2 with Gradle 1.11 with Plugin 0.9.0 on Mac OSX

My project structure is as follows;

```<code>MyProject/
   src/
      androidTest/
         java/
             com.myproject.app.test/
                … (tests source code) …
      main/
         java/
             com.myproject.app/
                … (source code) …
         res/
                … (resources code) …
   build.gradle
</code>```

My build.gradle file looks similar to the following:

```<code>…
android {
    compileSdkVersion 19
    buildToolsVersion "19.0.1"

    defaultConfig {
        versionCode 12
        versionName "2.0"
        minSdkVersion 9
        targetSdkVersion 19
    testPackageName "com.test.foo"
        testInstrumentationRunner "android.test.InstrumentationTestRunner"
    }
}
…
</code>```

If anyone has any suggestions, I will be more than happy to here them.

答:
As mentioned here by azizbekian in the Android 10 API 29 documentation this issue can happen when running tests on an Emulator for the first time where the  app targets API29.

The emulator may be waiting for user input on a screen showing:

Choose what to allow TestServices to access

There is more information about this in the docs here, but it seems there is a known issue with some versions of the android-test dependencies that can cause this prompt to appear.

https://developer.android.com/about/versions/10/privacy/changes?hl=en#user-permission-legacy-apps

So be sure to check the screen on your emulator. In my case the issue was that my Emulator was awaiting confirmation that the TestServices component was granted the Storage permission, as per the screenshot in the linked SO issue and the Android documentation.

Title: Android Studio "No tests were found"

Body:
Has anyone been able to get tests to run in Android Studio (from the GUI and not terminal), I have been unable to run tests from the GUI.

Everytime I try to run tests through the GUI I just get the following message:

I am able to run the tests from terminal using the following command:

./gradlew connectedAndroidTest

I am running Android Studio 0.5.2 with Gradle 1.11 with Plugin 0.9.0 on Mac OSX

My project structure is as follows;

MyProject/
   src/
      androidTest/
         java/
             com.myproject.app.test/
                … (tests source code) …
      main/
         java/
             com.myproject.app/
                … (source code) …
         res/
                … (resources code) …
   build.gradle

My build.gradle file looks similar to the following:

…
android {
    compileSdkVersion 19
    buildToolsVersion "19.0.1"

    defaultConfig {
        versionCode 12
        versionName "2.0"
        minSdkVersion 9
        targetSdkVersion 19
    testPackageName "com.test.foo"
        testInstrumentationRunner "android.test.InstrumentationTestRunner"
    }
}
…

If anyone has any suggestions, I will be more than happy to here them.


问:
Elements in the array not recognized

    var userInput = prompt('Which fruit would you like?');
      var fruitList = ["banana", 'strawberries', "mango"];

      for(var i=0; i<fruitList.length; i++);
        if(userInput == fruitList[i]){
          alert("Sorry, we are out of " + userInput);
        }else{
          var userFruit = document.createElement('li');
          userFruit.textContent = userInput;
          var fruits = document.getElementById('list');
          fruits.appendChild(userFruit);
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div id="list"></div></code>```

It looks like for loop is not working as it's adding the user input into the list but it doesn't recognize elements from the array. The list which I didn't add here has id="list" and it has the three elements from the array. Thank you!

```<code>  var userInput = prompt('Which fruit would you like?');
  var fruitList = ["banana", 'strawberries', "mango"];

  for(var i=0; i<fruitList.length; i++);
    if(userInput == fruitList[i]){
      alert("Sorry, we are out of " + userInput);
    }else{
      var userFruit = document.createElement('li');
      userFruit.textContent = userInput;
      var fruits = document.getElementById('list');
      fruits.appendChild(userFruit);
    }
</code>```

答:
It's because it compares your entry against all the fruits in the array, so any time there isn't a much it will add it to the list. You may instead use includes method to check the existence of the element in the array.

  var userInput = prompt('Which fruit would you like?');

  var fruitList = ["banana", 'strawberries', "mango"];

  if(fruitList.includes(userInput)) {
    alert("Sorry, we are out of " + userInput);
  }
  else {
    var userFruit = document.createElement('li');
    userFruit.textContent = userInput;
    var fruits = document.getElementById('list');
    fruits.appendChild(userFruit);
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div id="list"></div></code>```

Title: Elements in the array not recognized

Body:
    var userInput = prompt('Which fruit would you like?');
      var fruitList = ["banana", 'strawberries', "mango"];

      for(var i=0; i<fruitList.length; i++);
        if(userInput == fruitList[i]){
          alert("Sorry, we are out of " + userInput);
        }else{
          var userFruit = document.createElement('li');
          userFruit.textContent = userInput;
          var fruits = document.getElementById('list');
          fruits.appendChild(userFruit);
        }

It looks like for loop is not working as it's adding the user input into the list but it doesn't recognize elements from the array. The list which I didn't add here has id="list" and it has the three elements from the array. Thank you!

  var userInput = prompt('Which fruit would you like?');
  var fruitList = ["banana", 'strawberries', "mango"];

  for(var i=0; i<fruitList.length; i++);
    if(userInput == fruitList[i]){
      alert("Sorry, we are out of " + userInput);
    }else{
      var userFruit = document.createElement('li');
      userFruit.textContent = userInput;
      var fruits = document.getElementById('list');
      fruits.appendChild(userFruit);
    }

Body:
It's because it compares your entry against all the fruits in the array, so any time there isn't a much it will add it to the list. You may instead use includes method to check the existence of the element in the array.

  var userInput = prompt('Which fruit would you like?');

  var fruitList = ["banana", 'strawberries', "mango"];

  if(fruitList.includes(userInput)) {
    alert("Sorry, we are out of " + userInput);
  }
  else {
    var userFruit = document.createElement('li');
    userFruit.textContent = userInput;
    var fruits = document.getElementById('list');
    fruits.appendChild(userFruit);
  }

 <div id="list"></div>


问:
React- Unable to change state from child component using function defined within a container component
This is my container component:

```<code> import React, {useState} from 'react';
import Search from '../components/Search';
import Weather from '../components/Weather';
import Location from '../components/Location';
import 'tachyons';

const api = {
  key: '1e96cf99930c0192bd53fe21fa67fbc1',
  base: 'https://api.openweathermap.org/data/2.5/weather'
}

const App = () => {
  const [query, setQuery] = useState('q');
  const [weather, setWeather] = useState({});

  const getWeather = (e) => {
    if (e.key === 'Enter') {
      setQuery(e.target.value);
      fetch(`${api.base}?q=${query}&units=imperial&APPID=${api.key}`)
        .then(res => res.json())
        .then(data => {
          setWeather(data);
          setQuery('');
          console.log(data);
        });
    }
  }

  return (
    <div className="app tc">
      <div className="search-box">
        <Search getWeather={getWeather} />
      </div>
    </div>
  );
}

export default App;
</code>```

And this is my child component:

```<code>import React from 'react';

const Search = ({ getWeather }) => {
  return (
    <input type="search" className="search-bar" onKeyPress={getWeather} />
  );
}

export default Search;
</code>```

I am having an issue where even though the getWeather function runs on key press, it's not changing the state of weather or query. What am I doing wrong in case?

Thanks everyone in advance!

答:
You are setting the query when pressing enter. Move it to search component and update the value there.

```<code>const Search = ({ getWeather, onChange }) => {
  return (
    <input type="search" onChange={(e) => onChange(e.target.value)} className="search-bar" onKeyPress={getWeather} />
  );
}
</code>```

In your search component do, and remove setQuery from getWeather.

```<code><Search onChange={setQuery} getWeather={getWeather} />
</code>```

// Get a hook function
const {useState, useEffect} = React;

const api = {
  key: '1e96cf99930c0192bd53fe21fa67fbc1',
  base: 'https://api.openweathermap.org/data/2.5/weather'
}

    const Search = ({ getWeather, onChange }) => {
      return (
        <input type="search" onChange={(e) => onChange(e.target.value)} className="search-bar" onKeyPress={getWeather} />
      );
    }

function App(){
  const [query, setQuery] = useState('q');
  const [weather, setWeather] = useState({});

  const getWeather = (e) => {
    if (e.key === 'Enter') {
      fetch(`${api.base}?q=${query}&units=imperial&APPID=${api.key}`)
        .then(res => res.json())
        .then(data => {
          setWeather(data);
          setQuery('');
          console.log(data);
        });
    }
  }

  return (

        <Search onChange={setQuery} getWeather={getWeather} />

  );
}

// Render it
ReactDOM.render(
  <App />,
  document.getElementById("react")
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div></code>```

Body:
This is my container component:

 import React, {useState} from 'react';
import Search from '../components/Search';
import Weather from '../components/Weather';
import Location from '../components/Location';
import 'tachyons';

const api = {
  key: '1e96cf99930c0192bd53fe21fa67fbc1',
  base: 'https://api.openweathermap.org/data/2.5/weather'
}

const App = () => {
  const [query, setQuery] = useState('q');
  const [weather, setWeather] = useState({});

  const getWeather = (e) => {
    if (e.key === 'Enter') {
      setQuery(e.target.value);
      fetch(`${api.base}?q=${query}&units=imperial&APPID=${api.key}`)
        .then(res => res.json())
        .then(data => {
          setWeather(data);
          setQuery('');
          console.log(data);
        });
    }
  }

  return (

        <Search getWeather={getWeather} />

  );
}

export default App;

And this is my child component:

import React from 'react';

const Search = ({ getWeather }) => {
  return (
    <input type="search" className="search-bar" onKeyPress={getWeather} />
  );
}

export default Search;

I am having an issue where even though the getWeather function runs on key press, it's not changing the state of weather or query. What am I doing wrong in case?

Thanks everyone in advance!

Body:
You are setting the query when pressing enter. Move it to search component and update the value there.

const Search = ({ getWeather, onChange }) => {
  return (
    <input type="search" onChange={(e) => onChange(e.target.value)} className="search-bar" onKeyPress={getWeather} />
  );
}

In your search component do, and remove setQuery from getWeather.

<Search onChange={setQuery} getWeather={getWeather} />

// Get a hook function
const {useState, useEffect} = React;

const api = {
  key: '1e96cf99930c0192bd53fe21fa67fbc1',
  base: 'https://api.openweathermap.org/data/2.5/weather'
}

    const Search = ({ getWeather, onChange }) => {
      return (
        <input type="search" onChange={(e) => onChange(e.target.value)} className="search-bar" onKeyPress={getWeather} />
      );
    }

function App(){
  const [query, setQuery] = useState('q');
  const [weather, setWeather] = useState({});

  const getWeather = (e) => {
    if (e.key === 'Enter') {
      fetch(`${api.base}?q=${query}&units=imperial&APPID=${api.key}`)
        .then(res => res.json())
        .then(data => {
          setWeather(data);
          setQuery('');
          console.log(data);
        });
    }
  }

  return (
    <div className="app tc">
      <div className="search-box">
        <Search onChange={setQuery} getWeather={getWeather} />
      </div>
    </div>
  );
}

// Render it
ReactDOM.render(
  <App />,
  document.getElementById("react")
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>


问:
Need help adding an object to my array list, whenever it changes
It may sound confusing at first, but i got this code

```<code>const updateFav = (value, index) => {
  const tempData = _.cloneDeep(listProyectos);
  console.log(tempData);
  tempData[index].fav = value;
  setListProyectos(tempData);
};

const listaFavoritos = _.filter(listProyectos, item => item.fav);
const finalObject = listaFavoritos;//{[thisParam]:listaFavoritos};
</code>```

i got a flatlist with an array with several items inside, and a dropdown menu where i select an item and depending on the id, it'll match the items with id of the flatlist object, the thing is, the items in flat list will display switches, and the code from updateFav, will save the value from the switches, and the whole idea, is whenever i switch on an element from the flatlist, it'll save it in a ListProyectos array.

the _.filter will get rid of all the elements that DO NOT contain the fav: true

So here is the problem, whenever i change the item from the dropdown, and change the flatlist, the whole listProyectos array get's replaced and i only see the last change i did.

here is the code for the dropdown

```<code><ModalDropdown
  defaultValue={'Seleccionar'}
  onSelect={async (index, value) =>
    {
      await ParametersBusiness.GetInstance().getProjectClients(value);
      setListProyectos(DataManager.ResponseProjectClient);
    }
  }
  options={DataManager.ListCliente}
/>
</code>```

and here the flatlist

```<code><FlatList
  data={listProyectos}
  renderItem={({item, index}) => (
</code>```

images to show what the actual problem is

ok the so when i switch on that project from that client, it saves the project to a new object, everything is fine there, BUT.

notice when i select a different client and switch another project, ONLY the LAST one i switched is saved, instead of both

gif where i select many projects from different clients

答:
Better have a separate state to store all fav items
like below</p>

```<code>const updateFav = (value, index) => {
  const tempData = _.cloneDeep(listProyectos);
  tempData[index].fav = value;
  setListProyectos(tempData);
  setListProyectos(DataManager.FavoriteList);

  const allFavItems = [...favItems];
  allFavItems.push(tempData[index]);
  setFavItems(allFavItems);
};
const [favItems,setFavItems]= useState([]); should be on top
</code>```

Body:
It may sound confusing at first, but i got this code

const updateFav = (value, index) => {
  const tempData = _.cloneDeep(listProyectos);
  console.log(tempData);
  tempData[index].fav = value;
  setListProyectos(tempData);
};

const listaFavoritos = _.filter(listProyectos, item => item.fav);
const finalObject = listaFavoritos;//{[thisParam]:listaFavoritos};

i got a flatlist with an array with several items inside, and a dropdown menu where i select an item and depending on the id, it'll match the items with id of the flatlist object, the thing is, the items in flat list will display switches, and the code from updateFav, will save the value from the switches, and the whole idea, is whenever i switch on an element from the flatlist, it'll save it in a ListProyectos array.

the _.filter will get rid of all the elements that DO NOT contain the fav: true

So here is the problem, whenever i change the item from the dropdown, and change the flatlist, the whole listProyectos array get's replaced and i only see the last change i did.

here is the code for the dropdown

<ModalDropdown
  defaultValue={'Seleccionar'}
  onSelect={async (index, value) =>
    {
      await ParametersBusiness.GetInstance().getProjectClients(value);
      setListProyectos(DataManager.ResponseProjectClient);
    }
  }
  options={DataManager.ListCliente}
/>

and here the flatlist

<FlatList
  data={listProyectos}
  renderItem={({item, index}) => (

images to show what the actual problem is

ok the so when i switch on that project from that client, it saves the project to a new object, everything is fine there, BUT.

notice when i select a different client and switch another project, ONLY the LAST one i switched is saved, instead of both

gif where i select many projects from different clients

Body:
Better have a separate state to store all fav items
like below

const updateFav = (value, index) => {
  const tempData = _.cloneDeep(listProyectos);
  tempData[index].fav = value;
  setListProyectos(tempData);
  setListProyectos(DataManager.FavoriteList);

  const allFavItems = [...favItems];
  allFavItems.push(tempData[index]);
  setFavItems(allFavItems);
};
const [favItems,setFavItems]= useState([]); should be on top


问:
How to compare the last words of the lines in a file
I'm using a Raspberry Pi as a backup server. I use cron to run each backup job nightly and log the output to a file specific to each job. So each morning I have a bunch of log files (job1.log .. jobN.log). The log files are overwritten each time the job runs. I have another cron job (that runs after all the backup jobs) that sends me an email showing the last line of each log file. This all works as expected.

I'd like to be able to get a status in the subject of the email based on the last lines of the log files. When a backup job is successfully completed, the last line of the log file has some info followed by the word "completed" (which isn't included if the job fails). In my script that sends the email, I use "tail -1  >> summary.txt" for each log file, so summary.txt is a collection containing the last line of each logfile (and is included in the body of the email sent to me).

What I'd like to do is to check the last word of each line in summary.txt to see if all jobs completed successfully, and set the subject of the email appropriately (a simple "backup succeeded" or "backup failed" would be sufficient).

What would be the best way to do this? I know one possibility would be to use awk '{print $NF}' to get the last word of each line, but I'm not sure how to use that.

EDIT: As requested, here is the simplified code I'm currently using to send the "status" email to myself:

```<code>#!/bin/sh
tail -1 job1.log > summary.txt
tail -1 job2.log >> summary.txt
tail -1 job3.log >> summary.txt

mail -s "PI Backup Report" myemail@myhost  < summary.txt
</code>```

I know I could create an additional file with just the last lines by adding

```<code>awk '{print $NF}' summary.txt > results.txt
</code>```

to the above script before the "mail" line, but then I still need to parse the results.txt file. How would I determine the status based on that file? Thanks again!

答:
Measure total vs success lines in summary.txt.

xargs echo to trim results of excess whitespace

grep with regex specifying the line should end in "completed"

wc -l for line count

Set the title using an if statement

TOTAL=$(wc -l < summary.txt | xargs echo)
SUCCESS=$(grep -e 'completed$' summary.txt | wc -l)
title=$(if [ $TOTAL = $SUCCESS ]; then echo 'All Succeeded'; else echo "$SUCCESS/$TOTAL succeeded"; fi)
echo $title # or pass into mail command as subject
```

Body:
I'm using a Raspberry Pi as a backup server. I use cron to run each backup job nightly and log the output to a file specific to each job. So each morning I have a bunch of log files (job1.log .. jobN.log). The log files are overwritten each time the job runs. I have another cron job (that runs after all the backup jobs) that sends me an email showing the last line of each log file. This all works as expected.

I'd like to be able to get a status in the subject of the email based on the last lines of the log files. When a backup job is successfully completed, the last line of the log file has some info followed by the word "completed" (which isn't included if the job fails). In my script that sends the email, I use "tail -1  >> summary.txt" for each log file, so summary.txt is a collection containing the last line of each logfile (and is included in the body of the email sent to me).

What I'd like to do is to check the last word of each line in summary.txt to see if all jobs completed successfully, and set the subject of the email appropriately (a simple "backup succeeded" or "backup failed" would be sufficient).

What would be the best way to do this? I know one possibility would be to use awk '{print $NF}' to get the last word of each line, but I'm not sure how to use that.

EDIT: As requested, here is the simplified code I'm currently using to send the "status" email to myself:

#!/bin/sh
tail -1 job1.log > summary.txt
tail -1 job2.log >> summary.txt
tail -1 job3.log >> summary.txt

mail -s "PI Backup Report" myemail@myhost  < summary.txt

I know I could create an additional file with just the last lines by adding

awk '{print $NF}' summary.txt > results.txt

to the above script before the "mail" line, but then I still need to parse the results.txt file. How would I determine the status based on that file? Thanks again!


问:
Accessing App.config in a location different from the binary
In a .NET Win console application, I would like to access an App.config file in a location different from the console application binary. For example, how can C:\bin\Text.exe get its settings from C:\Test.exe.config?</p>

答:
```<code>AppDomainSetup domainSetup = new AppDomainSetup();
        domainSetup.ConfigurationFile = @"D:\Mine\Company\";
        string browserName = ConfigurationManager.AppSettings["browser"];
</code>```

OwnerDisplayName: Chris Comeaux

ContentLicense: CC BY-SA 2.5


问:
Field 'index_id' doesn't have a default value" when trying to use the primary_key as part of composite key in Hibernate
I am using Hibernate to update the data in the MySQL database.
I have two tables index and properties as described below.

The index_id in the first table is not auto-generated and I am assigning the value.

When I try to make index_id as part of the composite key in properties table, I am getting " Field 'index_id' doesn't have a default value". I am able insert the data manually in MySQL but my problem is that I am not able to do it via Hibernate code.

```<code>CREATE TABLE index (
    index_id BINARY(16),
    index_name VARCHAR(225) NOT NULL ,
    config VARCHAR(255) NOT NULL,

    PRIMARY KEY (index_id)
);

CREATE TABLE properties (
    index_id BINARY(16),
    property_key VARCHAR(225) NOT NULL,
    property_value VARCHAR(225) NOT NULL,

    PRIMARY KEY (index_id, property_key),
    FOREIGN KEY (index_id) REFERENCES index(index_id)
);
</code>```

Corresponding classes for the same with Hibernate annotations.

```<code>import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import java.util.Date;
import java.util.Set;
import java.util.UUID;

import com.sun.istack.NotNull;

@Entity
@Table(name = "index")
public class Index {
    @Id
    @Column(name = "index_id")
    private UUID indexId;

    @Column(name = "index_name")
    private String indexName;

    @Column(name = "config")
    private String config;

    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "index_id")
    private Set<Property> properties;

    public Index() {}
}
</code>```

The answers suggested in other posts are using auto-generated value which is not what I am looking for.

```<code>import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;

@Entity
@Table(name = "properties")
public class Property implements Serializable {
    private static final long serialVersionUID = 1881413500711441951L;

    @Id
    @Column(name = "property_key")
    private String propertyKey;

    @Id
    @Column(name = "property_value")
    private String propertyValue;

    public Property() {}

    public Property(String propertyKey, String propertyValue) {
        this.propertyKey = propertyKey;
        this.propertyValue = propertyValue;
    }
}
</code>```

hibernate.cfg.xml

```<code><?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name = "hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- JDBC Database connection settings -->
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/index?useSSL=false</property>
        <property name="connection.username">###</property>
        <property name="connection.password">###</property>
        <!-- JDBC connection pool settings ... using built-in test pool -->
        <property name="connection.pool_size">1</property>
        <!-- Select our SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <!-- Echo the SQL to stdout -->
        <property name="show_sql">true</property>
        <!-- Set the current session context -->
        <property name="current_session_context_class">thread</property>
        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>
        <!-- dbcp connection pool configuration -->
        <mapping class="com.learning.models.Index" />
        <mapping class="com.learning.models.Property" />
    </session-factory>
</hibernate-configuration>
</code>```

HibernateUtil.java

```<code>import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtil {
    private static StandardServiceRegistry registry;
    private static SessionFactory sessionFactory;
    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            try {
                // Create registry
                registry = new StandardServiceRegistryBuilder().configure().build();
                // Create MetadataSources
                MetadataSources sources = new MetadataSources(registry);
                // Create Metadata
                Metadata metadata = sources.getMetadataBuilder().build();
                // Create SessionFactory
                sessionFactory = metadata.getSessionFactoryBuilder().build();
            } catch (Exception e) {
                e.printStackTrace();
                if (registry != null) {
                    StandardServiceRegistryBuilder.destroy(registry);
                }
            }
        }
        return sessionFactory;
    }
    public static void shutdown() {
        if (registry != null) {
            StandardServiceRegistryBuilder.destroy(registry);
        }
    }
}
</code>```

答:
I was able to resolve the issue. I had a one to many relation as given in the Index class

```<code>@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "index_id")
private Set<Property> properties;
</code>```

The issue was that I have to do a many to one mapping in the properties class with the index_id.

I changed the Properties class as below.

```<code>import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;

@Entity
@Table(name = "properties")
public class Property implements Serializable {
    private static final long serialVersionUID = 1881413500711441951L;

    @Id
    @Column(name = "property_key")
    private String propertyKey;

    @Id
    @Column(name = "property_value")
    private String propertyValue;

    @Id
    @ManyToOne
    @JoinColumn(name ="index_id")
    private Index index;

    public Property() {}

    public Property(String propertyKey, String propertyValue, Index index) {
        this.propertyKey = propertyKey;
        this.propertyValue = propertyValue;
        this.index = index;
    }
}
</code>```

Body:
I am using Hibernate to update the data in the MySQL database.
I have two tables index and properties as described below.

The index_id in the first table is not auto-generated and I am assigning the value.

When I try to make index_id as part of the composite key in properties table, I am getting " Field 'index_id' doesn't have a default value". I am able insert the data manually in MySQL but my problem is that I am not able to do it via Hibernate code.

CREATE TABLE index (
    index_id BINARY(16),
    index_name VARCHAR(225) NOT NULL ,
    config VARCHAR(255) NOT NULL,

    PRIMARY KEY (index_id)
);

CREATE TABLE properties (
    index_id BINARY(16),
    property_key VARCHAR(225) NOT NULL,
    property_value VARCHAR(225) NOT NULL,

    PRIMARY KEY (index_id, property_key),
    FOREIGN KEY (index_id) REFERENCES index(index_id)
);

Corresponding classes for the same with Hibernate annotations.

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import java.util.Date;
import java.util.Set;
import java.util.UUID;

import com.sun.istack.NotNull;

@Entity
@Table(name = "index")
public class Index {
    @Id
    @Column(name = "index_id")
    private UUID indexId;

    @Column(name = "index_name")
    private String indexName;

    @Column(name = "config")
    private String config;

    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "index_id")
    private Set<Property> properties;

    public Index() {}
}

The answers suggested in other posts are using auto-generated value which is not what I am looking for.

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;

@Entity
@Table(name = "properties")
public class Property implements Serializable {
    private static final long serialVersionUID = 1881413500711441951L;

    @Id
    @Column(name = "property_key")
    private String propertyKey;

    @Id
    @Column(name = "property_value")
    private String propertyValue;

    public Property() {}

    public Property(String propertyKey, String propertyValue) {
        this.propertyKey = propertyKey;
        this.propertyValue = propertyValue;
    }
}

hibernate.cfg.xml

<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name = "hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/index?useSSL=false</property>
        <property name="connection.username">###</property>
        <property name="connection.password">###</property>

        <property name="connection.pool_size">1</property>

        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>

        <property name="show_sql">true</property>

        <property name="current_session_context_class">thread</property>

        <property name="hbm2ddl.auto">update</property>

        <mapping class="com.learning.models.Index" />
        <mapping class="com.learning.models.Property" />
    </session-factory>
</hibernate-configuration>

HibernateUtil.java

import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtil {
    private static StandardServiceRegistry registry;
    private static SessionFactory sessionFactory;
    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            try {
                // Create registry
                registry = new StandardServiceRegistryBuilder().configure().build();
                // Create MetadataSources
                MetadataSources sources = new MetadataSources(registry);
                // Create Metadata
                Metadata metadata = sources.getMetadataBuilder().build();
                // Create SessionFactory
                sessionFactory = metadata.getSessionFactoryBuilder().build();
            } catch (Exception e) {
                e.printStackTrace();
                if (registry != null) {
                    StandardServiceRegistryBuilder.destroy(registry);
                }
            }
        }
        return sessionFactory;
    }
    public static void shutdown() {
        if (registry != null) {
            StandardServiceRegistryBuilder.destroy(registry);
        }
    }
}

Body:
I was able to resolve the issue. I had a one to many relation as given in the Index class

@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "index_id")
private Set<Property> properties;

The issue was that I have to do a many to one mapping in the properties class with the index_id.

I changed the Properties class as below.

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;

@Entity
@Table(name = "properties")
public class Property implements Serializable {
    private static final long serialVersionUID = 1881413500711441951L;

    @Id
    @Column(name = "property_key")
    private String propertyKey;

    @Id
    @Column(name = "property_value")
    private String propertyValue;

    @Id
    @ManyToOne
    @JoinColumn(name ="index_id")
    private Index index;

    public Property() {}

    public Property(String propertyKey, String propertyValue, Index index) {
        this.propertyKey = propertyKey;
        this.propertyValue = propertyValue;
        this.index = index;
    }
}


问:
yii2 cannot access root subfolder using htaccess
I'm really bad at htaccess setting and would like to have some help with it. I have a project inside a subfolder, and can be opened like this: www.mydomain.com/subfolder/. I put my project inside "subfolder". "subfolder" is not a subdomain, I just simply created a new folder in root folder.

I can open home page, but all other page like www.mydomain.com/subfolder/about, www.mydomain.com/subfolder/product have 500 internal server error page. I also can't access uploaded file in uploads folder, so URL like www.domain.com/subfolder/uploads/filename.jpg will return error 404. I'm pretty sure that there is no php error becase I also uploaded it in my other subdomain (different domain) and it works fine.

This is my htaccess setting:

```<code>Options +FollowSymlinks
RewriteEngine On

RewriteCond %{REQUEST_URI} /(backend)
RewriteRule ^backend/assets/(.*)$ backend/web/assets/$1 [L]
RewriteRule ^backend/css/(.*)$ backend/web/css/$1 [L]
RewriteRule ^backend/font/(.*)$ backend/web/font/$1 [L]
RewriteRule ^backend/plugins/(.*)$ backend/web/plugins/$1 [L]
RewriteRule ^backend/images/(.*)$ backend/web/images/$1 [L]
RewriteRule ^backend/js/(.*)$ backend/web/js/$1 [L]

RewriteCond %{REQUEST_URI} !/backend/web/(assets|css|font|plugins|images|js)/
RewriteCond %{REQUEST_URI} /(backend)
RewriteRule ^.*$ backend/web/index.php [L]

RewriteCond %{REQUEST_URI} /(assets|css|js|img|fonts|uploads)
RewriteRule ^assets/(.*)$ frontend/web/assets/$1 [L]
RewriteRule ^css/(.*)$ frontend/web/css/$1 [L]
RewriteRule ^js/(.*)$ frontend/web/js/$1 [L]
RewriteRule ^img/(.*)$ frontend/web/img/$1 [L]
RewriteRule ^fonts/(.*)$ frontend/web/fonts/$1 [L]
RewriteRule ^uploads/(.*)$ uploads/$1 [L]

RewriteCond %{REQUEST_URI} !/(frontend|backend)/web/(assets|css|js|img|images|fonts|uploads|plugins|font)/
RewriteCond %{REQUEST_URI} !index.php
RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ frontend/web/index.php
</code>```

Could someone help me?

答:
After i check the script, i found some different in the code.
And i try to fixing some code like this.

```<code>Options +FollowSymlinks
RewriteEngine On

RewriteCond %{REQUEST_URI} ^/(backend)
RewriteRule ^backend/assets/(.*)$ backend/web/assets/$1 [L]
RewriteRule ^backend/css/(.*)$ backend/web/css/$1 [L]
RewriteRule ^backend/font/(.*)$ backend/web/font/$1 [L]
RewriteRule ^backend/img/(.*)$ backend/web/img/$1 [L]
RewriteRule ^backend/js/(.*)$ backend/web/js/$1 [L]
RewriteRule ^backend/plugins/(.*)$ backend/web/plugins/$1 [L]

RewriteCond %{REQUEST_URI} !/backend/web/(assets|css|font|img|js|plugins)/
RewriteCond %{REQUEST_URI} ^/(backend)
RewriteRule ^.*$ backend/web/index.php [L]

RewriteCond %{REQUEST_URI} ^/(assets|css|font|img|js|uploads)
RewriteRule ^assets/(.*)$ frontend/web/assets/$1 [L]
RewriteRule ^css/(.*)$ frontend/web/css/$1 [L]
RewriteRule ^font/(.*)$ frontend/web/font/$1 [L]
RewriteRule ^img/(.*)$ frontend/web/img/$1 [L]
RewriteRule ^js/(.*)$ frontend/web/js/$1 [L]
RewriteRule ^uploads/(.*)$ frontend/web/uploads/$1 [L]

RewriteCond %{REQUEST_URI} !/(frontend|backend)/web/(assets|css|font|img|js|uploads|plugins)/
RewriteCond %{REQUEST_URI} !index.php
RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ frontend/web/index.php [L]
</code>```

There are some sign i add that is this sign ( ^ ).
And for uploading file (image, js, css, etc) i recommend you to upload to folder backend/web/somefolder or frontend/web/somefolder. Put beside those two place, for images, makes your images can not show on all over the place (in my experience).
And also, you can try to make the folder inside frontend/web/ or backend/web/ the same name, so that can makes you easier to remember (please see the code that i fix to see what i mean). I hope it helps for others.

If someone have the better solution, please share it here. Thanks.

Body:
I'm really bad at htaccess setting and would like to have some help with it. I have a project inside a subfolder, and can be opened like this: www.mydomain.com/subfolder/. I put my project inside "subfolder". "subfolder" is not a subdomain, I just simply created a new folder in root folder.

I can open home page, but all other page like www.mydomain.com/subfolder/about, www.mydomain.com/subfolder/product have 500 internal server error page. I also can't access uploaded file in uploads folder, so URL like www.domain.com/subfolder/uploads/filename.jpg will return error 404. I'm pretty sure that there is no php error becase I also uploaded it in my other subdomain (different domain) and it works fine.

This is my htaccess setting:

Options +FollowSymlinks
RewriteEngine On

RewriteCond %{REQUEST_URI} /(backend)
RewriteRule ^backend/assets/(.*)$ backend/web/assets/$1 [L]
RewriteRule ^backend/css/(.*)$ backend/web/css/$1 [L]
RewriteRule ^backend/font/(.*)$ backend/web/font/$1 [L]
RewriteRule ^backend/plugins/(.*)$ backend/web/plugins/$1 [L]
RewriteRule ^backend/images/(.*)$ backend/web/images/$1 [L]
RewriteRule ^backend/js/(.*)$ backend/web/js/$1 [L]

RewriteCond %{REQUEST_URI} !/backend/web/(assets|css|font|plugins|images|js)/
RewriteCond %{REQUEST_URI} /(backend)
RewriteRule ^.*$ backend/web/index.php [L]

RewriteCond %{REQUEST_URI} /(assets|css|js|img|fonts|uploads)
RewriteRule ^assets/(.*)$ frontend/web/assets/$1 [L]
RewriteRule ^css/(.*)$ frontend/web/css/$1 [L]
RewriteRule ^js/(.*)$ frontend/web/js/$1 [L]
RewriteRule ^img/(.*)$ frontend/web/img/$1 [L]
RewriteRule ^fonts/(.*)$ frontend/web/fonts/$1 [L]
RewriteRule ^uploads/(.*)$ uploads/$1 [L]

RewriteCond %{REQUEST_URI} !/(frontend|backend)/web/(assets|css|js|img|images|fonts|uploads|plugins|font)/
RewriteCond %{REQUEST_URI} !index.php
RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ frontend/web/index.php

Could someone help me?

Body:
After i check the script, i found some different in the code.
And i try to fixing some code like this.

Options +FollowSymlinks
RewriteEngine On

RewriteCond %{REQUEST_URI} ^/(backend)
RewriteRule ^backend/assets/(.*)$ backend/web/assets/$1 [L]
RewriteRule ^backend/css/(.*)$ backend/web/css/$1 [L]
RewriteRule ^backend/font/(.*)$ backend/web/font/$1 [L]
RewriteRule ^backend/img/(.*)$ backend/web/img/$1 [L]
RewriteRule ^backend/js/(.*)$ backend/web/js/$1 [L]
RewriteRule ^backend/plugins/(.*)$ backend/web/plugins/$1 [L]

RewriteCond %{REQUEST_URI} !/backend/web/(assets|css|font|img|js|plugins)/
RewriteCond %{REQUEST_URI} ^/(backend)
RewriteRule ^.*$ backend/web/index.php [L]

RewriteCond %{REQUEST_URI} ^/(assets|css|font|img|js|uploads)
RewriteRule ^assets/(.*)$ frontend/web/assets/$1 [L]
RewriteRule ^css/(.*)$ frontend/web/css/$1 [L]
RewriteRule ^font/(.*)$ frontend/web/font/$1 [L]
RewriteRule ^img/(.*)$ frontend/web/img/$1 [L]
RewriteRule ^js/(.*)$ frontend/web/js/$1 [L]
RewriteRule ^uploads/(.*)$ frontend/web/uploads/$1 [L]

RewriteCond %{REQUEST_URI} !/(frontend|backend)/web/(assets|css|font|img|js|uploads|plugins)/
RewriteCond %{REQUEST_URI} !index.php
RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ frontend/web/index.php [L]

There are some sign i add that is this sign ( ^ ).
And for uploading file (image, js, css, etc) i recommend you to upload to folder backend/web/somefolder or frontend/web/somefolder. Put beside those two place, for images, makes your images can not show on all over the place (in my experience).
And also, you can try to make the folder inside frontend/web/ or backend/web/ the same name, so that can makes you easier to remember (please see the code that i fix to see what i mean). I hope it helps for others.

If someone have the better solution, please share it here. Thanks.


问:
pivothigh/pivotlow not working as expected
Why is this code showing me wrong pivothighs it there are any? It is counting every second bar to the left and to the right not only one... If I change if to:

bar_index % 1 == 0, it is working right .

Here my code :

```<code>//@version=4
study("fckn test", overlay=true)

if bar_index % 2 == 0
    ph = pivothigh(1,1)

    label.new(bar_index-1, low, tostring(ph))
</code>```

答:
Not too sure what you are trying to do. Perhaps this?

```<code>//@version=4
study("fckn test", overlay=true)
pivotLegs = 1
// Find pivot outside `if` block because needs to run on every bar.
ph = pivothigh(pivotLegs, pivotLegs)
// Detect a new pivot.
newPh = not na(ph)
// If a new pivot is found, save the bar index where it was found.
bh = newPh ? bar_index - pivotLegs : na
if bar_index % 2 == 0 and not na(ph)
    label.new(bh, high[pivotLegs], tostring(ph))
</code>```

Body:
Why is this code showing me wrong pivothighs it there are any? It is counting every second bar to the left and to the right not only one... If I change if to:

bar_index % 1 == 0, it is working right .

Here my code :

//@version=4
study("fckn test", overlay=true)

if bar_index % 2 == 0
    ph = pivothigh(1,1)

    label.new(bar_index-1, low, tostring(ph))

Body:
Not too sure what you are trying to do. Perhaps this?

//@version=4
study("fckn test", overlay=true)
pivotLegs = 1
// Find pivot outside `if` block because needs to run on every bar.
ph = pivothigh(pivotLegs, pivotLegs)
// Detect a new pivot.
newPh = not na(ph)
// If a new pivot is found, save the bar index where it was found.
bh = newPh ? bar_index - pivotLegs : na
if bar_index % 2 == 0 and not na(ph)
    label.new(bh, high[pivotLegs], tostring(ph))


问:
undefined C struct forward declaration
I have a header file port.h, port.c, and my main.c

I get the following error: 'ports' uses undefined struct 'port_t'

I thought as I have declared the struct in my .h file and having the actual structure in the .c file was ok.

I need to have the forward declaration as I want to hide some data in my port.c file.

In my port.h I have the following:

```<code>/* port.h */
struct port_t;
</code>```

port.c:

```<code>/* port.c */
#include "port.h"
struct port_t
{
    unsigned int port_id;
    char name;
};
</code>```

main.c:

```<code>/* main.c */
#include <stdio.h>
#include "port.h"

int main(void)
{
struct port_t ports;

return 0;
}
</code>```

Many thanks for any suggestions,

答:
If you want to hide the internal data of the port_t structure you can use a technique like how the standard library handles FILE objects.  Client code only deals with FILE* items, so they do not need (indeed, then generally can't) have any knowlege of what is actually in the FILE structure.  The drawback to this method is that the client code can't simply declare a variable to be of that type - they can only have pointers to it, so the object needs to be created and destroyed using some API, and all uses of the object have to be through some API.

The advantage to this is that you have a nice clean interface to how port_t objects must be used, and lets you keep private things private (non-private things need getter/setter functions for the client to access them).

Just like how FILE I/O is handled in the C library.

OwnerDisplayName: robUK

Title: undefined C struct forward declaration

Body:
I have a header file port.h, port.c, and my main.c

I get the following error: 'ports' uses undefined struct 'port_t'

I thought as I have declared the struct in my .h file and having the actual structure in the .c file was ok.

I need to have the forward declaration as I want to hide some data in my port.c file.

In my port.h I have the following:

/* port.h */
struct port_t;

port.c:

/* port.c */
#include "port.h"
struct port_t
{
    unsigned int port_id;
    char name;
};

main.c:

/* main.c */
#include <stdio.h>
#include "port.h"

int main(void)
{
struct port_t ports;

return 0;
}

Many thanks for any suggestions,

LastEditorDisplayName: Chris Young

OwnerDisplayName: Michael Burr

LastEditorDisplayName: Jonathan Leffler


问:
Support "Open In supported Application" popover to open the file in another supported application - ipad
my application has all types of file, how i can handle to open files which are present in my application with supported application which are in my ipad.</p>

答: You need to check out UIDocumentInteractionController</p>


问:
Why doesn't Html.fromHtml not working for String in Android?

One String value is coming from my firebase:

if (task.isSuccessful()) {
    //   binding.contentMain.noData.setVisibility(View.GONE);
    for (QueryDocumentSnapshot document : Objects.requireNonNull(task.getResult()))
        postMap.putAll(document.getData());

    try {
        if (postMap != null)
            //binding.desc1.setText(Objects.requireNonNull(postMap.get(CONTENT)).toString());
            binding.desc1.setText(Html.fromHtml(Objects.requireNonNull(postMap.get(CONTENT)).toString()));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
```

<p>Now, I'll tell you what is coming inside String from Firestore, Actually I only manually written as a String field inside Firestore collection.:</p>

```This is the first text. \n\n This is a second text. \n This is the third text. \n\n Done. \n
```

Make sure that above line is just one String/firestore field.

In firestore, I stored the above value as a String, and fetching that value and showing it in Android. But it is not taking a new line. Instead, it is showing written \n along with other characters.

I tried with and without HTML. with \n and \r\n.

UPDATE: You can see below image how I stored in Firestore.
https://drive.google.com/open?id=19yry9top_W8LREw5SEaZKWYWSlnCP1io

答:
In firestore you need to put two \s before n to add a new line.

if you are getting data from user or reading it from a file add this line before storing data:

```<code>str.replaceAll("\\n", "\n");
</code>```

Body:
One String value is coming from my firebase:

if (task.isSuccessful()) {
    //   binding.contentMain.noData.setVisibility(View.GONE);
    for (QueryDocumentSnapshot document : Objects.requireNonNull(task.getResult()))
        postMap.putAll(document.getData());

    try {
        if (postMap != null)
            //binding.desc1.setText(Objects.requireNonNull(postMap.get(CONTENT)).toString());
            binding.desc1.setText(Html.fromHtml(Objects.requireNonNull(postMap.get(CONTENT)).toString()));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Now, I'll tell you what is coming inside String from Firestore, Actually I only manually written as a String field inside Firestore collection.:

This is the first text. \n\n This is a second text. \n This is the third text. \n\n Done. \n

Make sure that above line is just one String/firestore field.

In firestore, I stored the above value as a String, and fetching that value and showing it in Android. But it is not taking a new line. Instead, it is showing written \n along with other characters.

I tried with and without HTML. with \n and \r\n.

UPDATE: You can see below image how I stored in Firestore.
https://drive.google.com/open?id=19yry9top_W8LREw5SEaZKWYWSlnCP1io

Body:
In firestore you need to put two \s before n to add a new line.

if you are getting data from user or reading it from a file add this line before storing data:

str.replaceAll("\\n", "\n");


问:
Two Dependent Combo Boxes

**Edit:** Managed to find the solution to it thanks to fellow user @Tin Bum

I'm trying to make 2 Combo Box where the the first one (Cmb1) will show only unique values from Column 1 and then (Cmb2) will show a list of values from Column 2 that are related to Column 1.

Populating the Cmb1 has been successful however the problem lies with populating Cmb2.
```<code>Column 1    Column 2
1             a
1             b
1             c
2             d
2             e
</code>```

The problem lies with populating Cmb2

```<code>Private Sub UserForm_Activate()
Dim wslk As Worksheet
Set wslk = Worksheets("w1")
With wslk
t1 = .Cells(Rows.Count, "B").End(xlUp).Offset(1, 0).row

On Error Resume Next
For y = 2 To t1
Set c = .Cells(y, 2)
Set t1rng = .Range(.Cells(2, 2), .Cells(y, 2))
x = Application.WorksheetFunction.CountIf(t1rng, c)
If x = 1 Then Cmb1.AddItem c
Next y
On Error GoTo 0
End With

End Sub

Private Sub Cmb1_Change()
Dim wslk As Worksheet
Set wslk = Worksheets("w1")

Private Sub Cmb1_Change()
Dim wslk As Worksheet
Set wslk = Worksheets("w1")

Cmb2.ListIndex = -1
If Cmb1.ListIndex > -1 Then
'Currently I am stuck over here
Cmb2.List =

**Solution:**
Dim i As Integer
    Cmb2.Clear

For i = 2 To wslk.Range("B" & Application.Rows.Count).End(xlUp).row
    If wslk.Range("B" & i).Value = Cmb1.Value Then
    Cmb2.AddItem wslk.Range("C" & i)
End If

End If
End Sub
</code>```

答:
```<code>Private Sub Cmb1_Change()
Dim wslk As Worksheet
Set wslk = Worksheets("w1")

Dim i As Integer
    Cmb2.Clear

For i = 2 To wslk.Range("B" & Application.Rows.Count).End(xlUp).row
    If wslk.Range("B" & i).Value = Cmb1.Value Then
    Cmb2.AddItem wslk.Range("C" & i)
End If
</code>```

Title: Two Dependent Combo Boxes

Body:
**Edit:** Managed to find the solution to it thanks to fellow user @Tin Bum

I'm trying to make 2 Combo Box where the the first one (Cmb1) will show only unique values from Column 1 and then (Cmb2) will show a list of values from Column 2 that are related to Column 1.

Populating the Cmb1 has been successful however the problem lies with populating Cmb2.

Column 1    Column 2
1             a
1             b
1             c
2             d
2             e

The problem lies with populating Cmb2

Private Sub UserForm_Activate()
Dim wslk As Worksheet
Set wslk = Worksheets("w1")
With wslk
t1 = .Cells(Rows.Count, "B").End(xlUp).Offset(1, 0).row

On Error Resume Next
For y = 2 To t1
Set c = .Cells(y, 2)
Set t1rng = .Range(.Cells(2, 2), .Cells(y, 2))
x = Application.WorksheetFunction.CountIf(t1rng, c)
If x = 1 Then Cmb1.AddItem c
Next y
On Error GoTo 0
End With

End Sub

Private Sub Cmb1_Change()
Dim wslk As Worksheet
Set wslk = Worksheets("w1")

Private Sub Cmb1_Change()
Dim wslk As Worksheet
Set wslk = Worksheets("w1")

Cmb2.ListIndex = -1
If Cmb1.ListIndex > -1 Then
'Currently I am stuck over here
Cmb2.List =

**Solution:**
Dim i As Integer
    Cmb2.Clear

For i = 2 To wslk.Range("B" & Application.Rows.Count).End(xlUp).row
    If wslk.Range("B" & i).Value = Cmb1.Value Then
    Cmb2.AddItem wslk.Range("C" & i)
End If

End If
End Sub


问:
How to read contents from a file and store it in a hash-map in clojure?
I got a small problem in clojure. I am new to this programming environment and need a little help. I have got a text file in this format :

```<code>1|John Smith|123 Here Street|456-4567
2|Sue Jones|43 Rose Court Street|345-7867
3|Fan Yuhong|165 Happy Lane|345-4533
</code>```

I want to parse each line in file and want to store data in hashmap in this way :

```<code>{ 1 : [John Smith, 123 here street, 456-4567], 2 : ... }
</code>```

Here is my code till now but I have not got any success.

```<code>(defn readcustfile[]
  (def cust-file (clojure.string/split-lines (slurp "cust.txt")))

  (doseq [line cust-file]
    (def cust-id (nth (clojure.string/split line #"\|") 0))
    (def cust-name (str (nth (clojure.string/split line #"\|") 1)))
    (def cust-add (str (nth (clojure.string/split line #"\|") 2)))
    (def cust-phone (str (nth (clojure.string/split line #"\|") 3)))
    (def cust-data (str cust-name "," cust-add "," cust-phone))
    (def cust (map (fn [[id name add phone]]
                     (list (Integer/parseInt cust-id)
                           (hash-map :name cust-name
                                     :add cust-add
                                     :phone cust-phone))
    )
  )
(readcustfile)
</code>```

答:
You should use a library to read CSV data.  Here is another one.

Here is an example:

```<code>(ns tst.demo.core
  (:use tupelo.core tupelo.test)
  (:require
    [tupelo.csv :as csv]
    ))

; use (slurp <filename>) to read data into a string
(def data-str
  "id|name|address|phone
   1|John Smith|123 Here Street|456-4567
   2|Sue Jones|43 Rose Court Street|345-7867
   3|Fan Yuhong|165 Happy Lane|345-4533 ")
</code>```

Note that I added a header line to describe the fields of each CSV record.
Unit tests show the result:

```<code>(dotest
  (let [entity-maps (csv/parse->entities data-str :delimiter \|)
        grouped     (group-by :id entity-maps)]

    (is= entity-maps
      [{:id      "1",
        :name    "John Smith",
        :address "123 Here Street",
        :phone   "456-4567"}
       {:id      "2",
        :name    "Sue Jones",
        :address "43 Rose Court Street",
        :phone   "345-7867"}
       {:id      "3",
        :name    "Fan Yuhong",
        :address "165 Happy Lane",
        :phone   "345-4533"}])

    (is= grouped
      {"1"
       [{:id      "1",
         :name    "John Smith",
         :address "123 Here Street",
         :phone   "456-4567"}],
       "2"
       [{:id      "2",
         :name    "Sue Jones",
         :address "43 Rose Court Street",
         :phone   "345-7867"}],
       "3"
       [{:id      "3",
         :name    "Fan Yuhong",
         :address "165 Happy Lane",
         :phone   "345-4533"}]})))
</code>```

Be sure to see this list of documentation, especially the Clojure CheatSheet.

Body:
I got a small problem in clojure. I am new to this programming environment and need a little help. I have got a text file in this format :

1|John Smith|123 Here Street|456-4567
2|Sue Jones|43 Rose Court Street|345-7867
3|Fan Yuhong|165 Happy Lane|345-4533

I want to parse each line in file and want to store data in hashmap in this way :

{ 1 : [John Smith, 123 here street, 456-4567], 2 : ... }

Here is my code till now but I have not got any success.

(defn readcustfile[]
  (def cust-file (clojure.string/split-lines (slurp "cust.txt")))

  (doseq [line cust-file]
    (def cust-id (nth (clojure.string/split line #"\|") 0))
    (def cust-name (str (nth (clojure.string/split line #"\|") 1)))
    (def cust-add (str (nth (clojure.string/split line #"\|") 2)))
    (def cust-phone (str (nth (clojure.string/split line #"\|") 3)))
    (def cust-data (str cust-name "," cust-add "," cust-phone))
    (def cust (map (fn [[id name add phone]]
                     (list (Integer/parseInt cust-id)
                           (hash-map :name cust-name
                                     :add cust-add
                                     :phone cust-phone))
    )
  )
(readcustfile)

Body:
You should use a library to read CSV data.  Here is another one.

Here is an example:

(ns tst.demo.core
  (:use tupelo.core tupelo.test)
  (:require
    [tupelo.csv :as csv]
    ))

; use (slurp <filename>) to read data into a string
(def data-str
  "id|name|address|phone
   1|John Smith|123 Here Street|456-4567
   2|Sue Jones|43 Rose Court Street|345-7867
   3|Fan Yuhong|165 Happy Lane|345-4533 ")

Note that I added a header line to describe the fields of each CSV record.
Unit tests show the result:

(dotest
  (let [entity-maps (csv/parse->entities data-str :delimiter \|)
        grouped     (group-by :id entity-maps)]

    (is= entity-maps
      [{:id      "1",
        :name    "John Smith",
        :address "123 Here Street",
        :phone   "456-4567"}
       {:id      "2",
        :name    "Sue Jones",
        :address "43 Rose Court Street",
        :phone   "345-7867"}
       {:id      "3",
        :name    "Fan Yuhong",
        :address "165 Happy Lane",
        :phone   "345-4533"}])

    (is= grouped
      {"1"
       [{:id      "1",
         :name    "John Smith",
         :address "123 Here Street",
         :phone   "456-4567"}],
       "2"
       [{:id      "2",
         :name    "Sue Jones",
         :address "43 Rose Court Street",
         :phone   "345-7867"}],
       "3"
       [{:id      "3",
         :name    "Fan Yuhong",
         :address "165 Happy Lane",
         :phone   "345-4533"}]})))

Be sure to see this list of documentation, especially the Clojure CheatSheet.


问:
Iphone - Assigning properties and instance variables
Well, i am still confused about objective c properties and instance variables.
I create a LocationManager-object in my viewDidLoad. On the one hand the LocationMan is just an instance variable on the other hand it is declared as a property. Have a look at the examples:

First example:

Header:

```<code>CLLocationManager* _locationMan;
</code>```

Implementation:

```<code>CLLocationManager* theManager = [[[CLLocationManager alloc] init] autorelease];
_locationMan = theManager;
_locationMan.delegate = self;
</code>```

Second Example

Header:

```<code>CLLocationManager* _locationMan;
@property (retain, nonatomic) CLLocationManager* locationMan;
</code>```

Implementation:

```<code>self.locationMan = [[[CLLocationManager alloc] init] autorelease];
self.locationMan.delegate = self;
</code>```

Whats the difference between those examples except of that the second one is working and the first one not? What's going on there with the memory management?

答:
I marked the changes of the retains in your code, maybe it will become more clear.

```<code>CLLocationManager* theManager = [[[CLLocationManager alloc] init] autorelease];
                                                     ^^^^^ + 1    ^^^^^^^^^^^ - 1 = 0
_locationMan = theManager;
</code>```

when your retains drop to 0 the object doesn't exist anymore. Next time you try to access it your app crashs. Because of the autorelease this will happen after your autorelease pool gets drained, at an unknown point in the future after you have left the current method.

```<code>self.locationMan = [[[CLLocationManager alloc] init] autorelease];
    ^ + 1                               ^^^^^ + 1    ^^^^^^^^^^^ - 1 = +1
</code>```

you have still retained that object. You have to release it later but you can access it without problems.

Body:
Well, i am still confused about objective c properties and instance variables.
I create a LocationManager-object in my viewDidLoad. On the one hand the LocationMan is just an instance variable on the other hand it is declared as a property. Have a look at the examples:

First example:

Header:

CLLocationManager* _locationMan;

Implementation:

CLLocationManager* theManager = [[[CLLocationManager alloc] init] autorelease];
_locationMan = theManager;
_locationMan.delegate = self;

Second Example

Header:

CLLocationManager* _locationMan;
@property (retain, nonatomic) CLLocationManager* locationMan;

Implementation:

self.locationMan = [[[CLLocationManager alloc] init] autorelease];
self.locationMan.delegate = self;

Whats the difference between those examples except of that the second one is working and the first one not? What's going on there with the memory management?

Body:
I marked the changes of the retains in your code, maybe it will become more clear.

CLLocationManager* theManager = [[[CLLocationManager alloc] init] autorelease];
                                                     ^^^^^ + 1    ^^^^^^^^^^^ - 1 = 0
_locationMan = theManager;

when your retains drop to 0 the object doesn't exist anymore. Next time you try to access it your app crashs. Because of the autorelease this will happen after your autorelease pool gets drained, at an unknown point in the future after you have left the current method.

self.locationMan = [[[CLLocationManager alloc] init] autorelease];
    ^ + 1                               ^^^^^ + 1    ^^^^^^^^^^^ - 1 = +1

you have still retained that object. You have to release it later but you can access it without problems.


答:
use this method:

  public Spanned getHtmlFormattedString(String value) {
        Spanned result = null;
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                result = Html.fromHtml(value, Html.FROM_HTML_MODE_COMPACT);
            } else {
                result = Html.fromHtml(value);
            }

        } catch (Exception ex) {
        }
        return result;
    }
```

<p>in your case :</p>

<pre class="lang-java prettyprint-override"><code>binding.desc1.setText(getHtmlFormattedString(Objects.requireNonNull(postMap.get(CONTENT)).toString()));

</code>```

Update Answer

\n is not html tag , if you want to handle with Html.fromHtml you should replace \n with
 tag

so in your case :

```<code>binding.desc1.setText(getHtmlFormattedString(Objects.requireNonNull(postMap.get(CONTENT)).toString().replaceAll("\\n","<br/>")));
</code>```

Title: Why doesn't Html.fromHtml not working for String in Android?

Body:
use this method:

  public Spanned getHtmlFormattedString(String value) {
        Spanned result = null;
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                result = Html.fromHtml(value, Html.FROM_HTML_MODE_COMPACT);
            } else {
                result = Html.fromHtml(value);
            }

        } catch (Exception ex) {
        }
        return result;
    }

in your case :

binding.desc1.setText(getHtmlFormattedString(Objects.requireNonNull(postMap.get(CONTENT)).toString()));

Update Answer

\n is not html tag , if you want to handle with Html.fromHtml you should replace \n with <br/> tag

so in your case :

binding.desc1.setText(getHtmlFormattedString(Objects.requireNonNull(postMap.get(CONTENT)).toString().replaceAll("\\n","<br/>")));


问:
Changing AWS configuration directory
AWS stores the default configuration files in ~/.aws/.

I'm trying to have all hidden directories inside ~/.config/, and would like to change the default location to ~/.config/aws/

How would I do this from the AWS CLI?

答:
You can specify a non-default location for the config file by setting the AWS_CONFIG_FILE environment variable to another local path.

```<code>Steps I used:
1. Create a folder with the name of your choice. I used .awscheck (mkdir .awscheck)
2. Create a file named credentials within the folder.
3. Configure the variable. (export AWS_CONFIG_FILE=~/.awscheck/credentials)
4. Run aws configure and add your values.
</code>```

Similarly, if you want to store configurations, you can create a config file and add the configurations like profiles and regions in the config file.

Title: Changing AWS configuration directory

Body:
You can specify a non-default location for the config file by setting the AWS_CONFIG_FILE environment variable to another local path.

Steps I used:
1. Create a folder with the name of your choice. I used .awscheck (mkdir .awscheck)
2. Create a file named credentials within the folder.
3. Configure the variable. (export AWS_CONFIG_FILE=~/.awscheck/credentials)
4. Run aws configure and add your values.

Similarly, if you want to store configurations, you can create a config file and add the configurations like profiles and regions in the config file.


问:
Is there a way to load components within components with http-vue-loader
I am trying to load vue components within components but do not use a webpack for practical reasons.
I use http-vue-loader to load the vue files.

So far I managed to to create vue files and load them in my HTML in the following way:

main.js

```<code>new Vue({
  el: '#app-shop',
  components: {
    'comp-products': httpVueLoader('components/comp-products.vue'),
    'comp-shop': httpVueLoader('components/comp-shop.vue')
  },
});
</code>```

comp.shop.vue

```<code><script>
    module.exports =  {
        props:{
            quantity: {
            type: Number
            }
        }
    }
</script>
</code>```

comp.products.vue

```<code><template>
    <div id="products">
        <div class="productsItemContainer" v-for="product in products">
            <div class="productsItem">
                <div class="">
                    <div class="mkcenter" style="position:relative">
                        <a class="item">
                            <img class="productImg" width="120px" height="120px" v-bind:src="'assets/products/' + product.image">
                            <div class="floating ui red label" v-if="product.new">NEW</div>
                        </a>
                    </div>
                </div>
                <div class="productItemName" >
                    <a>{{ product.name }}</a>
                </div>
                <div class="mkdivider mkcenter"></div>
                <div class="productItemPrice" >
                    <a>€ {{ product.unit_price }}</a>
                </div>
                <div v-on:click="addToCart" class="mkcenter">
                    <div class="ui vertical animated basic button" tabindex="0">
                        <div class="hidden content">Koop</div>
                        <div class="visible content">
                            <i class="shop icon"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    module.exports =  {
        name: 'Products',

        data() {
            return {
                products: [],
                addToCart: function(){
                    // quantity++;
                    console.log("test")
                    console.log(quantity)
                }
            }

        }
  },

        mounted() {
            axios
            .get("json/products.json")
            .then(response => {
            this.products = response.data.products;
            });
        }
    }
</script>

<style>
    #products{display:flex;flex-wrap:wrap;padding:20px}
    .productsItemContainer{padding:5px;margin:auto;text-align: center}
    .productsItem{width: 200px;padding:20px 0px 10px 0px;;border:1px solid #ddd}
    .productsItem:hover{border:1px solid #ddd;-webkit-box-shadow: 0px 0px 13px -1px rgba(0,0,0,0.13);-moz-box-shadow: 0px 0px 13px -1px rgba(0,0,0,0.13);box-shadow: 0px 0px 13px -1px rgba(0,0,0,0.13);}
    .item{width: 50%;margin: 0px}
    .productImg{transition: all .5s ease-in-out;}
    .productImg:hover{transform: scale(1.1);}
    .productItemName{text-align: center}
    .productItemName a{font: Roboto; color:#333745;font-size: 17px}
    .productItemPrice{text-align: center; padding: 5px 0 10px 0; }
    .productItemPrice a{color:red; font-size: 16px;font: Roboto; color:black; font-weight: 700}
</style>
</code>```

The above works but what I am looking for is a way to call comp.products.vue from within the comp.shop.vue.

答:
From within your comp.shop.vue import comp.products.vue as a component:

```<code><script>
    module.exports =  {
        props:{
            quantity: {
            type: Number
            }
        },
        components: {
            'comp-products': httpVueLoader('components/comp-products.vue')
        }
    }
</script>
</code>```

Body:
I am trying to load vue components within components but do not use a webpack for practical reasons.
I use http-vue-loader to load the vue files.

So far I managed to to create vue files and load them in my HTML in the following way:

main.js

new Vue({
  el: '#app-shop',
  components: {
    'comp-products': httpVueLoader('components/comp-products.vue'),
    'comp-shop': httpVueLoader('components/comp-shop.vue')
  },
});

comp.shop.vue

comp.products.vue

<template>

NEW

                    {{ product.name }}

                    € {{ product.unit_price }}

Koop

</template>

The above works but what I am looking for is a way to call comp.products.vue from within the comp.shop.vue.

Body:
From within your comp.shop.vue import comp.products.vue as a component:

<script>
    module.exports =  {
        props:{
            quantity: {
            type: Number
            }
        },
        components: {
            'comp-products': httpVueLoader('components/comp-products.vue')
        }
    }
</script>


问:
MySQL Update if value is x or y
I have following procedures which help me to update the dates in my table on a daily basis, keeping them relevant for demo purposes. The difference between those two procedures is only that they are being executed for 2 different clients with property_id being 2 and 3 respectively.

```<code>UPDATE `opera_pms_detail` SET `arrival` = SUBDATE(curdate(), 2), `departure` = SUBDATE(curdate(), 1), `read_on` = NULL WHERE `property_id` = 2 AND `import_type` = '1'

UPDATE `opera_pms_detail` SET `arrival` = SUBDATE(curdate(), 2), `departure` = SUBDATE(curdate(), 1), `read_on` = NULL WHERE `property_id` = 3 AND `import_type` = '1'
</code>```

Now, for efficiency's sake, is there a better way of doing this? Instead of having to call the procedure twice, can I just update the columns for both clients in one call?

Thank you

答:
Try implementing your procedure like this

```<code>PROCEDURE ýour_procedure_name(IN p_property_id INT)
BEGIN
UPDATE `opera_pms_detail`
SET `arrival` = SUBDATE(curdate(), 2),
`departure` = SUBDATE(curdate(), 1),
`read_on` = NULL
WHERE `property_id` = p_property_id
AND `import_type` = '1';
END
</code>```

And you will call your procedure as:

```<code>CALL `your_procedure_name`(property_id)
</code>```

Title: MySQL Update if value is x or y

Body:
I have following procedures which help me to update the dates in my table on a daily basis, keeping them relevant for demo purposes. The difference between those two procedures is only that they are being executed for 2 different clients with property_id being 2 and 3 respectively.

UPDATE `opera_pms_detail` SET `arrival` = SUBDATE(curdate(), 2), `departure` = SUBDATE(curdate(), 1), `read_on` = NULL WHERE `property_id` = 2 AND `import_type` = '1'

UPDATE `opera_pms_detail` SET `arrival` = SUBDATE(curdate(), 2), `departure` = SUBDATE(curdate(), 1), `read_on` = NULL WHERE `property_id` = 3 AND `import_type` = '1'

Now, for efficiency's sake, is there a better way of doing this? Instead of having to call the procedure twice, can I just update the columns for both clients in one call?

Thank you

Body:
Try implementing your procedure like this

PROCEDURE ýour_procedure_name(IN p_property_id INT)
BEGIN
UPDATE `opera_pms_detail`
SET `arrival` = SUBDATE(curdate(), 2),
`departure` = SUBDATE(curdate(), 1),
`read_on` = NULL
WHERE `property_id` = p_property_id
AND `import_type` = '1';
END

And you will call your procedure as:

CALL `your_procedure_name`(property_id)