问:
mySQL 5.5.43 syntax error
I am doing Mantis database upgrade and I am getting the below error when running the create table  command. Can someone please help me to see whats wrong with the mysql syntax?

This is the error msg:

```<code>Schema CreateTableSQL ( )   BAD
CREATE TABLE (
email_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
email VARCHAR(64) NOT NULL DEFAULT '',
subject VARCHAR(250) NOT NULL DEFAULT '',
submitted DATETIME NOT NULL DEFAULT '1970-01-01 00:00:01',
metadata LONGTEXT NOT NULL,
body LONGTEXT NOT NULL,
PRIMARY KEY (email_id) )
ENGINE=MyISAM
</code>```

You have an error in your SQL syntax; check the manual that
  corresponds to  your MySQL server version for the right syntax to use
  near '( email_id  INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, email ' at
  line 1

This is a part of the create table code in schema.php

```<code>$upgrade[] = Array('CreateTableSQL',Array(config_get('mantis_email_table'),"
email_id              I  UNSIGNED NOTNULL PRIMARY AUTOINCREMENT,
email                 C(64) NOTNULL DEFAULT \" '' \",
subject               C(250) NOTNULL DEFAULT \" '' \",
submitted     T NOTNULL DEFAULT '1970-01-01 00:00:01',
metadata              XL NOTNULL,
body                  XL NOTNULL
",Array('mysql' => 'ENGINE=MyISAM', 'pgsql' => 'WITHOUT OIDS')));
</code>```

答:
You have not provided the table a name:</p>

```<code>CREATE TABLE  # name is missing here

    ( email_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT
    , email VARCHAR(64) NOT NULL DEFAULT ''
    , subject VARCHAR(250) NOT NULL DEFAULT ''
    , submitted DATETIME NOT NULL DEFAULT '1970-01-01 00:00:01'
    , metadata LONGTEXT NOT NULL
    , body LONGTEXT NOT NULL
    , PRIMARY KEY (email_id)
)ENGINE=MyISAM
</code>```

Title: mySQL 5.5.43 syntax error

Body:
I am doing Mantis database upgrade and I am getting the below error when running the create table  command. Can someone please help me to see whats wrong with the mysql syntax?

This is the error msg:

Schema CreateTableSQL ( )   BAD
CREATE TABLE (
email_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
email VARCHAR(64) NOT NULL DEFAULT '',
subject VARCHAR(250) NOT NULL DEFAULT '',
submitted DATETIME NOT NULL DEFAULT '1970-01-01 00:00:01',
metadata LONGTEXT NOT NULL,
body LONGTEXT NOT NULL,
PRIMARY KEY (email_id) )
ENGINE=MyISAM

You have an error in your SQL syntax; check the manual that
  corresponds to  your MySQL server version for the right syntax to use
  near '( email_id  INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, email ' at
  line 1

This is a part of the create table code in schema.php

