问:
display max and min number from user inputted numbers c++
```<code># include <iostream>
using std::endl;
using std::cout;
using std::cin;
int main()
{
    int numUserInt;         // Number of integers the user inputs
    int integers;
    int number;
    int maxNumber = 0;
    int minNumber = 0;

    // Get the number of integers
    cout << "How many integers would you like to enter?" << endl;
    cin  >> numUserInt;
    cout << "Please enter " << numUserInt << " integers." << endl;

    integers = 1;

    while (integers <= numUserInt)
    {
        cin >> number;

        if (numUserInt == 1)
            maxNumber = minNumber = number;

        if (number > maxNumber)
            maxNumber = number;

        if (number < minNumber)
            minNumber = number;

        integers++;
    }

    cout << "min: " << minNumber << endl;
    cout << "max: " << maxNumber << endl;
    return 0;
}
</code>```

For a homework assignment I am supposed to ask a user "How many integers they would like to enter" and then find the Max and min number from the amount without using arrays. For the most part my program works, however when the user let's say enters -6 -6 the output is min: -6 and max: 0. I want this to say the min and max is -6 but I have no idea how to do this with making the rest of the code work. Anybody out there know of a way to do this?

答:
Your code works exactly as intended, if you replace

if (numUserInt == 1)

by

if (integers == 1).

That way, the recommendation from comment and other answers,

to init min and max with first input,

is implemented.

Output:

```<code>How many integers would you like to enter?
2
Please enter 2 integers.
-6
-6
min: -6
max: -6
</code>```

Body:
# include <iostream>
using std::endl;
using std::cout;
using std::cin;
int main()
{
    int numUserInt;         // Number of integers the user inputs
    int integers;
    int number;
    int maxNumber = 0;
    int minNumber = 0;

    // Get the number of integers
    cout << "How many integers would you like to enter?" << endl;
    cin  >> numUserInt;
    cout << "Please enter " << numUserInt << " integers." << endl;

    integers = 1;

    while (integers <= numUserInt)
    {
        cin >> number;

        if (numUserInt == 1)
            maxNumber = minNumber = number;

        if (number > maxNumber)
            maxNumber = number;

        if (number < minNumber)
            minNumber = number;

        integers++;
    }

    cout << "min: " << minNumber << endl;
    cout << "max: " << maxNumber << endl;
    return 0;
}

For a homework assignment I am supposed to ask a user "How many integers they would like to enter" and then find the Max and min number from the amount without using arrays. For the most part my program works, however when the user let's say enters -6 -6 the output is min: -6 and max: 0. I want this to say the min and max is -6 but I have no idea how to do this with making the rest of the code work. Anybody out there know of a way to do this?

Body:
Your code works exactly as intended, if you replace

if (numUserInt == 1)

by

if (integers == 1).

That way, the recommendation from comment and other answers,

to init min and max with first input,

is implemented.

Output:

How many integers would you like to enter?
2
Please enter 2 integers.
-6
-6
min: -6
max: -6


来源: stackexchange

问:
creating a grouping ID based on values in another column
Trying to figure out how to do this in Oracle PL/SQL.

I want to create values in a column that would group records based on when a certain value appears in another column.  For example, based on the values in the first column in this image, I want to create the values in the 'Group' column.  The value of 'red' is always the first value in a group of records.  Any subsequent color value other than 'red' belongs to the same group.  The next 'red' value means a new 'group' value needs to be created.

Any ideas on how to create the values in the 'Group' column?  Thanks in advance.

答:
You can use a ROWS BETWEEN Clause to get the sum of "red" color till the current ROW               </p>

```<code>          SELECT a.color,
             SUM(DECODE(color,'red',1,0) ) OVER ( ORDER BY ROWNUM
                 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) rn
           FROM colors a;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can use a ROWS BETWEEN Clause to get the sum of "red" color till the current ROW

          SELECT a.color,
             SUM(DECODE(color,'red',1,0) ) OVER ( ORDER BY ROWNUM
                 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) rn
           FROM colors a;


问:
Weird behaviour of Kbhit and getchar
Consider this block of C++ code.

```<code>    if(_kbhit()){
        //printf("Enter\n");
        c = getchar();
        int d = c;
        printf("%d", d);
        //printf("Exit \n");
    }
</code>```

The output I get is

```<code>sd115d100s100
</code>```

If I press s, d and then d, s. Weird thing is that when I pressed some character, the ascii of previously pressed character was displayed.

Now consider,

```<code>    if(_kbhit()){
        printf("Enter\n");
        c = getchar();
        int d = c;
        printf("%d", d);
        printf("Exit \n");
    }
</code>```

The output I got this time is

```<code>aEnter
97
Exit
dEnter
100
Exit
dEnter
100
Exit
aEnter
97
Exit
</code>```

Now everything is correct the ascii code of correct character is being displayed after I pressed a character.

Why this anomaly ? How can I correct this anomaly ?

答:
As mentioned in the comments, it's hard to say for sure without seeing the entire function, but I suspect the additional printf statements are flushing the output buffer for you, since they contain newline characters. Change

printf("%d", d);

to

printf("%d\n", d);

and see if that doesn't have the result you want.

Title: Weird behaviour of Kbhit and getchar

Body:
Consider this block of C++ code.

    if(_kbhit()){
        //printf("Enter\n");
        c = getchar();
        int d = c;
        printf("%d", d);
        //printf("Exit \n");
    }

The output I get is

sd115d100s100

If I press s, d and then d, s. Weird thing is that when I pressed some character, the ascii of previously pressed character was displayed.

Now consider,

    if(_kbhit()){
        printf("Enter\n");
        c = getchar();
        int d = c;
        printf("%d", d);
        printf("Exit \n");
    }

The output I got this time is

aEnter
97
Exit
dEnter
100
Exit
dEnter
100
Exit
aEnter
97
Exit

Now everything is correct the ascii code of correct character is being displayed after I pressed a character.

Why this anomaly ? How can I correct this anomaly ?


问:
Hovering effect over image link is overextending the div it is surrounded in
So for some reason when I hover over specific points below an image link I have that is wrapped in a div, it will trigger the hovering effect for the image link that I have created through CSS. I have tried multiple things (overflow:hidden, display:inline-block) but nothing seems to work. I will post my code and a jsfiddle link. Thanks in advance.

HTML:

```<code><div class="div_for_projects">
 <div class="project_inner_divs">
  <div id="portfolio_project">
    <div id="portfolio_project_child">
      <a href="index.html">
        <!--
        Image Source:
        http://www.connectwithchildlife.com/2015/10/child-life-portfolio.html
        -->
        <img class="portfolio_page_projects"
        src="http://www.vandelaydesign.com/wp-content/uploads/portfolio2.jpg"
        alt="portfolio_image">
      </a>
      <p>
        <a href="index.html"
        class="text_align project_description">
          PROJECT
        </a>
      </p>
      <a href="#">
        <img class="portfolio_sm_links"
        src="https://maxcdn.icons8.com/Share/icon/Editing//arrow_filled1600.png"
        alt="Portfolio Image Link">
      </a>
   </div>
  </div>
 </div>
</div>
</code>```

CSS:

```<code>.div_for_projects {
  width: 100%;
  height: 420px;
}
.project_inner_divs {
  float: left;
  width: 35%;
}
#portfolio_project {
  position: relative;
  width: 426px;
  height: 420px;
  pointer-events: none;
  transition-duration: 0.4s;
}
#portfolio_project_child {
  pointer-events: auto;
  width: 100%;
  height: 100%;
}
#portfolio_project:hover {
  -webkit-filter: brightness(70%);
}
#portfolio_project:hover .project_description {
  visibility: visible;
  opacity: 1;
}
#portfolio_project:hover .portfolio_sm_links {
  visibility: visible;
  opacity: 1;
}
.portfolio_page_projects {
  width: 426px;
  height: 420px;
}
.project_description {
  position: relative;
  bottom: 250px;
  visibility: hidden;
  opacity: 0;
  transition-duration: 0.4s;
  font-size: 18px;
  font-family: Tahoma, Geneva, sans-serif;
  color: rgb(50, 50, 50);
  display: inline-block;
  left: 170px;
 }
.text_align {
  text-align: center;
}
.portfolio_sm_links {
  width: 40px;
  height: 40px;
  position: relative;
  bottom: 130px;
  left: 350px;
  visibility: hidden;
  display: inline-block;
  opacity: 0;
}
.portfolio_sm_links:hover {
  background-color: grey;
}
</code>```

jsfiddle link: https://jsfiddle.net/26vutwz9/

答:
The nested
 is part of the div you are checking for the hover so its size is included. If you can move the
 outside of the
 or its parent it will solve the problem (but introduce others).

```<code><div class="div_for_projects">
 <div class="project_inner_divs">
  <div id="portfolio_project">
    <div id="portfolio_project_child">
      <a href="index.html">
        <!--
        Image Source:
        http://www.connectwithchildlife.com/2015/10/child-life-portfolio.html
        -->
        <img class="portfolio_page_projects"
        src="http://www.vandelaydesign.com/wp-content/uploads/portfolio2.jpg"
        alt="portfolio_image">
      </a>
      <a href="#">
        <img class="portfolio_sm_links"
        src="https://maxcdn.icons8.com/Share/icon/Editing//arrow_filled1600.png"
        alt="Portfolio Image Link">
      </a>
   </div>
   <p>
     <a href="index.html"
      class="text_align project_description">
      PROJECT
     </a>
   </p>
  </div>
 </div>
