答:
You need to update the data state instead of returning an item.

```<code>handleIncrement = i => {

  const item = this.state.data[i];

  this.setState({
    data: [
      ...this.state.data.slice(0, i),
      Object.assign({}, this.state.data[i], { quantity: item.quantity + 1 }),
      ...this.state.data.slice(i + 1)
    ]
  });
};
</code>```

You can refactor the function and use it for both - and +.

```<code>// pass array index and quantity 1 for + and -1 for -
handleIncrement = (i, qty) => {
  const item = this.state.data[i];

  if (item && item.quantity === 0 && qty === -1) {
    return;
  }

  this.setState({
    data: [
      ...this.state.data.slice(0, i),
      Object.assign({}, this.state.data[i], { quantity: item.quantity + qty, }),
      ...this.state.data.slice(i + 1),
    ],
  });
};
</code>```

Below is demo that uses the above function, it's in reactjs. The function will work in react native too.

h1, p {
  font-family: Lato;
}

.container {
  display: flex;
  flex-direction: row;
  border-bottom-style: solid;
  margin-bottom: 5px;
}

.image-container {
  flex-grow: 0;
}

.info-container {
  display: flex;
  margin-left: 10px;
  flex-direction: row;
}

.title {
  margin-top: 0;
}

.titleContainer {
  width: 100px;
}

.cover {
  width: 30px;
}

.buttons {
  flex-grow: 1;
  display: flex;
  margin-left: 10px;
}