$upgrade[] = Array('CreateTableSQL',Array(config_get('mantis_email_table'),"
email_id              I  UNSIGNED NOTNULL PRIMARY AUTOINCREMENT,
email                 C(64) NOTNULL DEFAULT \" '' \",
subject               C(250) NOTNULL DEFAULT \" '' \",
submitted     T NOTNULL DEFAULT '1970-01-01 00:00:01',
metadata              XL NOTNULL,
body                  XL NOTNULL
",Array('mysql' => 'ENGINE=MyISAM', 'pgsql' => 'WITHOUT OIDS')));

Body:
You have not provided the table a name:

CREATE TABLE  # name is missing here

    ( email_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT
    , email VARCHAR(64) NOT NULL DEFAULT ''
    , subject VARCHAR(250) NOT NULL DEFAULT ''
    , submitted DATETIME NOT NULL DEFAULT '1970-01-01 00:00:01'
    , metadata LONGTEXT NOT NULL
    , body LONGTEXT NOT NULL
    , PRIMARY KEY (email_id)
)ENGINE=MyISAM


来源: stackexchange

问:
How to make a responsive row of images
I'm trying to work out how to make a row of images responsive to the window width. So far I have:

```<code><div class="image-slider">
  <div><img src="/img1.jpg"></div>
  <div><img src="/img2.jpg"></div>
  <div><img src="/img3.jpg"></div>
  <div><img src="/img4.jpg"></div>
  <div><img src="/img5.jpg"></div>
</div>
</code>```

and...

```<code>.image-slider {
  display: flex;
  overflow-y: scroll;
}

.image-slider div {
  flex: 1;
  margin: 5px
}

.image-slider div img {
  width: 100%;
  height: auto;
  min-width: 125px;
}
</code>```

This works nicely but what I want now is to make the fifth image disappear when the window is less than 880px and have the remaining four images resize to take up the remaining space.

I've tried adding a wide-only class to the fifth div tag:

```<code><div class="wide-only"><img src="/img5.jpg"></div>
</code>```

and then added a few media rules as shown below but it isn't quite working:

```<code>.image-slider div img.wide-only {
  display:none;
}

@media(min-width:880px) {
  .image-slider div img.wide-only {
    flex: 1 /* not sure what this should be - tried display: flex too */
  }
}
</code>```

答:
If you want to avoid adding additional classes in your html markup you can accomplish this with the nth-child pseudo selector and keep your markup cleaner and more maintainable.

.image-slider div:nth-child(n+5); is going to match the 5th, 6th, and so on child divs of image slider.

As an example below there are two of your 'sliders' one containing 5 elements and one containing 9 elements. Below 880px it will only show 4.  Above that all will show.

An approach like this is more scalable because you can simply add additional media queries with a higher nth-child value, for instance if you wanted to show 6 at 1024 or something, 8 at 1280, etc.  And you don't have to edit your HTML and your CSS to do it.

You'll notice I also reversed the media query to use max-width, so that we start with small screens, and improve the experience as they get larger.  Sort of a mobile first approach.

(Obviously, view the snippet full screen)

.image-slider {
  display: flex;
  margin-bottom: 1rem;
}

.image-slider div {
  flex: 1;
  margin: 3px;
}

.image-slider div img {
  width: auto;
  max-width: 100%;
}

@media(max-width:879px) {
  .image-slider div:nth-child(n+5) {
    display: none;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="image-slider">
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
</div>

<div class="image-slider">
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Title: How to make a responsive row of images

Body:
I'm trying to work out how to make a row of images responsive to the window width. So far I have:

and...

.image-slider {
  display: flex;
  overflow-y: scroll;
}

.image-slider div {
  flex: 1;
  margin: 5px
}

.image-slider div img {
  width: 100%;
  height: auto;
  min-width: 125px;
}

This works nicely but what I want now is to make the fifth image disappear when the window is less than 880px and have the remaining four images resize to take up the remaining space.

I've tried adding a wide-only class to the fifth div tag:

and then added a few media rules as shown below but it isn't quite working:

.image-slider div img.wide-only {
  display:none;
}

@media(min-width:880px) {
  .image-slider div img.wide-only {
    flex: 1 /* not sure what this should be - tried display: flex too */
  }
}

Body:
If you want to avoid adding additional classes in your html markup you can accomplish this with the nth-child pseudo selector and keep your markup cleaner and more maintainable.

.image-slider div:nth-child(n+5); is going to match the 5th, 6th, and so on child divs of image slider.

As an example below there are two of your 'sliders' one containing 5 elements and one containing 9 elements. Below 880px it will only show 4.  Above that all will show.

An approach like this is more scalable because you can simply add additional media queries with a higher nth-child value, for instance if you wanted to show 6 at 1024 or something, 8 at 1280, etc.  And you don't have to edit your HTML and your CSS to do it.

You'll notice I also reversed the media query to use max-width, so that we start with small screens, and improve the experience as they get larger.  Sort of a mobile first approach.

(Obviously, view the snippet full screen)

.image-slider {
  display: flex;
  margin-bottom: 1rem;
}

.image-slider div {
  flex: 1;
  margin: 3px;
}

.image-slider div img {
  width: auto;
  max-width: 100%;
}

@media(max-width:879px) {
  .image-slider div:nth-child(n+5) {
    display: none;
  }
}

<div class="image-slider">
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
</div>

<div class="image-slider">
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
  <div><img src="https://lorempixel.com/400/400/"></div>
</div>


问:
How to submit slider value when user change it's value, without any buttons?
I'm trying to get a sphere floater to answer to my web page as soon as the user releases a slider, just as in a remote controller. However, with my little to no experience in HTML, I was not able to come up with a solution like "if slider's value changes, post new value (do what the submit button does)", as I probably could on something like C++ or Python.

Right now, my HTML code is as follows:

```<code><!DOCTYPE html>
<html>
<style>
#slidecontainer {
    width: 100%;
}

.slider {
    -webkit-appearance: none;
    -webkit-transform: rotate(270deg);
    width: 250px;
    height: 10px;
  position:absolute;
    top:50%;
    left:50%;
    left:30px;
    top:300px;
    background: #d3d3d3;
    outline: none;
    opacity: 0.7;
    -webkit-transition: .2s;
    transition: opacity .2s;
}

}
</style>
<body>
<h1 style="color:blue;">Floating spheres</h1>
<p>Use slider to change sphere's height.</p>

<FORM action="/" method="post">
<P>
<input type="range" name="POT" min="0" max="100" value="50" class="slider" id="myRange">
<p>Power: <span id="demo"></span>%</p><br>
<INPUT type="submit" name="Send">
</P>
</FORM>

<script>
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value;

slider.oninput = function() {
  output.innerHTML = this.value;
}

</script>
</body>
</html>
</code>```

EDIT:

I don't have much time to go deeper into HTML right now, so straight forward answers are much appreciated.

I want to change the value of "myRange".

答:
You can accomplish this by using the onmouseup event.  This one is triggered when the user releases the mouse over your slider, meaning it is triggered when their done sliding it.  From there, you can have it run the submit function. I added an id attribute to the form, but you can navigate to it via relative selectors from your slider (but that is more messy).

var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value;

slider.oninput = function() {
  output.innerHTML = this.value;
}

slider.onmouseup = function () {
  document.getElementById("form").submit();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#slidecontainer {
    width: 100%;
}

.slider {
    -webkit-appearance: none;
    -webkit-transform: rotate(270deg);
    width: 250px;
    height: 10px;
  position:absolute;
    top:50%;
    left:50%;
    left:30px;
    top:300px;
    background: #d3d3d3;
    outline: none;
    opacity: 0.7;
    -webkit-transition: .2s;
    transition: opacity .2s;
}

}</code>```

Floating spheres

Use slider to change sphere's height.

<FORM action="/" method="post" id="form">

<input type="range" name="POT" min="0" max="100" value="50" class="slider" id="myRange">

Power: %

<INPUT type="submit" name="Send">

</FORM>```

Body:
I'm trying to get a sphere floater to answer to my web page as soon as the user releases a slider, just as in a remote controller. However, with my little to no experience in HTML, I was not able to come up with a solution like "if slider's value changes, post new value (do what the submit button does)", as I probably could on something like C++ or Python.

Right now, my HTML code is as follows:

<!DOCTYPE html>

Floating spheres

Use slider to change sphere's height.

<FORM action="/" method="post">

<input type="range" name="POT" min="0" max="100" value="50" class="slider" id="myRange">

Power: %

<INPUT type="submit" name="Send">

</FORM>

EDIT:

I don't have much time to go deeper into HTML right now, so straight forward answers are much appreciated.

I want to change the value of "myRange".

Body:
You can accomplish this by using the onmouseup event.  This one is triggered when the user releases the mouse over your slider, meaning it is triggered when their done sliding it.  From there, you can have it run the submit function. I added an id attribute to the form, but you can navigate to it via relative selectors from your slider (but that is more messy).

var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value;

slider.oninput = function() {
  output.innerHTML = this.value;
}

slider.onmouseup = function () {
  document.getElementById("form").submit();
}

#slidecontainer {
    width: 100%;
}

.slider {
    -webkit-appearance: none;
    -webkit-transform: rotate(270deg);
    width: 250px;
    height: 10px;
  position:absolute;
    top:50%;
    left:50%;
    left:30px;
    top:300px;
    background: #d3d3d3;
    outline: none;
    opacity: 0.7;
    -webkit-transition: .2s;
    transition: opacity .2s;
}

}

<h1 style="color:blue;">Floating spheres</h1>
<p>Use slider to change sphere's height.</p>

<FORM action="/" method="post" id="form">
<P>
<input type="range" name="POT" min="0" max="100" value="50" class="slider" id="myRange">
<p>Power: <span id="demo"></span>%</p><br>
<INPUT type="submit" name="Send">
</P>
</FORM>


问:
React-router scroll to top when back button is clicked
I was able to solve the scroll position problem in react router by creating a method

```<code> scrollToTop() {
   window.scrollTo(0, 0);
}
</code>```

then applying it to a button with

```<code>onClick={scrollToTop}
</code>```

This works for links but this doesnt work when the back button is clicked. How can I make it also work for the back button?

答:
I created a new component to do this function.

ScrollToTop.jsx

```<code>   import React, { Component } from 'react';
    import {withRouter} from 'react-router';
    import $ from 'jquery'

    class ScrollToTop extends Component {

      componentDidUpdate(prevProps) {
        if (this.props.location.pathname !== prevProps.location.pathname) {
         $('html,body').animate({scrollTop:0},'slow');
         return false;
        }
      }
      render() {
        return (
                 this.props.children

            )
      }
    }

    export default withRouter(ScrollToTop)
</code>```

Add this component on the root of your react app

```<code>index.js

    import React from 'react'
    import  ReactDOM from 'react-dom'
    import App from './jsx/App.jsx'
    import {browserHistory} from 'react-router'
    import {HashRouter as Routers} from 'react-router-dom'
    import ScrollToTop from './jsx/ScrollToTop.jsx'
    import {Provider} from 'react-redux';
    import {store} from './redux/store'
    ReactDOM.render((
         <Provider store={store}>
           <Routers>
           <ScrollToTop>
                <App />
           </ScrollToTop>
            </Routers>
            </Provider>
        ),document.getElementById('main-container'))
</code>```

Body:
I was able to solve the scroll position problem in react router by creating a method

 scrollToTop() {
   window.scrollTo(0, 0);
}

then applying it to a button with

onClick={scrollToTop}

This works for links but this doesnt work when the back button is clicked. How can I make it also work for the back button?

Body:
I created a new component to do this function.

ScrollToTop.jsx

   import React, { Component } from 'react';
    import {withRouter} from 'react-router';
    import $ from 'jquery'

    class ScrollToTop extends Component {

      componentDidUpdate(prevProps) {
        if (this.props.location.pathname !== prevProps.location.pathname) {
         $('html,body').animate({scrollTop:0},'slow');
         return false;
        }
      }
      render() {
        return (
                 this.props.children

            )
      }
    }

    export default withRouter(ScrollToTop)

Add this component on the root of your react app

index.js

    import React from 'react'
    import  ReactDOM from 'react-dom'
    import App from './jsx/App.jsx'
    import {browserHistory} from 'react-router'
    import {HashRouter as Routers} from 'react-router-dom'
    import ScrollToTop from './jsx/ScrollToTop.jsx'
    import {Provider} from 'react-redux';
    import {store} from './redux/store'
    ReactDOM.render((
         <Provider store={store}>
           <Routers>
           <ScrollToTop>
                <App />
           </ScrollToTop>
            </Routers>
            </Provider>
        ),document.getElementById('main-container'))


问:
Accessing the front facing camera. iPhone/iPod 4
Hey I was wondering how I can access the front facing camera. Maybe there's some guide for it?
But I don't want all buttons etc. I just want to access the from facing camera, I don't ant the button to take a photo or anything like that.</p>

答:
You can access the front facing camera like:

```<code>picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
</code>```

Check out the UIImagePickerController Class Reference

ContentLicense: CC BY-SA 2.5

Body:
You can access the front facing camera like:

picker.cameraDevice = UIImagePickerControllerCameraDeviceFront;

Check out the UIImagePickerController Class Reference


问:
How to increment a number in a string?
I want to increment a number in a string.

My model:

```<code>public partial class updown
{
    public int id { get; set; }
    public string number { get; set; }
}
</code>```

My controller:

```<code>[HttpPost]
public ActionResult Index(updown viewModel)
{
    var lastPO = db.updowns
                   .OrderByDescending(o => o.number)
                   .Select(m => m.number)
                   .FirstOrDefault() ?? "00001";

    item.number = lastPO++; // I get an error on this line
    db.updowns.Add(item);
    db.SaveChanges();

    return View(viewModel);
}
</code>```

The error:

Operator '++' cannot be applied to operand of type 'string'

Expected result:

```<code>item.number // "00002"
</code>```

Update

Based on the now-deleted comments, I have:

```<code>[HttpPost]
public ActionResult Index(updown viewModel)
{
    var s = db.updowns
              .OrderByDescending(o => o.number)
              .Select(m => m.number)
              .FirstOrDefault() ?? "00001/S2";

    var lastPO = Convert.ToInt32(s.Substring(s.Length - 5 - 3, s.Length - 3)); // *
    item.number = "EMOC-" + (++lastPO).ToString("00000");
    db.updowns.Add(item);
    db.SaveChanges();

    return View(viewModel);
}
</code>```

Expected result:

```<code>item.number // "EMOC-00002/S2"
</code>```

But I get an error on the line marked // * when I run it the second time.

答:
Expected result:

```<code>item.number // "EMOC-00002/S2"
</code>```

You need + "/S2" here:

```<code>item.number = "EMOC-" + (++lastPO).ToString("00000") + "/S2";
</code>```

Explanation

What happens when you ran previous code the second time is that var s = "EMOC-00002" so s.Substring(s.Length - 5 - 3, s.Length - 3) gives "OC-00" instead of "00002" string, which Convert.ToInt32() cannot handle.

Title: How to increment a number in a string?

Body:
I want to increment a number in a string.

My model:

public partial class updown
{
    public int id { get; set; }
    public string number { get; set; }
}

My controller:

[HttpPost]
public ActionResult Index(updown viewModel)
{
    var lastPO = db.updowns
                   .OrderByDescending(o => o.number)
                   .Select(m => m.number)
                   .FirstOrDefault() ?? "00001";

    item.number = lastPO++; // I get an error on this line
    db.updowns.Add(item);
    db.SaveChanges();

    return View(viewModel);
}

The error:

Operator '++' cannot be applied to operand of type 'string'

Expected result:

item.number // "00002"

Update

Based on the now-deleted comments, I have:

[HttpPost]
public ActionResult Index(updown viewModel)
{
    var s = db.updowns
              .OrderByDescending(o => o.number)
              .Select(m => m.number)
              .FirstOrDefault() ?? "00001/S2";

    var lastPO = Convert.ToInt32(s.Substring(s.Length - 5 - 3, s.Length - 3)); // *
    item.number = "EMOC-" + (++lastPO).ToString("00000");
    db.updowns.Add(item);
    db.SaveChanges();

    return View(viewModel);
}

Expected result:

item.number // "EMOC-00002/S2"

But I get an error on the line marked // * when I run it the second time.

Body:
Expected result:

item.number // "EMOC-00002/S2"

You need + "/S2" here:

item.number = "EMOC-" + (++lastPO).ToString("00000") + "/S2";

Explanation

What happens when you ran previous code the second time is that var s = "EMOC-00002" so s.Substring(s.Length - 5 - 3, s.Length - 3) gives "OC-00" instead of "00002" string, which Convert.ToInt32() cannot handle.


问:
If N is positive then output all values from N down to and excluding 0. If N is negative, then output every value from N up to and excluding 0
As I said before I'm a beginner trying to learn Python in a college course, but what they teach us, doesn't always apply to the real world, and when I try to research a solution, there's nothing to be found. Anyway my latest problem is:

```<code>This is a tricky challenge for you.

We will pass in a value N. N can be positive or negative.

If N is positive then output all values from N down to and excluding 0.
If N is negative, then output every value from N up to and excluding 0.

and the starting code is:

# Get N from the command line
import sys
N = int(sys.argv[1])

# Your code goes here
counter = 0
while counter <= N:
print(counter)
counter = counter + 1
elif counter >= N:
print(N+counter)
counter = counter - 1

My solution produced an error:

SyntaxError: unexpected EOF while parsing
There is an error is your program.
</code>```

And I honestly don't know where to start, as our textbook doesn't cover these challenges. Thanks in advance for any assistance rendered in this matter. BTW my code is inputted in Codio, and must pass in Codio's IDE.

答:
The main problem here is that you have a while and an elif. Elif is used with other if statements.

For example:

```<code>if condition:
    do something
elif condtion:
    do something else
else:
    do something as a "last resort"
</code>```

I think you are trying to do this:

```<code>#Checks To See if N is Positive
if N > 0:
    #Sets counter to 1
    counter = 1
    #Iterates Thru Each Num from 1 To N-1
    while counter < N:
        print counter
        #Increments Counter
        counter += 1
#Checks To See If N Is Negative
elif N < 0:
    #Sets Counter to -1
    counter = -1
    #Iterates Thru Each Num From -1 To N-1
    while counter > N:
        print counter
        #Decrements Counter
        counter -= 1
</code>```

A couple final things:

If you want to learn what you consider "real world" programming, then I suggest that you look at some online resources such as https://www.codecademy.com/ or looking through the docs.

When posting on Stack Overflow, please explain your question/problem thoroughly

When inputting your code on Stack Overflow, make sure that it is properly formatted (e.g. indentations), as they make decoding larger programs much easier.

Stack Overflow is not a "do my homework for me" site

Body:
As I said before I'm a beginner trying to learn Python in a college course, but what they teach us, doesn't always apply to the real world, and when I try to research a solution, there's nothing to be found. Anyway my latest problem is:

This is a tricky challenge for you.

We will pass in a value N. N can be positive or negative.

If N is positive then output all values from N down to and excluding 0.
If N is negative, then output every value from N up to and excluding 0.

and the starting code is:

# Get N from the command line
import sys
N = int(sys.argv[1])

# Your code goes here
counter = 0
while counter <= N:
print(counter)
counter = counter + 1
elif counter >= N:
print(N+counter)
counter = counter - 1

My solution produced an error:

SyntaxError: unexpected EOF while parsing
There is an error is your program.

And I honestly don't know where to start, as our textbook doesn't cover these challenges. Thanks in advance for any assistance rendered in this matter. BTW my code is inputted in Codio, and must pass in Codio's IDE.

Body:
The main problem here is that you have a while and an elif. Elif is used with other if statements.

For example:

if condition:
    do something
elif condtion:
    do something else
else:
    do something as a "last resort"

I think you are trying to do this:

#Checks To See if N is Positive
if N > 0:
    #Sets counter to 1
    counter = 1
    #Iterates Thru Each Num from 1 To N-1
    while counter < N:
        print counter
        #Increments Counter
        counter += 1
#Checks To See If N Is Negative
elif N < 0:
    #Sets Counter to -1
    counter = -1
    #Iterates Thru Each Num From -1 To N-1
    while counter > N:
        print counter
        #Decrements Counter
        counter -= 1

A couple final things:

If you want to learn what you consider "real world" programming, then I suggest that you look at some online resources such as https://www.codecademy.com/ or looking through the docs.

When posting on Stack Overflow, please explain your question/problem thoroughly

When inputting your code on Stack Overflow, make sure that it is properly formatted (e.g. indentations), as they make decoding larger programs much easier.

Stack Overflow is not a "do my homework for me" site


问:
openCV3: Not getting the expected output on morphologically transforming an image in opencv
I am trying to do top hat morphological transformation to an image but not getting the expected output for some reason.

```<code># Top Hat: difference between input image and opening
kernel = np.ones((5,5),np.float32)/25
tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel)
plt.subplot(121),plt.imshow(img, cmap='gray'),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(tophat, cmap='gray'),plt.title('Top Hat')
plt.xticks([]), plt.yticks([])
plt.show()
</code>```

What is expected

What I am getting

EDIT: Added the kernel.

答:
```<code>kernel = cv2.getStructuringElement(cv2.MORPH_RECT, ksize=(9,9))
tophat = cv2.morphologyEx(image, cv2.MORPH_TOPHAT, kernel)
</code>```

Edit:

For details please read the following:

https://docs.opencv.org/3.3.1/d9/d61/tutorial_py_morphological_ops.html

https://docs.opencv.org/3.3.1/d4/d86/group__imgproc__filter.html#gac342a1bb6eabf6f55c803b09268e36dc

Iterations vs. Kernel Size in Morphological Operations (OpenCV)

Body:
I am trying to do top hat morphological transformation to an image but not getting the expected output for some reason.

# Top Hat: difference between input image and opening
kernel = np.ones((5,5),np.float32)/25
tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel)
plt.subplot(121),plt.imshow(img, cmap='gray'),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(tophat, cmap='gray'),plt.title('Top Hat')
plt.xticks([]), plt.yticks([])
plt.show()