</div>
</code>```

https://jsfiddle.net/26vutwz9/1/

Body:
So for some reason when I hover over specific points below an image link I have that is wrapped in a div, it will trigger the hovering effect for the image link that I have created through CSS. I have tried multiple things (overflow:hidden, display:inline-block) but nothing seems to work. I will post my code and a jsfiddle link. Thanks in advance.

HTML:

          PROJECT

CSS:

.div_for_projects {
  width: 100%;
  height: 420px;
}
.project_inner_divs {
  float: left;
  width: 35%;
}
#portfolio_project {
  position: relative;
  width: 426px;
  height: 420px;
  pointer-events: none;
  transition-duration: 0.4s;
}
#portfolio_project_child {
  pointer-events: auto;
  width: 100%;
  height: 100%;
}
#portfolio_project:hover {
  -webkit-filter: brightness(70%);
}
#portfolio_project:hover .project_description {
  visibility: visible;
  opacity: 1;
}
#portfolio_project:hover .portfolio_sm_links {
  visibility: visible;
  opacity: 1;
}
.portfolio_page_projects {
  width: 426px;
  height: 420px;
}
.project_description {
  position: relative;
  bottom: 250px;
  visibility: hidden;
  opacity: 0;
  transition-duration: 0.4s;
  font-size: 18px;
  font-family: Tahoma, Geneva, sans-serif;
  color: rgb(50, 50, 50);
  display: inline-block;
  left: 170px;
 }
.text_align {
  text-align: center;
}
.portfolio_sm_links {
  width: 40px;
  height: 40px;
  position: relative;
  bottom: 130px;
  left: 350px;
  visibility: hidden;
  display: inline-block;
  opacity: 0;
}
.portfolio_sm_links:hover {
  background-color: grey;
}

jsfiddle link: https://jsfiddle.net/26vutwz9/

Body:
The nested <p> is part of the div you are checking for the hover so its size is included. If you can move the <p> outside of the <div id="portfolio_project_child"> or its parent it will solve the problem (but introduce others).

<div class="div_for_projects">
 <div class="project_inner_divs">
  <div id="portfolio_project">
    <div id="portfolio_project_child">
      <a href="index.html">
        <!--
        Image Source:
        http://www.connectwithchildlife.com/2015/10/child-life-portfolio.html
        -->
        <img class="portfolio_page_projects"
        src="http://www.vandelaydesign.com/wp-content/uploads/portfolio2.jpg"
        alt="portfolio_image">
      </a>
      <a href="#">
        <img class="portfolio_sm_links"
        src="https://maxcdn.icons8.com/Share/icon/Editing//arrow_filled1600.png"
        alt="Portfolio Image Link">
      </a>
   </div>
   <p>
     <a href="index.html"
      class="text_align project_description">
      PROJECT
     </a>
   </p>
  </div>
 </div>
</div>

https://jsfiddle.net/26vutwz9/1/


问:
Ruby on Rails Oracle DB connection
My main database is a local mysql database, however I would like to occasionally connect to an Oracle database directly in my applications code.

The oracle database is hosted on another RHEL server.

I was unsuccessfull tried to install the ruby-OCI8 gem (ERROR: Failed to build gem native extension.)

I am wondering whether the oracle database has to be local in order to use this gem, or if there are any better ways of achieving this.

```<code>gem install ruby-oci8

Building native extensions.  This could take a while...
ERROR:  Error installing ruby-oci8:
        ERROR: Failed to build gem native extension.

/usr/bin/ruby extconf.rb
checking for load library path...
  LD_LIBRARY_PATH...
    checking /opt/instantclient... yes
  /opt/instantclient/libclntsh.so.11.1 looks like an instant client.
checking for cc... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
        --with-opt-dir
        --without-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=/usr/bin/ruby
        --with-instant-client
        --without-instant-client
./oraconf.rb:562:in `check_cc': RuntimeError (RuntimeError)
        from ./oraconf.rb:549:in `init'
        from ./oraconf.rb:1001:in `initialize'
        from ./oraconf.rb:343:in `new'
        from ./oraconf.rb:343:in `get'
        from extconf.rb:18
ng
---------------------------------------------------
Error Message:
  C compiler doesn't work correctly.
Backtrace:
  ./oraconf.rb:562:in `check_cc'
  ./oraconf.rb:549:in `init'
  ./oraconf.rb:1001:in `initialize'
  ./oraconf.rb:343:in `new'
  ./oraconf.rb:343:in `get'
  extconf.rb:18
---------------------------------------------------
See:
 * http://ruby-oci8.rubyforge.org/en/HowToInstall.html
 * http://ruby-oci8.rubyforge.org/en/ReportInstallProblem.html
</code>```

I checked the mkmf.log file:

```<code> "gcc -o conftest -I. -I/usr/lib64/ruby/1.8/x86_64-linux -I.   -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fs    tack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -fno-strict-aliasing  -fPIC conftest.c  -L. -L/usr/lib64 -L.      -rdynamic -Wl,-export-dynamic     -lruby-static  -lpthread -lrt -ldl -lcrypt -lm   -lc"
  /usr/bin/ld: skipping incompatible /usr/lib/libruby-static.a when searching for -lruby-static
  /usr/bin/ld: cannot find -lruby-static
  collect2: ld returned 1 exit status
  checked program was:
  /* begin */
  1: int main() { return 0; }
  8 /* end */
</code>```

答:
At first you need to install Oracle Instant Client - choose corresponding Linux 32-bit or 64-bit binaries. To be safe use older version 10.2.0.4 which I use in all my Ruby and Oracle projects. Install Basic, SDK and SQL*Plus packages.

Then include Oracle Instant Client installation directory in LD_LIBRARY_PATH environment variable so that Oracle Instant Client dynamic libraries would be in load path.

Then try to install ruby-oci8 gem.

Afterwards install activerecord-oracle_enhanced-adapter gem to be able to access Oracle database from ActiveRecord.

I have posted instructions how to install ruby-oci8 on Mac OS X - majority of this applies to Linux as well (DYLD_LIBRARY_PATH on Mac corresponds to LD_LIBRARY_PATH on Linux).

In addition I have created Sprinkle recipe for automated Oracle client installation on Linux - probably it is not the best way to start with this but in case you want to build automated server installation scripts then you can take a look on it.

ContentLicense: CC BY-SA 2.5

Title: Ruby on Rails Oracle DB connection

Body:
My main database is a local mysql database, however I would like to occasionally connect to an Oracle database directly in my applications code.

The oracle database is hosted on another RHEL server.

I was unsuccessfull tried to install the ruby-OCI8 gem (ERROR: Failed to build gem native extension.)

I am wondering whether the oracle database has to be local in order to use this gem, or if there are any better ways of achieving this.

gem install ruby-oci8

Building native extensions.  This could take a while...
ERROR:  Error installing ruby-oci8:
        ERROR: Failed to build gem native extension.

/usr/bin/ruby extconf.rb
checking for load library path...
  LD_LIBRARY_PATH...
    checking /opt/instantclient... yes
  /opt/instantclient/libclntsh.so.11.1 looks like an instant client.
checking for cc... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
        --with-opt-dir
        --without-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=/usr/bin/ruby
        --with-instant-client
        --without-instant-client
./oraconf.rb:562:in `check_cc': RuntimeError (RuntimeError)
        from ./oraconf.rb:549:in `init'
        from ./oraconf.rb:1001:in `initialize'
        from ./oraconf.rb:343:in `new'
        from ./oraconf.rb:343:in `get'
        from extconf.rb:18
ng
---------------------------------------------------
Error Message:
  C compiler doesn't work correctly.
Backtrace:
  ./oraconf.rb:562:in `check_cc'
  ./oraconf.rb:549:in `init'
  ./oraconf.rb:1001:in `initialize'
  ./oraconf.rb:343:in `new'
  ./oraconf.rb:343:in `get'
  extconf.rb:18
---------------------------------------------------
See:
 * http://ruby-oci8.rubyforge.org/en/HowToInstall.html
 * http://ruby-oci8.rubyforge.org/en/ReportInstallProblem.html

I checked the mkmf.log file:

 "gcc -o conftest -I. -I/usr/lib64/ruby/1.8/x86_64-linux -I.   -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fs    tack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -fno-strict-aliasing  -fPIC conftest.c  -L. -L/usr/lib64 -L.      -rdynamic -Wl,-export-dynamic     -lruby-static  -lpthread -lrt -ldl -lcrypt -lm   -lc"
  /usr/bin/ld: skipping incompatible /usr/lib/libruby-static.a when searching for -lruby-static
  /usr/bin/ld: cannot find -lruby-static
  collect2: ld returned 1 exit status
  checked program was:
  /* begin */
  1: int main() { return 0; }
  8 /* end */


问:
seleniumerror while executing below code
I little help here will be appreciated.I am simply trying to open a site using selenium and here is the code. Getting java.lang.IllegalStateException error.</p>

```<code>   package pkg1;

   import org.openqa.selenium.WebDriver;
   import org.openqa.selenium.chrome.ChromeDriver;
   //import org.openqa.selenium.firefox.FirefoxDriver;

   public class training1 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
   System.setProperty("webdriver.chrome.driver","D:\\SeleniumTools\\chromedriver\\chromedriver.exe");
        System.out.println("Welcome to Selenium");
        driver.get("https://in.yahoo.com/");

    }

}

----- Error -----
Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://chromedriver.storage.googleapis.com/index.html
    at com.google.common.base.Preconditions.checkState(Preconditions.java:738)
    at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:124)
    at org.openqa.selenium.chrome.ChromeDriverService.access$000(ChromeDriverService.java:32)
    at org.openqa.selenium.chrome.ChromeDriverService$Builder.findDefaultExecutable(ChromeDriverService.java:137)
    at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:330)
    at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:88)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:124)
    at pkg1.training1.main(training1.java:14)