.incrementButtons {
  width: 20px;
  height: 20px;
  margin-left: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<div id="root"></div>

<script type="text/babel">

class Item extends React.Component {
  render() {
    return (
      <div className="container">
        <div className="image-container">
          <img className="cover" src={this.props.image} />
        </div>
        <div className="info-container">
          <div className="titleContainer">
            <p className="title">{this.props.title}</p>
          </div>
          <div className="buttons">
            <p className="title">{this.props.qty}</p>
            <img onClick={() => this.props.increment(this.props.index, -1)} className="incrementButtons" src="https://img.icons8.com/metro/26/000000/minus-math.png" />
            <img onClick={() => this.props.increment(this.props.index, 1)} className="incrementButtons" src="https://img.icons8.com/metro/26/000000/plus-math.png" />
          </div>
        </div>
      </div>
    )
  }
}

class App extends React.Component {

  state = {
    data: [
      {
        id: 1,
        name: 'Avocado',
        price: '400',
        imageS: 'https://img.icons8.com/metro/26/000000/avocado.png',
        quantity: 0,
      },
      {
        id: 6,
        name: 'Bread',
        price: '300',
        imageS: 'https://img.icons8.com/metro/26/000000/bread.png',
        quantity: 0,
      },
      {
        id: 2,
        name: 'Milk',
        price: '300',
        imageS: 'https://img.icons8.com/metro/26/000000/milk-bottle.png',
        quantity: 0,
      },
    ],
  };

  handleIncrement = (i, qty) => {
    const item = this.state.data[i];

    if (item && item.quantity === 0 && qty === -1) {
      return;
    }

    this.setState({
      data: [
        ...this.state.data.slice(0, i),
        Object.assign({}, this.state.data[i], { quantity: item.quantity + qty, }),
        ...this.state.data.slice(i + 1),
      ],
    });
  };

  render() {

    const items = this.state.data.map((item, index) => (
      <Item qty={item.quantity} index={index} key={index} increment={this.handleIncrement} title={item.name} image={item.imageS} />
    ))
    return (
      <div>
        {items}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
</script></code>```

Title: How to handle state on Flat List Items in React-Native

Body:
I am setting a counter on the items of the FlatList component of React-Native. How can I update the list item every time the user press the "+" or "-" button?

I am currently being able to update the value on the state, however the list doesnt display the new state. I have tried adding extraData component to the FlatList, but it doesnt seem to update anyways.

This is the data structure

      data: [
        {
          id: 1,
          name: "Bread",
          price: "400",
          imageS: "../resources/pan-corteza-blanda.jpg",
          quantity: 2
        },
... more data

This is the function that handles the increment

  handleIncrement = i => {
    this.setState(state => {
      const formatData = state.data.map((item, j) => {
        console.log("Id", i + " /// " + item.id);
        if (item.id === i) {
          item.quantity = item.quantity + 1;
          return item;
        } else {
          return item;
        }
      });
      console.log("FormatData" + formatData); //Displays the correct  quantity of the item updated

      return {
        formatData
      };
    });
  };

And this is the list component

  <FlatList
          data={this.state.data}
          style={styles.list}
          extraData={this.state.data}
          renderItem={this.renderItem}
        />

I expect to update the text component of the list item with the right quantity value every time a user presses the "+" or "-" button.

Body:
You need to update the data state instead of returning an item.

handleIncrement = i => {

  const item = this.state.data[i];

  this.setState({
    data: [
      ...this.state.data.slice(0, i),
      Object.assign({}, this.state.data[i], { quantity: item.quantity + 1 }),
      ...this.state.data.slice(i + 1)
    ]
  });
};

You can refactor the function and use it for both - and +.

// pass array index and quantity 1 for + and -1 for -
handleIncrement = (i, qty) => {
  const item = this.state.data[i];

  if (item && item.quantity === 0 && qty === -1) {
    return;
  }

  this.setState({
    data: [
      ...this.state.data.slice(0, i),
      Object.assign({}, this.state.data[i], { quantity: item.quantity + qty, }),
      ...this.state.data.slice(i + 1),
    ],
  });
};

Below is demo that uses the above function, it's in reactjs. The function will work in react native too.

h1, p {
  font-family: Lato;
}

.container {
  display: flex;
  flex-direction: row;
  border-bottom-style: solid;
  margin-bottom: 5px;
}

.image-container {
  flex-grow: 0;
}

.info-container {
  display: flex;
  margin-left: 10px;
  flex-direction: row;
}

.title {
  margin-top: 0;
}

.titleContainer {
  width: 100px;
}

.cover {
  width: 30px;
}

.buttons {
  flex-grow: 1;
  display: flex;
  margin-left: 10px;
}

.incrementButtons {
  width: 20px;
  height: 20px;
  margin-left: 10px;
}

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

<script type="text/babel">

class Item extends React.Component {
  render() {
    return (
      <div className="container">
        <div className="image-container">
          <img className="cover" src={this.props.image} />
        </div>
        <div className="info-container">
          <div className="titleContainer">
            <p className="title">{this.props.title}</p>
          </div>
          <div className="buttons">
            <p className="title">{this.props.qty}</p>
            <img onClick={() => this.props.increment(this.props.index, -1)} className="incrementButtons" src="https://img.icons8.com/metro/26/000000/minus-math.png" />
            <img onClick={() => this.props.increment(this.props.index, 1)} className="incrementButtons" src="https://img.icons8.com/metro/26/000000/plus-math.png" />
          </div>
        </div>
      </div>
    )
  }
}

class App extends React.Component {

  state = {
    data: [
      {
        id: 1,
        name: 'Avocado',
        price: '400',
        imageS: 'https://img.icons8.com/metro/26/000000/avocado.png',
        quantity: 0,
      },
      {
        id: 6,
        name: 'Bread',
        price: '300',
        imageS: 'https://img.icons8.com/metro/26/000000/bread.png',
        quantity: 0,
      },
      {
        id: 2,
        name: 'Milk',
        price: '300',
        imageS: 'https://img.icons8.com/metro/26/000000/milk-bottle.png',
        quantity: 0,
      },
    ],
  };

  handleIncrement = (i, qty) => {
    const item = this.state.data[i];

    if (item && item.quantity === 0 && qty === -1) {
      return;
    }

    this.setState({
      data: [
        ...this.state.data.slice(0, i),
        Object.assign({}, this.state.data[i], { quantity: item.quantity + qty, }),
        ...this.state.data.slice(i + 1),
      ],
    });
  };

  render() {

    const items = this.state.data.map((item, index) => (
      <Item qty={item.quantity} index={index} key={index} increment={this.handleIncrement} title={item.name} image={item.imageS} />
    ))
    return (
      <div>
        {items}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
</script>


来源: stackexchange

问:
Best method to determine if viewport or 'standard' browser
So, by now we all know that iOS mobile Safari uses viewports (as does Android browser), rather than a 'standard' browser window. And this causes issues with overflow:hidden, and position:fixed.

This unfortunately is the same case with the iPad. I presume this is the case for other Android tablets too.

Rather than browser sniffing each time, is there an easy way to determine if the browser has a viewport or if it is standard?

答:
Unfortunately, there's currently no good fix for mobile browsers' lack of support for position:fixed.  The reason position:fixed is "broken" in the first place is because—among other things—no browser vendor knows exactly how to handle what happens when zooming in on the document.  If you have some time to do some reading, I highly recommend the following articles, which will explain browser viewports and the problems surrounding fixed positioning on mobile in great, painstaking detail:

A tale of two viewports – part two — how viewports work and the problem of mobile browsers.  (If you're not familiar with viewports in desktop browsers or want the background info, see also part one.)

The fifth position value does a fantastic job of explaining the problems surrounding position:fixed in a mobile browser, and suggests we might need a new position value – device-fixed.

Those articles will give you the why, but not the how to fix it.  For a truly fixed position, you're mostly out of luck.  However, if your goal is to have a fixed toolbar below scrolling content, there are a few ways to hack it.  I've had success with iScroll.

Edit: The correct way to determine if you are running on a touch-based device is the following feature detection:

```<code>var isTouch = ('ontouchstart' in window);
</code>```

ontouchstart is an event fired in mobile Safari and the Android browser.  It is not present on desktop browsers, where you can just use overflow:auto and have regular scrollbars.  If isTouch is true, you can then use iScroll.

ContentLicense: CC BY-SA 3.0

Body:
Unfortunately, there's currently no good fix for mobile browsers' lack of support for position:fixed.  The reason position:fixed is "broken" in the first place is because—among other things—no browser vendor knows exactly how to handle what happens when zooming in on the document.  If you have some time to do some reading, I highly recommend the following articles, which will explain browser viewports and the problems surrounding fixed positioning on mobile in great, painstaking detail:

A tale of two viewports – part two — how viewports work and the problem of mobile browsers.  (If you're not familiar with viewports in desktop browsers or want the background info, see also part one.)

The fifth position value does a fantastic job of explaining the problems surrounding position:fixed in a mobile browser, and suggests we might need a new position value – device-fixed.

Those articles will give you the why, but not the how to fix it.  For a truly fixed position, you're mostly out of luck.  However, if your goal is to have a fixed toolbar below scrolling content, there are a few ways to hack it.  I've had success with iScroll.

Edit: The correct way to determine if you are running on a touch-based device is the following feature detection:

var isTouch = ('ontouchstart' in window);

ontouchstart is an event fired in mobile Safari and the Android browser.  It is not present on desktop browsers, where you can just use overflow:auto and have regular scrollbars.  If isTouch is true, you can then use iScroll.


问:
How do I extract a list of URLs off a page with selenium?
I am attempting to extract all urls that https://shop.freedommobile.ca/devices has when you click the 'see options' button under each phone and place them into a list of strings.

I am using python with Selenium and wait libraries.
Ive already tried using .text in my parameters. However, I keep running into an error that states:

typeError: 'str' object is not callable
line 17 is the issue.

```<code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

class phoneCost:

    driver.get("https://shop.freedommobile.ca/devices")

    # extract the names of the phones
    wait = WebDriverWait(driver, 20) #10 second wait
    XPathLocation = """B//*[@id="skip-navigation"]/div/div/div[1]/div/div[2]/a'"""
    phonePlanLinksRaw = wait.until(EC.presence_of_all_elements_located(By.XPATH(XPathLocation)))
    phonePlanLinks = []

    for element in range(len(phonePlanLinksRaw)):
        link = element
        phonePlanLinks.append(str(link))

    numLink = 1
    for element in range(len(phonePlanLinks)):
        print("phone " + str(numLink) + " : " + phonePlanLinks[element])
        numLink += 1
</code>```

should return a list of urls in string format:

[https://shop.freedommobile.ca/devices/Apple/iPhone_XS_Max?sku=190198786135&planSku=Freedom%20Big%20Gig%2015GB

,

https://shop.freedommobile.ca/devices/Apple/iPhone_XS?sku=190198790569&planSku=Freedom%20Big%20Gig%

,

https://shop.freedommobile.ca/devices/Apple/iPhone_XR?sku=190198776631&planSku=Freedom%20Big%20Gig%2015GB]

Any help is appreciated
Thank you

答:
To extract all urls that https://shop.freedommobile.ca/devices has using Selenium you have to induce WebDriverWait for the visibility_of_all_elements_located() and you can use the following Locator Strategy:

Code Block:

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
# options.add_argument('disable-infobars')
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')
driver.get("https://shop.freedommobile.ca/devices")
print([my_elem.get_attribute("href") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//a[text()='See Options']")))])
</code>```

Console Output:

```<code>['https://shop.freedommobile.ca/devices/Apple/iPhone_XS_Max?sku=190198786135&planSku=Freedom%20Big%20Gig%2015GB', 'https://shop.freedommobile.ca/devices/Apple/iPhone_XS?sku=190198790569&planSku=Freedom%20Big%20Gig%2015GB', 'https://shop.freedommobile.ca/devices/Apple/iPhone_XR?sku=190198776631&planSku=Freedom%20Big%20Gig%2015GB', 'https://shop.freedommobile.ca/devices/Apple/iPhone_8_Plus?sku=190198454249&planSku=Freedom%20Big%20Gig%20%2B%20Talk%205GB', 'https://shop.freedommobile.ca/devices/Apple/iPhone_8?sku=190198450944&planSku=Freedom%20Big%20Gig%20%2B%20Talk%205GB', 'https://shop.freedommobile.ca/devices/Samsung/Galaxy_S10+?sku=887276301570&planSku=Freedom%20Big%20Gig%20%2B%20Talk%205GB', 'https://shop.freedommobile.ca/devices/Samsung/Galaxy_S10?sku=887276312163&planSku=Freedom%20Big%20Gig%20%2B%20Talk%2015GB', 'https://shop.freedommobile.ca/devices/Samsung/Galaxy_S10e?sku=887276313870&planSku=Freedom%20Big%20Gig%2015GB', 'https://shop.freedommobile.ca/devices/Samsung/Galaxy_Tab_A_8_LTE?sku=887276299440&planSku=Promo%20Tablet%2015', 'https://shop.freedommobile.ca/devices/Samsung/Galaxy_Note9?sku=887276279916&planSku=Freedom%20Big%20Gig%2015GB', 'https://shop.freedommobile.ca/devices/Samsung/Galaxy_S9?sku=887276250861&planSku=Freedom%20Big%20Gig%20%2B%20Talk%205GB', 'https://shop.freedommobile.ca/devices/Motorola/G7_Power?sku=723755134249&planSku=Freedom%20Big%20Gig%20%2B%20Talk%205GB', 'https://shop.freedommobile.ca/devices/Motorola/Moto_E5_Play?sku=723755125940&planSku=Freedom%20LTE%2B3G%209.5GB%20Promo', 'https://shop.freedommobile.ca/devices/Google/Pixel_3a?sku=842776111326&planSku=Freedom%20Big%20Gig%20%2B%20Talk%205GB', 'https://shop.freedommobile.ca/devices/Google/Pixel_3?sku=842776109798&planSku=Freedom%20Big%20Gig%20%2B%20Talk%2010GB', 'https://shop.freedommobile.ca/devices/Google/Pixel_3_XL?sku=842776109828&planSku=Freedom%20Big%20Gig%20%2B%20Talk%2010GB', 'https://shop.freedommobile.ca/devices/ZTE/Z557?sku=885913107448&planSku=Freedom%20500MB', 'https://shop.freedommobile.ca/devices/LG/G7_ThinQ?sku=652810830737&planSku=Freedom%20Big%20Gig%20%2B%20Talk%205GB', 'https://shop.freedommobile.ca/devices/Huawei/P30_lite?sku=886598061131&planSku=Freedom%20Big%20Gig%20%2B%20Talk%205GB', 'https://shop.freedommobile.ca/devices/Huawei/Mate_20_Pro?sku=886598058964&planSku=Freedom%20Big%20Gig%20%2B%20Talk%2010GB', 'https://shop.freedommobile.ca/devices/LG/X_Power_3?sku=652810831130&planSku=Freedom%20LTE%2B3G%209.5GB%20Promo', 'https://shop.freedommobile.ca/devices/LG/G8_ThinQ?sku=652810832434&planSku=Freedom%20Big%20Gig%20%2B%20Talk%2010GB', 'https://shop.freedommobile.ca/devices/LG/Q_Stylo_+?sku=652810831222&planSku=Freedom%202GB', 'https://shop.freedommobile.ca/devices/Alcatel/GoFLIP?sku=889063504010&planSku=Freedom%20500MB', 'https://shop.freedommobile.ca/devices/Bring_Your/Own_Device?sku=byod']
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am attempting to extract all urls that https://shop.freedommobile.ca/devices has when you click the 'see options' button under each phone and place them into a list of strings.

I am using python with Selenium and wait libraries.
Ive already tried using .text in my parameters. However, I keep running into an error that states:

typeError: 'str' object is not callable
line 17 is the issue.

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

class phoneCost:

    driver.get("https://shop.freedommobile.ca/devices")

    # extract the names of the phones
    wait = WebDriverWait(driver, 20) #10 second wait
    XPathLocation = """B//*[@id="skip-navigation"]/div/div/div[1]/div/div[2]/a'"""
    phonePlanLinksRaw = wait.until(EC.presence_of_all_elements_located(By.XPATH(XPathLocation)))
    phonePlanLinks = []

    for element in range(len(phonePlanLinksRaw)):
        link = element
        phonePlanLinks.append(str(link))

    numLink = 1
    for element in range(len(phonePlanLinks)):
        print("phone " + str(numLink) + " : " + phonePlanLinks[element])
        numLink += 1

should return a list of urls in string format:

[https://shop.freedommobile.ca/devices/Apple/iPhone_XS_Max?sku=190198786135&planSku=Freedom%20Big%20Gig%2015GB

,

https://shop.freedommobile.ca/devices/Apple/iPhone_XS?sku=190198790569&planSku=Freedom%20Big%20Gig%

,

https://shop.freedommobile.ca/devices/Apple/iPhone_XR?sku=190198776631&planSku=Freedom%20Big%20Gig%2015GB]

Any help is appreciated
Thank you

Body:
To extract all urls that https://shop.freedommobile.ca/devices has using Selenium you have to induce WebDriverWait for the visibility_of_all_elements_located() and you can use the following Locator Strategy:

Code Block:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
# options.add_argument('disable-infobars')
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')
driver.get("https://shop.freedommobile.ca/devices")
print([my_elem.get_attribute("href") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//a[text()='See Options']")))])

Console Output:

['https://shop.freedommobile.ca/devices/Apple/iPhone_XS_Max?sku=190198786135&planSku=Freedom%20Big%20Gig%2015GB', 'https://shop.freedommobile.ca/devices/Apple/iPhone_XS?sku=190198790569&planSku=Freedom%20Big%20Gig%2015GB', 'https://shop.freedommobile.ca/devices/Apple/iPhone_XR?sku=190198776631&planSku=Freedom%20Big%20Gig%2015GB', 'https://shop.freedommobile.ca/devices/Apple/iPhone_8_Plus?sku=190198454249&planSku=Freedom%20Big%20Gig%20%2B%20Talk%205GB', 'https://shop.freedommobile.ca/devices/Apple/iPhone_8?sku=190198450944&planSku=Freedom%20Big%20Gig%20%2B%20Talk%205GB', 'https://shop.freedommobile.ca/devices/Samsung/Galaxy_S10+?sku=887276301570&planSku=Freedom%20Big%20Gig%20%2B%20Talk%205GB', 'https://shop.freedommobile.ca/devices/Samsung/Galaxy_S10?sku=887276312163&planSku=Freedom%20Big%20Gig%20%2B%20Talk%2015GB', 'https://shop.freedommobile.ca/devices/Samsung/Galaxy_S10e?sku=887276313870&planSku=Freedom%20Big%20Gig%2015GB', 'https://shop.freedommobile.ca/devices/Samsung/Galaxy_Tab_A_8_LTE?sku=887276299440&planSku=Promo%20Tablet%2015', 'https://shop.freedommobile.ca/devices/Samsung/Galaxy_Note9?sku=887276279916&planSku=Freedom%20Big%20Gig%2015GB', 'https://shop.freedommobile.ca/devices/Samsung/Galaxy_S9?sku=887276250861&planSku=Freedom%20Big%20Gig%20%2B%20Talk%205GB', 'https://shop.freedommobile.ca/devices/Motorola/G7_Power?sku=723755134249&planSku=Freedom%20Big%20Gig%20%2B%20Talk%205GB', 'https://shop.freedommobile.ca/devices/Motorola/Moto_E5_Play?sku=723755125940&planSku=Freedom%20LTE%2B3G%209.5GB%20Promo', 'https://shop.freedommobile.ca/devices/Google/Pixel_3a?sku=842776111326&planSku=Freedom%20Big%20Gig%20%2B%20Talk%205GB', 'https://shop.freedommobile.ca/devices/Google/Pixel_3?sku=842776109798&planSku=Freedom%20Big%20Gig%20%2B%20Talk%2010GB', 'https://shop.freedommobile.ca/devices/Google/Pixel_3_XL?sku=842776109828&planSku=Freedom%20Big%20Gig%20%2B%20Talk%2010GB', 'https://shop.freedommobile.ca/devices/ZTE/Z557?sku=885913107448&planSku=Freedom%20500MB', 'https://shop.freedommobile.ca/devices/LG/G7_ThinQ?sku=652810830737&planSku=Freedom%20Big%20Gig%20%2B%20Talk%205GB', 'https://shop.freedommobile.ca/devices/Huawei/P30_lite?sku=886598061131&planSku=Freedom%20Big%20Gig%20%2B%20Talk%205GB', 'https://shop.freedommobile.ca/devices/Huawei/Mate_20_Pro?sku=886598058964&planSku=Freedom%20Big%20Gig%20%2B%20Talk%2010GB', 'https://shop.freedommobile.ca/devices/LG/X_Power_3?sku=652810831130&planSku=Freedom%20LTE%2B3G%209.5GB%20Promo', 'https://shop.freedommobile.ca/devices/LG/G8_ThinQ?sku=652810832434&planSku=Freedom%20Big%20Gig%20%2B%20Talk%2010GB', 'https://shop.freedommobile.ca/devices/LG/Q_Stylo_+?sku=652810831222&planSku=Freedom%202GB', 'https://shop.freedommobile.ca/devices/Alcatel/GoFLIP?sku=889063504010&planSku=Freedom%20500MB', 'https://shop.freedommobile.ca/devices/Bring_Your/Own_Device?sku=byod']


问:
Gitlab CE not sending email
I have setup Gitlab CE on a local Ubuntu Server, and I'm trying to use Zoho to send email to users. But, mails are not sent. Even when testing with gitlab-rails console :

```<code>irb(main):003:0> Notify.test_email('destination_email@address.com', 'Message Subject', 'Message Body').deliver_now
</code>```

My SMTP config is as follow :

```<code>gitlab_rails['smtp_enable'] = true
gitlab_rails['smtp_address'] = "smtp.zoho.com"
gitlab_rails['smtp_port'] = 587 # I've also changed to 465, but in vain
gitlab_rails['smtp_authentication'] = "plain"
gitlab_rails['smtp_enable_starttls_auto'] = true
gitlab_rails['smtp_user_name'] = "gitlab@mydomain.com"
gitlab_rails['smtp_password'] = "mypassword"
gitlab_rails['smtp_domain'] = "smtp.zoho.com"
</code>```

And Reply by email config :

```<code>gitlab_rails['incoming_email_enabled'] = true
gitlab_rails['incoming_email_address'] = "gitlab-incoming+{key}@domain.com"
gitlab_rails['incoming_email_email'] = "gitlab@domain.com"
gitlab_rails['incoming_email_password'] = "Password"
gitlab_rails['incoming_email_host'] = "imap.zoho.com"
gitlab_rails['incoming_email_port'] = 993
gitlab_rails['incoming_email_ssl'] = true
gitlab_rails['incoming_email_mailbox_name'] = "inbox"
gitlab_rails['incoming_email_idle_timeout'] = 60
</code>```

Can somebody help me fix this ?

Update : This is the output of the test in gitlab_rails console

Notify#test_email: processed outbound mail in 414.5ms

Sent mail to user@domain.com (65666.5ms)
  Date: Wed, 23 Nov 2016 12:47:12 +0100
  From: GitLab
  Reply-To: GitLab

To: user@domain.com

Message-ID: <583581c03dae3_a7303fac34cdb0fc64a7@administrateur-virtual-machine.mail>

Subject: Test

Mime-Version: 1.0

Content-Type: text/html;
   charset=UTF-8
  Content-Transfer-Encoding: 7bit

Testons

Net::ReadTimeout: Net::ReadTimeout
          from /opt/gitlab/embedded/lib/ruby/2.3.0/net/protocol.rb:158:in rbuf_fill'
          from /opt/gitlab/embedded/lib/ruby/2.3.0/net/protocol.rb:136:inreaduntil'
          from /opt/gitlab/embedded/lib/ruby/2.3.0/net/protocol.rb:146:in readline'
          from /opt/gitlab/embedded/lib/ruby/2.3.0/net/smtp.rb:946:inrecv_response'
          from /opt/gitlab/embedded/lib/ruby/2.3.0/net/smtp.rb:556:in block in do_start'
          from /opt/gitlab/embedded/lib/ruby/2.3.0/net/smtp.rb:956:incritical'
          from /opt/gitlab/embedded/lib/ruby/2.3.0/net/smtp.rb:556:in do_start'
          from /opt/gitlab/embedded/lib/ruby/2.3.0/net/smtp.rb:521:instart'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/mail-2.6.4/lib/mail/network/deli          very_methods/smtp.rb:113:in deliver!'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/mail-2.6.4/lib/mail/message.rb:2          149:indo_delivery'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/mail-2.6.4/lib/mail/message.rb:2          37:in block in deliver'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/actionmailer-4.2.7.1/lib/action_          mailer/base.rb:543:inblock in deliver_mail'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/activesupport-4.2.7.1/lib/active          _support/notifications.rb:164:in block in instrument'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/activesupport-4.2.7.1/lib/active          _support/notifications/instrumenter.rb:20:ininstrument'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/activesupport-4.2.7.1/lib/active          _support/notifications.rb:164:in instrument'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/actionmailer-4.2.7.1/lib/action_          mailer/base.rb:541:indeliver_mail'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/mail-2.6.4/lib/mail/message.rb:2          37:in deliver'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/actionmailer-4.2.7.1/lib/action_          mailer/message_delivery.rb:85:indeliver_now'
          from (irb):1
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/railties-4.2.7.1/lib/rails/comma          nds/console.rb:110:in start'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/railties-4.2.7.1/lib/rails/comma          nds/console.rb:9:instart'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/railties-4.2.7.1/lib/rails/comma          nds/commands_tasks.rb:68:in console'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/railties-4.2.7.1/lib/rails/comma          nds/commands_tasks.rb:39:inrun_command!'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/railties-4.2.7.1/lib/rails/comma          nds.rb:17:in <top (required)>'
          from bin/rails:9:inrequire'
          from bin/rails:9:in `'

答:
I managed to solve it with the accepted answer here: ActionMailer "Net::ReadTimeout" when using Delayed Job with Rackspace "emailsrvr.com"

It could be that some of the suggested settings in the documentation (https://docs.gitlab.com/omnibus/settings/smtp.html) cause problems.

These settings work for me:

```<code>gitlab_rails['smtp_address'] = "secure.emailsrvr.com"
gitlab_rails['smtp_port'] = 465
gitlab_rails['smtp_domain'] = "domain.com"
gitlab_rails['smtp_authentication'] = "login"
gitlab_rails['smtp_tls'] = true
gitlab_rails['smtp_user_name'] = "no-reply@domain.com"
gitlab_rails['smtp_password'] = "XXX"

gitlab_rails['gitlab_email_from'] = "no-reply@domain.com"
gitlab_rails['gitlab_support_email'] = "support@domain.com"
gitlab_rails['gitlab_email_reply_to'] = "support@domain.com"
</code>```

Title: Gitlab CE not sending email

Body:
I have setup Gitlab CE on a local Ubuntu Server, and I'm trying to use Zoho to send email to users. But, mails are not sent. Even when testing with gitlab-rails console :

irb(main):003:0> Notify.test_email('destination_email@address.com', 'Message Subject', 'Message Body').deliver_now

My SMTP config is as follow :

gitlab_rails['smtp_enable'] = true
gitlab_rails['smtp_address'] = "smtp.zoho.com"
gitlab_rails['smtp_port'] = 587 # I've also changed to 465, but in vain
gitlab_rails['smtp_authentication'] = "plain"
gitlab_rails['smtp_enable_starttls_auto'] = true
gitlab_rails['smtp_user_name'] = "gitlab@mydomain.com"
gitlab_rails['smtp_password'] = "mypassword"
gitlab_rails['smtp_domain'] = "smtp.zoho.com"

And Reply by email config :

gitlab_rails['incoming_email_enabled'] = true
gitlab_rails['incoming_email_address'] = "gitlab-incoming+{key}@domain.com"
gitlab_rails['incoming_email_email'] = "gitlab@domain.com"
gitlab_rails['incoming_email_password'] = "Password"
gitlab_rails['incoming_email_host'] = "imap.zoho.com"
gitlab_rails['incoming_email_port'] = 993
gitlab_rails['incoming_email_ssl'] = true
gitlab_rails['incoming_email_mailbox_name'] = "inbox"
gitlab_rails['incoming_email_idle_timeout'] = 60

Can somebody help me fix this ?

Update : This is the output of the test in gitlab_rails console

Notify#test_email: processed outbound mail in 414.5ms

Sent mail to user@domain.com (65666.5ms)
  Date: Wed, 23 Nov 2016 12:47:12 +0100
  From: GitLab
  Reply-To: GitLab

To: user@domain.com

Message-ID: <583581c03dae3_a7303fac34cdb0fc64a7@administrateur-virtual-machine.mail>

Subject: Test

Mime-Version: 1.0

Content-Type: text/html;
   charset=UTF-8
  Content-Transfer-Encoding: 7bit

Testons

Net::ReadTimeout: Net::ReadTimeout
          from /opt/gitlab/embedded/lib/ruby/2.3.0/net/protocol.rb:158:in rbuf_fill'
          from /opt/gitlab/embedded/lib/ruby/2.3.0/net/protocol.rb:136:inreaduntil'
          from /opt/gitlab/embedded/lib/ruby/2.3.0/net/protocol.rb:146:in readline'
          from /opt/gitlab/embedded/lib/ruby/2.3.0/net/smtp.rb:946:inrecv_response'
          from /opt/gitlab/embedded/lib/ruby/2.3.0/net/smtp.rb:556:in block in do_start'
          from /opt/gitlab/embedded/lib/ruby/2.3.0/net/smtp.rb:956:incritical'
          from /opt/gitlab/embedded/lib/ruby/2.3.0/net/smtp.rb:556:in do_start'
          from /opt/gitlab/embedded/lib/ruby/2.3.0/net/smtp.rb:521:instart'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/mail-2.6.4/lib/mail/network/deli          very_methods/smtp.rb:113:in deliver!'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/mail-2.6.4/lib/mail/message.rb:2          149:indo_delivery'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/mail-2.6.4/lib/mail/message.rb:2          37:in block in deliver'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/actionmailer-4.2.7.1/lib/action_          mailer/base.rb:543:inblock in deliver_mail'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/activesupport-4.2.7.1/lib/active          _support/notifications.rb:164:in block in instrument'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/activesupport-4.2.7.1/lib/active          _support/notifications/instrumenter.rb:20:ininstrument'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/activesupport-4.2.7.1/lib/active          _support/notifications.rb:164:in instrument'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/actionmailer-4.2.7.1/lib/action_          mailer/base.rb:541:indeliver_mail'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/mail-2.6.4/lib/mail/message.rb:2          37:in deliver'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/actionmailer-4.2.7.1/lib/action_          mailer/message_delivery.rb:85:indeliver_now'
          from (irb):1
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/railties-4.2.7.1/lib/rails/comma          nds/console.rb:110:in start'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/railties-4.2.7.1/lib/rails/comma          nds/console.rb:9:instart'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/railties-4.2.7.1/lib/rails/comma          nds/commands_tasks.rb:68:in console'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/railties-4.2.7.1/lib/rails/comma          nds/commands_tasks.rb:39:inrun_command!'
          from /opt/gitlab/embedded/service/gem/ruby/2.3.0/gems/railties-4.2.7.1/lib/rails/comma          nds.rb:17:in <top (required)>'
          from bin/rails:9:inrequire'
          from bin/rails:9:in `'

Body:
I managed to solve it with the accepted answer here: ActionMailer "Net::ReadTimeout" when using Delayed Job with Rackspace "emailsrvr.com"

It could be that some of the suggested settings in the documentation (https://docs.gitlab.com/omnibus/settings/smtp.html) cause problems.

These settings work for me:

gitlab_rails['smtp_address'] = "secure.emailsrvr.com"
gitlab_rails['smtp_port'] = 465
gitlab_rails['smtp_domain'] = "domain.com"
gitlab_rails['smtp_authentication'] = "login"
gitlab_rails['smtp_tls'] = true
gitlab_rails['smtp_user_name'] = "no-reply@domain.com"
gitlab_rails['smtp_password'] = "XXX"

gitlab_rails['gitlab_email_from'] = "no-reply@domain.com"
gitlab_rails['gitlab_support_email'] = "support@domain.com"
gitlab_rails['gitlab_email_reply_to'] = "support@domain.com"


问:
Getting strange googleapi Err 400 message connecting to postgresql CloudSQL instance
I´m getting a strange Err 400 missing project parameter when trying to connect to a CloudSQL instance using the cloud_sql_proxy mechanism

I have a GCE project with a working CloudSQL postgres database, my apps on the compute api can use it and I can do regular psql from any of the VM I have configured inside my GCE project.

However, when I try to connect to the database from my laptop using the cloud_sql_proxy I get this strange error.

I´m following to the letter this documentation: https://cloud.google.com/sql/docs/postgres/connect-admin-proxy#install

So, following that documentation I have:

CloudSQL enabled and working as I commented

Proxy Installed

I have a service account created as the documentation say with Cloud SQL Admin role as follows:

```<code>{
  "type": "service_account",
  "project_id": "my-proyect-21432",
  "private_key_id": "<hidden intentionally>",
  "private_key": "<hidden intentionally>",
  "client_email": "cloudsql-serviceaccount@my-proyect-21432.iam.gserviceaccount.com",
  "client_id": "<hidden intentionally>",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/cloudsql-serviceaccount@my-proyect-21432.iam.gserviceaccount.com"
}
</code>```

I started the cloud_sql_proxy successfully as follows:

```<code>user@hostname:~$ ./cloud_sql_proxy -instances=db1=tcp:15432 -credential_file=my-proyect-21432.json
2019/05/29 10:17:25 Rlimits for file descriptors set to {&{8500 65536}}
2019/05/29 10:17:25 using credential file for authentication; email=cloudsql-serviceaccount@my-proyect-21432.iam.gserviceaccount.com
2019/05/29 10:17:25 Listening on 127.0.0.1:15432 for db1
2019/05/29 10:17:25 Ready for new connections
</code>```

And finally I launch the psql client as follows:

```<code>psql "host=127.0.0.1 port=15432 sslmode=disable dbname=db1 user=dbuser"
</code>```

I see on the cloud_sql_proxy the following error:

```<code>2019/05/29 10:17:33 New connection for "db1"
2019/05/29 10:17:34 couldn't connect to "db1": googleapi: Error 400: Missing parameter: project., required
</code>```

And on the client side I'm getting:

```<code>psql: server closed the connection unexpectedly
        This probably means the server terminated abnormally
        before or while processing the request.
</code>```

At this point I should get my psql client connected successfully and I can´t find anything about this error online or in the google's documentation

I have no clue where I need to set a project parameter, I tried crazy places like on the psql side with -v or using the url with ? at the end with no luck, I also tried on the cloud_sql_proxy side using the -projects flag, also with no luck.

EDIT: New findings!!!

I think I'm close to solve this, the first setup I did (as commented above) was on my windows pc that I use at home, today I'm at the office and I decided to replicate all of that using macos, I don't think that the OS matter at all, the interesting thing is that I replicated all and founded a small thing that make me to move forward

So, I started again and execute points 1., 2., 3., 4. and wait? the documentation states that the instances string is as follows: myproject:us-central1:myinstance NOT what I originally wrote, so I changed that and start having a more reasonable error:

I started cloud_sql_proxy make the connection with psql and got this:

```<code>user@hostname:~$ ./cloud_sql_proxy -instances=my-proyect-21432:us-east1:db1=tcp:15432 -credential_file=my-proyect-21432.json
2019/05/30 14:13:25 Rlimits for file descriptors set to {&{8500 65536}}
2019/05/30 14:13:25 using credential file for authentication; email=cloudsql-serviceaccount@my-proyect-21432.iam.gserviceaccount.com
2019/05/30 14:13:25 Listening on 127.0.0.1:15432 for db1
2019/05/30 14:13:25 Ready for new connections

<< when I run psql>>

2019/05/30 14:14:08 New connection for "my-proyect-21432:us-east1:db1"
2019/05/30 14:15:24 couldn't connect to "my-proyect-21432:us-east1:db1": dial tcp 10.26.112.3:3307: connect: operation timed out
</code>```

My db1 instance has only the private IP 10.26.112.3

I started to look for that error around the internet and found a sugestion to allow incoming traffic to 3307 port:

Cannot Connect by Cloud SQL Proxy from Cloud Shell By Proxy
https://github.com/GoogleCloudPlatform/cloudsql-proxy/issues/164

So I added the following rule:

```<code>allow-cloudsqlproxy | Ingress | Apply to all | IP Ranges 0.0.0.0/0 | tcp,udp 3307 | allow | default | 1000
</code>```

But that didn't make any difference because after that I'm still getting the same error message :(

EDIT: from a VM on the same project

I created a VM on that project and replicate all this, I was able to connect, no connection refused on port 3307 message.

I have no idea who is blocking that traffic...

答:
Ok, apparently the cloud_sql_proxy does not work if your db instance only has a private ip address, I had to add a public one so the proxy server had access to my instance.

I understand certain limitations but if Google provides a cloud_sql_proxy it should support all customer cases, I mean, I´m using the default network, that network is managed by google, the network should allow somehow the Proxy Server to reach my db instances.. I don't know ...

The second I added the public IP the second it started working ... but I honestly don't want a public IP on my db instances.

Body:
I´m getting a strange Err 400 missing project parameter when trying to connect to a CloudSQL instance using the cloud_sql_proxy mechanism

I have a GCE project with a working CloudSQL postgres database, my apps on the compute api can use it and I can do regular psql from any of the VM I have configured inside my GCE project.

However, when I try to connect to the database from my laptop using the cloud_sql_proxy I get this strange error.

I´m following to the letter this documentation: https://cloud.google.com/sql/docs/postgres/connect-admin-proxy#install

So, following that documentation I have:

CloudSQL enabled and working as I commented

Proxy Installed

I have a service account created as the documentation say with Cloud SQL Admin role as follows:

{
  "type": "service_account",
  "project_id": "my-proyect-21432",
  "private_key_id": "<hidden intentionally>",
  "private_key": "<hidden intentionally>",
  "client_email": "cloudsql-serviceaccount@my-proyect-21432.iam.gserviceaccount.com",
  "client_id": "<hidden intentionally>",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/cloudsql-serviceaccount@my-proyect-21432.iam.gserviceaccount.com"
}

I started the cloud_sql_proxy successfully as follows:

user@hostname:~$ ./cloud_sql_proxy -instances=db1=tcp:15432 -credential_file=my-proyect-21432.json
2019/05/29 10:17:25 Rlimits for file descriptors set to {&{8500 65536}}
2019/05/29 10:17:25 using credential file for authentication; email=cloudsql-serviceaccount@my-proyect-21432.iam.gserviceaccount.com
2019/05/29 10:17:25 Listening on 127.0.0.1:15432 for db1
2019/05/29 10:17:25 Ready for new connections

And finally I launch the psql client as follows:

psql "host=127.0.0.1 port=15432 sslmode=disable dbname=db1 user=dbuser"

I see on the cloud_sql_proxy the following error:

2019/05/29 10:17:33 New connection for "db1"
2019/05/29 10:17:34 couldn't connect to "db1": googleapi: Error 400: Missing parameter: project., required

And on the client side I'm getting:

psql: server closed the connection unexpectedly
        This probably means the server terminated abnormally
        before or while processing the request.

At this point I should get my psql client connected successfully and I can´t find anything about this error online or in the google's documentation

I have no clue where I need to set a project parameter, I tried crazy places like on the psql side with -v or using the url with ? at the end with no luck, I also tried on the cloud_sql_proxy side using the -projects flag, also with no luck.

EDIT: New findings!!!

I think I'm close to solve this, the first setup I did (as commented above) was on my windows pc that I use at home, today I'm at the office and I decided to replicate all of that using macos, I don't think that the OS matter at all, the interesting thing is that I replicated all and founded a small thing that make me to move forward

So, I started again and execute points 1., 2., 3., 4. and wait? the documentation states that the instances string is as follows: myproject:us-central1:myinstance NOT what I originally wrote, so I changed that and start having a more reasonable error:

I started cloud_sql_proxy make the connection with psql and got this:

user@hostname:~$ ./cloud_sql_proxy -instances=my-proyect-21432:us-east1:db1=tcp:15432 -credential_file=my-proyect-21432.json
2019/05/30 14:13:25 Rlimits for file descriptors set to {&{8500 65536}}
2019/05/30 14:13:25 using credential file for authentication; email=cloudsql-serviceaccount@my-proyect-21432.iam.gserviceaccount.com
2019/05/30 14:13:25 Listening on 127.0.0.1:15432 for db1
2019/05/30 14:13:25 Ready for new connections

<< when I run psql>>

2019/05/30 14:14:08 New connection for "my-proyect-21432:us-east1:db1"
2019/05/30 14:15:24 couldn't connect to "my-proyect-21432:us-east1:db1": dial tcp 10.26.112.3:3307: connect: operation timed out

My db1 instance has only the private IP 10.26.112.3

I started to look for that error around the internet and found a sugestion to allow incoming traffic to 3307 port:

Cannot Connect by Cloud SQL Proxy from Cloud Shell By Proxy
https://github.com/GoogleCloudPlatform/cloudsql-proxy/issues/164

So I added the following rule:

allow-cloudsqlproxy | Ingress | Apply to all | IP Ranges 0.0.0.0/0 | tcp,udp 3307 | allow | default | 1000

But that didn't make any difference because after that I'm still getting the same error message :(

EDIT: from a VM on the same project

I created a VM on that project and replicate all this, I was able to connect, no connection refused on port 3307 message.

I have no idea who is blocking that traffic...


问:
Many individual dependent variables, code for one by one linear regression
I have two datasets "bear" and "frog" and I am trying to write a function, which would take
columns one by one from "bear" as dependent variable in linear regression with same regressors in
all cases, print the name of the column in each case and the summary of linear regression with
coefficients, standard errors, t-value, R squared and residual standard errors.I want to get 25 separate outputs

I tried the following code

```<code>  print(lm(bear[,i]~frog$MK_RF+frog$SMB+frog$HML))
  print(colnames(bear[,i]))
  summary (lm(bear[,i]~frog$Mkt.RF+frog$SMB+frog$HML))}
</code>```

I wrote this function, but instead of column name i get NULL, and the summary only shows coefficients, no error message.
For reproductible examples:

```<code># dput(head(frog, 10))
frog <- structure(list(date = c(192607L, 192608L, 192609L, 192610L, 192611L,
192612L, 192701L, 192702L, 192703L, 192704L), Mkt.RF = c(2.96,
2.64, 0.36, -3.24, 2.53, 2.62, -0.06, 4.18, 0.13, 0.46), SMB = c(-2.3,
-1.4, -1.32, 0.04, -0.2, -0.04, -0.56, -0.1, -1.6, 0.43), HML = c(-2.87,
4.19, 0.01, 0.51, -0.35, -0.02, 4.83, 3.17, -2.67, 0.6), RF = c(0.22,
0.25, 0.23, 0.32, 0.31, 0.28, 0.25, 0.26, 0.3, 0.25)), row.names = c(NA,
10L), class = "data.frame")
</code>```

and for the bear dataset

```<code># dput(head(bear[, 1:3], 10))
bear <- structure(list(date = c(192607L, 192608L, 192609L, 192610L, 192611L,
192612L, 192701L, 192702L, 192703L, 192704L), SMALL.LoBM = c(3.5582,
-2.4574, -6.4413, -8.9441, 3.1644, 13.6658, 0.1974, 2.2284, 6.0998,
5.5863), ME1.BM2 = c(-0.6319, -8.9775, -0.5289, -4.0732, 6.3376,
-2.2572, -8.5499, -0.5649, -2.0464, 7.5611)), row.names = c(NA,
10L), class = "data.frame")
</code>```

答:
I'd strongly recommend that you merge your data frames: relying on the row ordering being consistent is dangerous. The only reason not to is if your data sets are enormous and you can't afford the extra memory consumption.

```<code>bear_vars <- names(bear)[-1]
frog_vars <- names(frog)[-1]
bf <- merge(bear, frog, by = "date")
</code>```

Now loop, using reformulate() to build a linear model formula with the values in frog_vars as the predictor (independent) variables and each value in bear_vars as the response (dependent) variable:

```<code>for (b in bear_vars) {
    m <- lm(reformulate(frog_vars, response=b), data=bf)
    cat(b,"\n")
    print(m)
    print(summary(m))
}
</code>```

You can use tidyverse methods if you want, but this should work OK.

Body:
I have two datasets "bear" and "frog" and I am trying to write a function, which would take
columns one by one from "bear" as dependent variable in linear regression with same regressors in
all cases, print the name of the column in each case and the summary of linear regression with
coefficients, standard errors, t-value, R squared and residual standard errors.I want to get 25 separate outputs

I tried the following code

  print(lm(bear[,i]~frog$MK_RF+frog$SMB+frog$HML))
  print(colnames(bear[,i]))
  summary (lm(bear[,i]~frog$Mkt.RF+frog$SMB+frog$HML))}

I wrote this function, but instead of column name i get NULL, and the summary only shows coefficients, no error message.
For reproductible examples:

# dput(head(frog, 10))
frog <- structure(list(date = c(192607L, 192608L, 192609L, 192610L, 192611L,
192612L, 192701L, 192702L, 192703L, 192704L), Mkt.RF = c(2.96,
2.64, 0.36, -3.24, 2.53, 2.62, -0.06, 4.18, 0.13, 0.46), SMB = c(-2.3,
-1.4, -1.32, 0.04, -0.2, -0.04, -0.56, -0.1, -1.6, 0.43), HML = c(-2.87,
4.19, 0.01, 0.51, -0.35, -0.02, 4.83, 3.17, -2.67, 0.6), RF = c(0.22,
0.25, 0.23, 0.32, 0.31, 0.28, 0.25, 0.26, 0.3, 0.25)), row.names = c(NA,
10L), class = "data.frame")

and for the bear dataset

# dput(head(bear[, 1:3], 10))
bear <- structure(list(date = c(192607L, 192608L, 192609L, 192610L, 192611L,
192612L, 192701L, 192702L, 192703L, 192704L), SMALL.LoBM = c(3.5582,
-2.4574, -6.4413, -8.9441, 3.1644, 13.6658, 0.1974, 2.2284, 6.0998,
5.5863), ME1.BM2 = c(-0.6319, -8.9775, -0.5289, -4.0732, 6.3376,
-2.2572, -8.5499, -0.5649, -2.0464, 7.5611)), row.names = c(NA,
10L), class = "data.frame")

Body:
I'd strongly recommend that you merge your data frames: relying on the row ordering being consistent is dangerous. The only reason not to is if your data sets are enormous and you can't afford the extra memory consumption.

bear_vars <- names(bear)[-1]
frog_vars <- names(frog)[-1]
bf <- merge(bear, frog, by = "date")

Now loop, using reformulate() to build a linear model formula with the values in frog_vars as the predictor (independent) variables and each value in bear_vars as the response (dependent) variable:

for (b in bear_vars) {
    m <- lm(reformulate(frog_vars, response=b), data=bf)
    cat(b,"\n")
    print(m)
    print(summary(m))
}

You can use tidyverse methods if you want, but this should work OK.


问:
Convert List of Lists to Dictionary with unique keys and all related values
I'm python newbie and I'am currently struggling with one problem. I have a list of lists:

[[0,1], [1,2,8], [3,4], [4,2], [2,5], [5,6,7], [8,9,10,11,12]]

My aim is to make a dictionary from it with the following format:

{0:[1],1:[2,8],2:[8,1,4,5],3:[4],5:[6,7,2],6:[5,7],7:[5,6],8:[1,2,10,9,11,12],9:[8,10,11,12],10:[8,9,11,12],11:[12,10,9,8],12:[11,9,10,8]}.

In short:

It has to make a dictionary with unique keys from 1 to 12 in this case (all unique numbers in a list), and to each key it assigns a list of values, which is a common subset for this key i.e for key 2 it appears in lists [4,2], [2,5], [1,2,8] so it has to assign to a key 2 a value which is a list of numbers in those 3 lists except 2.

Thus the output for key 2 should be: 2:[8,1,4,5] etc.

I've made some code:

```<code>data = [[0,1], [1,2,8], [3,4], [4,2], [2,5], [5,6,7], [8,9,10,11,12]]

graph = {}
for i in range(13):
    graph[i] = 3

numbers = list(range(0,13))
for row in data:
    for i in graph.keys():
        if i in row:
            graph[i] = row

for key,value in graph.items():
    graph[key] = graph[key][1:]

print(graph)
</code>```

Yet, it gives me output:

{0: [1], 1: [2, 8], 2: [5], 3: [4], 4: [2], 5: [6, 7], 6: [6, 7], 7: [6, 7], 8: [9, 10, 11, 12], 9: [9, 10, 11, 12], 10: [9, 10, 11, 12], 11: [9, 10, 11, 12], 12: [9, 10, 11, 12]}

I really don't know how to combine those lists from this in such a way that I will get desired output.

答:
Are you looking to fix your code specifically or are you just looking for a solution?

```<code>data = [[0,1], [1,2,8], [3,4], [4,2], [2,5], [5,6,7], [8,9,10,11,12]]
n = 12

# Create dict with empty list for each key
result = {key: [] for key in range(n + 1)}

for key in result:
    for x in data:
        if key in x:
            # We need to make a copy of `x` because otherwise we'd modify `data`
            x = x.copy()
            x.remove(key)
            result[key].extend(x)

print(result)
</code>```

It's an approach with emphasis on clarity so I'm sure runtime could still be improved. It prints:

```<code>{0: [1], 1: [0, 2, 8], 2: [1, 8, 4, 5], 3: [4], 4: [3, 2], 5: [2, 6, 7], 6: [5, 7], 7: [5, 6], 8: [1, 2, 9, 10, 11, 12], 9: [8, 10, 11, 12], 10: [8, 9, 11, 12], 11: [8, 9, 10, 12], 12: [8, 9, 10, 11]}
</code>```

Also, does the order matter?

Body:
I'm python newbie and I'am currently struggling with one problem. I have a list of lists:

[[0,1], [1,2,8], [3,4], [4,2], [2,5], [5,6,7], [8,9,10,11,12]]

My aim is to make a dictionary from it with the following format:

{0:[1],1:[2,8],2:[8,1,4,5],3:[4],5:[6,7,2],6:[5,7],7:[5,6],8:[1,2,10,9,11,12],9:[8,10,11,12],10:[8,9,11,12],11:[12,10,9,8],12:[11,9,10,8]}.

In short:

It has to make a dictionary with unique keys from 1 to 12 in this case (all unique numbers in a list), and to each key it assigns a list of values, which is a common subset for this key i.e for key 2 it appears in lists [4,2], [2,5], [1,2,8] so it has to assign to a key 2 a value which is a list of numbers in those 3 lists except 2.

Thus the output for key 2 should be: 2:[8,1,4,5] etc.

I've made some code:

data = [[0,1], [1,2,8], [3,4], [4,2], [2,5], [5,6,7], [8,9,10,11,12]]

graph = {}
for i in range(13):
    graph[i] = 3

numbers = list(range(0,13))
for row in data:
    for i in graph.keys():
        if i in row:
            graph[i] = row

for key,value in graph.items():
    graph[key] = graph[key][1:]

print(graph)

Yet, it gives me output:

{0: [1], 1: [2, 8], 2: [5], 3: [4], 4: [2], 5: [6, 7], 6: [6, 7], 7: [6, 7], 8: [9, 10, 11, 12], 9: [9, 10, 11, 12], 10: [9, 10, 11, 12], 11: [9, 10, 11, 12], 12: [9, 10, 11, 12]}

I really don't know how to combine those lists from this in such a way that I will get desired output.

Body:
Are you looking to fix your code specifically or are you just looking for a solution?

data = [[0,1], [1,2,8], [3,4], [4,2], [2,5], [5,6,7], [8,9,10,11,12]]
n = 12

# Create dict with empty list for each key
result = {key: [] for key in range(n + 1)}

for key in result:
    for x in data:
        if key in x:
            # We need to make a copy of `x` because otherwise we'd modify `data`
            x = x.copy()
            x.remove(key)
            result[key].extend(x)

print(result)

It's an approach with emphasis on clarity so I'm sure runtime could still be improved. It prints:

{0: [1], 1: [0, 2, 8], 2: [1, 8, 4, 5], 3: [4], 4: [3, 2], 5: [2, 6, 7], 6: [5, 7], 7: [5, 6], 8: [1, 2, 9, 10, 11, 12], 9: [8, 10, 11, 12], 10: [8, 9, 11, 12], 11: [8, 9, 10, 12], 12: [8, 9, 10, 11]}

Also, does the order matter?


问:
Keras Tensorboard for DQN reinforcement learning
I am using keras to build a DQN and train it in a classical DQN algorithm with a experience replay memory. Since in dqn you need to call model.fit many many times, meaning each time you sample batch data from the replay memory, new event log file is generation by each fit when using keras' model.fit( .... callbacks=TensorBoard(...)). It creates 2 problems, first it generates too mancy event log files and slow down a lot the training, and in the Tensorboard you cannot see any trend for example the gradual decrease of loss.

What is the method to visualize the training process like see the change of gradients and activations in reinforcement learning especial DQN implementation?

答:
You can go through TensorFlow :</p>

```<code># Create FileWriter
file_writer = tf.summary.FileWriter(log_dir, tf.get_default_graph())
history = model.fit(state, Q_values, epochs=1, verbose=0)
loss = history.history['loss'][0]

# Add values to Tensorboard
training_summary = tf.Summary(value=[tf.Summary.Value(tag="loss", simple_value=loss),
                                     tf.Summary.Value(tag="score", simple_value=score)])
file_writer.add_summary(training_summary, global_step=total_frames)
</code>```

Body:
You can go through TensorFlow :

# Create FileWriter
file_writer = tf.summary.FileWriter(log_dir, tf.get_default_graph())
history = model.fit(state, Q_values, epochs=1, verbose=0)
loss = history.history['loss'][0]

# Add values to Tensorboard
training_summary = tf.Summary(value=[tf.Summary.Value(tag="loss", simple_value=loss),
                                     tf.Summary.Value(tag="score", simple_value=score)])
file_writer.add_summary(training_summary, global_step=total_frames)


问:
Why am I getting a NameError which trying to run this For loop
I am trying to access Salesforce through their API. I am trying to run the preliminary code but I get a NameError which doesn't make any sense to me at the moment.

This is my first time taking the previous developers code and trying to run it. I keep getting an error after error.

l=[]
for p in products:
    query = 'SELECT '
    for c in columns[:-1]:
        query += c+','
    if (p=='Sigma Upgrade to Insight'):
        query += columns[-1] + ' FROM Implementation__c WHERE Imp_Type__c = \''+p+'\''
    else:
        query += columns[-1] + ' FROM Implementation__c WHERE Imp_Type__c INCLUDES (\''+p+'\') AND Implementation_Status__c != \'PE Trial Ended\''

    df_temp = pd.DataFrame(sf.query(query))
    l.append(df_temp)

    runthrough = ('nextRecordsUrl' in df_temp.columns)
    while runthrough:
        df_temp = pd.DataFrame(sf.query_more(nextRecord,True))
        l.append(df_temp)
        runthrough = ('nextRecordsUrl' in df_temp.columns)

```

<p>I am expecting to run this without any errors but I keep getting a NameError</p>

```NameError                                 Traceback (most recent call last)
<ipython-input-4-7b44b14c79ff> in <module>
     14     runthrough = ('nextRecordsUrl' in df_temp.columns)
     15     while runthrough:
---> 16         df_temp = pd.DataFrame(sf.query_more(nextRecord,True))
     17         l.append(df_temp)
     18         runthrough = ('nextRecordsUrl' in df_temp.columns)

NameError: name 'nextRecord' is not defined
```

答:
You need to set nextRecord to the value of the nextRecordsUrl element of df_temp.

```<code>    df_temp = pd.DataFrame(sf.query(query))
    l.append(df_temp)

    while 'nextRecordsUrl' in df_temp.columns:
        nextRecord = df_temp['nextRecordsUrl']
        df_temp = pd.DataFrame(sf.query_more(nextRecord,True))
        l.append(df_temp)
</code>```

Body:
I am trying to access Salesforce through their API. I am trying to run the preliminary code but I get a NameError which doesn't make any sense to me at the moment.

This is my first time taking the previous developers code and trying to run it. I keep getting an error after error.

l=[]
for p in products:
    query = 'SELECT '
    for c in columns[:-1]:
        query += c+','
    if (p=='Sigma Upgrade to Insight'):
        query += columns[-1] + ' FROM Implementation__c WHERE Imp_Type__c = \''+p+'\''
    else:
        query += columns[-1] + ' FROM Implementation__c WHERE Imp_Type__c INCLUDES (\''+p+'\') AND Implementation_Status__c != \'PE Trial Ended\''

    df_temp = pd.DataFrame(sf.query(query))
    l.append(df_temp)

    runthrough = ('nextRecordsUrl' in df_temp.columns)
    while runthrough:
        df_temp = pd.DataFrame(sf.query_more(nextRecord,True))
        l.append(df_temp)
        runthrough = ('nextRecordsUrl' in df_temp.columns)

I am expecting to run this without any errors but I keep getting a NameError

NameError                                 Traceback (most recent call last)
<ipython-input-4-7b44b14c79ff> in <module>
     14     runthrough = ('nextRecordsUrl' in df_temp.columns)
     15     while runthrough:
---> 16         df_temp = pd.DataFrame(sf.query_more(nextRecord,True))
     17         l.append(df_temp)
     18         runthrough = ('nextRecordsUrl' in df_temp.columns)

NameError: name 'nextRecord' is not defined

Body:
You need to set nextRecord to the value of the nextRecordsUrl element of df_temp.

    df_temp = pd.DataFrame(sf.query(query))
    l.append(df_temp)

    while 'nextRecordsUrl' in df_temp.columns:
        nextRecord = df_temp['nextRecordsUrl']
        df_temp = pd.DataFrame(sf.query_more(nextRecord,True))
        l.append(df_temp)


问:
Python random numbers
I can't understand the problem in python. I have such code:

```<code>class Rain:
    def __init__(self):
       self.x = random.randint(0, Core.Utils.ScreenResolutionX)
       print type(Core.Utils.ScreenResolutionX) # prints int
       print Core.Utils.ScreenResolutionX # print 1152
</code>```

Error:

```<code>    self.x = random.randint(0, Core.Utils.ScreenResolutionX)
  File "/usr/lib/python2.7/random.py", line 241, in randint
    return self.randrange(a, b+1)
  File "/usr/lib/python2.7/random.py", line 213, in randrange
    if width >= maxwidth:
AttributeError: 'Rain' object has no attribute 'getType'
</code>```

答: NULL is being returned to Python in one of your methods erroneously. Always make sure to incref and return PyNone to Python if no exception needs to be raised.

Title: Python random numbers

Body:
I can't understand the problem in python. I have such code:

class Rain:
    def __init__(self):
       self.x = random.randint(0, Core.Utils.ScreenResolutionX)
       print type(Core.Utils.ScreenResolutionX) # prints int
       print Core.Utils.ScreenResolutionX # print 1152

Error:

    self.x = random.randint(0, Core.Utils.ScreenResolutionX)
  File "/usr/lib/python2.7/random.py", line 241, in randint
    return self.randrange(a, b+1)
  File "/usr/lib/python2.7/random.py", line 213, in randrange
    if width >= maxwidth:
AttributeError: 'Rain' object has no attribute 'getType'


问:
Using GCP Cloud SQL SocketFactory with Hibernate Configuration
I am trying to connect to a Cloud SQL Postgres Database instance from GCP App Engine (GAE) Standard.  Using the database instance connection name (my-project-id:europe-west1:db-instance-name) with the Cloud SQL SocketFactory with Hibernate.

```<code>    public static SessionFactory getSessionFactory()
    {
        if (sessionFactory == null) {
            try {
                Configuration configuration = new Configuration();

                // Hibernate settings equivalent to hibernate.cfg.xml's properties
                Properties settings = new Properties();

                settings.put("hibernate.connection.provider_class","com.google.cloud.sql.postgres.SocketFactory");

                settings.put("hibernate.hikari.minimumIdle","5");
                settings.put("hibernate.hikari.maximumPoolSize","10");
                settings.put("hibernate.hikari.idleTimeout","30000");
                 settings.put("hibernate.hikari.dataSource.url","jdbc:postgres://google/database-name?cloudSqlInstance=project:europe-west1:instance-id&socketFactory=com.google.cloud.sql.postgres.SocketFactory");
                settings.put("hibernate.hikari.dataSource.user","postgres");
                settings.put("hibernate.hikari.dataSource.password","password");

                      settings.put("hibernate.dialect","org.hibernate.dialect.MySQLDialect");
        configuration.addAnnotatedClass(Country.class);

                ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties()).build();
                sessionFactory = configuration.buildSessionFactory(serviceRegistry);
            } catch (Exception e) {
                LOGGER.info("============EXCEPTION===========>"+e.getMessage());
            System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
        return sessionFactory;
</code>```

Unable to create requested service [org.hibernate.engine.jdbc.connections.spi.ConnectionProvider]

答:
I think that the implementation you’re using isn’t fit for App Engine Standard, you should check the Google implementation that can be found on the official documentation.

Official Google documentation to connect to CloudSQL from App Engine

Google example project on GitHub

Body:
I am trying to connect to a Cloud SQL Postgres Database instance from GCP App Engine (GAE) Standard.  Using the database instance connection name (my-project-id:europe-west1:db-instance-name) with the Cloud SQL SocketFactory with Hibernate.

    public static SessionFactory getSessionFactory()
    {
        if (sessionFactory == null) {
            try {
                Configuration configuration = new Configuration();

                // Hibernate settings equivalent to hibernate.cfg.xml's properties
                Properties settings = new Properties();

                settings.put("hibernate.connection.provider_class","com.google.cloud.sql.postgres.SocketFactory");

                settings.put("hibernate.hikari.minimumIdle","5");
                settings.put("hibernate.hikari.maximumPoolSize","10");
                settings.put("hibernate.hikari.idleTimeout","30000");
                 settings.put("hibernate.hikari.dataSource.url","jdbc:postgres://google/database-name?cloudSqlInstance=project:europe-west1:instance-id&socketFactory=com.google.cloud.sql.postgres.SocketFactory");
                settings.put("hibernate.hikari.dataSource.user","postgres");
                settings.put("hibernate.hikari.dataSource.password","password");

                      settings.put("hibernate.dialect","org.hibernate.dialect.MySQLDialect");
        configuration.addAnnotatedClass(Country.class);

                ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties()).build();
                sessionFactory = configuration.buildSessionFactory(serviceRegistry);
            } catch (Exception e) {
                LOGGER.info("============EXCEPTION===========>"+e.getMessage());
            System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
        return sessionFactory;

Unable to create requested service [org.hibernate.engine.jdbc.connections.spi.ConnectionProvider]


问:
Halting macro code execution until SQL query is completed
I have written a fairly complex application that uses Excel (2016) as front-end application for data stored in a MS Access database, using the ADO 6.1 library. I have noticed during macro code execution that SQL transactions triggered by my Excel application can take quite long to complete, and often the execution of the next line of code in my Excel macro depends on this SQL transaction first being completed. Unfortunately, macro code execution and SQL transactions are asynchronous operations, which means that the macro jumps to the next line of code even though the SQL transaction hasn't been completed.

My current work-around is to use a Sleep() function using the Windows API to insert a fixed delay, but this is a really ugly solution as it does reduce the performance of my application and depends very much on the CPU load, so it may sometimes work, sometimes not.

I haven't been able to find so far a solution to this problem, I can't find any hints on the Internet either.

Using Application.CalculateUntilAsyncQueriesDone doesn't help here either.

Does anyone have an idea or a hint how to halt macro code execution in Excel until an SQL transaction has been completed? Is there a method in ADO to check the completion of an SQL transaction?

答:
Is your query within the Data/connections section?

I had this problem to, I turned off "Enable Background refresh" and added "DoEvents" to the VBA, this forces the data connection to refresh before it allows the code to continue. Downside to this is it makes excel feel like its locked up, But this resolved my issue.

```<code>Sub Button1_Click()
ActiveWorkbook.Connections("ScrapData").Refresh
DoEvents

....Other code....

End With
</code>```

Body:
Is your query within the Data/connections section?

I had this problem to, I turned off "Enable Background refresh" and added "DoEvents" to the VBA, this forces the data connection to refresh before it allows the code to continue. Downside to this is it makes excel feel like its locked up, But this resolved my issue.

Sub Button1_Click()
ActiveWorkbook.Connections("ScrapData").Refresh
DoEvents

....Other code....

End With


问:
How to remove a subset of the variables in a function's local environment in R?
Right before a function returns in R, I would like to remove all of the local variables with the exception of one or two.

Here's a minimum reproducible example:

```<code>f <- function(){
  keep_this_local_var <- 3
  remove_this_local_var <- 4
  rm(setdiff(ls(environment()), c("keep_local_var"))) # doesn't work
  return(ls(environment()))
}
f() # should only be 3
</code>```

Motivation: my "real life" f function calls source() several times. There will be a possibly large, random amount of variables generated by each source() call. I won't know the names of each variable in advance; however, I do have a short list of variable names I want to to keep. Similar code has worked for me in the past, but when I source to the .GlobalEnv.

答:
This works:

```<code>f <- function(){
  keep_this_local_var <- 3
  remove_this_local_var <- 4
  rm(
    list=setdiff(ls(environment()), "keep_this_local_var"),
    envir = environment()
    )
  return(ls(environment()))
}
f() # should only be 3
</code>```

As this thread mentions, you need to specify list=.

Body:
Right before a function returns in R, I would like to remove all of the local variables with the exception of one or two.

Here's a minimum reproducible example:

f <- function(){
  keep_this_local_var <- 3
  remove_this_local_var <- 4
  rm(setdiff(ls(environment()), c("keep_local_var"))) # doesn't work
  return(ls(environment()))
}
f() # should only be 3

Motivation: my "real life" f function calls source() several times. There will be a possibly large, random amount of variables generated by each source() call. I won't know the names of each variable in advance; however, I do have a short list of variable names I want to to keep. Similar code has worked for me in the past, but when I source to the .GlobalEnv.

Body:
This works:

f <- function(){
  keep_this_local_var <- 3
  remove_this_local_var <- 4
  rm(
    list=setdiff(ls(environment()), "keep_this_local_var"),
    envir = environment()
    )
  return(ls(environment()))
}
f() # should only be 3

As this thread mentions, you need to specify list=.


问:
Can separate_rows() separate by individual character?
I'm looking to use separate_rows() to tidy data, but my data does not have a delimiter. Instead, I want to "separate" by each individual character. Because there is no delimiter in the data, I'm not sure what can be put in the sep= option.

My data is set up like:

```<code>    cog   func
COG0115    EH
COG0117    H
COG0119    E
COG0124    J
COG0126    G
COG0129    EG
</code>```

I've tried:

```<code>df %>% separate_rows(., 'func', sep='[A-Z]')
</code>```

But I realize this is telling the function to consider each capital letter a "delimiter" and is definitely not what I want as it results in an empty column...

Instead I am looking for:

```<code>    cog   func
COG0115    E
COG0115    H
COG0117    H
COG0119    E
COG0124    J
COG0126    G
COG0129    E
COG0129    G
</code>```

答:
A regex lookaround can be used as sep.

```<code>library(dplyr)
library(tidyr)
df %>%
   separate_rows(func, sep = '(?<=.)(?=.)')
#       cog func
#1 COG0115    E
#2 COG0115    H
#3 COG0117    H
#4 COG0119    E
#5 COG0124    J
#6 COG0126    G
#7 COG0129    E
#8 COG0129    G
</code>```

data

```<code>df <- structure(list(cog = c("COG0115", "COG0117", "COG0119", "COG0124",
"COG0126", "COG0129"), func = c("EH", "H", "E", "J", "G", "EG"
)), class = "data.frame", row.names = c(NA, -6L))
</code>```

Body:
I'm looking to use separate_rows() to tidy data, but my data does not have a delimiter. Instead, I want to "separate" by each individual character. Because there is no delimiter in the data, I'm not sure what can be put in the sep= option.

My data is set up like:

    cog   func
COG0115    EH
COG0117    H
COG0119    E
COG0124    J
COG0126    G
COG0129    EG

I've tried:

df %>% separate_rows(., 'func', sep='[A-Z]')

But I realize this is telling the function to consider each capital letter a "delimiter" and is definitely not what I want as it results in an empty column...

Instead I am looking for:

    cog   func
COG0115    E
COG0115    H
COG0117    H
COG0119    E
COG0124    J
COG0126    G
COG0129    E
COG0129    G

Body:
A regex lookaround can be used as sep.

library(dplyr)
library(tidyr)
df %>%
   separate_rows(func, sep = '(?<=.)(?=.)')
#       cog func
#1 COG0115    E
#2 COG0115    H
#3 COG0117    H
#4 COG0119    E
#5 COG0124    J
#6 COG0126    G
#7 COG0129    E
#8 COG0129    G

data

df <- structure(list(cog = c("COG0115", "COG0117", "COG0119", "COG0124",
"COG0126", "COG0129"), func = c("EH", "H", "E", "J", "G", "EG"
)), class = "data.frame", row.names = c(NA, -6L))


问:
Deployment of Angular 5 app on AWS EC2
I am building a project for university with Angular 5. I built two separate services:

parentFolder

InputService

package.json

...

WebClient

package.json

...

My folder structure has a parent folder called projectX and within it two sub-folders who both have their own package.json etc. They are separate projects but exist within the same parentFolder. I set up a EC2 instance and have succesfully installed all dependencies there incl. node, npm and the correct version of angular CLI.

Locally, i start my project like so:
ng serve --port 6060 for the input service and
ng serve --port 4200 for the WebClient. I already ran ng build --prod succesfully ON THE SERVER (via ssh) and created two dist folders (one within each folder). I now want to access both my services from within "the internet". I already set up inbound rules for my EC2 instance which should allow connection.

What is the easiest way to make my two dist folders available? Should i use express? I tried to use a pm2 http server which did not work.

Dont hesitate to ask if you have further questions.

答:
Let's put that your angular app is not set to as server side rendering, I can suggest you the following:

build each app with ng build --prod --aot

create your buckets in S3 (2 in your case)

put the content of dist/ folder of each app inside the respective bucket

set the properties of each bucket: 'static website hosting' choose 'use this bucket to host a website' and set the index document field as 'index.html' generated by your build (will be in the root of dist/ folder)

set the permissions of each bucket to a public and set the CORS configuration with allowed methods (below an example)

```<code><AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>DELETE</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>*</AllowedHeader>
</code>```

you can use the end points generated on 'static website hosting' to access your applications

Regarding your backend, more details are required!

Title: Deployment of Angular 5 app on AWS EC2

Body:
Let's put that your angular app is not set to as server side rendering, I can suggest you the following:

build each app with ng build --prod --aot

create your buckets in S3 (2 in your case)

put the content of dist/ folder of each app inside the respective bucket

set the properties of each bucket: 'static website hosting' choose 'use this bucket to host a website' and set the index document field as 'index.html' generated by your build (will be in the root of dist/ folder)

set the permissions of each bucket to a public and set the CORS configuration with allowed methods (below an example)

<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>DELETE</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>*</AllowedHeader>

you can use the end points generated on 'static website hosting' to access your applications

Regarding your backend, more details are required!


问:
Is there a way to omit layout_height in order to have two views have identical heights?
I wish to accomplish having the height of a view conform the the height of the another view, in other words have them exactly the same. I've tried using constraintview, but this requires omitting layout_height in order for it to work.

The following gives me a crash and requires layout_height:

```<code><ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:src="@drawable/img"
            android:id="@+id/bg"
            android:adjustViewBounds="true"
            android:layout_marginTop="8dp" app:layout_constraintTop_toBottomOf="@+id/dateText" app:layout_constraintStart_toStartOf="parent"/>
    <TextView
            android:gravity="center_vertical"
            android:text="Test text"
            android:layout_width="wrap_content"
            android:id="@+id/textView"
            android:textColor="@color/bluetext"
            app:layout_constraintBottom_toBottomOf="@+id/bg"
            app:layout_constraintStart_toStartOf="@+id/leftGuideline"
            app:layout_constraintTop_toTopOf="@+id/bg"/>
</code>```

Is there a simple way to make the heights exactly the same without using a fixed height for both views?

答:
Add android:layout_height="0dp" (a.k.a., "match constraint"), to say that you want the height to be determined by the top and bottom constraints that you have set up.

Note that you may need to adjust the android:gravity attribute of your TextView to your liking. The TextView itself will take up the desired height, but the text may be smaller (or larger, if it has lots of lines).

Body:
I wish to accomplish having the height of a view conform the the height of the another view, in other words have them exactly the same. I've tried using constraintview, but this requires omitting layout_height in order for it to work.

The following gives me a crash and requires layout_height:

<ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:src="@drawable/img"
            android:id="@+id/bg"
            android:adjustViewBounds="true"
            android:layout_marginTop="8dp" app:layout_constraintTop_toBottomOf="@+id/dateText" app:layout_constraintStart_toStartOf="parent"/>
    <TextView
            android:gravity="center_vertical"
            android:text="Test text"
            android:layout_width="wrap_content"
            android:id="@+id/textView"
            android:textColor="@color/bluetext"
            app:layout_constraintBottom_toBottomOf="@+id/bg"
            app:layout_constraintStart_toStartOf="@+id/leftGuideline"
            app:layout_constraintTop_toTopOf="@+id/bg"/>

Is there a simple way to make the heights exactly the same without using a fixed height for both views?


答:
The error occurred because you used the wrong name for one of the variables (there is no frog$MK_RF). The correct call would be

```<code>lm(as.matrix(bear) ~ frog$Mkt.RF+frog$SMB+frog$HML)
</code>```

or

```<code>mmod <- lm(as.matrix(bear) ~ Mkt.RF + SMB + HML, data=frog)
summary(mmod)
</code>```

This gives precisely the same coefficients, standard errors, t-values etc. as if you had looped over the columns in bear individually. Doing it this way has multiple advantages, however.

Try, f.ex.

```<code>anova(mmod)
coef(mmod)
residuals(mmod)
</code>```

Very handy.

Title: Many individual dependent variables, code for one by one linear regression

Body:
The error occurred because you used the wrong name for one of the variables (there is no frog$MK_RF). The correct call would be

lm(as.matrix(bear) ~ frog$Mkt.RF+frog$SMB+frog$HML)

or

mmod <- lm(as.matrix(bear) ~ Mkt.RF + SMB + HML, data=frog)
summary(mmod)

This gives precisely the same coefficients, standard errors, t-values etc. as if you had looped over the columns in bear individually. Doing it this way has multiple advantages, however.

Try, f.ex.

anova(mmod)
coef(mmod)
residuals(mmod)

Very handy.


问:
Focus on next Input field on Enter in Redux Form
I want to define a HOC(higher order Component) which will be responsible for handling the functionality.
import React, { Component } from 'react';

```<code>const NextFieldOnEnter = WrappedContainer =>
  class extends Component {
    componentDidMount() {
      console.log('hoc', this.refs);
      //move to next input field
    }
    render() {
      return <WrappedContainer {...this.props} />;
    }
  };
export default NextFieldOnEnter;
</code>```

It says this.refs is deprecated. So how can I achieve tab like behavior when enter key is pressed.
My form is

```<code><Form>
<Field
  withRef
  hasFeedback
  name="name"
  ref={ref => {
    this.field1 = ref;
  }}
  refField = "field1"
  component={makeField}
  type="date"
/>
<Field
    withRef
    hasFeedback
    name="address"
    ref={ref => {
      this.field2 = ref;
    }}
     refField ="field2"
    component={makeField}
    type="date"
  />
</Form>
</code>```

//makefield

```<code>render() {
  const {type, input, label, ref, refField, ...rest} = this.props;
  return (
    <Form.Item
      label={label}
      colon={false}
      type={type}
      value={value}
      ref={ref}
    >
      <Input {...props} />
    </Form.Item>
  );
}
</code>```

答:
This is how I solved this issue:

My Form with the field components:

When expirationDate field is active and the user presses the next key, the focus goes to the next field called securityCode . Also, when securityCode is active, and the user presses the next button, we submitted the form (because this is the last field of the form). This is why this Field has the onSubmitEditing prop defined.

```<code><Form>
  <Field
    name={'expirationDate'}
    component={renderInputRef}
    withRef
    forwardRef
    ref={componentRef => (this.expirationDate = componentRef)}
    refField="expirationDate"
    onEnter={() => {
        try {
        this.cvc.getRenderedComponent().refs.cvc._root.focus();
        } catch {
        /*Do nothing */
        }
    }}
    onChange={(event, newValue) => {
        try {
            if (newValue?.length == 5) {
                this.cvc.getRenderedComponent().refs.cvc._root.focus();
            }
        } catch {
        /*Do nothing */
        }
    }}
  />

  <Field
    name={'securityCode'}
    component={renderInputRef}
    onSubmitEditing={!invalid ? handleSubmit(this.submit) : null}
    accessibilityLabel={'new-card-cvc'}
    keyboardType={'number-pad'}
    withRef
    forwardRef
    refField="cvc"
    ref={componentRef => (this.cvc = componentRef)}
  />
</Form>
</code>```

And the renderInputRef component: (In this project we're using native-base, but it's almost the same without it.)

```<code>export class renderInputRef extends PureComponent<Props> {
 render() {
  const {
    input,
    onEnter,
    refField,
    display,
    description,
    iconRight,
    meta: { touched, warning },
    ...custom
  } = this.props;
  var hasError = touched && (error !== undefined || warning !== undefined);
  return (
    <React.Fragment>
      <Item
        withRef
        forwardRef
      >
        <Input
          ref={refField}
          returnKeyType={'next'}
          onSubmitEditing={onEnter}
          {...input}
          {...custom}
        />
      </Item>
    </React.Fragment>
  );
 }
}
</code>```

Body:
I want to define a HOC(higher order Component) which will be responsible for handling the functionality.
import React, { Component } from 'react';

const NextFieldOnEnter = WrappedContainer =>
  class extends Component {
    componentDidMount() {
      console.log('hoc', this.refs);
      //move to next input field
    }
    render() {
      return <WrappedContainer {...this.props} />;
    }
  };
export default NextFieldOnEnter;

It says this.refs is deprecated. So how can I achieve tab like behavior when enter key is pressed.
My form is

<Form>
<Field
  withRef
  hasFeedback
  name="name"
  ref={ref => {
    this.field1 = ref;
  }}
  refField = "field1"
  component={makeField}
  type="date"
/>
<Field
    withRef
    hasFeedback
    name="address"
    ref={ref => {
      this.field2 = ref;
    }}
     refField ="field2"
    component={makeField}
    type="date"
  />
</Form>

//makefield

render() {
  const {type, input, label, ref, refField, ...rest} = this.props;
  return (
    <Form.Item
      label={label}
      colon={false}
      type={type}
      value={value}
      ref={ref}
    >
      <Input {...props} />
    </Form.Item>
  );
}

Body:
This is how I solved this issue:

My Form with the field components:

When expirationDate field is active and the user presses the next key, the focus goes to the next field called securityCode . Also, when securityCode is active, and the user presses the next button, we submitted the form (because this is the last field of the form). This is why this Field has the onSubmitEditing prop defined.

<Form>
  <Field
    name={'expirationDate'}
    component={renderInputRef}
    withRef
    forwardRef
    ref={componentRef => (this.expirationDate = componentRef)}
    refField="expirationDate"
    onEnter={() => {
        try {
        this.cvc.getRenderedComponent().refs.cvc._root.focus();
        } catch {
        /*Do nothing */
        }
    }}
    onChange={(event, newValue) => {
        try {
            if (newValue?.length == 5) {
                this.cvc.getRenderedComponent().refs.cvc._root.focus();
            }
        } catch {
        /*Do nothing */
        }
    }}
  />

  <Field
    name={'securityCode'}
    component={renderInputRef}
    onSubmitEditing={!invalid ? handleSubmit(this.submit) : null}
    accessibilityLabel={'new-card-cvc'}
    keyboardType={'number-pad'}
    withRef
    forwardRef
    refField="cvc"
    ref={componentRef => (this.cvc = componentRef)}
  />
</Form>

And the renderInputRef component: (In this project we're using native-base, but it's almost the same without it.)

export class renderInputRef extends PureComponent<Props> {
 render() {
  const {
    input,
    onEnter,
    refField,
    display,
    description,
    iconRight,
    meta: { touched, warning },
    ...custom
  } = this.props;
  var hasError = touched && (error !== undefined || warning !== undefined);
  return (
    <React.Fragment>
      <Item
        withRef
        forwardRef
      >
        <Input
          ref={refField}
          returnKeyType={'next'}
          onSubmitEditing={onEnter}
          {...input}
          {...custom}
        />
      </Item>
    </React.Fragment>
  );
 }
}


问:
iPhone + CGAffineTransFormRotate(pi/2) + statusBarHidden:YES + presentModalViewController = 20 pixels of white space
I think the title is pretty descriptive:

I perform all 3 of these operations on a view, the result is 20 pixels of white space along the left side of the screen (if holding the iPhone is landscapeLeft).

I tried to fix it by performing a CGAffineTransFormTranslate(transform, -20, 0)

That just "slides" the view underneath the whitespace.

This is starting to feel like a bug, anyone else have this issue?

To clarify, I am not rotating any views.  I am sensing the orientation of the device:

```<code>[[UIDevice currentDevice] orientation]
</code>```

And if the device (not interface) is in landscape, then:

```<code>[navigationController presentModalViewController:NewView animated:NO]
</code>```

The transform is to rotate my view (created in IB) to landscape, before displaying it.

My Transform code:

```<code>    CGRect myFrame = CGRectMake(0, 0, 480, 320);
    CGAffineTransform transform = [[self.myPeriodicTableViewController view] transform];
    transform = CGAffineTransformRotate(transform, degreesToRadians(rotationDirection * 90));
    transform =  CGAffineTransformTranslate(transform, -20, 0);
    [[self.myPeriodicTableViewController view] setFrame: myFrame];
    CGPoint center = CGPointMake(myFrame.size.height/2.0, myFrame.size.width/2.0);
    [[self.myPeriodicTableViewController view] setTransform: transform];
    [[self.myPeriodicTableViewController view] setCenter: center];
</code>```

答:
I think you may need to recenter your center:

```<code>// Set the center point of the view to the center point of the window's content area.
self.view.center = CGPointMake(160.0, 240.0);
</code>```

This is the whole init method I use for landscape views and works without an issue.  Just make sure to set your nib to the right size too.

```<code>// Implement viewDidLoad to do additional setup after loading the view.
- (void)viewDidLoad {
  [super viewDidLoad];

  // Rotate to landscape
  self.view.frame = CGRectMake(0, 0, 480.0, 320.0);
  if ([[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationLandscapeRight) {
    CGAffineTransform transform = self.view.transform;

    // Set the center point of the view to the center point of the window's content area.
    self.view.center = CGPointMake(160.0, 240.0);

    // Rotate the view 90 degrees around its new center point.
    transform = CGAffineTransformRotate(transform, (M_PI / 2.0));
    self.view.transform = transform;
  }
}
</code>```

OwnerDisplayName: Corey

ContentLicense: CC BY-SA 2.5

Body:
I think the title is pretty descriptive:

I perform all 3 of these operations on a view, the result is 20 pixels of white space along the left side of the screen (if holding the iPhone is landscapeLeft).

I tried to fix it by performing a CGAffineTransFormTranslate(transform, -20, 0)

That just "slides" the view underneath the whitespace.

This is starting to feel like a bug, anyone else have this issue?

To clarify, I am not rotating any views.  I am sensing the orientation of the device:

[[UIDevice currentDevice] orientation]

And if the device (not interface) is in landscape, then:

[navigationController presentModalViewController:NewView animated:NO]

The transform is to rotate my view (created in IB) to landscape, before displaying it.

My Transform code:

    CGRect myFrame = CGRectMake(0, 0, 480, 320);
    CGAffineTransform transform = [[self.myPeriodicTableViewController view] transform];
    transform = CGAffineTransformRotate(transform, degreesToRadians(rotationDirection * 90));
    transform =  CGAffineTransformTranslate(transform, -20, 0);
    [[self.myPeriodicTableViewController view] setFrame: myFrame];
    CGPoint center = CGPointMake(myFrame.size.height/2.0, myFrame.size.width/2.0);
    [[self.myPeriodicTableViewController view] setTransform: transform];
    [[self.myPeriodicTableViewController view] setCenter: center];

LastEditorDisplayName: Corey

Body:
I think you may need to recenter your center:

// Set the center point of the view to the center point of the window's content area.
self.view.center = CGPointMake(160.0, 240.0);

This is the whole init method I use for landscape views and works without an issue.  Just make sure to set your nib to the right size too.

// Implement viewDidLoad to do additional setup after loading the view.
- (void)viewDidLoad {
  [super viewDidLoad];

  // Rotate to landscape
  self.view.frame = CGRectMake(0, 0, 480.0, 320.0);
  if ([[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationLandscapeRight) {
    CGAffineTransform transform = self.view.transform;

    // Set the center point of the view to the center point of the window's content area.
    self.view.center = CGPointMake(160.0, 240.0);

    // Rotate the view 90 degrees around its new center point.
    transform = CGAffineTransformRotate(transform, (M_PI / 2.0));
    self.view.transform = transform;
  }
}

OwnerDisplayName: Squeegy

LastEditorDisplayName: Squeegy


问:
I want to change the size of any button clicked
I have used 9 Buttons and I want to be bigger on anyone clicked, and if any of the exit modes came out, they would return to their default.
All these buttons are used in a grid-layout
I have used 9 Buttons and I want to be bigger on anyone clicked you can see example View in here

this is my source code

```<code>public class MainActivity extends AppCompatActivity implements Animation.AnimationListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        content = 1;

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//add category
        searchButton = (Button) findViewById(R.id.addCategory);

        searchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final View promptsView = getLayoutInflater().inflate(R.layout.prompts_category, null);

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
                alertDialogBuilder.setView(promptsView);
                final AlertDialog dialog = alertDialogBuilder.create();

                dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                dialog.show();
                WindowManager.LayoutParams lp = new WindowManager.LayoutParams();

                lp.copyFrom(dialog.getWindow().getAttributes());
                lp.width = 800;
                lp.height = 675;
                dialog.getWindow().setAttributes(lp);

                dialog.getWindow().clearFlags(WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW);

                addCategoryButton = (Button) dialog.findViewById(R.id.addCatButton);
                insertCategoryName = (EditText) dialog.findViewById(R.id.insertCategoryName);

                gridColorsCategory = (GridLayout) dialog.findViewById(R.id.gridColorsCategory);

                setSingleEvent(gridColorsCategory);
                addCategoryButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        insertCategoryName.getText().toString();

                    }
                });
            }
        });

    }

    private void setSingleEvent(GridLayout gridColorsCategory) {
        for (int i = 0; i < gridColorsCategory.getChildCount(); i++) {
            final Button button = (Button) gridColorsCategory.getChildAt(i);
            final int finalI = i;

            final ViewGroup.LayoutParams layoutParams = button.getLayoutParams();

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

                   }
                }
            });
        }

    }
</code>```

答:
You could create an xml file in your drawable folder called something like btn_go.xml that looks like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- NOTE: order is important (the first matching state(s) is what is rendered) -->
    <item
        android:state_pressed="true"
        android:drawable="@drawable/go_pressed_big” />
    <item
        android:drawable="@drawable/go_normal_small” />
 </selector>
</code>```

Then, in your view's layout.xml file, you'd reference your button's source like this:

```<code><ImageButton
    android:id="@+id/button_go”
    android:layout_width=“wrap_contents”
    android:layout_height=“wrap_contents”
    android:src="@drawable/btn_go”/>
</code>```

The go_pressed_big image would be slightly larger than the go_normal_small image, and, by specifying wrap_contents for the width and height, the button should adjust.

Body:
I have used 9 Buttons and I want to be bigger on anyone clicked, and if any of the exit modes came out, they would return to their default.
All these buttons are used in a grid-layout
I have used 9 Buttons and I want to be bigger on anyone clicked you can see example View in here

this is my source code

public class MainActivity extends AppCompatActivity implements Animation.AnimationListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        content = 1;

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//add category
        searchButton = (Button) findViewById(R.id.addCategory);

        searchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final View promptsView = getLayoutInflater().inflate(R.layout.prompts_category, null);

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
                alertDialogBuilder.setView(promptsView);
                final AlertDialog dialog = alertDialogBuilder.create();

                dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                dialog.show();
                WindowManager.LayoutParams lp = new WindowManager.LayoutParams();

                lp.copyFrom(dialog.getWindow().getAttributes());
                lp.width = 800;
                lp.height = 675;
                dialog.getWindow().setAttributes(lp);

                dialog.getWindow().clearFlags(WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW);

                addCategoryButton = (Button) dialog.findViewById(R.id.addCatButton);
                insertCategoryName = (EditText) dialog.findViewById(R.id.insertCategoryName);

                gridColorsCategory = (GridLayout) dialog.findViewById(R.id.gridColorsCategory);

                setSingleEvent(gridColorsCategory);
                addCategoryButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        insertCategoryName.getText().toString();

                    }
                });
            }
        });

    }

    private void setSingleEvent(GridLayout gridColorsCategory) {
        for (int i = 0; i < gridColorsCategory.getChildCount(); i++) {
            final Button button = (Button) gridColorsCategory.getChildAt(i);
            final int finalI = i;

            final ViewGroup.LayoutParams layoutParams = button.getLayoutParams();

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

                   }
                }
            });
        }

    }

Body:
You could create an xml file in your drawable folder called something like btn_go.xml that looks like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- NOTE: order is important (the first matching state(s) is what is rendered) -->
    <item
        android:state_pressed="true"
        android:drawable="@drawable/go_pressed_big” />
    <item
        android:drawable="@drawable/go_normal_small” />
 </selector>

Then, in your view's layout.xml file, you'd reference your button's source like this:

<ImageButton
    android:id="@+id/button_go”
    android:layout_width=“wrap_contents”
    android:layout_height=“wrap_contents”
    android:src="@drawable/btn_go”/>

The go_pressed_big image would be slightly larger than the go_normal_small image, and, by specifying wrap_contents for the width and height, the button should adjust.