What is expected

What I am getting

EDIT: Added the kernel.

Body:
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, ksize=(9,9))
tophat = cv2.morphologyEx(image, cv2.MORPH_TOPHAT, kernel)

Edit:

For details please read the following:

https://docs.opencv.org/3.3.1/d9/d61/tutorial_py_morphological_ops.html

https://docs.opencv.org/3.3.1/d4/d86/group__imgproc__filter.html#gac342a1bb6eabf6f55c803b09268e36dc

Iterations vs. Kernel Size in Morphological Operations (OpenCV)


问:
Mongoose find() not working with $not query
Here is my find request:

```<code>Recipe.find({'author.id': {$not: {user}}}
</code>```

Here is the documentation: https://docs.mongodb.com/manual/reference/operator/query/not/index.html

Here is the error:

```<code>Error: Can't use $not with ObjectId.
</code>```

I want to find all Recipes that are not authored by the current user. The arguments are working fine, so that's not the issue. There must be a way to do this, or am I doing something wrong?

答:
You should use $ne

```<code>Recipe.find({ "author.id": { "$ne": user }});
</code>```

Body:
Here is my find request:

Recipe.find({'author.id': {$not: {user}}}

Here is the documentation: https://docs.mongodb.com/manual/reference/operator/query/not/index.html

Here is the error:

Error: Can't use $not with ObjectId.

I want to find all Recipes that are not authored by the current user. The arguments are working fine, so that's not the issue. There must be a way to do this, or am I doing something wrong?

Body:
You should use $ne

Recipe.find({ "author.id": { "$ne": user }});


问:
azure interactive shell history
I am wondering if there is a command that gives me history of the commands I've used inside azure interactive shell. Well, I can press up and down arrow to circle through my recent commands, but I'd like to see them all. Just to clarify: I know how to use "history" in the bash, with grep and so forth; I am running Linux Subsystem on Windows.</p>

答:
Currently, Azure Cli 2.0 does not support this. If you use bash shell, you could use command history to check history command. Like below:

```<code>history| grep az|grep -v "grep"
</code>```

Also, your suggestion is a good idea, you could give feedback to developer with command az feedback.

Title: azure interactive shell history

Body:
Currently, Azure Cli 2.0 does not support this. If you use bash shell, you could use command history to check history command. Like below:

history| grep az|grep -v "grep"

Also, your suggestion is a good idea, you could give feedback to developer with command az feedback.


问:
PHP Regex to allow only one decimal and one percentage sign
Hello I'm trying to create a regex to validate a percentage value but I only want to allow one decimal after at least one digit and and one percentage sign as the last character. For example the following values below should be valid:

```<code>8%

10%

12.60%

7.750%
</code>```

So far this is my regex code for my php function.

```<code>if(!preg_match('/[^0-9.%]/', $string)){
    return true;
} else {
    return false;
}
</code>```

答:
This can be accomplished by making your regex more specific:

```<code>^\d+(?:\.\d+)?%$
</code>```

Try it out on regex101:

https://regex101.com/r/D9JN3e/3

Body:
Hello I'm trying to create a regex to validate a percentage value but I only want to allow one decimal after at least one digit and and one percentage sign as the last character. For example the following values below should be valid:

8%

10%

12.60%

7.750%

So far this is my regex code for my php function.

if(!preg_match('/[^0-9.%]/', $string)){
    return true;
} else {
    return false;
}

Body:
This can be accomplished by making your regex more specific:

^\d+(?:\.\d+)?%$

Try it out on regex101:

https://regex101.com/r/D9JN3e/3


问:
Inserting data in sql from RadGrid with check box
I am trying to insert data from my radGrid that has some data to my sql. in my rad grid i also have a check box column so i want the checked rows to be inserted in my db. i am using the code below but gives me this error:
Error 30  'Telerik.Web.UI.RadGrid' does not contain a definition for 'Rows' and no extension method 'Rows' accepting a first argument of type 'Telerik.Web.UI.RadGrid' could be found (are you missing a using directive or an assembly reference?)   any idea where i am doing wrong???

```<code>  protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.BindGrid();
        }
    }

    private void BindGrid()
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT [ReportId], [Report], [IsSelected] FROM Hobbies"))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataTable dt = new DataTable())
                    {
                        sda.Fill(dt);
                        RadGrid1.DataSource = dt;
                        RadGrid1.DataBind();
                    }
                }
            }
        }
    }

    protected void Rows()
    {

    }
</code>```

protected void Save2_Click(object sender, EventArgs e)
{

```<code>            try
            {

                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Rights"].ConnectionString);

                string insert = "insert into Rights(Name,Mbiemri,Gjinia,Departamenti,Mosha,IntRights,Transferta,Depozita,Rapore) values (@Name,@Mbiemri,@Gjinia,@Departamenti,@Mosha,@IntRights,@Transferta,@Depozita,@Rapore)";
                SqlCommand cnd = new SqlCommand(insert, con);
                con.Open();
                foreach (GridViewRow row in RadGrid1.Rows)
                {
                    //Get the HobbyId from the DataKey property.
                    int ReportID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Values[0]);

                    //Get the checked value of the CheckBox.
                    bool isSelected = (row.FindControl("chkSelect") as CheckBox).Checked;

                    //Save to database
                    cmd.Parameters.Clear();
                    cmd.Parameters.AddWithValue("@ReportId", ReportID);
                    cmd.Parameters.AddWithValue("@IsSelected", isSelected);
                    cmd.ExecuteNonQuery();
                }
                cnd.Parameters.AddWithValue("@Name", TextBox1.Text);
                cnd.Parameters.AddWithValue("@Mbiemri", TextBox2.Text);
                cnd.Parameters.AddWithValue("@Gjinia", RadioButtonList1.SelectedValue);
                cnd.Parameters.AddWithValue("@Departamenti", SelectDepartament.SelectedItem.Text);
                cnd.Parameters.AddWithValue("@Mosha", RadDropDownList1.SelectedItem.Text);
                cnd.Parameters.AddWithValue("@IntRights", RadDropDownList2.SelectedItem.Text);
                cnd.Parameters.AddWithValue("@Transferta", TransfertaBtn.SelectedValue);
                cnd.Parameters.AddWithValue("@Depozita", DepoziteBtn.SelectedValue);

                cnd.ExecuteNonQuery();

                Response.Redirect("Home.aspx");

                con.Close();

            }

            catch (Exception ex)
            {

            }

telerik:RadGrid ID="RadGrid1"
                       runat="server" AllowMultiRowSelection="True" AllowPaging="True"  DataSourceID="SqlDataSource1" GridLines="Both" PageSize="5" >
                       <GroupingSettings CollapseAllTooltip="Collapse all groups" />
                       <ClientSettings>
                           <Selecting AllowRowSelect="True" />
                       </ClientSettings>
                       <MasterTableView>
                           <Columns>
                               <asp:TemplateField>
                               <ItemTemplate>
                                    <asp:CheckBox ID="chkSelect" runat="server" Checked='<%# Eval("IsSelected") %>' />
                               </ItemTemplate>
                                   </asp:TemplateField>
                               <asp:BoundField DataField="Report" HeaderText="Report" ItemStyle-Width="150px" />

                               </telerik:GridTemplateColumn>
                           </Columns>
                       </MasterTableView>
                   </telerik:RadGrid>

                   <asp:SqlDataSource ID="SqlDataSource1" runat="server"
                        ConnectionString="<%$ ConnectionStrings:AdventureWorks2014ConnectionString %>" SelectCommand="SELECT [ReportID], [Report] FROM [Report]"></asp:SqlDataSource>
                   <br />
</code>```

答:
To access the rows, loop through its DataItems. More about Accessing Cells and Rows

protected void Button1_Click(object sender, EventArgs e)
{
    foreach (GridDataItem row in RadGrid1.Items)
    {
        string rowValue = row["ColumnUniqueName"].Text;
    }
}
```

<p>Better approach would be to create a method that takes few parameters to Update the SQL database. Once done, call it inside the ItemDataBound event of RadGrid (Differences Between ItemCreated and ItemDataBound). In this event you can access the row, its cells, get the necessary value and update the database row-by-row. </p>

<pre class="lang-cs prettyprint-override"><code>bool IsClicked = false;
protected void Button1_Click(object sender, EventArgs e)
{
    IsClicked = true;
    RadGrid1.Rebind();
}

protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
    if (IsClicked && e.Item is GridDataItem)
    {
        updateDatabase(((GridDataItem)e.Item)["ColumnUniqueName"].Text);
    }
}

protected void updateDatabase(string field)
{
    // update SQL
}
</code>```

Body:
I am trying to insert data from my radGrid that has some data to my sql. in my rad grid i also have a check box column so i want the checked rows to be inserted in my db. i am using the code below but gives me this error:
Error 30  'Telerik.Web.UI.RadGrid' does not contain a definition for 'Rows' and no extension method 'Rows' accepting a first argument of type 'Telerik.Web.UI.RadGrid' could be found (are you missing a using directive or an assembly reference?)   any idea where i am doing wrong???

  protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.BindGrid();
        }
    }

    private void BindGrid()
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT [ReportId], [Report], [IsSelected] FROM Hobbies"))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataTable dt = new DataTable())
                    {
                        sda.Fill(dt);
                        RadGrid1.DataSource = dt;
                        RadGrid1.DataBind();
                    }
                }
            }
        }
    }

    protected void Rows()
    {

    }