</code>```

答:
You must set path of the chromedriver.exe before calling new ChromeDriver()

```<code>public static void main(String[] args) {
    System.setProperty("webdriver.chrome.driver","D:\\SeleniumTools\\chromedriver\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    System.out.println("Welcome to Selenium");
    driver.get("https://in.yahoo.com/");
}
</code>```

Body:
I little help here will be appreciated.I am simply trying to open a site using selenium and here is the code. Getting java.lang.IllegalStateException error.

   package pkg1;

   import org.openqa.selenium.WebDriver;
   import org.openqa.selenium.chrome.ChromeDriver;
   //import org.openqa.selenium.firefox.FirefoxDriver;

   public class training1 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
   System.setProperty("webdriver.chrome.driver","D:\\SeleniumTools\\chromedriver\\chromedriver.exe");
        System.out.println("Welcome to Selenium");
        driver.get("https://in.yahoo.com/");

    }

}

----- Error -----
Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://chromedriver.storage.googleapis.com/index.html
    at com.google.common.base.Preconditions.checkState(Preconditions.java:738)
    at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:124)
    at org.openqa.selenium.chrome.ChromeDriverService.access$000(ChromeDriverService.java:32)
    at org.openqa.selenium.chrome.ChromeDriverService$Builder.findDefaultExecutable(ChromeDriverService.java:137)
    at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:330)
    at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:88)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:124)
    at pkg1.training1.main(training1.java:14)

Body:
You must set path of the chromedriver.exe before calling new ChromeDriver()

public static void main(String[] args) {
    System.setProperty("webdriver.chrome.driver","D:\\SeleniumTools\\chromedriver\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    System.out.println("Welcome to Selenium");
    driver.get("https://in.yahoo.com/");
}


问:
Filter out existing objects in an array of objects
I don't think this is difficult, I just can't figure out the best way to do it. This function is creating an array, from a group of checkboxes. I then want to break up the array and create an array of objects, because each object can have corresponding data. How do I filter out existing rolesInterestedIn.roleType.

```<code>handleTypeOfWorkSelection(event) {
    const newSelection = event.target.value;
    let newSelectionArray;

    if(this.state.typeOfWork.indexOf(newSelection) > -1) {
      newSelectionArray = this.state.typeOfWork.filter(s => s !== newSelection)
    } else {
      newSelectionArray = [...this.state.typeOfWork, newSelection];
    }
    this.setState({ typeOfWork: newSelectionArray }, function() {
      this.state.typeOfWork.map((type) => {
        this.setState({
          rolesInterestedIn: this.state.rolesInterestedIn.concat([
            {
              roleType: type,
            }
          ])
        }, function() {
          console.log(this.state.rolesInterestedIn);
        });
      })
    });
  }
</code>```

UDPATE

```<code>rolesInterestedIn: [
  {
    roleType: '',
    experienceYears: ''
  }
],
</code>```

答:
Because each time you do setState you are concatenating the new value to the prev one in rolesInterestedIn array. Add new value only when you are adding new item, otherwise remove the object from both the state variable typeOfWork and rolesInterestedIn.

Try this:

```<code>handleTypeOfWorkSelection(event) {
    const newSelection = event.target.value;
    let newSelectionArray, rolesInterestedIn = this.state.rolesInterestedIn.slice(0);

    if(this.state.typeOfWork.indexOf(newSelection) > -1) {
        newSelectionArray = this.state.typeOfWork.filter(s => s !== newSelection);
        rolesInterestedIn = rolesInterestedIn.filter(s => s.roleType !== newSelection)
    } else {
        newSelectionArray = [...this.state.typeOfWork, newSelection];
        rolesInterestedIn = newSelectionArray.map((workType) => {
            return {
                roleType: workType,
                experienceYears: '',
            }
        });
    }
    this.setState({
         typeOfWork: newSelectionArray,
         rolesInterestedIn: rolesInterestedIn
    });
}
</code>```

Suggestion: Don't use multiple setState within a function, do all the calculation then use setState once to update all the values in the last.

Body:
I don't think this is difficult, I just can't figure out the best way to do it. This function is creating an array, from a group of checkboxes. I then want to break up the array and create an array of objects, because each object can have corresponding data. How do I filter out existing rolesInterestedIn.roleType.

handleTypeOfWorkSelection(event) {
    const newSelection = event.target.value;
    let newSelectionArray;

    if(this.state.typeOfWork.indexOf(newSelection) > -1) {
      newSelectionArray = this.state.typeOfWork.filter(s => s !== newSelection)
    } else {
      newSelectionArray = [...this.state.typeOfWork, newSelection];
    }
    this.setState({ typeOfWork: newSelectionArray }, function() {
      this.state.typeOfWork.map((type) => {
        this.setState({
          rolesInterestedIn: this.state.rolesInterestedIn.concat([
            {
              roleType: type,
            }
          ])
        }, function() {
          console.log(this.state.rolesInterestedIn);
        });
      })
    });
  }

UDPATE

rolesInterestedIn: [
  {
    roleType: '',
    experienceYears: ''
  }
],

Body:
Because each time you do setState you are concatenating the new value to the prev one in rolesInterestedIn array. Add new value only when you are adding new item, otherwise remove the object from both the state variable typeOfWork and rolesInterestedIn.

Try this:

handleTypeOfWorkSelection(event) {
    const newSelection = event.target.value;
    let newSelectionArray, rolesInterestedIn = this.state.rolesInterestedIn.slice(0);

    if(this.state.typeOfWork.indexOf(newSelection) > -1) {
        newSelectionArray = this.state.typeOfWork.filter(s => s !== newSelection);
        rolesInterestedIn = rolesInterestedIn.filter(s => s.roleType !== newSelection)
    } else {
        newSelectionArray = [...this.state.typeOfWork, newSelection];
        rolesInterestedIn = newSelectionArray.map((workType) => {
            return {
                roleType: workType,
                experienceYears: '',
            }
        });
    }
    this.setState({
         typeOfWork: newSelectionArray,
         rolesInterestedIn: rolesInterestedIn
    });
}

Suggestion: Don't use multiple setState within a function, do all the calculation then use setState once to update all the values in the last.


问:
Single Linked List is Palindrome or not
I have a Single Linked List. I want to find that Linked List is Palindrome or not.
I have implemented it in One way as below.

bool palindromeOrNot(node *head) {
  node *tailPointer;
  node *headLocal=head;
  node *reverseList=reverseLinkedListIteratively(head);
  int response=1;

  while(headLocal != NULL && reverseList!=NULL) {
    if(headLocal->id==reverseList->id) {
      headLocal=headLocal->next;
      reverseList=reverseList->next;
    }
    else
      return false;
  }

  if(headLocal == NULL && reverseList==NULL)
    return fasle;
  else
    return true;
}
```

I am reversing the original Linked List and then comparing Node by Node. If everything is fine
then I will return 1 else return 0.

Is there a better algorithm to solve the problem.

答:
the python program to check the input linked list is palindrome or not</p>

```<code>class Node:
   def __init__(self, val):
     self.data=val
     self.next=None

def rec_palindrome(slow, fast):
  if fast == None:
      # Even number of nodes
      return 0, slow
  elif fast.next == None:
      return -1, slow
   else:
      res, ptr = rec_palindrome(slow.next, fast.next.next)
      if res == -1:
         tmp = ptr.next
         if tmp.data != slow.data:
             return 1, None
         else:
             return 0, tmp.next
      elif res == 1:
         return 1, None
      elif res == 0:
         if ptr.data != slow.data:
            return 1, None
         else:
            return 0, ptr.next
      else:
         return res, None

 class LinkedList:
   def __init__(self):
     self.head = None

   def append(self, node):
     if self.head == None:
         self.head = node
     else:
         cur = self.head
         while cur.next != None:
             cur = cur.next
         cur.next = node

   def display(self, msg):
     print(msg)
     cur = self.head
     while cur != None:
         print("%d" %cur.data, end="")
         if cur.next != None:
             print("->", end="")
         else:
             print("")
         cur = cur.next

   def is_palindrome(self):
     res, ptr = rec_palindrome(self.head, self.head)
     if res :
         print("The input list is NOT palindrome")
     else:
         print("The input list is palindrome")

if __name__ == "__main__":
  print("Pyhton program to check if the input list is palindrome or not")
  N = int(input("How many elements?"))
  llist = LinkedList()
  for i in range(N):
     val = int(input("Enter the element of node %d" %(i+1)))
     llist.append(Node(val))
  llist.display("Input Linked List")
  llist.is_palindrome()

example output:
pyhton program to check if the input list is palindrome or not
How many elements?7
Enter the element of node 112
Enter the element of node 245
Enter the element of node 389
Enter the element of node 47
Enter the element of node 589
Enter the element of node 645
Enter the element of node 712
Input Linked List
     12->45->89->7->89->45->12
The input list is palindrome
</code>```

Title: Single Linked List is Palindrome or not

Body:
I have a Single Linked List. I want to find that Linked List is Palindrome or not.
I have implemented it in One way as below.

bool palindromeOrNot(node *head) {
  node *tailPointer;
  node *headLocal=head;
  node *reverseList=reverseLinkedListIteratively(head);
  int response=1;

  while(headLocal != NULL && reverseList!=NULL) {
    if(headLocal->id==reverseList->id) {
      headLocal=headLocal->next;
      reverseList=reverseList->next;
    }
    else
      return false;
  }

  if(headLocal == NULL && reverseList==NULL)
    return fasle;
  else
    return true;
}

I am reversing the original Linked List and then comparing Node by Node. If everything is fine
then I will return 1 else return 0.

Is there a better algorithm to solve the problem.

Body:
the python program to check the input linked list is palindrome or not

class Node:
   def __init__(self, val):
     self.data=val
     self.next=None

def rec_palindrome(slow, fast):
  if fast == None:
      # Even number of nodes
      return 0, slow
  elif fast.next == None:
      return -1, slow
   else:
      res, ptr = rec_palindrome(slow.next, fast.next.next)
      if res == -1:
         tmp = ptr.next
         if tmp.data != slow.data:
             return 1, None
         else:
             return 0, tmp.next
      elif res == 1:
         return 1, None
      elif res == 0:
         if ptr.data != slow.data:
            return 1, None
         else:
            return 0, ptr.next
      else:
         return res, None

 class LinkedList:
   def __init__(self):
     self.head = None

   def append(self, node):
     if self.head == None:
         self.head = node
     else:
         cur = self.head
         while cur.next != None:
             cur = cur.next
         cur.next = node

   def display(self, msg):
     print(msg)
     cur = self.head
     while cur != None:
         print("%d" %cur.data, end="")
         if cur.next != None:
             print("->", end="")
         else:
             print("")
         cur = cur.next

   def is_palindrome(self):
     res, ptr = rec_palindrome(self.head, self.head)
     if res :
         print("The input list is NOT palindrome")
     else:
         print("The input list is palindrome")

if __name__ == "__main__":
  print("Pyhton program to check if the input list is palindrome or not")
  N = int(input("How many elements?"))
  llist = LinkedList()
  for i in range(N):
     val = int(input("Enter the element of node %d" %(i+1)))
     llist.append(Node(val))
  llist.display("Input Linked List")
  llist.is_palindrome()

example output:
pyhton program to check if the input list is palindrome or not
How many elements?7
Enter the element of node 112
Enter the element of node 245
Enter the element of node 389
Enter the element of node 47
Enter the element of node 589
Enter the element of node 645
Enter the element of node 712
Input Linked List
     12->45->89->7->89->45->12
The input list is palindrome


问:
Java - Sorting a 2D Array by Row Sum
Trying to write a method that swaps the rows of a 2D array in order of increasing row sum.

For example, if I have the following 2d array:

```<code>int [][] array = {4,5,6},{3,4,5},{2,3,4};
</code>```

I would want it to output an array as so:

```<code>{2 3 4}, {3 4 5}, {4 5 6}
</code>```

Methodology:

a.) take the sums of each row and make a 1D array of the sums

b.) do a bubble sort on rowSum array

c.) swap the rows of the original array based on the bubble sort swaps made

d.) then print the newly row sorted array.

Here's my code so far:

```<code>      public void sortedArrayByRowTot() {
        int [][] tempArray2 = new int [salaryArray.length [salaryArray[0].length];

        for (int i = 0; i < tempArray2.length; i++) {
          for (int j = 0; j < tempArray2[i].length; j++) {
            tempArray2[i][j] = salaryArray[i][j];
          }
        }

        int [] rowSums = new int [tempArray2.length];
        int sum = 0;
        for (int i = 0; i < tempArray2.length; i++) {
          for (int j = 0; j < tempArray2[i].length; j++) {
            sum += tempArray2[i][j];
          }
          rowSums[i] = sum;
          sum = 0;
        }

        int temp;
        int i = -1;
        for(int j = rowSums.length; j > 0; j--){
          boolean isSwap = false;
          for (i = 1; i < j; i++) {
            if(rowSums[i-1] > rowSums[i]) {
              temp = rowSums[i-1];
              rowSums[i-1] = rowSums[i];
              rowSums[i] = temp;
              isSwap = true;
            }
          }

          if(!isSwap){
            break;
          }
        }

        for (int k = 0; k < tempArray2.length; k++) {
          temp = tempArray2[i-1][k];
          tempArray2[i-1][k] = tempArray2[i][k];
          tempArray2[i][k] = temp;
        }

        for (int b = 0; b < tempArray2.length; b++) {
          for (int c = 0; c < tempArray2[b].length; c++) {
            System.out.print(tempArray2[b][c] + " ");
          }
        }
      }
    }
</code>```

Not sure if I am doing part c of my methodology correctly?

It keeps saying "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2"

答:
As @shmosel said, you can do it like this:</p>

```<code>public static void sortedArrayByRowTot() {
    int [][] array = {{4,5,6},{3,4,5},{2,3,4}};
    Arrays.sort(array, Comparator.comparingInt(a -> IntStream.of(a).sum()));
}
</code>```

Title: Java - Sorting a 2D Array by Row Sum

Body:
Trying to write a method that swaps the rows of a 2D array in order of increasing row sum.

For example, if I have the following 2d array:

int [][] array = {4,5,6},{3,4,5},{2,3,4};

I would want it to output an array as so:

{2 3 4}, {3 4 5}, {4 5 6}

Methodology:

a.) take the sums of each row and make a 1D array of the sums

b.) do a bubble sort on rowSum array

c.) swap the rows of the original array based on the bubble sort swaps made

d.) then print the newly row sorted array.

Here's my code so far:

      public void sortedArrayByRowTot() {
        int [][] tempArray2 = new int [salaryArray.length [salaryArray[0].length];

        for (int i = 0; i < tempArray2.length; i++) {
          for (int j = 0; j < tempArray2[i].length; j++) {
            tempArray2[i][j] = salaryArray[i][j];
          }
        }

        int [] rowSums = new int [tempArray2.length];
        int sum = 0;
        for (int i = 0; i < tempArray2.length; i++) {
          for (int j = 0; j < tempArray2[i].length; j++) {
            sum += tempArray2[i][j];
          }
          rowSums[i] = sum;
          sum = 0;
        }

        int temp;
        int i = -1;
        for(int j = rowSums.length; j > 0; j--){
          boolean isSwap = false;
          for (i = 1; i < j; i++) {
            if(rowSums[i-1] > rowSums[i]) {
              temp = rowSums[i-1];
              rowSums[i-1] = rowSums[i];
              rowSums[i] = temp;
              isSwap = true;
            }
          }

          if(!isSwap){
            break;
          }
        }

        for (int k = 0; k < tempArray2.length; k++) {
          temp = tempArray2[i-1][k];
          tempArray2[i-1][k] = tempArray2[i][k];
          tempArray2[i][k] = temp;
        }

        for (int b = 0; b < tempArray2.length; b++) {
          for (int c = 0; c < tempArray2[b].length; c++) {
            System.out.print(tempArray2[b][c] + " ");
          }
        }
      }
    }

Not sure if I am doing part c of my methodology correctly?

It keeps saying "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2"

Body:
As @shmosel said, you can do it like this:

public static void sortedArrayByRowTot() {
    int [][] array = {{4,5,6},{3,4,5},{2,3,4}};
    Arrays.sort(array, Comparator.comparingInt(a -> IntStream.of(a).sum()));
}


问:
How to design a progress bar logic when inputs are less than 10?
I am parsing strings from an array and showing progress as the strings are parsed. This is my logic but it doesn't scale for inputs less than 10.

Divide by zero is already taken care of during the initial part of the function for 100*i/(lineLen-1)

```<code>progress := 0
for i:= 0; i<lineLen;i++ {
 //.. lineLen = array length
//.....String processing...
if (100*i/(lineLen-1)) >= progress {
     fmt.Printf("--%d%s--", progress, "%")
     progress += 10
}
}
</code>```

答:
Have a look at https://play.golang.org/p/xtRtk1T_ZW (code reproduced below):

```<code>func main() {
    // outputMax is the number of progress items to print, excluding the 100% completion item.
    // There will always be at least 2 items output: 0% and 100%.
    outputMax := 10

    for lineLen := 1; lineLen < 200; lineLen++ {
        fmt.Printf("lineLen=%-3d    ", lineLen)
        printProgress(lineLen, outputMax)
    }
}

// Calculate the current progress.
func progress(current, max int) int {
    return 100 * current / max
}

// Calculate the number of items in a group.
func groupItems(total, limit int) int {
    v := total / limit
    if total%limit != 0 {
        v++
    }
    return v
}

// Print the progress bar.
func printProgress(lineLen, outputMax int) {
    itemsPerGroup := groupItems(lineLen, outputMax)
    for i := 0; i < lineLen; i++ {
        if i%itemsPerGroup == 0 {
            fmt.Printf("--%d%%--", progress(i, lineLen))
        }
    }
    fmt.Println("--100%--")
}
</code>```

If you want, you can execute a loop over various values of outputMax and lineLen using https://play.golang.org/p/aR6coeLhAk to see which value for outputMax you like (8 <= outputMax < 13 looks best to me).  Output of the progress bar is disabled by default, but you can easily enable it in main.

Body:
I am parsing strings from an array and showing progress as the strings are parsed. This is my logic but it doesn't scale for inputs less than 10.

Divide by zero is already taken care of during the initial part of the function for 100*i/(lineLen-1)

progress := 0
for i:= 0; i<lineLen;i++ {
 //.. lineLen = array length
//.....String processing...
if (100*i/(lineLen-1)) >= progress {
     fmt.Printf("--%d%s--", progress, "%")
     progress += 10
}
}

Body:
Have a look at https://play.golang.org/p/xtRtk1T_ZW (code reproduced below):

func main() {
    // outputMax is the number of progress items to print, excluding the 100% completion item.
    // There will always be at least 2 items output: 0% and 100%.
    outputMax := 10

    for lineLen := 1; lineLen < 200; lineLen++ {
        fmt.Printf("lineLen=%-3d    ", lineLen)
        printProgress(lineLen, outputMax)
    }
}

// Calculate the current progress.
func progress(current, max int) int {
    return 100 * current / max
}

// Calculate the number of items in a group.
func groupItems(total, limit int) int {
    v := total / limit
    if total%limit != 0 {
        v++
    }
    return v
}

// Print the progress bar.
func printProgress(lineLen, outputMax int) {
    itemsPerGroup := groupItems(lineLen, outputMax)
    for i := 0; i < lineLen; i++ {
        if i%itemsPerGroup == 0 {
            fmt.Printf("--%d%%--", progress(i, lineLen))
        }
    }
    fmt.Println("--100%--")
}

If you want, you can execute a loop over various values of outputMax and lineLen using https://play.golang.org/p/aR6coeLhAk to see which value for outputMax you like (8 <= outputMax < 13 looks best to me).  Output of the progress bar is disabled by default, but you can easily enable it in main.


问:
Click link store variable pass to select on new page
I have links on a few pages which stores the name of a Room

```<code><a href="/booking/" class="book" data-book="Room One">
<a href="/booking/" class="book" data-book="Room Two">
</code>```

On clicking I want to store the data variable and pass the Room Name to a form on a new page and preselect the select option.

I have tried this:

```<code>$('.book').on('click', function(){
var roomSuiteLink = $(this).data('book');
});
</code>```

I want the value of 'roomSuiteLink' to be the selected select option. Ive been trying this with no luck:

```<code>function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
var roomSuite = getURLParameter('roomSuiteLink');
$('#my-select').val( roomSuite );
</code>```

Then on the new page I have a select menu:

```<code><select id="my-select" name="my-select">
<option value="Room One">Room One</option>
<option value="Room Two">Room Two</option>
</select>
</code>```

I dont want to add anything to the URL like this: /booking/?room name. Can I do this with jquery or do I need a session variable?

Thanks

答:
You need to set the selected property to true

```<code>$('#my-select [value="' + roomSuite + '"]').prop('selected', true)
</code>```

JSFiddle result

Body:
I have links on a few pages which stores the name of a Room

On clicking I want to store the data variable and pass the Room Name to a form on a new page and preselect the select option.

I have tried this:

$('.book').on('click', function(){
var roomSuiteLink = $(this).data('book');
});

I want the value of 'roomSuiteLink' to be the selected select option. Ive been trying this with no luck:

function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
var roomSuite = getURLParameter('roomSuiteLink');
$('#my-select').val( roomSuite );

Then on the new page I have a select menu:

<select id="my-select" name="my-select">
<option value="Room One">Room One</option>
<option value="Room Two">Room Two</option>
</select>

I dont want to add anything to the URL like this: /booking/?room name. Can I do this with jquery or do I need a session variable?

Thanks

Body:
You need to set the selected property to true

$('#my-select [value="' + roomSuite + '"]').prop('selected', true)

JSFiddle result


问:
angularjs2 cli, building chrome extension, troubles to defining content and background sripts
Say I've generated a new angularjs-2 app with cli,
so that with ng build it builds my sources to /dist folder.

Since I'm building chrome extension, in manifest.json, I have to define where is my content-script (that loads with page) and where is background script/ event page (that loads once).

So I have to define them in my manifest.json,

```<code>  "content_scripts": [
    {
      "matches": ["*"],
      "css": ["content-script.css"],
      "js": ["content-script.js"]
    }

    "background": {
       "scripts": ["eventPage.js"],
       "persistent": false
    },
</code>```

The trouble is that when I configure .angular-cli.json to define what should be placed into /dist folder by ng build I'm a bit puzzled what to put where.

There is a script section, where I can put my content-script

```<code>  "scripts": [
    "content-script.ts"
  ],
</code>```

then (whether it is one file or more) it will compile all in one dist/scripts.bundle.js