protected void Save2_Click(object sender, EventArgs e)
{

            try
            {

                SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Rights"].ConnectionString);

                string insert = "insert into Rights(Name,Mbiemri,Gjinia,Departamenti,Mosha,IntRights,Transferta,Depozita,Rapore) values (@Name,@Mbiemri,@Gjinia,@Departamenti,@Mosha,@IntRights,@Transferta,@Depozita,@Rapore)";
                SqlCommand cnd = new SqlCommand(insert, con);
                con.Open();
                foreach (GridViewRow row in RadGrid1.Rows)
                {
                    //Get the HobbyId from the DataKey property.
                    int ReportID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Values[0]);

                    //Get the checked value of the CheckBox.
                    bool isSelected = (row.FindControl("chkSelect") as CheckBox).Checked;

                    //Save to database
                    cmd.Parameters.Clear();
                    cmd.Parameters.AddWithValue("@ReportId", ReportID);
                    cmd.Parameters.AddWithValue("@IsSelected", isSelected);
                    cmd.ExecuteNonQuery();
                }
                cnd.Parameters.AddWithValue("@Name", TextBox1.Text);
                cnd.Parameters.AddWithValue("@Mbiemri", TextBox2.Text);
                cnd.Parameters.AddWithValue("@Gjinia", RadioButtonList1.SelectedValue);
                cnd.Parameters.AddWithValue("@Departamenti", SelectDepartament.SelectedItem.Text);
                cnd.Parameters.AddWithValue("@Mosha", RadDropDownList1.SelectedItem.Text);
                cnd.Parameters.AddWithValue("@IntRights", RadDropDownList2.SelectedItem.Text);
                cnd.Parameters.AddWithValue("@Transferta", TransfertaBtn.SelectedValue);
                cnd.Parameters.AddWithValue("@Depozita", DepoziteBtn.SelectedValue);

                cnd.ExecuteNonQuery();

                Response.Redirect("Home.aspx");

                con.Close();

            }

            catch (Exception ex)
            {

            }

telerik:RadGrid ID="RadGrid1"
                       runat="server" AllowMultiRowSelection="True" AllowPaging="True"  DataSourceID="SqlDataSource1" GridLines="Both" PageSize="5" >
                       <GroupingSettings CollapseAllTooltip="Collapse all groups" />
                       <ClientSettings>
                           <Selecting AllowRowSelect="True" />
                       </ClientSettings>
                       <MasterTableView>
                           <Columns>
                               <asp:TemplateField>
                               <ItemTemplate>
                                    <asp:CheckBox ID="chkSelect" runat="server" Checked='<%# Eval("IsSelected") %>' />
                               </ItemTemplate>
                                   </asp:TemplateField>
                               <asp:BoundField DataField="Report" HeaderText="Report" ItemStyle-Width="150px" />

                               </telerik:GridTemplateColumn>
                           </Columns>
                       </MasterTableView>
                   </telerik:RadGrid>

                   <asp:SqlDataSource ID="SqlDataSource1" runat="server"
                        ConnectionString="<%$ ConnectionStrings:AdventureWorks2014ConnectionString %>" SelectCommand="SELECT [ReportID], [Report] FROM [Report]"></asp:SqlDataSource>

Body:
To access the rows, loop through its DataItems. More about Accessing Cells and Rows

protected void Button1_Click(object sender, EventArgs e)
{
    foreach (GridDataItem row in RadGrid1.Items)
    {
        string rowValue = row["ColumnUniqueName"].Text;
    }
}

Better approach would be to create a method that takes few parameters to Update the SQL database. Once done, call it inside the ItemDataBound event of RadGrid (Differences Between ItemCreated and ItemDataBound). In this event you can access the row, its cells, get the necessary value and update the database row-by-row.

bool IsClicked = false;
protected void Button1_Click(object sender, EventArgs e)
{
    IsClicked = true;
    RadGrid1.Rebind();
}

protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
    if (IsClicked && e.Item is GridDataItem)
    {
        updateDatabase(((GridDataItem)e.Item)["ColumnUniqueName"].Text);
    }
}

protected void updateDatabase(string field)
{
    // update SQL
}


问:
UI Freezes Even with Task & Platform.runLater (Full Example)
I've read similar questions but my UI is still freezing when I add many nodes to a VBox. I've provided a fully functional program below which demonstrates the problem clearly.

After 4 seconds, the ProgressIndicator freezes as 5000 nodes are added to the VBox. This is an excessive amount used to demonstrate the JavaFX thread freezing despite using Task (for non-UI work) and then Platform.runLater() for adding the nodes to the scene.

In my actual application, instead of adding blank TitlePanes I'm adding a TitlePane obtained from an FXML file via new FXMLLoader(), and the resulting loader.load() then initializes the associated controller, which in turn initializes some moderately demanding computations - which are being performed on the JavaFX thread! So even though I'm adding closer to 250 nodes, the UI still freezes when the Platform.runLater is eventually used. How do I keep the ProgressIndicator from freezing until the red background is shown?

Full Example:

```<code>import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Accordion;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TitledPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.util.Timer;
import java.util.TimerTask;

public class FreezingUI extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {

        VBox mainBox = new VBox();
        mainBox.setPrefHeight(800);
        mainBox.setStyle("-fx-background-color: #f1f1f1; -fx-alignment: center");
        Label label = new Label();
        label.setMinHeight(50);
        label.setStyle("-fx-font-size: 24px; -fx-text-fill: #515151");

        ProgressIndicator progressIndicator = new ProgressIndicator(ProgressIndicator.INDETERMINATE_PROGRESS);
        mainBox.getChildren().addAll(progressIndicator, label);

        Scene scene = new Scene(mainBox, 500, 800);
        primaryStage.setScene(scene);
        primaryStage.show();

        Timer timer = new Timer();
        TimerTask task = new TimerTask(){
            private int i = 4;
            public void run(){
                if (i >= 0) {
                    Platform.runLater(()->{
                        label.setText("Freezing in " + i--);
                    });
                }else{
                    addNodesToUI(mainBox);
                    timer.cancel();
                }
            }
        };
        timer.scheduleAtFixedRate(task, 0, 1000);
    }

    private void addNodesToUI(VBox mainBox) {
        final int[] i = {0};
        Platform.runLater(() -> {
            Accordion temp = new Accordion();
            mainBox.getChildren().add(temp);
            while (i[0] < 5000) {

                TitledPane tp = new TitledPane();
                tp.setPrefWidth(300);
                tp.setPrefHeight(12);
                tp.setPadding(new Insets(10));
                tp.setStyle("-fx-background-color: red;");
                temp.getPanes().add(tp);
                i[0]++;

            }

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

答:
This is happening because you are asking the UI thread to do a big bunch of things in one big lump. There is no way for the UI thread to exit the while loop until all 5000 nodes are created and added to the scene.

```<code>private void addNodesToUI(VBox mainBox) {
    final int[] i = {0};

    Accordion temp = new Accordion();

    Platform.runLater(() -> {
        mainBox.getChildren().add(temp);
    });

    while (i[0] < 5000) {
        TitledPane tp = new TitledPane();
        tp.setPrefWidth(300);
        tp.setPrefHeight(12);
        tp.setPadding(new Insets(10));
        tp.setStyle("-fx-background-color: red;");

        i[0]++;

        Platform.runLater(() -> {
            temp.getPanes().add(tp);
        });
    }
}
</code>```

This will allow your nodes to be created in small batches. This way, the UI thread can attempt to render the UI while the nodes are added progressively.

For your FXML case, you can create and load the FXML in another thread. You only need to be in UI thread when you attach a scene branch into the scene. However, I would suspect that would only mitigate the effects, as you are still going to attach a big chunk at one go.

Body:
I've read similar questions but my UI is still freezing when I add many nodes to a VBox. I've provided a fully functional program below which demonstrates the problem clearly.

After 4 seconds, the ProgressIndicator freezes as 5000 nodes are added to the VBox. This is an excessive amount used to demonstrate the JavaFX thread freezing despite using Task (for non-UI work) and then Platform.runLater() for adding the nodes to the scene.

In my actual application, instead of adding blank TitlePanes I'm adding a TitlePane obtained from an FXML file via new FXMLLoader(), and the resulting loader.load() then initializes the associated controller, which in turn initializes some moderately demanding computations - which are being performed on the JavaFX thread! So even though I'm adding closer to 250 nodes, the UI still freezes when the Platform.runLater is eventually used. How do I keep the ProgressIndicator from freezing until the red background is shown?

Full Example:

import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Accordion;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TitledPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.util.Timer;
import java.util.TimerTask;

public class FreezingUI extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {

        VBox mainBox = new VBox();
        mainBox.setPrefHeight(800);
        mainBox.setStyle("-fx-background-color: #f1f1f1; -fx-alignment: center");
        Label label = new Label();
        label.setMinHeight(50);
        label.setStyle("-fx-font-size: 24px; -fx-text-fill: #515151");

        ProgressIndicator progressIndicator = new ProgressIndicator(ProgressIndicator.INDETERMINATE_PROGRESS);
        mainBox.getChildren().addAll(progressIndicator, label);

        Scene scene = new Scene(mainBox, 500, 800);
        primaryStage.setScene(scene);
        primaryStage.show();

        Timer timer = new Timer();
        TimerTask task = new TimerTask(){
            private int i = 4;
            public void run(){
                if (i >= 0) {
                    Platform.runLater(()->{
                        label.setText("Freezing in " + i--);
                    });
                }else{
                    addNodesToUI(mainBox);
                    timer.cancel();
                }
            }
        };
        timer.scheduleAtFixedRate(task, 0, 1000);
    }

    private void addNodesToUI(VBox mainBox) {
        final int[] i = {0};
        Platform.runLater(() -> {
            Accordion temp = new Accordion();
            mainBox.getChildren().add(temp);
            while (i[0] < 5000) {

                TitledPane tp = new TitledPane();
                tp.setPrefWidth(300);
                tp.setPrefHeight(12);
                tp.setPadding(new Insets(10));
                tp.setStyle("-fx-background-color: red;");
                temp.getPanes().add(tp);
                i[0]++;

            }

        });
    }
}

Body:
This is happening because you are asking the UI thread to do a big bunch of things in one big lump. There is no way for the UI thread to exit the while loop until all 5000 nodes are created and added to the scene.

private void addNodesToUI(VBox mainBox) {
    final int[] i = {0};

    Accordion temp = new Accordion();

    Platform.runLater(() -> {
        mainBox.getChildren().add(temp);
    });

    while (i[0] < 5000) {
        TitledPane tp = new TitledPane();
        tp.setPrefWidth(300);
        tp.setPrefHeight(12);
        tp.setPadding(new Insets(10));
        tp.setStyle("-fx-background-color: red;");

        i[0]++;

        Platform.runLater(() -> {
            temp.getPanes().add(tp);
        });
    }
}

This will allow your nodes to be created in small batches. This way, the UI thread can attempt to render the UI while the nodes are added progressively.

For your FXML case, you can create and load the FXML in another thread. You only need to be in UI thread when you attach a scene branch into the scene. However, I would suspect that would only mitigate the effects, as you are still going to attach a big chunk at one go.


问:
C#: How to access an Excel cell?
I am trying to open an Excel file and populate its cells with data? I have done the following coding so far.

Currently I am at this stage with the following code but still I am getting errors:

```<code>Microsoft.Office.Interop.Excel.ApplicationClass appExcel =
                new Microsoft.Office.Interop.Excel.ApplicationClass();
try
{
    // is there already such a file ?
    if (System.IO.File.Exists("C:\\csharp\\errorreport1.xls"))
    {
        // then go and load this into excel
        Microsoft.Office.Interop.Excel.Workbooks.Open(
            "C:\\csharp\\errorreport1.xls", true, false,
            Missing.Value, Missing.Value, Missing.Value, Missing.Value,
            Missing.Value, Missing.Value, Missing.Value, Missing.Value,
            Missing.Value, Missing.Value, Missing.Value, Missing.Value);
    }
    else
    {
        // if not go and create a workbook:
        newWorkbook = appExcel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
        Microsoft.Office.Interop.Excel._Worksheet excelWorksheet =
            (Microsoft.Office.Interop.Excel._Worksheet)
                newWorkBook.Worksheets.get_Item(1);
    }
i++;
j = 1;

j++;
objsheet.Cells(i, j).Value = "Tabelle: " + rs.Fields["Table_Name"];
j++;
objsheet.Cells(i, j).Value = "kombinationsschluessel:FALL "
                                + rs3.Fields[1].Value;
j++;
objsheet.Cells(i, j).Value = "Null Value: ";
j++;
objsheet.Cells(i, j).Value = "Updated with 888";
</code>```

These are the top 2 errors I am getting:

```<code>Error 1 An object reference is required for the nonstatic field, method, or
        property 'Microsoft.Office.Interop.Excel.Workbooks.Open(string, object,
        object, object, object, object, object, object, object, object, object,
        object, object, object, object)'

Error 2 The name 'newWorkbook' does not exist in the current context
</code>```

答:
If you are trying to automate Excel, you probably shouldn't be opening a Word document and using the Word automation ;)

Check this out, it should get you started,

http://www.codeproject.com/KB/office/package.aspx

And here is some code. It is taken from some of my code and has a lot of stuff deleted, so it doesn't do anything and may not compile or work exactly, but it should get you going. It is oriented toward reading, but should point you in the right direction.

```<code>Microsoft.Office.Interop.Excel.Worksheet sheet = newWorkbook.ActiveSheet;

if ( sheet != null )
{
    Microsoft.Office.Interop.Excel.Range range = sheet.UsedRange;
    if ( range != null )
    {
        int nRows = usedRange.Rows.Count;
        int nCols = usedRange.Columns.Count;
        foreach ( Microsoft.Office.Interop.Excel.Range row in usedRange.Rows )
        {
            string value = row.Cells[0].FormattedValue as string;
        }
    }
 }
</code>```

You can also do

```<code>Microsoft.Office.Interop.Excel.Sheets sheets = newWorkbook.ExcelSheets;

if ( sheets != null )
{
     foreach ( Microsoft.Office.Interop.Excel.Worksheet sheet in sheets )
     {
          // Do Stuff
     }
}
</code>```

And if you need to insert rows/columns

```<code>// Inserts a new row at the beginning of the sheet
Microsoft.Office.Interop.Excel.Range a1 = sheet.get_Range( "A1", Type.Missing );
a1.EntireRow.Insert( Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown, Type.Missing );
</code>```

OwnerDisplayName: tksy

Title: C#: How to access an Excel cell?

Body:
I am trying to open an Excel file and populate its cells with data? I have done the following coding so far.

Currently I am at this stage with the following code but still I am getting errors:

Microsoft.Office.Interop.Excel.ApplicationClass appExcel =
                new Microsoft.Office.Interop.Excel.ApplicationClass();
try
{
    // is there already such a file ?
    if (System.IO.File.Exists("C:\\csharp\\errorreport1.xls"))
    {
        // then go and load this into excel
        Microsoft.Office.Interop.Excel.Workbooks.Open(
            "C:\\csharp\\errorreport1.xls", true, false,
            Missing.Value, Missing.Value, Missing.Value, Missing.Value,
            Missing.Value, Missing.Value, Missing.Value, Missing.Value,
            Missing.Value, Missing.Value, Missing.Value, Missing.Value);
    }
    else
    {
        // if not go and create a workbook:
        newWorkbook = appExcel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
        Microsoft.Office.Interop.Excel._Worksheet excelWorksheet =
            (Microsoft.Office.Interop.Excel._Worksheet)
                newWorkBook.Worksheets.get_Item(1);
    }
i++;
j = 1;

j++;
objsheet.Cells(i, j).Value = "Tabelle: " + rs.Fields["Table_Name"];
j++;
objsheet.Cells(i, j).Value = "kombinationsschluessel:FALL "
                                + rs3.Fields[1].Value;
j++;
objsheet.Cells(i, j).Value = "Null Value: ";
j++;
objsheet.Cells(i, j).Value = "Updated with 888";

These are the top 2 errors I am getting:

Error 1 An object reference is required for the nonstatic field, method, or
        property 'Microsoft.Office.Interop.Excel.Workbooks.Open(string, object,
        object, object, object, object, object, object, object, object, object,
        object, object, object, object)'

Error 2 The name 'newWorkbook' does not exist in the current context

LastEditorDisplayName: tksy

Body:
If you are trying to automate Excel, you probably shouldn't be opening a Word document and using the Word automation ;)

Check this out, it should get you started,

http://www.codeproject.com/KB/office/package.aspx

And here is some code. It is taken from some of my code and has a lot of stuff deleted, so it doesn't do anything and may not compile or work exactly, but it should get you going. It is oriented toward reading, but should point you in the right direction.

Microsoft.Office.Interop.Excel.Worksheet sheet = newWorkbook.ActiveSheet;

if ( sheet != null )
{
    Microsoft.Office.Interop.Excel.Range range = sheet.UsedRange;
    if ( range != null )
    {
        int nRows = usedRange.Rows.Count;
        int nCols = usedRange.Columns.Count;
        foreach ( Microsoft.Office.Interop.Excel.Range row in usedRange.Rows )
        {
            string value = row.Cells[0].FormattedValue as string;
        }
    }
 }

You can also do

Microsoft.Office.Interop.Excel.Sheets sheets = newWorkbook.ExcelSheets;

if ( sheets != null )
{
     foreach ( Microsoft.Office.Interop.Excel.Worksheet sheet in sheets )
     {
          // Do Stuff
     }
}

And if you need to insert rows/columns

// Inserts a new row at the beginning of the sheet
Microsoft.Office.Interop.Excel.Range a1 = sheet.get_Range( "A1", Type.Missing );
a1.EntireRow.Insert( Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown, Type.Missing );

OwnerDisplayName: Rob Prouse

LastEditorDisplayName: Rob Prouse


问:
Can/should I use mod_rewrite to change the paths of links on a local Dev environment? (Kohana)
First time collaborating on a large project: I may be in over my head.

All the links on the site broke when I try to run the code on my local machine.

/localhost/dir/file need to become /localhost/appname/html/dir/file

I changed APPPATH, SYSPATH &tc to reflect the dir change & that all works now, but the html/css/js links are all broken still. I think I need to change .htaccess & mod_rewrite to prepend appname/html/ to the links, but perhaps not?

edit: I was able to get some of the links working using the html <base> tag, the ones still not working seem to be created using Kohana classes, so I'm guessing there is a variable somewhere I still need to change.

答:
I got it to work by adding this JS to the ready function:

```<code>$( "[href]" ).attr("href",function(){ return "http://kohana/index.php" + $( this ).attr( "href" ); });
</code>```

Terrible, I know. If anyone has a better solution I will be glad.

Body:
I got it to work by adding this JS to the ready function:

$( "[href]" ).attr("href",function(){ return "http://kohana/index.php" + $( this ).attr( "href" ); });

Terrible, I know. If anyone has a better solution I will be glad.


问:
CSS animation keyframes overlapping
I am not adept at css animations at all. I am trying to animate 4 text elements in
 tags using the code from https://codepen.io/nucliweb/pen/ymedj as a reference.

I want them to fade in one after the other. Basically a text slider. Hence I tried doing this but unfortunately cannot get the 4th
 to behave like the 1st 3. I am sure it is because the keyframes were written for 3 elements and I added the 4th hence causing text overlap issues.

Could someone please correct the keyframes value such that there is no overlap as is happening if a 4th paragraph is added.
Html

```<code><p class="item-1">All showing good.</p>
<p class="item-2">Until the 4th element is added</p>

<p class="item-3">Because keyframes values are no longer adding up</p>
<p class="item-4"> I created this as I wanted to add this text to end the slider and all hell broke loose </p>
</code>```

The css is:
        @import url(https://fonts.googleapis.com/css?family=Open+Sans:600);

```<code>body {
  font-family: 'Open Sans', 'sans-serif';
 color: #cecece;
background: #222;
overflow: hidden;
}

.item-1,
.item-2,
.item-3,
.item-4 {
position: absolute;
 display: block;
top: 2em;

width: 60%;

font-size: 2em;

animation-duration: 20s;
animation-timing-function: ease-in-out;
animation-iteration-count: infinite;
}

.item-1{
animation-name: anim-1;
}

.item-2{
animation-name: anim-2;
}

.item-3{
animation-name: anim-3;
}
.item-4{
animation-name: anim-4; /*added by me*/
}
  @keyframes anim-1 { /*for anim 1,2 and 3 the code runs flawless.*/
  0%, 8.3% { opacity: 0; }
  8.3%,25% {  opacity: 1; }
  33.33%, 100% { opacity: 0; }
 }

@keyframes anim-2 {
0%, 33.33% {  opacity: 0; }
41.63%, 58.29% {  opacity: 1; }
66.66%, 100% { opacity: 0; }
}