So then in my manifest.json I have to set:
 "content_scripts": [

```<code>{
  "matches": ["*"],
  "css": ["mystyles.css"],
  "js": ["scripts.bundle.js"]
}
</code>```

But.. as I said there is only one scripts.bundle.js. What should I do for background /event page then ? (I can not load background one when I need content and vise versa).

That all sounds to me like as if in order to build a plugin with angularjs 2, I actually need build application with 3 angulaj apps in it:

app for popup page (by click on ext icon)

app for content page

app for options page (by right click on ext icon)

(when I say app, I mean angularjs2 app)

CLI seems does not support it?
Are there any ways (others than not using CLI)?

答:
@Ses,I was trying to also use angular-cli and build a Chrome extension that would have a background JS. After hitting a few dead ends ejecting it was the final solution. Even though angular-cli seems to be a consolidation of a lot of things, ejecting the webpack config and having to type 'npm run ' as opposed to ng  is a small step.

Run

```<code>Ng eject
</code>```

Then in the new autogenerated webpack.config.js

```<code>  "entry": {
    ...
    "background": [
      "./src/background/background.ts"
    ],
    "content-scripts": [
      "./src/content-scripts.ts"
    ]
  },
...
// Added bonus, copy the manifest.json file as an asset
    new GlobCopyWebpackPlugin({
      "patterns": [
        "manifest.json",
        "assets",
        "favicon.ico"
      ],
</code>```

You can always revert the ejection by changing the ejected property in .angular-cli.json. Enjoy.

Body:
Say I've generated a new angularjs-2 app with cli,
so that with ng build it builds my sources to /dist folder.

Since I'm building chrome extension, in manifest.json, I have to define where is my content-script (that loads with page) and where is background script/ event page (that loads once).

So I have to define them in my manifest.json,

  "content_scripts": [
    {
      "matches": ["*"],
      "css": ["content-script.css"],
      "js": ["content-script.js"]
    }

    "background": {
       "scripts": ["eventPage.js"],
       "persistent": false
    },

The trouble is that when I configure .angular-cli.json to define what should be placed into /dist folder by ng build I'm a bit puzzled what to put where.

There is a script section, where I can put my content-script

  "scripts": [
    "content-script.ts"
  ],

then (whether it is one file or more) it will compile all in one dist/scripts.bundle.js

So then in my manifest.json I have to set:
 "content_scripts": [

{
  "matches": ["*"],
  "css": ["mystyles.css"],
  "js": ["scripts.bundle.js"]
}

But.. as I said there is only one scripts.bundle.js. What should I do for background /event page then ? (I can not load background one when I need content and vise versa).

That all sounds to me like as if in order to build a plugin with angularjs 2, I actually need build application with 3 angulaj apps in it:

app for popup page (by click on ext icon)

app for content page

app for options page (by right click on ext icon)

(when I say app, I mean angularjs2 app)

CLI seems does not support it?
Are there any ways (others than not using CLI)?

Body:
@Ses,I was trying to also use angular-cli and build a Chrome extension that would have a background JS. After hitting a few dead ends ejecting it was the final solution. Even though angular-cli seems to be a consolidation of a lot of things, ejecting the webpack config and having to type 'npm run ' as opposed to ng  is a small step.

Run

Ng eject

Then in the new autogenerated webpack.config.js

  "entry": {
    ...
    "background": [
      "./src/background/background.ts"
    ],
    "content-scripts": [
      "./src/content-scripts.ts"
    ]
  },
...
// Added bonus, copy the manifest.json file as an asset
    new GlobCopyWebpackPlugin({
      "patterns": [
        "manifest.json",
        "assets",
        "favicon.ico"
      ],

You can always revert the ejection by changing the ejected property in .angular-cli.json. Enjoy.


问:
I want only values of 1st index then 2nd and then 3rd index. How can I iterate through this with a loop and get the values dynamically?
I want the values from this array for each index. I tried to access the values using foreach but I can´t figure out how to get all values for each index (i.e. for 1st, 2nd, 3rd)</p>

```<code>Array
    (
        [1] => Array
            (
                [0] => 244
                [1] => 6014
                [2] => 5067
                [3] => 5059
                [4] => 1726
                [5] => 56
                [6] => 1234
                [7] => 56
            )

        [2] => Array
            (
                [0] => 122
                [1] => 123
                [2] => 56
                [3] => 246
                [4] => 7360
                [5] => 8058
                [6] => 1290
                [7] => 1234
                [8] => 5454
            )

        [3] => Array
            (
                [0] => 7890
                [1] => 5454
            )

    )
</code>```

答:
Follow this sample I made, if you still don't get it, leave a comment.

```<code>$array = array(
        array('abc','def','xyz'),
        array('asd','fun','bad'),
        array('blue','red','green')

 );

foreach($array as $key=>$value){
    foreach($value as $subkey=>$subvalue) {
        echo $subkey . " : " . $subvalue . "<br>";
    }
}
</code>```

If you want to get the currency pair key also, use this example:

```<code>$assoc_array = array(
        "eurusd" =>     array('abc','def','xyz'),
        "usdjpy" =>     array('good','bad','ugly'),
        "aususd" =>     array('blue','red','green')
</code>```

);

```<code>foreach($assoc_array as $key=>$value){
        echo $key . ":: <br>";
    foreach($value as $subkey=>$subvalue) {
        echo $subkey . " : " . $subvalue . "<br>";
    }
}
</code>```

I want to show result this way

Body:
I want the values from this array for each index. I tried to access the values using foreach but I can´t figure out how to get all values for each index (i.e. for 1st, 2nd, 3rd)

Array
    (
        [1] => Array
            (
                [0] => 244
                [1] => 6014
                [2] => 5067
                [3] => 5059
                [4] => 1726
                [5] => 56
                [6] => 1234
                [7] => 56
            )

        [2] => Array
            (
                [0] => 122
                [1] => 123
                [2] => 56
                [3] => 246
                [4] => 7360
                [5] => 8058
                [6] => 1290
                [7] => 1234
                [8] => 5454
            )

        [3] => Array
            (
                [0] => 7890
                [1] => 5454
            )

    )

Body:
Follow this sample I made, if you still don't get it, leave a comment.

$array = array(
        array('abc','def','xyz'),
        array('asd','fun','bad'),
        array('blue','red','green')

 );

foreach($array as $key=>$value){
    foreach($value as $subkey=>$subvalue) {
        echo $subkey . " : " . $subvalue . "<br>";
    }
}

If you want to get the currency pair key also, use this example:

$assoc_array = array(
        "eurusd" =>     array('abc','def','xyz'),
        "usdjpy" =>     array('good','bad','ugly'),
        "aususd" =>     array('blue','red','green')

);

foreach($assoc_array as $key=>$value){
        echo $key . ":: <br>";
    foreach($value as $subkey=>$subvalue) {
        echo $subkey . " : " . $subvalue . "<br>";
    }
}

I want to show result this way


问:
coding for custom uicollectionview layout
Where/How would I code for this cell layout behavior.

I need each cell to overlap the previous.

Cell 2 centerX is Cell 1 right edge and so forth...

What method would I override in my custom UICollectionViewLayout?

答:
When creating a custom collectionView layout, override layoutAttributesForItem to configure cells layout behavior...

```<code>var preferredSize: CGSize? = CGSize(width: 100, height: 100)

override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
    let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)

    attributes.size = preferredSize!
//Modifying the centerX property adjust the overlapping effect
    let centerX = (preferredSize?.width)! / 2.0 + CGFloat(indexPath.item) * ((preferredSize?.width)! * 0.5 )
    let centerY = collectionView!.bounds.height / 2.0
    attributes.center = CGPoint(x: centerX, y: centerY)
    attributes.zIndex = -(indexPath.item)

    return attributes
}
</code>```

Body:
When creating a custom collectionView layout, override layoutAttributesForItem to configure cells layout behavior...

var preferredSize: CGSize? = CGSize(width: 100, height: 100)

override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
    let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)

    attributes.size = preferredSize!
//Modifying the centerX property adjust the overlapping effect
    let centerX = (preferredSize?.width)! / 2.0 + CGFloat(indexPath.item) * ((preferredSize?.width)! * 0.5 )
    let centerY = collectionView!.bounds.height / 2.0
    attributes.center = CGPoint(x: centerX, y: centerY)
    attributes.zIndex = -(indexPath.item)

    return attributes
}


问:
C program to input date as dd-mm-yy and display date as January 3rd, 1999
I'm trying to write a program in C, read data from the keyboard in the form dd-mm-yy and want to display the date as January 3rd, 1999.
How can i do it?

答:
Use strptime & strftime. Like this ->

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int main()
{
   struct tm tm;
   char buf[255];

   memset(&tm, 0, sizeof(struct tm));
   strptime("3-1-1999", "%d-%m-%Y ", &tm);
   strftime(buf, sizeof(buf), "%d %b %Y", &tm);
   puts(buf);
   exit(EXIT_SUCCESS);
}
</code>```

It will show the output =>

03 Jan 1999

Body:
Use strptime & strftime. Like this ->

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int main()
{
   struct tm tm;
   char buf[255];

   memset(&tm, 0, sizeof(struct tm));
   strptime("3-1-1999", "%d-%m-%Y ", &tm);
   strftime(buf, sizeof(buf), "%d %b %Y", &tm);
   puts(buf);
   exit(EXIT_SUCCESS);
}

It will show the output =>

03 Jan 1999


问:
Create Pages Automatically
Is there any method in Php by which I can create a page automatically based on a predefined template. Like if we create a new post in blogger it automatically creates page for that post with the name of that post, like this one:

http://learntoflash.blogspot.com/2009/12/exit-button-in-flash.html

Here Exit Button In Flash is the name of my post I have written and an automatic page is created for it.

Or like here on this website if we ask a question it automatically creates a page for that question. I want to know can I achieve this in Php or anything close to this ?

答:
You should use URL rewriting. This Apache module lets you define rules to rewrite web addresses in your desired way.

The process to make your web application ready for this, is not a short story so you should read more about it.

This article is a good starting point:

http://articles.sitepoint.com/article/guide-url-rewriting

Title: Create Pages Automatically


问:
R 3.4.1 "Single Candle" Personal Library Path Error: unable to create ‘NA’
I just updated to R (3.4.1 "Single Candle") on my Linux Mint 18.1 Cinnamon machine and I attempted to install a package. R returned the following:

```<code>> install.packages('ggplot2')
Installing package into ‘/usr/local/lib/R/site-library’
(as ‘lib’ is unspecified)
Warning in install.packages("ggplot2") :
  'lib = "/usr/local/lib/R/site-library"' is not writable
Would you like to use a personal library instead?  (y/n) y
Would you like to create a personal library
NA
to install packages into?  (y/n) y
Error in install.packages("ggplot2") : unable to create ‘NA’
</code>```

I have encountered the 'lib not writable' output before but typically it offers a solution like this one:

```<code>Would you like to create a personal library
~/R/x86_64-pc-linux-gnu-library/3.4
to install packages into?  (y/n) y
</code>```

Any ideas why the personal library is suggesting NA? Is there a way to manually override this?

答:
After July 8, 2017 this will resolve all problems</p>

```<code>sudo apt-get update
</code>```

Body:
I just updated to R (3.4.1 "Single Candle") on my Linux Mint 18.1 Cinnamon machine and I attempted to install a package. R returned the following:

> install.packages('ggplot2')
Installing package into ‘/usr/local/lib/R/site-library’
(as ‘lib’ is unspecified)
Warning in install.packages("ggplot2") :
  'lib = "/usr/local/lib/R/site-library"' is not writable
Would you like to use a personal library instead?  (y/n) y
Would you like to create a personal library
NA
to install packages into?  (y/n) y
Error in install.packages("ggplot2") : unable to create ‘NA’

I have encountered the 'lib not writable' output before but typically it offers a solution like this one:

Would you like to create a personal library
~/R/x86_64-pc-linux-gnu-library/3.4
to install packages into?  (y/n) y

Any ideas why the personal library is suggesting NA? Is there a way to manually override this?

Body:
After July 8, 2017 this will resolve all problems

sudo apt-get update


问:
thread.lock during custom parameter search class using Dask distributed
I wrote my own parameter search implementation mostly due to the fact that I don't need cross-validation of GridSearch and RandomizedSearch of scikit-learn.

I use dask to deliver optimal distributed performance.

Here is what I have:

```<code>from scipy.stats import uniform
class Params(object):
    def __init__(self,fixed,loc=0.0,scale=1.0):
        self.fixed=fixed
        self.sched=uniform(loc=loc,scale=scale)

    def _getsched(self,i,size):
        return self.sched.rvs(size=size,random_state=i)

    def param(self,i,size=None):
        tmp=self.fixed.copy()
        if size is None:
            size=tmp['niter']
        tmp.update({'schd':self._getsched(i,size)})
        return tmp

class Mymodel(object):
    def __init__(self,func,params_object,score,ntries,client):
        self.params=params_object
        self.func=func
        self.score=score
        self.ntries=ntries
        self.client=client

    def _run(self,params,train,test):
        return self.func(params,train,test,self.score)

    def build(self,train,test):
        res=[]
        for i in range(self.ntries):
            cparam=self.params.param(i)
            res.append( (cparam, self.client.submit(self._run, cparam, train,test)) )
        self._results=res
        return res

    def compute_optimal(self,res=None):
        from operator import itemgetter
        if res is None:
            res=self._results
        self._sorted=sorted(self.client.compute(res),key=itemgetter(1))

        return self._sorted[0]

def score(test,correct):
    return np.linalg.norm(test-correct)

def myfunc(params,ldata,data,score):
    schd=params['schd']
    niter=len(schd)
    #here I do some magic after which ldata is changing
    return score(test=ldata,correct=data)
</code>```

After I start dask.distributed:

```<code>from distributed import Client
scheduler_host='myhostname:8786'
cli=Client(scheduler_host)
</code>```

I run it like this:

```<code>%%time
params=Params({'niter':50},loc=1.0e-06,scale=1.0)
model=Mymodel(myfunc,params,score,100,cli)
ptdata=bad_data_example.copy()
graph=model.build(ptdata,good_data)
</code>```

And get this:

```<code>distributed.protocol.pickle - INFO - Failed to serialize
<bound method Mymodel._run of <__main__.Mymodel object at 0x2b8961903050>>.
Exception: can't pickle thread.lock objects
</code>```

Could you please help me to understand what is going on and how to fix this?

I'm also curious about the way how I find the minimum within all the parameters results. Is there a better way to do it with Dask?

I wrote this code fairly fast and never tried it in serial.
I'm learning Dask together with many other topics (machine learning, gpu programming, Numba, Python OOP and etc.) so this code is not optimal by any means...

P.S. To actually execute it I use this call: model.compute_optimal(). Haven't got here yet - due to the error above.

答:
It looks like the main issue was due to the fact that I tried to map a method of a function. I had similar issues with joblib as well. So I re-coded the problem and removed all the classes.

The following issues regarding optimization are posted here: Parameter search using dask

I'll definetely use dask-searchcv in my work - when I'll need cross-validation - but for now it's really only a simple search for an optimal solution - so had to create my own implementation...

Body:
I wrote my own parameter search implementation mostly due to the fact that I don't need cross-validation of GridSearch and RandomizedSearch of scikit-learn.

I use dask to deliver optimal distributed performance.

Here is what I have:

from scipy.stats import uniform
class Params(object):
    def __init__(self,fixed,loc=0.0,scale=1.0):
        self.fixed=fixed
        self.sched=uniform(loc=loc,scale=scale)

    def _getsched(self,i,size):
        return self.sched.rvs(size=size,random_state=i)

    def param(self,i,size=None):
        tmp=self.fixed.copy()
        if size is None:
            size=tmp['niter']
        tmp.update({'schd':self._getsched(i,size)})
        return tmp

class Mymodel(object):
    def __init__(self,func,params_object,score,ntries,client):
        self.params=params_object
        self.func=func
        self.score=score
        self.ntries=ntries
        self.client=client

    def _run(self,params,train,test):
        return self.func(params,train,test,self.score)

    def build(self,train,test):
        res=[]
        for i in range(self.ntries):
            cparam=self.params.param(i)
            res.append( (cparam, self.client.submit(self._run, cparam, train,test)) )
        self._results=res
        return res

    def compute_optimal(self,res=None):
        from operator import itemgetter
        if res is None:
            res=self._results
        self._sorted=sorted(self.client.compute(res),key=itemgetter(1))

        return self._sorted[0]

def score(test,correct):
    return np.linalg.norm(test-correct)

def myfunc(params,ldata,data,score):
    schd=params['schd']
    niter=len(schd)
    #here I do some magic after which ldata is changing
    return score(test=ldata,correct=data)

After I start dask.distributed:

from distributed import Client
scheduler_host='myhostname:8786'
cli=Client(scheduler_host)

I run it like this:

%%time
params=Params({'niter':50},loc=1.0e-06,scale=1.0)
model=Mymodel(myfunc,params,score,100,cli)
ptdata=bad_data_example.copy()
graph=model.build(ptdata,good_data)

And get this:

distributed.protocol.pickle - INFO - Failed to serialize
<bound method Mymodel._run of <__main__.Mymodel object at 0x2b8961903050>>.
Exception: can't pickle thread.lock objects

Could you please help me to understand what is going on and how to fix this?

I'm also curious about the way how I find the minimum within all the parameters results. Is there a better way to do it with Dask?

I wrote this code fairly fast and never tried it in serial.
I'm learning Dask together with many other topics (machine learning, gpu programming, Numba, Python OOP and etc.) so this code is not optimal by any means...

P.S. To actually execute it I use this call: model.compute_optimal(). Haven't got here yet - due to the error above.


问:
Sorting alphabetically applied coupons in WooCommerce
For some reasons I need to apply coupons to an order in a correct sequence - alphabetic (A-B-C). User is able to add coupons a various ways (B-A-C, C-A-B etc or even C-A). So I'd like to sort added coupons and add these to the order in correct way.

I'm trying to fix but with no luck:

```<code>add_action( 'woocommerce_applied_coupon', 'sort_coupon' );
if (!function_exists('sort_coupon') ) {

    function sort_coupon() {
        global $woocommerce;
        $cart_coupons = WC()->cart->get_applied_coupons();
        sort($cart_coupons);
        WC()->cart->remove_coupons();
        foreach ( $cart_coupons as $code ) {
            WC()->cart->add_discount( $code );
        }
        WC()->cart->calculate_totals();
    }
}
</code>```

How can I make it work?

答:
As woocommerce_applied_coupon hook is already located in WC_Cart add_discount() method, then you can't use it as it makes a kind of loop…

Instead you should hook in your function in woocommerce_cart_coupon action hook this way:

```<code>add_action( 'woocommerce_cart_coupon', 'custom_sort_coupons' );
function custom_sort_coupons() {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $applied_coupons = WC()->cart->get_applied_coupons();
    WC()->cart->remove_coupons();

    sort($applied_coupons);

    foreach ( $applied_coupons as $coupon_code ) {
        WC()->cart->add_discount( $coupon_code );
        wc_clear_notices(); // Avoid repetitive notices
    }
    WC()->cart->calculate_totals();
}
</code>```

Code goes in any php file of your active child theme (or theme) or also in any plugin php file.

Now this is working. I have add wc_clear_notices() in the last loop to avoid repetitive notices

Body:
For some reasons I need to apply coupons to an order in a correct sequence - alphabetic (A-B-C). User is able to add coupons a various ways (B-A-C, C-A-B etc or even C-A). So I'd like to sort added coupons and add these to the order in correct way.

I'm trying to fix but with no luck:

add_action( 'woocommerce_applied_coupon', 'sort_coupon' );
if (!function_exists('sort_coupon') ) {

    function sort_coupon() {
        global $woocommerce;
        $cart_coupons = WC()->cart->get_applied_coupons();
        sort($cart_coupons);
        WC()->cart->remove_coupons();
        foreach ( $cart_coupons as $code ) {
            WC()->cart->add_discount( $code );
        }
        WC()->cart->calculate_totals();
    }
}

How can I make it work?

Body:
As woocommerce_applied_coupon hook is already located in WC_Cart add_discount() method, then you can't use it as it makes a kind of loop…

Instead you should hook in your function in woocommerce_cart_coupon action hook this way:

add_action( 'woocommerce_cart_coupon', 'custom_sort_coupons' );
function custom_sort_coupons() {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $applied_coupons = WC()->cart->get_applied_coupons();
    WC()->cart->remove_coupons();

    sort($applied_coupons);

    foreach ( $applied_coupons as $coupon_code ) {
        WC()->cart->add_discount( $coupon_code );
        wc_clear_notices(); // Avoid repetitive notices
    }
    WC()->cart->calculate_totals();
}

Code goes in any php file of your active child theme (or theme) or also in any plugin php file.

Now this is working. I have add wc_clear_notices() in the last loop to avoid repetitive notices


问:
Calling func textfield(...) without using keyboard
I have a button that changes the value of a text field.
How do I get that to also execute the textField function bellow, as if the value was typed inside the text field?

This function only works if you're using the keyboard to type. I need to also call it without using the keyboard.

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    print("some actions her")

    return true
}
</code>```

答:
You don't. This delegate method is only called as a user types. It will never be called if you explicitly set the text property of the text field. And this is a good thing. It's not uncommon to set the text field's text inside the shouldChangeCharactersIn delegate method. If setting the text caused the delegate method to be called you could end up with infinite recursion.

Since your code is explicitly setting the text, there is no need for the delegate to be called. Simply set the text to the desired value.

If there is logic to format the text or some other processing, put that logic in another function and then you can call that function from two places - from shouldChangeCharactersIn and from wherever you set the text field's text.

Body:
I have a button that changes the value of a text field.
How do I get that to also execute the textField function bellow, as if the value was typed inside the text field?

This function only works if you're using the keyboard to type. I need to also call it without using the keyboard.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    print("some actions her")

    return true
}


问:
Extract URL from body of email
I have data to add to Excel. I found that we can do that by Outlook VBA. The content comes in the following format:

Title: Undergraduate student

Gender: Male

Country: Albania

Keyword:

1.Environment

2. Population

First Name: John

Phone number: 0532432444

Username: test@dda.com

File upload: http://all-free-download.com/free-photos/download/autumns-evening-sun_513398.html

I followed an old article and created this code:

Sub CopyToExcel()
    Dim xlApp As Object
    Dim xlWB As Object
    Dim xlSheet As Object

    Dim olItem As Outlook.MailItem
    Dim vText As Variant
    Dim sText As String
    Dim vItem As Variant

    Dim i As Long
    Dim rCount As Long
    Dim bXStarted As Boolean

    Const strPath As String = "E:\Project\Test oulook.xlsx"   ' the path of the workbook

    If Application.ActiveExplorer.Selection.Count = 0 Then
        MsgBox "No Items selected!", vbCritical, "Error"
        Exit Sub
    End If

    On Error Resume Next

    Set xlApp = GetObject(, "Excel.Application")
    If Err <> 0 Then
        Application.StatusBar = "Please wait while Excel source is opened ... "
        Set xlApp = CreateObject("Excel.Application")
        bXStarted = True
    End If

    On Error GoTo 0

    ' Open the workbook to input the data
    Set xlWB = xlApp.Workbooks.Open(strPath)
    Set xlSheet = xlWB.Sheets("Sheet1")

    ' Process each selected record
    rCount = xlSheet.UsedRange.Rows.Count
    For Each olItem In Application.ActiveExplorer.Selection
        sText = olItem.Body
        vText = Split(sText, Chr(13))

        ' Find the next empty line of the worksheet
        rCount = rCount + 1

        ' Check each line of text in the message body
        For i = UBound(vText) To 0 Step -1

            If InStr(1, vText(i), "title: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("A" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "gender: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("B" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "country: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("C" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "keyword: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("E" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "first_name: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("G" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "phone_number: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("I" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "username: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("F" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "upload: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("O" & rCount) = Trim(vItem(1))
            End If

        Next i
        xlWB.Save

    Next olItem
    xlWB.Close SaveChanges:=True

    If bXStarted Then
        xlApp.Quit
    End If

    Set olItem = Nothing
    Set xlSheet = Nothing
    Set xlWB = Nothing
    Set xlApp = Nothing
End Sub
```

The upload field displays " http " not " http://all-free-download.com/free-photos/download/autumns-evening-sun_513398.html  ".

答:
i tried your code.  there is an issue with finding the next available cell when the worksheet is blank (the formula xlSheet.UsedRange.Rows.Count returns 1 for both, no rows used, and one row used)

here is a rewrite that seems to work correctly

if-then routines have been replaced by case statements

```<code>Sub CopyToExcel()
    Dim xlApp As Object
    Dim xlWB As Object
    Dim xlSheet As Object

    Dim olItem As Outlook.mailItem
    Dim vText As Variant
    Dim rCount As Long

    Dim vItem As Variant
    Dim i As Long
    Dim bXStarted As Boolean
    Const strPath As String = "E:\Project\Test outlook.xlsx"      ' the path of the workbook

    If Application.ActiveExplorer.Selection.Count = 0 Then
         MsgBox "No Items selected!", vbCritical, "Error"
         Exit Sub
    End If

    On Error Resume Next

    Set xlApp = GetObject(, "Excel.Application")

    If Err <> 0 Then
        Application.StatusBar = "Please wait while Excel source is opened ... "
        Set xlApp = CreateObject("Excel.Application")
        bXStarted = True
    End If

'   xlApp.Visible = True                                          ' show worksheet (for debugging)

    On Error GoTo 0

    Set xlWB = xlApp.Workbooks.Open(strPath)                      ' Open the workbook to input the data
    Set xlSheet = xlWB.Sheets("Sheet1")

'   rCount = xlSheet.UsedRange.Rows.Count                         ' does not work (returns 1 when no data on worksheet)

    Dim formula As String                                         '
    formula = "MATCH(TRUE, INDEX(ISBLANK(A:A), 0, 0), 0)"         ' cell formula: =MATCH(TRUE, INDEX(ISBLANK(A:A), 0, 0), 0)

    rCount = xlApp.Evaluate(formula)                              ' find next empty line on worksheet using a cell formula

    For Each olItem In Application.ActiveExplorer.Selection       ' Process each selected email

        vText = Split(olItem.body, vbCrLf)                        ' convert email body to an array of text lines
        For i = 0 To UBound(vText)                                ' Check each line of text in the message body

            vItem = Split(":" & vText(i), ":", 3)                 ' split line into max 3 parts (leading ":" added to prevent fail on blank lines)

            Select Case LCase(vItem(1))                           ' LCase for case insensitive comparison
                Case "title"
                    xlSheet.Range("A" & rCount) = Trim(vItem(2))
                Case "gender"
                    xlSheet.Range("B" & rCount) = Trim(vItem(2))
                Case "country"
                    xlSheet.Range("C" & rCount) = Trim(vItem(2))
                Case "keyword"
                    xlSheet.Range("E" & rCount) = Trim(vItem(2))
                Case "first name"
                    xlSheet.Range("G" & rCount) = Trim(vItem(2))
                Case "phone number"
                    xlSheet.Range("I" & rCount) = Trim(vItem(2))
                Case "username"
                    xlSheet.Range("F" & rCount) = Trim(vItem(2))
                Case "file upload"
                    xlSheet.Range("O" & rCount) = Trim(vItem(2))
'               Case Else
'                   do something else here
            End Select

        Next i
        xlWB.Save

        rCount = rCount + 1                                       ' point to next empty line of the worksheet

    Next olItem
    Set olItem = Nothing

    xlWB.Close SaveChanges:=True

    If bXStarted Then
        xlApp.Quit
    End If

    Set xlSheet = Nothing
    Set xlWB = Nothing
    Set xlApp = Nothing
End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Title: Extract URL from body of email

Body:
I have data to add to Excel. I found that we can do that by Outlook VBA. The content comes in the following format:

Title: Undergraduate student

Gender: Male

Country: Albania

Keyword:

1.Environment

2. Population

First Name: John

Phone number: 0532432444

Username: test@dda.com

File upload: http://all-free-download.com/free-photos/download/autumns-evening-sun_513398.html

I followed an old article and created this code:

Sub CopyToExcel()
    Dim xlApp As Object
    Dim xlWB As Object
    Dim xlSheet As Object

    Dim olItem As Outlook.MailItem
    Dim vText As Variant
    Dim sText As String
    Dim vItem As Variant

    Dim i As Long
    Dim rCount As Long
    Dim bXStarted As Boolean

    Const strPath As String = "E:\Project\Test oulook.xlsx"   ' the path of the workbook

    If Application.ActiveExplorer.Selection.Count = 0 Then
        MsgBox "No Items selected!", vbCritical, "Error"
        Exit Sub
    End If

    On Error Resume Next

    Set xlApp = GetObject(, "Excel.Application")
    If Err <> 0 Then
        Application.StatusBar = "Please wait while Excel source is opened ... "
        Set xlApp = CreateObject("Excel.Application")
        bXStarted = True
    End If

    On Error GoTo 0

    ' Open the workbook to input the data
    Set xlWB = xlApp.Workbooks.Open(strPath)
    Set xlSheet = xlWB.Sheets("Sheet1")

    ' Process each selected record
    rCount = xlSheet.UsedRange.Rows.Count
    For Each olItem In Application.ActiveExplorer.Selection
        sText = olItem.Body
        vText = Split(sText, Chr(13))

        ' Find the next empty line of the worksheet
        rCount = rCount + 1

        ' Check each line of text in the message body
        For i = UBound(vText) To 0 Step -1

            If InStr(1, vText(i), "title: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("A" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "gender: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("B" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "country: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("C" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "keyword: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("E" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "first_name: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("G" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "phone_number: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("I" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "username: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("F" & rCount) = Trim(vItem(1))
            End If

            If InStr(1, vText(i), "upload: ") > 0 Then
                vItem = Split(vText(i), Chr(58))
                xlSheet.Range("O" & rCount) = Trim(vItem(1))
            End If

        Next i
        xlWB.Save

    Next olItem
    xlWB.Close SaveChanges:=True

    If bXStarted Then
        xlApp.Quit
    End If

    Set olItem = Nothing
    Set xlSheet = Nothing
    Set xlWB = Nothing
    Set xlApp = Nothing
End Sub

The upload field displays " http " not " http://all-free-download.com/free-photos/download/autumns-evening-sun_513398.html  ".

Body:
i tried your code.  there is an issue with finding the next available cell when the worksheet is blank (the formula xlSheet.UsedRange.Rows.Count returns 1 for both, no rows used, and one row used)

here is a rewrite that seems to work correctly

if-then routines have been replaced by case statements

Sub CopyToExcel()
    Dim xlApp As Object
    Dim xlWB As Object
    Dim xlSheet As Object

    Dim olItem As Outlook.mailItem
    Dim vText As Variant
    Dim rCount As Long

    Dim vItem As Variant
    Dim i As Long
    Dim bXStarted As Boolean
    Const strPath As String = "E:\Project\Test outlook.xlsx"      ' the path of the workbook

    If Application.ActiveExplorer.Selection.Count = 0 Then
         MsgBox "No Items selected!", vbCritical, "Error"
         Exit Sub
    End If

    On Error Resume Next

    Set xlApp = GetObject(, "Excel.Application")

    If Err <> 0 Then
        Application.StatusBar = "Please wait while Excel source is opened ... "
        Set xlApp = CreateObject("Excel.Application")
        bXStarted = True
    End If

'   xlApp.Visible = True                                          ' show worksheet (for debugging)

    On Error GoTo 0

    Set xlWB = xlApp.Workbooks.Open(strPath)                      ' Open the workbook to input the data
    Set xlSheet = xlWB.Sheets("Sheet1")

'   rCount = xlSheet.UsedRange.Rows.Count                         ' does not work (returns 1 when no data on worksheet)

    Dim formula As String                                         '
    formula = "MATCH(TRUE, INDEX(ISBLANK(A:A), 0, 0), 0)"         ' cell formula: =MATCH(TRUE, INDEX(ISBLANK(A:A), 0, 0), 0)

    rCount = xlApp.Evaluate(formula)                              ' find next empty line on worksheet using a cell formula

    For Each olItem In Application.ActiveExplorer.Selection       ' Process each selected email

        vText = Split(olItem.body, vbCrLf)                        ' convert email body to an array of text lines
        For i = 0 To UBound(vText)                                ' Check each line of text in the message body

            vItem = Split(":" & vText(i), ":", 3)                 ' split line into max 3 parts (leading ":" added to prevent fail on blank lines)

            Select Case LCase(vItem(1))                           ' LCase for case insensitive comparison
                Case "title"
                    xlSheet.Range("A" & rCount) = Trim(vItem(2))
                Case "gender"
                    xlSheet.Range("B" & rCount) = Trim(vItem(2))
                Case "country"
                    xlSheet.Range("C" & rCount) = Trim(vItem(2))
                Case "keyword"
                    xlSheet.Range("E" & rCount) = Trim(vItem(2))
                Case "first name"
                    xlSheet.Range("G" & rCount) = Trim(vItem(2))
                Case "phone number"
                    xlSheet.Range("I" & rCount) = Trim(vItem(2))
                Case "username"
                    xlSheet.Range("F" & rCount) = Trim(vItem(2))
                Case "file upload"
                    xlSheet.Range("O" & rCount) = Trim(vItem(2))
'               Case Else
'                   do something else here
            End Select

        Next i
        xlWB.Save

        rCount = rCount + 1                                       ' point to next empty line of the worksheet

    Next olItem
    Set olItem = Nothing

    xlWB.Close SaveChanges:=True

    If bXStarted Then
        xlApp.Quit
    End If

    Set xlSheet = Nothing
    Set xlWB = Nothing
    Set xlApp = Nothing
End Sub


问:
How does one test a file to see if it's a valid XML file before loading it with XDocument.Load()?
I'm loading an XML document in my C# application with the following:

```<code>XDocument xd1 = new XDocument();
xd1 = XDocument.Load(myfile);
</code>```

but before that, I do test to make sure the file exists with:

```<code>File.Exists(myfile);
</code>```

But... is there an (easy) way to test the file before the XDocument.Load() to make sure it's a valid XML file?  In other words, my user can accidentally click on a different file in the file browser and trying to load, say, a .php file causes an exception.

The only way I can think of is to load it into a StreamWriter and simple do a text search on the first few characters to make sure they say "

Thanks!

-Adeena

答:
I would not XDocument.Load(), as per the accepted answer; why would you read the entire file into memory, it could be a huge file?

I'd probably read the first few bytes into a byteArray (it could even be any binary file), convert the byteArray to string
e.g. System.Text.Encoding.ASCII.GetString(byteArray) ,check if the converted string contains the Xml elements you are expecting, only then continue.

OwnerDisplayName: adeena

Body:
I'm loading an XML document in my C# application with the following:

XDocument xd1 = new XDocument();
xd1 = XDocument.Load(myfile);

but before that, I do test to make sure the file exists with:

File.Exists(myfile);

But... is there an (easy) way to test the file before the XDocument.Load() to make sure it's a valid XML file?  In other words, my user can accidentally click on a different file in the file browser and trying to load, say, a .php file causes an exception.

The only way I can think of is to load it into a StreamWriter and simple do a text search on the first few characters to make sure they say "

Thanks!

-Adeena


问:
Why this while loop does not work?
Thanks everyone! I changed my code, and it still gives the error:

list index out of range.

Why?

```<code>M  = []
B = [1, 3, 5]
C = [2, 4, 6]
while (B and C):
    if B[0] <= C[0]:
        M.append(B.pop(0))
    if C[0] <= B[0]:
        M.append(C.pop(0))

print('Updated list: ', M)
</code>```

`

答:
Because eventually you end up at a point in your code where one of your lists is empty - so it does not have an index 0 to reference. Specifically the 5 in list B is the last element of that list 'consumed' - copied to M and deleted from B, after which the list has no index 0.

I see two ways around this:

The first solution below solves your problem, in which you don't have a case where B and C exist at the start of your while loop to trigget the B and C to return False and break you out of the loop.Eventually, in B[0] <= C[0] the 5 in B is deleted, and the code moves next to C[0] <= B[0] whereupon it errors because B is empty. The code functions the same way in that if B[0] <= C[0] that part of the code runs, and if not (in which case C[0] <= B[0] is true) executes the code in your original second if statement without testing this that condition.

This means the while loop runs more times, because it only ever does one operation per cycle, but it means it tests while (B and C) after each change to a list, which avoids trying to do an operation on an empty list index, as B or C will evaluate to false if they are empty, and the while loop will exit.

```<code>M = []
B = [1, 3, 5]
C = [2, 4, 6]
while (B and C):
    if B[0] <= C[0]:
        M.append(B.pop(0))
    else:
        M.append(C.pop(0))

print('Updated list: ', M)
</code>```

The second solution I came up with (which I came up with first, and while more explicit, is less simple) is to specifically specify that both B and C need to have something in them (ie have to have an index 0) before running each of the if statements in your original code, and if either is empty, to break out of the while loop before the if statement that throws the error can run:

```<code>M = []
B = [1, 3, 5]
C = [2, 4, 6]

while (B and C):
    if len(B) == 0 or len(C) == 0:
        break
    if B[0] <= C[0]:
        M.append(B.pop(0))
    if len(B) == 0 or len(C) == 0:
        break
    if C[0] <= B[0]:
        M.append(C.pop(0))

print('Updated list: ', M)
</code>```

You could add this code in after your while loop and before your print function in either case, to ensure all of the list items is added to M:

```<code>D = B+C
M.append(D.pop(0))
</code>```

Basically this just adds the list which is empty to the list with one item, with the new list, D having a single item in it at index 0, and then appending that to M.

Title: Why this while loop does not work?

Body:
Thanks everyone! I changed my code, and it still gives the error:

list index out of range.

Why?

M  = []
B = [1, 3, 5]
C = [2, 4, 6]
while (B and C):
    if B[0] <= C[0]:
        M.append(B.pop(0))
    if C[0] <= B[0]:
        M.append(C.pop(0))

print('Updated list: ', M)

`

Body:
Because eventually you end up at a point in your code where one of your lists is empty - so it does not have an index 0 to reference. Specifically the 5 in list B is the last element of that list 'consumed' - copied to M and deleted from B, after which the list has no index 0.

I see two ways around this:

The first solution below solves your problem, in which you don't have a case where B and C exist at the start of your while loop to trigget the B and C to return False and break you out of the loop.Eventually, in B[0] <= C[0] the 5 in B is deleted, and the code moves next to C[0] <= B[0] whereupon it errors because B is empty. The code functions the same way in that if B[0] <= C[0] that part of the code runs, and if not (in which case C[0] <= B[0] is true) executes the code in your original second if statement without testing this that condition.

This means the while loop runs more times, because it only ever does one operation per cycle, but it means it tests while (B and C) after each change to a list, which avoids trying to do an operation on an empty list index, as B or C will evaluate to false if they are empty, and the while loop will exit.

M = []
B = [1, 3, 5]
C = [2, 4, 6]
while (B and C):
    if B[0] <= C[0]:
        M.append(B.pop(0))
    else:
        M.append(C.pop(0))

print('Updated list: ', M)

The second solution I came up with (which I came up with first, and while more explicit, is less simple) is to specifically specify that both B and C need to have something in them (ie have to have an index 0) before running each of the if statements in your original code, and if either is empty, to break out of the while loop before the if statement that throws the error can run:

M = []
B = [1, 3, 5]
C = [2, 4, 6]

while (B and C):
    if len(B) == 0 or len(C) == 0:
        break
    if B[0] <= C[0]:
        M.append(B.pop(0))
    if len(B) == 0 or len(C) == 0:
        break
    if C[0] <= B[0]:
        M.append(C.pop(0))

print('Updated list: ', M)

You could add this code in after your while loop and before your print function in either case, to ensure all of the list items is added to M:

D = B+C
M.append(D.pop(0))

Basically this just adds the list which is empty to the list with one item, with the new list, D having a single item in it at index 0, and then appending that to M.


问:
where should phpmyadmin folder be saved?
apache, mysql and phpmyadmin tutorial and the tutorial suggests to navigate to localhost/phpmyadmin/setup, however this gives me "the site cannot be reached" in the browser.

I have already ran "sudo apachectl start"

I think this is likely that I have phpmyadmin saved in the wrong folder but the tutorial doesn't explain which folder to save it in, so I currently have it in a downloads folder.

Can anyone tell me where to move phpmyadmin folder and how to get it to work

edit: I am using mac os x

答:
FIrst, you have to find your web root folder. This is the folder where files are being served. Typically on a Linux system, it will be /var/www/ but it depends on the Linux distribution you're using and the specific configuration you have. Once you have figured out the root directory of your website, simply add a directory called phpmyadmin. So in the typical case, you now have /var/www/phpmyadmin

To find the web directory, it is referred to as DocumentRoot in apache's configuration file.


问:
object-oriented shell for linux?
Is there anything similar to Microsoft Powershell (an object-oriented shell built on the .NET framework) for Linux (possibly built on Java, GObject, or its own object type/nothing)?

edit: especially if similar to bash or powershell or cmd etc. syntax (=''standard'' shell syntax)

答: You should rethink why it is you think you need an object-oriented shell. That said, if you're set trying weird shells you can't go wrong with zoid. Unlike many of the other suggestions I see here it really is a shell. On the other hand, if you don't know or don't like Perl you probably won't be happy.</p>

Title: object-oriented shell for linux?


问:
Git push failed: 403
Today I tried to setup a project with my friend. First, we decided to use GitLab, but later, we switched to GitHub. At the beginning, everything worked fine, I was able to push, pull and so on. But later, maybe 45-60 minutes, every push requests failed. Pull works fine.

I really don't know what to do, heres the error: IntelliJ IDEA Git Push fail

We are working together using IntelliJ IDEA 2017.1.5 and also tried switching to SSH - which did not help.

Do you guys know how to fix this error? The repository still exists and I still have access to it. I also tried re-creating the project (from GitHub) and I also tried re-installing Git.

答:
Double-check that you are the owner of that repo, and that you don't have 2FA (two factyor authentication) activated (if you have 2FA, see "IntelliJ How to access GIT remote repositories with 2-factor authentication")

Double-check also how your GitHub account is registered in IntelliJ.

Title: Git push failed: 403