@keyframes anim-3 { /*code is screwed on adding anim-4*/
0%, 66.66% { opacity: 0; }
74.96%, 91.62% {  opacity: 1; }
100% {  opacity: 0; }
}
  @keyframes anim-4 {          /*PLEASE GUIDE ABOUT THE VALUES NEEDED HERE*/
0%, 66.66% { opacity: 0; } /*PREVIOUS VALUES MUST CHANGE /*
74.96%, 91.62% {  opacity: 1; }/*BUT I AM CONFUSED ABOUT THE KEYFRAMES*/
100% {  opacity: 0; }
}
</code>```

Could someone kindly please provide the keyframe values such that no overlap happens.

Many thanks,

答:
As I see it, this is a pure math problem. You have X frames, each frame has 25% of its time (which is 100% / X) with opacity: 0, followed by 50% of this time with opacity: 1, followed by 25% of this time with opacity: 0.

You can work the calculations yourself and write elaborate calcs to provide for changing number of frames, but initial 8.3% (25% of 100%/3) would then become 25% of 100%/4 (since you have 4 items now), or 6.25%. And so on.

So,

.item-1 {
    animation-name: anim-1;
}
.item-2 {
    animation-name: anim-2;
}
.item-3 {
    animation-name: anim-3;
}
.item-4 {
    animation-name: anim-4;
}
@keyframes anim-1 { /* first quarter: 0 … 100% / X */
    0%, 0% { opacity: 0; }
    6.25%, 18.75% { opacity: 1; }  /* 100% / 16 … 100% / 16 * 3 */
    25%, 100% { opacity: 0; }
}
@keyframes anim-2 { /* second quarter */
    0%, 25% {  opacity: 0; }
    31.25%, 43.75% {  opacity: 1; } /* 100% / 16 * 5 … 100% / 16 * 7 */
    50%, 100% { opacity: 0; }
}
@keyframes anim-3 { /* third quarter */
    0%, 50% { opacity: 0; }
    56.25%, 68.75% {  opacity: 1; } /* 100% / 16 * 9 … 100% / 16 * 11 */
    75%, 100% {  opacity: 0; }
}
@keyframes anim-4 { /* fourth quarter: 100% / X * (X-1) … 100% */
    0%, 75% { opacity: 0; }
    81.25%, 93.75% {  opacity: 1; }  /* 100% / 16 * 13 … 100% / 16 * 15 */
    100%, 100% {  opacity: 0; }
}

OwnerDisplayName: Priyanka

Title: CSS animation keyframes overlapping

Body:
I am not adept at css animations at all. I am trying to animate 4 text elements in
 tags using the code from https://codepen.io/nucliweb/pen/ymedj as a reference.

I want them to fade in one after the other. Basically a text slider. Hence I tried doing this but unfortunately cannot get the 4th
 to behave like the 1st 3. I am sure it is because the keyframes were written for 3 elements and I added the 4th hence causing text overlap issues.

Could someone please correct the keyframes value such that there is no overlap as is happening if a 4th paragraph is added.
Html

All showing good.

Until the 4th element is added

Because keyframes values are no longer adding up

 I created this as I wanted to add this text to end the slider and all hell broke loose

The css is:
        @import url(https://fonts.googleapis.com/css?family=Open+Sans:600);

body {
  font-family: 'Open Sans', 'sans-serif';
 color: #cecece;
background: #222;
overflow: hidden;
}

.item-1,
.item-2,
.item-3,
.item-4 {
position: absolute;
 display: block;
top: 2em;

width: 60%;

font-size: 2em;

animation-duration: 20s;
animation-timing-function: ease-in-out;
animation-iteration-count: infinite;
}

.item-1{
animation-name: anim-1;
}

.item-2{
animation-name: anim-2;
}

.item-3{
animation-name: anim-3;
}
.item-4{
animation-name: anim-4; /*added by me*/
}
  @keyframes anim-1 { /*for anim 1,2 and 3 the code runs flawless.*/
  0%, 8.3% { opacity: 0; }
  8.3%,25% {  opacity: 1; }
  33.33%, 100% { opacity: 0; }
 }

@keyframes anim-2 {
0%, 33.33% {  opacity: 0; }
41.63%, 58.29% {  opacity: 1; }
66.66%, 100% { opacity: 0; }
}

@keyframes anim-3 { /*code is screwed on adding anim-4*/
0%, 66.66% { opacity: 0; }
74.96%, 91.62% {  opacity: 1; }
100% {  opacity: 0; }
}
  @keyframes anim-4 {          /*PLEASE GUIDE ABOUT THE VALUES NEEDED HERE*/
0%, 66.66% { opacity: 0; } /*PREVIOUS VALUES MUST CHANGE /*
74.96%, 91.62% {  opacity: 1; }/*BUT I AM CONFUSED ABOUT THE KEYFRAMES*/
100% {  opacity: 0; }
}

Could someone kindly please provide the keyframe values such that no overlap happens.

Many thanks,

OwnerDisplayName: Alexei Danchenkov


问:
Python / Pygame - How to blit different transparencies onto an invisible surface
I was wondering if it is possible to blit two images with let's say 120 and 200 alpha on to a surface with 0 alpha.

For example:

Here are all my variables

```<code>game_display = pygame.display.set_mode((1280, 720))
transparent_display = pygame.Surface((1280, 720), pygame.SRCALPHA)
transparent_display.set_alpha(0)
object1 = pygame.Surface((100, 100))
object1.fill((255, 0, 0))
object2 = pygame.Surface((150, 50))
object2.fill((0, 0, 255))
</code>```

Now I want to make a single surface (image) with all the components added into it
(I want them all on one surface so I don't have
to load each surface each game loop cycle)

```<code>transparent_display.blit(object1, (0, 0))
transparent_display.blit(object2, (50, 50))
game_display.blit(transparent_display, (0, 0)
</code>```

I apologize as I do not have very much knowledge on the subject of alphas with surfaces in pygame. Also, I know to update the screen and everything, that is not the issue.

(comment below if something isn't clear enough and I will elaborate)

答:
Just set the alpha values of the two objects and your code should work.

```<code>object1.set_alpha(120)
object2.set_alpha(200)
# Then blit them onto `transparent_display`.
</code>```

Note that set_alpha doesn't work with per-pixel alpha surfaces (images loaded with .convert_alpha() or surfaces to which you passed pygame.SRCALPHA), but you can still blit transparent surfaces onto these per-pixel alpha surfaces.

Body:
I was wondering if it is possible to blit two images with let's say 120 and 200 alpha on to a surface with 0 alpha.

For example:

Here are all my variables

game_display = pygame.display.set_mode((1280, 720))
transparent_display = pygame.Surface((1280, 720), pygame.SRCALPHA)
transparent_display.set_alpha(0)
object1 = pygame.Surface((100, 100))
object1.fill((255, 0, 0))
object2 = pygame.Surface((150, 50))
object2.fill((0, 0, 255))

Now I want to make a single surface (image) with all the components added into it
(I want them all on one surface so I don't have
to load each surface each game loop cycle)

transparent_display.blit(object1, (0, 0))
transparent_display.blit(object2, (50, 50))
game_display.blit(transparent_display, (0, 0)

I apologize as I do not have very much knowledge on the subject of alphas with surfaces in pygame. Also, I know to update the screen and everything, that is not the issue.

(comment below if something isn't clear enough and I will elaborate)

Body:
Just set the alpha values of the two objects and your code should work.

object1.set_alpha(120)
object2.set_alpha(200)
# Then blit them onto `transparent_display`.

Note that set_alpha doesn't work with per-pixel alpha surfaces (images loaded with .convert_alpha() or surfaces to which you passed pygame.SRCALPHA), but you can still blit transparent surfaces onto these per-pixel alpha surfaces.


问:
Issues with retrieving information from a class module for output within a switch statement
I know this may be something obvious to some with experience but I am in the middle of my first real class for C++ programming. I have come across something in my code that I have been trying to resolve without any success. I am trying to extract the sum of the total value of "m_cost" stored within a array that is inside of these class modules. I want to output the total value inside of a switch statement for print out. Just seeing if someone can point me in the right direction or if I have completely gone off-track with the logic.

Project Code section in question:

```<code>void materialsMenu()
{
  Inventory record[MAX_REC];
  int i, n;

  cout << "\n=====Inventory Management=====\n";
  cout << "\nHow many Materials are there to be used? : ";
  cin >> n;

  cout << "Enter " << n << " Materials\n";
  for (i = 0; i < n; i++)
    record[i].getdata();

  cout << "\n\n---Material Information---\n";
  cout << "\n" << setw(8) << "Item Name  "
      << setw(10) << " Price per foot "
      << setw(19) << " Cost " << endl;
  cout << endl << "-------------------------------------------" << endl;

  for (i = 0; i < n; i++)
    record[i].showdata();
}

void Inventory::getdata() {
  cout << endl;
  cout << "\nEnter Material Name : ";
  cin >> itemName;
  cout << "Enter Price Per Foot : ";
  cin >> ppf;
  cout << "Enter Total Length Needed in Feet (ft) : ";
  cin >> length;
  cout << endl;

  m_cost = ppf*length;
  m_costT=???????? **this is the issue**
}
</code>```

Materials.H file contents:

```<code>#ifndef MATERIALS_H

using namespace std;

class Materials {
private:
 char itemName[15];
 float ppf;
 float length;
 double m_cost;
 float m_costT;

public:
Materials()
{
    ppf = 0;
    length = 0;
    m_cost = 0;
    m_costT = 0;

}
Materials(int itemName, float ppf, float length, double m_cost, float
m_costT)
{
    length = getLength();
    ppf = getPpf();
    m_cost = getCost();
    m_costT = getTotal();

}

float getLength()
{
    return length;
}
float getPpf()
{
    return ppf;
}
double getCost()
{
    return m_cost;
}
float getTotal()
{
    return m_costT;
}
void getdata();
void showdata();

};
#endif // !MATERIALS_H
</code>```

答:
Consider something like this to hold your records.  It's very simple, but it demonstrates the idea of one class holding another and shows information hiding and all sorts of other tidbits.  You are struggling to get that total because the Record class shouldn't care about this.  The total is a concept outside of the scope of a Record.  And as such, it is very difficult to calculate this from where you wanted to do it.  (Though it is possible, it breaks all sorts of C++ rules and should be avoided)

Example:

```<code>class Record;

class RecordHolder
{
public:
    int GetTotal()
    {
        int retVal = 0;
        for(int i=0; i<10; i++)  // Magic number 10 for demo purposes only...
        {
            retVal += records[i].m_cost;  // Or use a public get function.
        }
        return retVal;
    }

private:
    Record records[10];  // Magic number 10 for demo purposes only...
};
</code>```

The RecordHolder could also do printing, add/removing records, etc.  It controls the records array.  The Records are just Records and don't care about such management.

Body:
I know this may be something obvious to some with experience but I am in the middle of my first real class for C++ programming. I have come across something in my code that I have been trying to resolve without any success. I am trying to extract the sum of the total value of "m_cost" stored within a array that is inside of these class modules. I want to output the total value inside of a switch statement for print out. Just seeing if someone can point me in the right direction or if I have completely gone off-track with the logic.

Project Code section in question:

void materialsMenu()
{
  Inventory record[MAX_REC];
  int i, n;

  cout << "\n=====Inventory Management=====\n";
  cout << "\nHow many Materials are there to be used? : ";
  cin >> n;

  cout << "Enter " << n << " Materials\n";
  for (i = 0; i < n; i++)
    record[i].getdata();

  cout << "\n\n---Material Information---\n";
  cout << "\n" << setw(8) << "Item Name  "
      << setw(10) << " Price per foot "
      << setw(19) << " Cost " << endl;
  cout << endl << "-------------------------------------------" << endl;

  for (i = 0; i < n; i++)
    record[i].showdata();
}

void Inventory::getdata() {
  cout << endl;
  cout << "\nEnter Material Name : ";
  cin >> itemName;
  cout << "Enter Price Per Foot : ";
  cin >> ppf;
  cout << "Enter Total Length Needed in Feet (ft) : ";
  cin >> length;
  cout << endl;

  m_cost = ppf*length;
  m_costT=???????? **this is the issue**
}

Materials.H file contents:

#ifndef MATERIALS_H

using namespace std;

class Materials {
private:
 char itemName[15];
 float ppf;
 float length;
 double m_cost;
 float m_costT;

public:
Materials()
{
    ppf = 0;
    length = 0;
    m_cost = 0;
    m_costT = 0;

}
Materials(int itemName, float ppf, float length, double m_cost, float
m_costT)
{
    length = getLength();
    ppf = getPpf();
    m_cost = getCost();
    m_costT = getTotal();

}

float getLength()
{
    return length;
}
float getPpf()
{
    return ppf;
}
double getCost()
{
    return m_cost;
}
float getTotal()
{
    return m_costT;
}
void getdata();
void showdata();

};
#endif // !MATERIALS_H

Body:
Consider something like this to hold your records.  It's very simple, but it demonstrates the idea of one class holding another and shows information hiding and all sorts of other tidbits.  You are struggling to get that total because the Record class shouldn't care about this.  The total is a concept outside of the scope of a Record.  And as such, it is very difficult to calculate this from where you wanted to do it.  (Though it is possible, it breaks all sorts of C++ rules and should be avoided)

Example:

class Record;

class RecordHolder
{
public:
    int GetTotal()
    {
        int retVal = 0;
        for(int i=0; i<10; i++)  // Magic number 10 for demo purposes only...
        {
            retVal += records[i].m_cost;  // Or use a public get function.
        }
        return retVal;
    }

private:
    Record records[10];  // Magic number 10 for demo purposes only...
};

The RecordHolder could also do printing, add/removing records, etc.  It controls the records array.  The Records are just Records and don't care about such management.


问:
How do I count the number of elements of list from another list in haskell
I have been trying to count the number of elements from a list which the elements are also from another list.

ys is the original list and ele is the list of elements.

So that count 6 [1,2,3] = 3 because it counts the elements of "0..5"

My idea is to implement the ele function into the count function to get this done, but I have no clue how to do that.

I have tried to insert ele n into "(filter (== ele n) ys)"in to code below :

```<code>count :: Eq a => a -> [a] -> Int
count n ys = length (filter (== n) ys)

ele n = [ n | n <- [0..n-1]]
</code>```

But apparently it doesn't work out and the above code is the code I got so far

答:
If I understand correctly what you're trying to do, you might try this

```<code>count n ys = length (filter (flip elem (ele n)) ys)
</code>```

Notice that in order to filter a list by (== ele n), you would have to have a list of lists of numbers, because each element in the list will be checked for equality against the list of numbers ele n. If you want to check that each element of ys is in ele n, you should use the elem function instead of ==.

Because elem takes the element as its first argument and the list as its second argument, you can use the flip function to set up your filter function. flip takes a function of two arguments and returns a function that does the same thing but takes its arguments in the opposite order. For example, instead of writing

```<code>elem 3 [1..5]
</code>```

you can write

```<code>flip elem [1..5] 3
</code>```

An alternative solution would be to use intersect from Data.List, in which case you wouldn't have to use a filter at all.

```<code>import Data.List
count n ys = length (intersect ys (ele n))
</code>```

Body:
I have been trying to count the number of elements from a list which the elements are also from another list.

ys is the original list and ele is the list of elements.

So that count 6 [1,2,3] = 3 because it counts the elements of "0..5"

My idea is to implement the ele function into the count function to get this done, but I have no clue how to do that.

I have tried to insert ele n into "(filter (== ele n) ys)"in to code below :

count :: Eq a => a -> [a] -> Int
count n ys = length (filter (== n) ys)

ele n = [ n | n <- [0..n-1]]

But apparently it doesn't work out and the above code is the code I got so far

Body:
If I understand correctly what you're trying to do, you might try this

count n ys = length (filter (flip elem (ele n)) ys)

Notice that in order to filter a list by (== ele n), you would have to have a list of lists of numbers, because each element in the list will be checked for equality against the list of numbers ele n. If you want to check that each element of ys is in ele n, you should use the elem function instead of ==.

Because elem takes the element as its first argument and the list as its second argument, you can use the flip function to set up your filter function. flip takes a function of two arguments and returns a function that does the same thing but takes its arguments in the opposite order. For example, instead of writing

elem 3 [1..5]

you can write

flip elem [1..5] 3

An alternative solution would be to use intersect from Data.List, in which case you wouldn't have to use a filter at all.

import Data.List
count n ys = length (intersect ys (ele n))


问:
How to filter an array inside of an array of objects?
I have this array that I want to check the days that has the job done inside.(In this case Monday)</p>

```<code>const done = [
 {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "not yet", "done"]},
 {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "done", "done"]},
 {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "not yet", "not yet"]},
]

 const freeTime = done
  .filter((event) => event.job === 'done')
console.log(freeTime) // I get nothing here?
</code>```

答:
Here's a functional way of doing it. A bit convoluted, but it gets the job done.

const done = [
 {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "not yet", "done"]},
 {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "done", "done"]},
 {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "not yet", "not yet"]},
]

// Keep days that occur done in all "weeks"
const numWeeks = done.length;

// Loop through all weeks and days to see when they are "done"
const daysObj = done.map((x) => x.job.map((x) => x == "done")
  .map((y, index) => y ? x.days[index] : ""))
  .map((x) => x.filter((day) => day))
  .reduce((acc, curr) => acc.concat(curr))
  .reduce(function(p, c){
    if (c in p) {
      p[c]++;
    } else {
      p[c]=1;
    }
    return p;
  }, {});
console.log(daysObj);
// {Monday: 3, Friday: 2, Tuesday: 1}

// Find days that occur done in all weeks
const result = Object.keys(daysObj)
  .map((x) => daysObj[x] == numWeeks ? x : null)
  .filter((x) => x)
console.log(result);
// ["Monday"]```

Body:
I have this array that I want to check the days that has the job done inside.(In this case Monday)

const done = [
 {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "not yet", "done"]},
 {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "done", "done"]},
 {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "not yet", "not yet"]},
]

 const freeTime = done
  .filter((event) => event.job === 'done')
console.log(freeTime) // I get nothing here?


答:
This regex should be what you're looking for:

```<code>^[0-9][0-9]?(?:\.[0-9]+)?\%{1}$
</code>```

all of the followings pass through this regex:

1%

1.5%

10%

10.5%

10.555%

Anything with two percent signs will fail, also mis-formatted expressions like 1.% will fail.

Title: PHP Regex to allow only one decimal and one percentage sign

Body:
Hello I'm trying to create a regex to validate a percentage value but I only want to allow one decimal after at least one digit and and one percentage sign as the last character. For example the following values below should be valid:

8%

10%

12.60%

7.750%

So far this is my regex code for my php function.

if(!preg_match('/[^0-9.%]/', $string)){
    return true;
} else {
    return false;
}

Body:
This regex should be what you're looking for:

^[0-9][0-9]?(?:\.[0-9]+)?\%{1}$

all of the followings pass through this regex:

1%

1.5%

10%

10.5%

10.555%

Anything with two percent signs will fail, also mis-formatted expressions like 1.% will fail.


问:
Branch.io - how to create custom links
Im creating an application where you can make an challenge with the parameters: category, title, days, frequency, bet.

If you set all the parameters you can invite friends to do the challenge with you. So my question is what is the best way to invite friends through whatsapp/email/facebook.

My first thought was deeplinking.

So I dived into Branch.io - you can create a deeplink on the website, this works. But I need to set my own parameters into the link because the user can specify many parameters.

Whats the best way to do this?

Edit

Flow

答:
You can create links dynamically with Branch.io (as opposed to static on their website).

If you check out this section of their docs : https://docs.branch.io/pages/links/integrate/ spesifically Create deep links, you can see that you have a few ways of creating links (dynamically) to which you can append any key-value pairs that you wish.
Using the key-value pairs, you can pass any data that you want.
(I guess that in your app the key-value pairs will hold the properties the user selected for the challenge )

You have a pretty good explanation of how to do it here : https://docs.branch.io/pages/apps/ios/#create-deep-link

Title: Branch.io - how to create custom links


问:
$firebaseObject undefined
So I have my AngularJs + AngularFire with email/password Authentication working, also have a node called "users" where I can list all the users authenticated to my app, as you can see:

So, in my authentication service I have an AngularJs factory:

```<code>.factory('Auth', function($firebaseAuth, $firebaseObject, $firebaseArray){

 var ref = firebase.database().ref();
 var auth = $firebaseAuth();
 var users = $firebaseArray(ref.child('users'));
 var firebaseUser = auth.$getAuth();

var Auth = {

getStudent: function(studentId){
  console.log(studentId)
  return $firebaseObject(ref.child('users').child(studentId));
},

studentSignupProfile: function(profile){
    console.log('Student profile service..!');
    var obj = Auth.getStudent(firebaseUser.uid);
    console.log(obj.name);

    return obj.$loaded().then(function(){
      obj.phone = profile.phone;
      obj.address = profile.address;
      return obj.$save();
    });
}

};

return Auth;
});
</code>```

This is my controller:

```<code> $scope.studentSignupProfile = function(profile){
    console.log(profile);
    if (profile == undefined) {
        toaster.pop('info','Deseamos saber más acerca de tí!');
    } else {
        Auth.studentSignupProfile(profile).then(function(msg){
            toaster.pop('info','Perfil actualizado!');
            $state.go('home');
        });
    }
}
</code>```

The response is undefined in console.log(obj.name). And as you can see the user UID exist (picture above).

In my getStudent function there is a console.log(studentId) that show me the exact uid => 4BAIdOXZv6NTEKsjgI15JTajFtz2. But when I tried to grab the $firebaseObject it show me undefined.

答:
You are writing to the console before your object has loaded. That console.log() should be inside the $loaded handler so it will wait before trying to write the name:

```<code>var obj = Auth.getStudent(firebaseUser.uid);

return obj.$loaded().then(function(){
   // object now loaded
   console.log(obj.name);

  obj.phone = profile.phone;
  obj.address = profile.address;
  return obj.$save();
});
</code>```

Title: $firebaseObject undefined

Body:
So I have my AngularJs + AngularFire with email/password Authentication working, also have a node called "users" where I can list all the users authenticated to my app, as you can see:

So, in my authentication service I have an AngularJs factory:

.factory('Auth', function($firebaseAuth, $firebaseObject, $firebaseArray){

 var ref = firebase.database().ref();
 var auth = $firebaseAuth();
 var users = $firebaseArray(ref.child('users'));
 var firebaseUser = auth.$getAuth();

var Auth = {

getStudent: function(studentId){
  console.log(studentId)
  return $firebaseObject(ref.child('users').child(studentId));
},

studentSignupProfile: function(profile){
    console.log('Student profile service..!');
    var obj = Auth.getStudent(firebaseUser.uid);
    console.log(obj.name);

    return obj.$loaded().then(function(){
      obj.phone = profile.phone;
      obj.address = profile.address;
      return obj.$save();
    });
}

};

return Auth;
});

This is my controller:

 $scope.studentSignupProfile = function(profile){
    console.log(profile);
    if (profile == undefined) {
        toaster.pop('info','Deseamos saber más acerca de tí!');
    } else {
        Auth.studentSignupProfile(profile).then(function(msg){
            toaster.pop('info','Perfil actualizado!');
            $state.go('home');
        });
    }
}

The response is undefined in console.log(obj.name). And as you can see the user UID exist (picture above).

In my getStudent function there is a console.log(studentId) that show me the exact uid => 4BAIdOXZv6NTEKsjgI15JTajFtz2. But when I tried to grab the $firebaseObject it show me undefined.

Body:
You are writing to the console before your object has loaded. That console.log() should be inside the $loaded handler so it will wait before trying to write the name:

var obj = Auth.getStudent(firebaseUser.uid);

return obj.$loaded().then(function(){
   // object now loaded
   console.log(obj.name);

  obj.phone = profile.phone;
  obj.address = profile.address;
  return obj.$save();
});


问:
What is the url to a Facebook open graph post?
Given a post id returned by a graph search, for example: 186173001411937

is there a url to link to the post in facebook?
The following url does not work:
http://www.facebook.com/post.php?id=186173001411937

答:
I found out, for a graph id 1099696306_140549259338782 the links is build like this:
http://www.facebook.com/1099696306/posts/140549259338782</p>


问:
Populating a Column in a Relation Using SQL Update Table and Set Commands in MS Access
I am using MS Access 2016 to learn SQL as part of a class on the fundamentals of databases. I am tasked with adding a new column to a table and then populating that column. The column should reveal whether an account is paid in full or if a balance remains to be paid. Based on that criteria it contains only 'Yes' or 'No.' The formula relies on data from two tables (ENROLLMENT and COURSE).
Here are the tables I created:

I have been researching the problem here and on other sites but not finding the logic and only getting syntax errors.
Here are a couple ways I have tried

I am looking for the direction to go to approach the issue and not asking for someone to do the coding for me. Can anyone point me in the right direction?

答:
The following should help populate the column you want to create:</p>

```<code>SELECT ENROLMENT.AmountPaid,  IIf([ENROLMENT]![AmountPaid]>0,"Yes","No") AS Paid
FROM ENROLMENT;
</code>```

Body:
The following should help populate the column you want to create:

SELECT ENROLMENT.AmountPaid,  IIf([ENROLMENT]![AmountPaid]>0,"Yes","No") AS Paid
FROM ENROLMENT;


问:
Name convention over a Rails Migration reference
i have a problem creating a db table through rails generators.

I named a table personal_data and works fine.

```<code>class CreatePersonalData < ActiveRecord::Migration
 def change
  create_table :personal_data do |t|
    t.string :name
    t.string :lastName
    t.string :dni
    t.string :contact
    t.references :user, index: true, foreign_key: true

    t.timestamps null: false
  end
 end
end
</code>```

But i created another table with a reference to Personal Data

```<code>class CreateMerchants < ActiveRecord::Migration
 def change
  create_table :merchants do |t|
    t.string :storeName
    t.references :personal_data, index: true, foreign_key: true
    t.references :category, index: true, foreign_key: true
    t.string :webPage
    t.string :city

    t.timestamps null: false
  end
 end
end
</code>```

And when a run the migration instead of seeking for personal_data_id the migrations looks for personal_datum_id and throws and exception.

PG::UndefinedColumn: ERROR:  no existe la columna «personal_datum_id» referida en la llave foránea
  : ALTER TABLE "merchants" ADD CONSTRAINT "fk_rails_e4239c30dc"
  FOREIGN KEY ("personal_datum_id")
    REFERENCES "personal_data" ("id")

I translate the error to English

column "personal_datum_id" referenced in foreign key constraint does not exist

答:
I'm not sure why it's confused, but perhaps you can set up your inflections such that the plural of personal_data is personal_data?

In the file: config/initializers/inflections.rb

```<code>ActiveSupport::Inflector.inflections do |inflect|
    inflect.irregular 'personal_data', 'personal_data'
end
</code>```

Body:
i have a problem creating a db table through rails generators.

I named a table personal_data and works fine.

class CreatePersonalData < ActiveRecord::Migration
 def change
  create_table :personal_data do |t|
    t.string :name
    t.string :lastName
    t.string :dni
    t.string :contact
    t.references :user, index: true, foreign_key: true

    t.timestamps null: false
  end
 end
end

But i created another table with a reference to Personal Data

class CreateMerchants < ActiveRecord::Migration
 def change
  create_table :merchants do |t|
    t.string :storeName
    t.references :personal_data, index: true, foreign_key: true
    t.references :category, index: true, foreign_key: true
    t.string :webPage
    t.string :city

    t.timestamps null: false
  end
 end
end

And when a run the migration instead of seeking for personal_data_id the migrations looks for personal_datum_id and throws and exception.

PG::UndefinedColumn: ERROR:  no existe la columna «personal_datum_id» referida en la llave foránea
  : ALTER TABLE "merchants" ADD CONSTRAINT "fk_rails_e4239c30dc"
  FOREIGN KEY ("personal_datum_id")
    REFERENCES "personal_data" ("id")

I translate the error to English

column "personal_datum_id" referenced in foreign key constraint does not exist

Body:
I'm not sure why it's confused, but perhaps you can set up your inflections such that the plural of personal_data is personal_data?

In the file: config/initializers/inflections.rb

ActiveSupport::Inflector.inflections do |inflect|
    inflect.irregular 'personal_data', 'personal_data'
end


问:
Angular 4 cannot read property variable from app component
Thank you for any help, I understand this may be a newby question... but I can't see what I am missing and I have no compilation problems in my TypeScript.

I'm trying to do something quite simple, I want to have a variable that tells me which of my Main Menu Items is selected.

So I binded my HTML with several variables like this: (if you know how I could bind an enum value directly I will appreciate that).

```<code><div id ="menu_popular" class="{{menuClass}}" style=" left:90px; top:368px;">
  Menu Item
</div>
</code>```

Then I want to update my code declarations by invoking a function selectMenu like this:

```<code>import {Component} from '@angular/core';
import {MainMenuItem} from './domain';

@Component ({
          selector: 'app-root',
          templateUrl: './app.component.html',
          styleUrls: ['./app.component.css']
        })
export class AppComponent
{
  title = 'Angular App';
  menuClass = 'div.menu_text';

}

let selectedItem: any = MainMenuItem.POPULAR;

const selectMenu = function (item: MainMenuItem) {
  console.log ('Switching Selected Menu from: ' + selectedItem + ' to: ' + item);
  selectedItem = item;
  console.log('Asigned');
  console.log(this.AppComponent.menuClass);
  if (item === MainMenuItem.YEIIIII)
  {
 ...
 selectMenu (MainMenuItem.YEIIIII);
</code>```

But I will send me a runtime error stating Cannot read property 'AppComponent' of undefined

It seems I can't reach the AppComponent values any way I

```<code>console.log(this.AppComponent.menuClass);
</code>```

or

```<code>console.log(this.menuClass);
</code>```

What am I doing wrong :(

Thanks!

答:
I am assuming that you have multiple menuItems that can be selected. A simple solution, is to store all menuItems in a array in your .ts file.

```<code>menuItem:string[] = ['item1', 'item2', 'etc'];
selectedItem: number = 0;
menuClass = 'div.menu_text';
</code>```

And then in your html file you can display them like so.

```<code><div
    *ngFor="let item of menuItem; let i=index"
    (click)="selectedItem = i"
    [ngClass]="selectedItem==i ? menuClass:''">{{item}}
</div>
</code>```

What the html does is it loops through the menuItem array and populates the view. In this case it would populate 3 divs. That is done by let item of menuItem. As you can see we are not just looping, we have also declared a index variable within the for-Loop. Each menuItem that is being spawned to the view does also contain a click event. OnClick we set the selectedItem to the index value. And last but not least we have the [ngClass] That is a angular directive which allows us to add class on a condition. selectedItem==i ? menuClass:''. If selectedItem is equal to the menuItem div's index we add the menuClass which is declared in the .ts else ' '.

Hope this gives you some idea of how you could do this. This is probably not the best way to solve your problem but might help you.

Body:
Thank you for any help, I understand this may be a newby question... but I can't see what I am missing and I have no compilation problems in my TypeScript.

I'm trying to do something quite simple, I want to have a variable that tells me which of my Main Menu Items is selected.

So I binded my HTML with several variables like this: (if you know how I could bind an enum value directly I will appreciate that).

  Menu Item

Then I want to update my code declarations by invoking a function selectMenu like this:

import {Component} from '@angular/core';
import {MainMenuItem} from './domain';

@Component ({
          selector: 'app-root',
          templateUrl: './app.component.html',
          styleUrls: ['./app.component.css']
        })
export class AppComponent
{
  title = 'Angular App';
  menuClass = 'div.menu_text';

}

let selectedItem: any = MainMenuItem.POPULAR;

const selectMenu = function (item: MainMenuItem) {
  console.log ('Switching Selected Menu from: ' + selectedItem + ' to: ' + item);
  selectedItem = item;
  console.log('Asigned');
  console.log(this.AppComponent.menuClass);
  if (item === MainMenuItem.YEIIIII)
  {
 ...
 selectMenu (MainMenuItem.YEIIIII);

But I will send me a runtime error stating Cannot read property 'AppComponent' of undefined

It seems I can't reach the AppComponent values any way I

console.log(this.AppComponent.menuClass);

or

console.log(this.menuClass);

What am I doing wrong :(

Thanks!

Body:
I am assuming that you have multiple menuItems that can be selected. A simple solution, is to store all menuItems in a array in your .ts file.

menuItem:string[] = ['item1', 'item2', 'etc'];
selectedItem: number = 0;
menuClass = 'div.menu_text';

And then in your html file you can display them like so.

<div
    *ngFor="let item of menuItem; let i=index"
    (click)="selectedItem = i"
    [ngClass]="selectedItem==i ? menuClass:''">{{item}}
</div>

What the html does is it loops through the menuItem array and populates the view. In this case it would populate 3 divs. That is done by let item of menuItem. As you can see we are not just looping, we have also declared a index variable within the for-Loop. Each menuItem that is being spawned to the view does also contain a click event. OnClick we set the selectedItem to the index value. And last but not least we have the [ngClass] That is a angular directive which allows us to add class on a condition. selectedItem==i ? menuClass:''. If selectedItem is equal to the menuItem div's index we add the menuClass which is declared in the .ts else ' '.

Hope this gives you some idea of how you could do this. This is probably not the best way to solve your problem but might help you.


问:
Disable delete row in transaction's grids
I need to disable o remove the "x" (delete) icon in transaction's grid.

Genexus X Ev.3 U1

Thanks!

答:
Including an error rule conditioned to delete mode.

Something like:
error("cannot delete")  if delete and level(ArticuloDescripcion);