问:
Converting a string to a date format?
I would like to convert a string '17.07.2019' to date format 17-07-2019 (or 17-Jul-2019)

I tried this code

```<code>from datetime import datetime
x = '17.07.2019'
y=datetime.strptime(x,'%d.%m.%y')
y=datetime.strftime(x,'%d.%m.%y')
</code>```

but I get this error

```<code>TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'
</code>```

I then tried

```<code>y=pd.to_datetime(x,'%d.'%m.%Y')
</code>```

but I got this error

SyntaxError: invalid syntax
```

答:
strftime is used to convert datetime to str, strptime is used to convert str to datetime.

This is what you need:

```<code>from datatime import datetime as date
x = '17.07.2019'
y = date.strptime(x, '%d.%m.%Y')
new_format = y.strftime('%d-%m-%Y')
</code>```

you also can convert to the new format directly

```<code>new_format = date.strptime('17.07.2019', '%d.%m.%Y').strftime('%d-%m-%Y')
</code>```

Title: Converting a string to a date format?

Body:
I would like to convert a string '17.07.2019' to date format 17-07-2019 (or 17-Jul-2019)

I tried this code

from datetime import datetime
x = '17.07.2019'
y=datetime.strptime(x,'%d.%m.%y')
y=datetime.strftime(x,'%d.%m.%y')

but I get this error

TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'

I then tried

y=pd.to_datetime(x,'%d.'%m.%Y')

but I got this error

SyntaxError: invalid syntax

Body:
strftime is used to convert datetime to str, strptime is used to convert str to datetime.

This is what you need:

from datatime import datetime as date
x = '17.07.2019'
y = date.strptime(x, '%d.%m.%Y')
new_format = y.strftime('%d-%m-%Y')

you also can convert to the new format directly

new_format = date.strptime('17.07.2019', '%d.%m.%Y').strftime('%d-%m-%Y')


来源: stackexchange

问:
What javascript would I need to open two web pages at the same time and close the previous tab?
I'm working on an exam project where students will click on an option which would open two tabs with different case studies and close the previous tab but I don't have experience with Javascript and I'm unsure how to approach the problem.

It's built on Wordpress and I've tried using various plugins but all of them have failed. I have managed to get links to open in new tab (no different to  but not close the previous one or open two tabs with individual webpages.

We're using anchor tags currently in HTML and putting the javascript inline but I think we might need to tackle it differently, potentially through calling a javascript file.

We want to use Javascript as it'll allow us to add code to track users when they click on the link.

The page layout is very basic with one link on it (it has a pageview conversion tracking code to track the number of students taking the exam) so there's very little chance the script will conflict with anything else, this is why the previous tab should close automatically to avoid distraction

```<code><a href="http://www.example.com" onclick="window.open('https://www.example.com');return false">Example</a>
</code>```

It opens the webpage in a new tab but I'm unsure how to make it open two new tabs (different URLs) and close the previous tab.

(I noticed there are similar questions asked but none address closing the previous tab)

答:
To open multiple pages at once you can use the following code.

```<code>window.open('url1.com');
window.open('url2.com');
</code>```

How to make a link open multiple pages when clicked

To close the current tab/window use

```<code>window.close();
</code>```

How to close current tab in a browser window?

To do all 3 actions within the inline eventhandler like your example code, you can call window.open twice with different urls, window.close(), and then return false.

ContentLicense: CC BY-SA 4.0

Body:
I'm working on an exam project where students will click on an option which would open two tabs with different case studies and close the previous tab but I don't have experience with Javascript and I'm unsure how to approach the problem.

It's built on Wordpress and I've tried using various plugins but all of them have failed. I have managed to get links to open in new tab (no different to  but not close the previous one or open two tabs with individual webpages.

We're using anchor tags currently in HTML and putting the javascript inline but I think we might need to tackle it differently, potentially through calling a javascript file.

We want to use Javascript as it'll allow us to add code to track users when they click on the link.

The page layout is very basic with one link on it (it has a pageview conversion tracking code to track the number of students taking the exam) so there's very little chance the script will conflict with anything else, this is why the previous tab should close automatically to avoid distraction

Example

It opens the webpage in a new tab but I'm unsure how to make it open two new tabs (different URLs) and close the previous tab.

(I noticed there are similar questions asked but none address closing the previous tab)

Body:
To open multiple pages at once you can use the following code.

window.open('url1.com');
window.open('url2.com');

How to make a link open multiple pages when clicked

To close the current tab/window use

window.close();

How to close current tab in a browser window?

To do all 3 actions within the inline eventhandler like your example code, you can call window.open twice with different urls, window.close(), and then return false.


问:
Jammit compression works in dev mode, but not as compressed JS
My Rails app is fairly progressed now, and I want to compress the included JS files (Aloha Editor with plugins + Gritter, making up multiple files with over 1MB of JS) properly. I have decided for Jammit, because of its fine Rails integration. Here is my config/assets.yml:

```<code>package_assets:          always
javascript_compressor:   closure
compressor_options:
  compilation_level: ADVANCED_OPTIMIZATIONS

javascripts:
  admin:
    - public/aloha/aloha.js
    - public/aloha/plugins/com.gentics.aloha.plugins.Format/plugin.js
    - public/aloha/plugins/com.gentics.aloha.plugins.Table/plugin.js
    - public/aloha/plugins/com.gentics.aloha.plugins.List/plugin.js
    - public/aloha/plugins/com.gentics.aloha.plugins.Link/plugin.js
    - public/javascripts/*.js
    - public/javascripts/gritter/*.js
</code>```

For explanation: aloha.js is an extended jQuery 1.4.2 lib, and the files in /javascripts/.js and /gritter/.js are mostly dependent on it (jQuery).
I am including the tags in my view code with

```<code><%= include_javascripts :admin %>
</code>```

straightforward.

When switched to dev mode (assets.yml has package_assets: on), Jammit leaves the JS files alone and embeds all of them, one by one, and my app is just fine.

However, when in production mode (env = :production, or assets.yml has package_assets: always), Jammit creates a compressed JS file of roughly 700kB (wow, that's a fat monster) which embeds correctly, but I get a JS error "jQuery is not defined" on page load. My first guess would be that the order of JS files is changed during compilation, even though it should not?

One more thing: Leaving the compressor at default (yui) causes even worse JS errors on loading.

Can someone help me, please?

答:
The order of the files is likely the issue. I would recommend specify each file explicitly and in the order you want them in (ie. do not do /*.js).

If this works for you, then you could move some of the javascript files that don't require an order into subfolders and call /*.js on that subfolder.

ContentLicense: CC BY-SA 2.5

Body:
My Rails app is fairly progressed now, and I want to compress the included JS files (Aloha Editor with plugins + Gritter, making up multiple files with over 1MB of JS) properly. I have decided for Jammit, because of its fine Rails integration. Here is my config/assets.yml:

package_assets:          always
javascript_compressor:   closure
compressor_options:
  compilation_level: ADVANCED_OPTIMIZATIONS

javascripts:
  admin:
    - public/aloha/aloha.js
    - public/aloha/plugins/com.gentics.aloha.plugins.Format/plugin.js
    - public/aloha/plugins/com.gentics.aloha.plugins.Table/plugin.js
    - public/aloha/plugins/com.gentics.aloha.plugins.List/plugin.js
    - public/aloha/plugins/com.gentics.aloha.plugins.Link/plugin.js
    - public/javascripts/*.js
    - public/javascripts/gritter/*.js

For explanation: aloha.js is an extended jQuery 1.4.2 lib, and the files in /javascripts/.js and /gritter/.js are mostly dependent on it (jQuery).
I am including the tags in my view code with

<%= include_javascripts :admin %>

straightforward.

When switched to dev mode (assets.yml has package_assets: on), Jammit leaves the JS files alone and embeds all of them, one by one, and my app is just fine.

However, when in production mode (env = :production, or assets.yml has package_assets: always), Jammit creates a compressed JS file of roughly 700kB (wow, that's a fat monster) which embeds correctly, but I get a JS error "jQuery is not defined" on page load. My first guess would be that the order of JS files is changed during compilation, even though it should not?

One more thing: Leaving the compressor at default (yui) causes even worse JS errors on loading.

Can someone help me, please?

ContentLicense: CC BY-SA 3.0


问:
React - event.target returns the innerText of the previously clicked element instead of the currently clicked element
I created a drop down menu that returns a selected option through an event handler when the option is clicked.

When I click on the option, I target the innerText of that option via event. It looks like this: event.target.innerText. The selected targets value is then used to fill in an 'input' to show the users selected value. Exactly how you expect a <select> input to work. The targets value is also used for filtering listed components, but that is not what I am worried about here.

When the drop down menu component loads, inside of a componentDidMount() method, the state is updated with a default value so that the drop down menus load with the first option pre-populated (this is so that they are not empty before a user selects an option).

When I click on an option to make a selection, the returned event.target.innerText is of the previous selection. So if option 1 was the default value when the component mounts, and then I select option 2 and console.log the result, the value would be option 1. If I then select another option, option 3, the returned console.log() would be option 2. It's one behind.

In this .gif, you can see that when componentDidMount() fires, it console.log()s the default values of the drop down menu. But when I make a selection, you'll notice the console.log() is only returning the event.target.innerText of the previously selected option.

Here is the component:

```<code>class DropDownSelect extends Component {
  constructor(props) {
    const { inputOptions } = props;
    const { option1 } = inputOptions;
    super(props);

    this.state = {
      showOptions: false,
      selectionMade: option1
    };
  }

  setShowOptions = () => {
    const { showOptions } = this.state;
    this.setState(prevState => ({ showOptions: !prevState.showOptions }));
  };

  setSelectionMade = event => {
    const { target } = event;
    event.stopPropagation();

    this.setShowOptions();
    this.setState({ selectionMade: target.innerText });
    console.log(this.state.selectionMade);
  };

  setDefaultSelectionOnLoad = () => {
    const { inputOptions } = this.props;
    this.setState({ selectionMade: inputOptions.option1 });
  };

  componentDidMount() {
    this.setDefaultSelectionOnLoad();
    console.log(this.state.selectionMade);
  }

  render() {
    const { showOptions, selectionMade } = this.state;
    const { inputOptions } = this.props;

    const inputOptionsArray = Object.keys(inputOptions);

    return (
      <DropDownSelectMenu>
        <DropDownSelectPlaceholder onClick={this.setShowOptions}>
          <p>{selectionMade}</p>
          <i>
            <FontAwesomeIcon icon={faCaretDown} />
          </i>
        </DropDownSelectPlaceholder>

        {showOptions ? (
          <DropDownSelectOptions>
            {inputOptionsArray.map((key, index) => {
              return (
                <DropDownOption
                  onClick={event => {
                    this.setSelectionMade(event);
                  }}
                  key={index}
                >
                  {inputOptions[key]}
                </DropDownOption>
              );
            })}
          </DropDownSelectOptions>
        ) : null}
      </DropDownSelectMenu>
    );
  }
}
</code>```

The DropDownOption styled component is where the function that updates the selection in the state is added as an onClick handler. Since this component is a child, and you need to click the parent component to open the DropDownOption component, I thought that maybe the event handler was bubbling up and grabbing the event.target value from the parent, so I added event.stopPropagation() to the event handler function setSelectionMade(). This didn't do anything for me.

答:
Your code works fine, only this debugging method fails ;)

This is of the most common errors in react - expecting state update immediatelly just after setState call.

Read docs, please. Value can be read in setState callback.

You can simply console.log(selectionMade) in render (before return () to get current value.

Body:
I created a drop down menu that returns a selected option through an event handler when the option is clicked.

When I click on the option, I target the innerText of that option via event. It looks like this: event.target.innerText. The selected targets value is then used to fill in an 'input' to show the users selected value. Exactly how you expect a <select> input to work. The targets value is also used for filtering listed components, but that is not what I am worried about here.

When the drop down menu component loads, inside of a componentDidMount() method, the state is updated with a default value so that the drop down menus load with the first option pre-populated (this is so that they are not empty before a user selects an option).

When I click on an option to make a selection, the returned event.target.innerText is of the previous selection. So if option 1 was the default value when the component mounts, and then I select option 2 and console.log the result, the value would be option 1. If I then select another option, option 3, the returned console.log() would be option 2. It's one behind.

In this .gif, you can see that when componentDidMount() fires, it console.log()s the default values of the drop down menu. But when I make a selection, you'll notice the console.log() is only returning the event.target.innerText of the previously selected option.

Here is the component:

class DropDownSelect extends Component {
  constructor(props) {
    const { inputOptions } = props;
    const { option1 } = inputOptions;
    super(props);

    this.state = {
      showOptions: false,
      selectionMade: option1
    };
  }

  setShowOptions = () => {
    const { showOptions } = this.state;
    this.setState(prevState => ({ showOptions: !prevState.showOptions }));
  };

  setSelectionMade = event => {
    const { target } = event;
    event.stopPropagation();

    this.setShowOptions();
    this.setState({ selectionMade: target.innerText });
    console.log(this.state.selectionMade);
  };

  setDefaultSelectionOnLoad = () => {
    const { inputOptions } = this.props;
    this.setState({ selectionMade: inputOptions.option1 });
  };

  componentDidMount() {
    this.setDefaultSelectionOnLoad();
    console.log(this.state.selectionMade);
  }

  render() {
    const { showOptions, selectionMade } = this.state;
    const { inputOptions } = this.props;

    const inputOptionsArray = Object.keys(inputOptions);

    return (
      <DropDownSelectMenu>
        <DropDownSelectPlaceholder onClick={this.setShowOptions}>

{selectionMade}

            <FontAwesomeIcon icon={faCaretDown} />

        </DropDownSelectPlaceholder>

        {showOptions ? (
          <DropDownSelectOptions>
            {inputOptionsArray.map((key, index) => {
              return (
                <DropDownOption
                  onClick={event => {
                    this.setSelectionMade(event);
                  }}
                  key={index}
                >
                  {inputOptions[key]}
                </DropDownOption>
              );
            })}
          </DropDownSelectOptions>
        ) : null}
      </DropDownSelectMenu>
    );
  }
}

The DropDownOption styled component is where the function that updates the selection in the state is added as an onClick handler. Since this component is a child, and you need to click the parent component to open the DropDownOption component, I thought that maybe the event handler was bubbling up and grabbing the event.target value from the parent, so I added event.stopPropagation() to the event handler function setSelectionMade(). This didn't do anything for me.


问:
On Pandas, how to drop multiple rows based in a column
I am new to Pandas and I am trying to drop all rows that contain some respective countries (Albania, Uzbekistan, Brazil) from the Column country. However, the way I figured it out to do is one by one, as below:

```<code>indexCountry = df[df['country'] == 'Albania'].index
df.drop(indexCountry, inplace = True)

indexCountry = df[df['country'] == 'Uzbekistan'].index
df.drop(indexCountry, inplace = True)

indexCountry = df[df['country'] == 'Brazil'].index
df.drop(indexCountry, inplace = True)
</code>```

Is there a way to do this in one single code line, instead of having to do one for every country?

答:
You can also use this:</p>

```<code>df = df[~df.country.str.contains('|'.join(["Albania","Uzbekistan","Brazil"]))]
</code>```

Body:
I am new to Pandas and I am trying to drop all rows that contain some respective countries (Albania, Uzbekistan, Brazil) from the Column country. However, the way I figured it out to do is one by one, as below:

indexCountry = df[df['country'] == 'Albania'].index
df.drop(indexCountry, inplace = True)

indexCountry = df[df['country'] == 'Uzbekistan'].index
df.drop(indexCountry, inplace = True)

indexCountry = df[df['country'] == 'Brazil'].index
df.drop(indexCountry, inplace = True)

Is there a way to do this in one single code line, instead of having to do one for every country?

Body:
You can also use this:

df = df[~df.country.str.contains('|'.join(["Albania","Uzbekistan","Brazil"]))]


问:
Find longest sublist with given average in sorted doubly linked list in O(n)
Given an number and a sorted doubly linked list (with data as integers), I have to find the longest sublist which average is the given number in O(n).
How would you go about it?</p>

答:
First, you find the cumulative sums of all the indexes. Say this is an array, cumsum[1..n]

Now, start with two pointers, one pointing at the first node and one at the last node. Compute average of this range as (cumsum[last]-cumsum[first])/(last-first+1). If this is larger than the target average (say k), then move the back pointer inwards, since that will always reduce the average (since it is sorted). Likewise, if avg < k, move the front pointer forward. This way you'll either end up with a range with average k if it exists, or realize that such a k doesn't exist if front and back pointers cross. Since we move at least one of the pointers in every step, this is O(n).


问:
Getting HTTP 404 Error when using a bootstrap / css template in Flask
I just started learning Flask yesterday, and tried to make a simple single page webpage. I copied a Bootstrap template I found online, but when I run my main python program I keep getting the following errors:

```<code>127.0.0.1 - - [26/May/2019 23:13:15] "GET / HTTP/1.1" 200 -

127.0.0.1 - - [26/May/2019 22:13:15] "GET /vendor/bootstrap.min.css HTTP/1.1" 404 -

127.0.0.1 - - [26/May/2019 22:13:15] "GET /vendor/jquery.min.js HTTP/1.1" 404 -

127.0.0.1 - - [26/May/2019 22:13:15] "GET /vendor/full-width-pics.css HTTP/1.1" 404 -

127.0.0.1 - - [26/May/2019 22:13:15] "GET /vendor/bootstrap.bundle.min.js HTTP/1.1" 404 -
</code>```

This is my root directory:

```<code>-FortniteStatBot.py

-Templates
|
|----index.html
|
|----vendor
|
|---- All the other static files

</code>```

I have looked at other posts on stack overflow and tried everything people suggested, but it doesn't fix the problem. Some things I have tried are adding static url paths / folders. Also saw someone recommend that I remove trailing '/' in the directory path, but that didn't fix it either.

```<code>app = Flask(__name__, static_url_path= '', static_folder= '/Templates/vendor')

app._static_folder = 'Templates/vendor'

</code>```

I tried something like this in my html file, and it didn't work either:

```<code><link href="{{ url_for('static', filename='/vendor/bootstrap.min.css/') }}" rel="stylesheet">
</code>```

I keep getting the same error despite trying multiple different things, so I'm wondering if anyone knows how to fix this error?

I am using this return value in the only function inside the .py file:

```<code>return render_template('index.html', stats = accountInfo, accountName = playerName)
</code>```

答:
You might be looking for templates_folder in combination with static_folder. From the docs:

static_folder – the folder with static files that should be served at

template_folder – the folder that contains the templates that should be used by the application. Defaults to 'templates' folder in the root path of the application.

Body:
I just started learning Flask yesterday, and tried to make a simple single page webpage. I copied a Bootstrap template I found online, but when I run my main python program I keep getting the following errors:

127.0.0.1 - - [26/May/2019 23:13:15] "GET / HTTP/1.1" 200 -

127.0.0.1 - - [26/May/2019 22:13:15] "GET /vendor/bootstrap.min.css HTTP/1.1" 404 -

127.0.0.1 - - [26/May/2019 22:13:15] "GET /vendor/jquery.min.js HTTP/1.1" 404 -

127.0.0.1 - - [26/May/2019 22:13:15] "GET /vendor/full-width-pics.css HTTP/1.1" 404 -

127.0.0.1 - - [26/May/2019 22:13:15] "GET /vendor/bootstrap.bundle.min.js HTTP/1.1" 404 -

This is my root directory:

-FortniteStatBot.py

-Templates
|
|----index.html
|
|----vendor
|
|---- All the other static files

I have looked at other posts on stack overflow and tried everything people suggested, but it doesn't fix the problem. Some things I have tried are adding static url paths / folders. Also saw someone recommend that I remove trailing '/' in the directory path, but that didn't fix it either.

app = Flask(__name__, static_url_path= '', static_folder= '/Templates/vendor')

app._static_folder = 'Templates/vendor'

I tried something like this in my html file, and it didn't work either:

<link href="{{ url_for('static', filename='/vendor/bootstrap.min.css/') }}" rel="stylesheet">

I keep getting the same error despite trying multiple different things, so I'm wondering if anyone knows how to fix this error?

I am using this return value in the only function inside the .py file:

return render_template('index.html', stats = accountInfo, accountName = playerName)


问:
How to most efficiently avoid ValueError when running str(), int(), float(), etc, on user input
I want to simplify the tests and control flow to check if user input is the right type of data before running either str() or int() on it.

I have already worked out the start of this. It's just incomplete and probably inefficient. This is actually a function inside of a user_prompt function I have, and this is the "form_check()" part, which is really what the topic concerns, so I left the rest of the code out.

```<code># the following is run on input from the user = indata
# with a string telling the user what type of data to give = req
def form_check(req, indata):
    if "int" in req:
        req = "int"
        if indata.isnumeric():
            print(req)
            return int(indata)
        else:
            exit(1)
    elif "str" in req:
        req = "str"
        if indata.isalnum():
            print(req)
            return str(indata)
        else:
            exit(1)
    elif "list" in req:
        req = "list"
        if indata.startswith("(") and indata.endswith(")"):
            print(req)
            return list(indata) # I know this isn't right but need to research; lists and dicts are new to me still
        else:
            exit(1)
    else:
        print("fail")
        exit(1)
</code>```

from my output...

```<code>>  USER: Prompting user for a number
                        Give input as integer
> 3243432
int
>  USER: Prompting user for your name
                        Give input as string
> sdfsaf243
str
>  USER: Prompting user for whatever
                        Give input as list
> (SDf)
list
3243432 sdfsaf243 ['(', 'S', 'D', 'f', ')']

</code>```

As you can see from the output, this code passes and doesn't error but it only begins to address what I want to do.

答:
Only str, float and int are necessary here. input always returns a string. Therefore, all inputs can be turned into a list by splitting into characters. You can use a try/except for int/float and use str as a fallback:

```<code>def form_check(req, data):
    if req in (int, 'int'):
        try:
            return int(data)
        except ValueError:
            exit(1)
    elif req in (float, 'float'):
        try:
            return float(data)
        except ValueError:
            exit(1)
    return str(data)
</code>```

However, if you are calling exit(1) for a bad input, it’s more beneficial to the user to raise a proper exception like ValueError('input must be convertible to "int"') to let the user know why the program failed.

If you want the user to input a list of values, it’s probably better to ask them to input comma-separated values and then return:

```<code>[item.strip() for item in data.split(',')]
</code>```

Body:
I want to simplify the tests and control flow to check if user input is the right type of data before running either str() or int() on it.

I have already worked out the start of this. It's just incomplete and probably inefficient. This is actually a function inside of a user_prompt function I have, and this is the "form_check()" part, which is really what the topic concerns, so I left the rest of the code out.

# the following is run on input from the user = indata
# with a string telling the user what type of data to give = req
def form_check(req, indata):
    if "int" in req:
        req = "int"
        if indata.isnumeric():
            print(req)
            return int(indata)
        else:
            exit(1)
    elif "str" in req:
        req = "str"
        if indata.isalnum():
            print(req)
            return str(indata)
        else:
            exit(1)
    elif "list" in req:
        req = "list"
        if indata.startswith("(") and indata.endswith(")"):
            print(req)
            return list(indata) # I know this isn't right but need to research; lists and dicts are new to me still
        else:
            exit(1)
    else:
        print("fail")
        exit(1)

from my output...

>  USER: Prompting user for a number
                        Give input as integer
> 3243432
int
>  USER: Prompting user for your name
                        Give input as string
> sdfsaf243
str
>  USER: Prompting user for whatever
                        Give input as list
> (SDf)
list
3243432 sdfsaf243 ['(', 'S', 'D', 'f', ')']

As you can see from the output, this code passes and doesn't error but it only begins to address what I want to do.

Body:
Only str, float and int are necessary here. input always returns a string. Therefore, all inputs can be turned into a list by splitting into characters. You can use a try/except for int/float and use str as a fallback:

def form_check(req, data):
    if req in (int, 'int'):
        try:
            return int(data)
        except ValueError:
            exit(1)
    elif req in (float, 'float'):
        try:
            return float(data)
        except ValueError:
            exit(1)
    return str(data)

However, if you are calling exit(1) for a bad input, it’s more beneficial to the user to raise a proper exception like ValueError('input must be convertible to "int"') to let the user know why the program failed.

If you want the user to input a list of values, it’s probably better to ask them to input comma-separated values and then return:

[item.strip() for item in data.split(',')]


问:
Remove White Spaces Between HTML Sections
Please how do I remove the white spaces in between the html sections when page is rendered on the browser.

Get the freedom you deserve.

        Support

        Terms of Use

```

答:
you can reduce the white spaces by removing the margins and padding;but choice is yours

*{
padding:0%;
margin:0%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="product-overview">
  <h1>Get the freedom you deserve.</h1>
</section>

<footer class="main-footer">
  <nav>
    <ul class="footer-ul__list">
      <li class="footer__link">
        Support
      </li>
      <li class="footer__link">
        Terms of Use
      </li>
    </ul>
  </nav>
</footer></code>```

font and background color you can set as per your requirement

Body:
you can reduce the white spaces by removing the margins and padding;but choice is yours

*{
padding:0%;
margin:0%;
}

<section id="product-overview">
  <h1>Get the freedom you deserve.</h1>
</section>

<footer class="main-footer">
  <nav>
    <ul class="footer-ul__list">
      <li class="footer__link">
        <a href="#">Support</a>
      </li>
      <li class="footer__link">
        <a href="#">Terms of Use</a>
      </li>
    </ul>
  </nav>
</footer>

font and background color you can set as per your requirement


问:
first letter up all uppercase words in string data with jquery
my string data as as follow.

```<code>var HmtlStr = "<span>My names is <u>KERBEROS</u>. AGE: 29, my eyes <b>BROWN</b>.</span"
</code>```

result must be like this which i want;

```<code><span>My names is <u>Kerberos</u>. Age: 29, my eyes <b>Brown</b>.</span
</code>```

thank you very much for your help, already now.

答:
Try this  one:

```<code>   'apple cat dog stack overflow'.replace(/(\b)([a-zA-Z])/g,
       function(firstLetter){
          return   firstLetter.toUpperCase();
       })
</code>```

:)

Body:
my string data as as follow.

var HmtlStr = "My names is KERBEROS. AGE: 29, my eyes BROWN.</span"

result must be like this which i want;

My names is Kerberos. Age: 29, my eyes Brown.</span

thank you very much for your help, already now.

Body:
Try this  one:

   'apple cat dog stack overflow'.replace(/(\b)([a-zA-Z])/g,
       function(firstLetter){
          return   firstLetter.toUpperCase();
       })

:)


问:
Replace guava Fluent Iterables with Streams
I have a method for a filter by type, it gets as input Collection<?> collection and Class<T> tClass. I want to replace FluentIterable by the Stream.

```<code>public static <T> List<T> filterByType(final Collection<?> filerCollection, final Class<T> classType)
{
    return FluentIterable.from(filerCollection).filter(classType).toList();
}
</code>```

I tried with this solution:

```<code>public static <T> List<T> typeFilter(final Collection<?> filter, final Class<T> classType) {
    return (List<T>) filter.stream()
            .filter(Objects::nonNull)
            .map(Object.class::cast)
            .collect(Collectors.toList());
}
</code>```

how to do that without casting the return Stream?

答:
Look carefully what FluentIterable::filter(Class<T>) does and compare it with maps each item to the classType with casting. Your intention is to filter those items of classType.

Next, the classType::cast should be used instead of Object.class::cast since the desired class is already passed through Class<T> classType and might be used directly as a method reference. The Object.class::cast casts to a parent Object which every object inherits from.

Here is what you want:

```<code>public static <T> List<T> typeFilter(final Collection<?> filter, final Class<T> classType) {
    return filter.stream()
        .filter(Objects::nonNull)
        .filter(item -> item.getClass().equals(classType))
        .map(classType::cast)
        .collect(Collectors.toList());
}
</code>```

Edit: As mentioned in another answer, the filter(classType::isInstance) might be used as well.

Body:
I have a method for a filter by type, it gets as input Collection<?> collection and Class<T> tClass. I want to replace FluentIterable by the Stream.

public static <T> List<T> filterByType(final Collection<?> filerCollection, final Class<T> classType)
{
    return FluentIterable.from(filerCollection).filter(classType).toList();
}

I tried with this solution:

public static <T> List<T> typeFilter(final Collection<?> filter, final Class<T> classType) {
    return (List<T>) filter.stream()
            .filter(Objects::nonNull)
            .map(Object.class::cast)
            .collect(Collectors.toList());
}

how to do that without casting the return Stream?

Body:
Look carefully what FluentIterable::filter(Class<T>) does and compare it with maps each item to the classType with casting. Your intention is to filter those items of classType.

Next, the classType::cast should be used instead of Object.class::cast since the desired class is already passed through Class<T> classType and might be used directly as a method reference. The Object.class::cast casts to a parent Object which every object inherits from.

Here is what you want:

public static <T> List<T> typeFilter(final Collection<?> filter, final Class<T> classType) {
    return filter.stream()
        .filter(Objects::nonNull)
        .filter(item -> item.getClass().equals(classType))
        .map(classType::cast)
        .collect(Collectors.toList());
}

Edit: As mentioned in another answer, the filter(classType::isInstance) might be used as well.


问:
Haskell: Modifying value at specific index of array
New to Haskell. I have created an char array and I am trying to figure out the best way to modify data in that array given a specific index.

I already have an array created that I am passing into the below method in my main. That part is working fine. I just cant figure out how to manipulate the data at each index. In this particular case I am trying to override the value if the below condition is met with a space. And I want to return this to my main so i can print out the updated board.

```<code>import System.Random
import Control.Monad
import Data.Array
import Data.List

modifyArray :: Array Int Char -> Int -> IO (Array Int Char)
modifyArray arr i =
    if i > 0 then
        if i `mod` 102 == 1 then do
            (MODIFY ARRAY AT INDEX:i to equal ' ')
        else modifyArray arr (i-1)
    else arr
</code>```

答:
If you plan to update your array only a few times, you can use the (//) :: Ix i => Array i e -> [(i, e)] -> Array i e operator, like @JosephSible says.

As is however discussed in the question "How fast is Data.Array?", this is not very effective if you want to update your array frequently:

Note that // is probably O(n) though because it has to traverse the list (just like an imperative program would). If you need a lot of mutation you can use MArray or MVector.

This thus means that for large arrays, updating the array might take some time, since each update results in making a copy of the original array, and modifying that specific value.

The IOArray is a specific type of such MArray. We can thus define the modifyArray with writeArray :: (MArray a e m, Ix i) => a i e -> i -> e -> m ():

```<code>modifyArray :: <b>IOArray</b> Int Char -> Int -> IO (<b>IOArray</b> Int Char)
modifyArray arr idx | i < 0 = return arr
                    | mod i 102 == 1 = <b>writeArray arr idx ' '</b> >> return arr
                    | otherwise = modifyarr arr idx</code>```

Note that here returning the array is not necessary, in essence the IOArray can be seen as a reference to a mutable array, so after the writeArray operation, arr refers to the modified array. If you use this in a larger IO operation, then after the modifyArray, that array is modified.

You here use a loop to obtain the largest index i that has div i 102 == 1 and is less than or equal to the initial index. You can however improve that, by subtracting the result of the modulo:

```<code>modifyArray :: IOArray Int Char -> Int -> IO (IOArray Int Char)
modifyArray arr idx | i < 0 = return arr
                    | otherwise = writeArray arr <b>(idx - mod (idx-1) 102)</b> ' ' >> return arr</code>```

Body:
New to Haskell. I have created an char array and I am trying to figure out the best way to modify data in that array given a specific index.

I already have an array created that I am passing into the below method in my main. That part is working fine. I just cant figure out how to manipulate the data at each index. In this particular case I am trying to override the value if the below condition is met with a space. And I want to return this to my main so i can print out the updated board.

import System.Random
import Control.Monad
import Data.Array
import Data.List

modifyArray :: Array Int Char -> Int -> IO (Array Int Char)
modifyArray arr i =
    if i > 0 then
        if i `mod` 102 == 1 then do
            (MODIFY ARRAY AT INDEX:i to equal ' ')
        else modifyArray arr (i-1)
    else arr

Body:
If you plan to update your array only a few times, you can use the (//) :: Ix i => Array i e -> [(i, e)] -> Array i e operator, like @JosephSible says.

As is however discussed in the question "How fast is Data.Array?", this is not very effective if you want to update your array frequently:

Note that // is probably O(n) though because it has to traverse the list (just like an imperative program would). If you need a lot of mutation you can use MArray or MVector.

This thus means that for large arrays, updating the array might take some time, since each update results in making a copy of the original array, and modifying that specific value.

The IOArray is a specific type of such MArray. We can thus define the modifyArray with writeArray :: (MArray a e m, Ix i) => a i e -> i -> e -> m ():

modifyArray :: IOArray Int Char -> Int -> IO (IOArray Int Char)
modifyArray arr idx | i < 0 = return arr
                    | mod i 102 == 1 = writeArray arr idx ' ' >> return arr
                    | otherwise = modifyarr arr idx

Note that here returning the array is not necessary, in essence the IOArray can be seen as a reference to a mutable array, so after the writeArray operation, arr refers to the modified array. If you use this in a larger IO operation, then after the modifyArray, that array is modified.

You here use a loop to obtain the largest index i that has div i 102 == 1 and is less than or equal to the initial index. You can however improve that, by subtracting the result of the modulo:

modifyArray :: IOArray Int Char -> Int -> IO (IOArray Int Char)
modifyArray arr idx | i < 0 = return arr
                    | otherwise = writeArray arr (idx - mod (idx-1) 102) ' ' >> return arr


问:
How do I add a timeseries plot to a regular plot?
I made a moving average of my timeseries and I'd like to super-impose it on top of my timeseries.

Here's my series ggplot(daily_revenue, aes(day, revenue)) + geom_line()

Here's my moving average ma(ts(daily_rev_full$revenue, start = c(2014, 1), frequency = 365), order = 15) %>% autoplot()

I tried to add them together by including them as separate geom_line values. I also tried to add autoplot to ggplot and I tried to create a regular plot and then add the moving average with lines().

答:
TTR can be used to generate the moving average more effectively in this case.

As an example, suppose 100 random numbers are generated, and a 30-period simple moving average is generated.

```<code>numbers<-rnorm(100)

#SMA
library("TTR")
simplemovingaverage<-SMA(numbers,n=30)
plot(numbers,type='l',col='blue',xlab="X",ylab="Y")
lines(simplemovingaverage,type='l',col='red')
title("Numbers")
</code>```

Using plot to plot the actual values, and lines to plot the SMA, here is the plot that is generated:

Body:
TTR can be used to generate the moving average more effectively in this case.

As an example, suppose 100 random numbers are generated, and a 30-period simple moving average is generated.

numbers<-rnorm(100)

#SMA
library("TTR")
simplemovingaverage<-SMA(numbers,n=30)
plot(numbers,type='l',col='blue',xlab="X",ylab="Y")
lines(simplemovingaverage,type='l',col='red')
title("Numbers")

Using plot to plot the actual values, and lines to plot the SMA, here is the plot that is generated:


答:
You could just use str.replace for something this simple.

```<code>y = x.replace('.', '-')
</code>```

Or to fix your code you need to just use strftime on y:

```<code>y = date.strptime(x, '%d.%m.%Y')
z = y.strftime('%d-%m-%Y')
</code>```

Title: Converting a string to a date format?

Body:
I would like to convert a string '17.07.2019' to date format 17-07-2019 (or 17-Jul-2019)

I tried this code

from datetime import datetime
x = '17.07.2019'
y=datetime.strptime(x,'%d.%m.%y')
y=datetime.strftime(x,'%d.%m.%y')

but I get this error

TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'

I then tried

y=pd.to_datetime(x,'%d.'%m.%Y')

but I got this error

SyntaxError: invalid syntax

Body:
You could just use str.replace for something this simple.

y = x.replace('.', '-')

Or to fix your code you need to just use strftime on y:

y = date.strptime(x, '%d.%m.%Y')
z = y.strftime('%d-%m-%Y')


问:
How to copy recursively files with multiple specific extensions in bash
I want to copy all files with specific extensions recursively in bash.

****editing****

I've written the full script. I have list of names in a csv file, I'm iterating through each name in that list, then creating a directory with that same name somewhere else, then I'm searching in my source directory for the directory with that name, inside it there are few files with endings of xlsx,tsv,html,gz and I'm trying to copy all of them into the newly created directory.

```<code>sample_list_filepath=/home/lists/papers
destination_path=/home/ds/samples
source_directories_path=/home/papers_final/new

cat $sample_list_filepath/sample_list.csv | while read line
 do
    echo $line
    cd $source_directories_path/$line
    cp -r *.{tsv,xlsx,html,gz} $source_directories_path/$line $destination_path

done
</code>```

This works, but it copies all the files there, with no discrimination for specific extension.

What is the problem?

答:
An easy way to solve your problem is to use find and regex :

```<code>find src/ -regex '.*\.\(tsv\|xlsx\|gz\|html\)$' -exec cp {} dest/ \;
</code>```

find look recursively in the directory you specify (in my example it's src/), allows you to filter with -regex and to apply a command for matching results with -exec

For the regex part :

```<code>.*\.
</code>```

will take the name of the file and the dot before extension,

```<code>\(tsv\|xlsx\|gz\|html\)$
</code>```

verify the extension with those you want.

The exec block is what you do with files you got from regex

```<code>-exec cp {} dest/ \;
</code>```

In this case, you copy what you got ({} meaning) to the destination directory.

Body:
I want to copy all files with specific extensions recursively in bash.

****editing****

I've written the full script. I have list of names in a csv file, I'm iterating through each name in that list, then creating a directory with that same name somewhere else, then I'm searching in my source directory for the directory with that name, inside it there are few files with endings of xlsx,tsv,html,gz and I'm trying to copy all of them into the newly created directory.

sample_list_filepath=/home/lists/papers
destination_path=/home/ds/samples
source_directories_path=/home/papers_final/new

cat $sample_list_filepath/sample_list.csv | while read line
 do
    echo $line
    cd $source_directories_path/$line
    cp -r *.{tsv,xlsx,html,gz} $source_directories_path/$line $destination_path

done

This works, but it copies all the files there, with no discrimination for specific extension.

What is the problem?

Body:
An easy way to solve your problem is to use find and regex :

find src/ -regex '.*\.\(tsv\|xlsx\|gz\|html\)$' -exec cp {} dest/ \;

find look recursively in the directory you specify (in my example it's src/), allows you to filter with -regex and to apply a command for matching results with -exec

For the regex part :

.*\.

will take the name of the file and the dot before extension,

\(tsv\|xlsx\|gz\|html\)$

verify the extension with those you want.

The exec block is what you do with files you got from regex

-exec cp {} dest/ \;

In this case, you copy what you got ({} meaning) to the destination directory.


问:
How to compare SQL Server CDC LSN values in C#?
In SQL its easy as it supports the binary(10) LSN values for comparison:

```<code>SELECT *, __$start_lsn, __$seqval
FROM cdc.fn_cdc_get_all_changes_dbo_sometable(@startLsn, @endLsn, 'all update old')
WHERE __$seqval > @seqval
ORDER BY __$start_lsn, __$seqval
</code>```

In C# it's more difficult:

```<code>byte[] mySeqval = ...
foreach(var row in cdcData)
{
    if(row.seqval > mySeqval) // Cannot perform this
        ...
}
</code>```

Can the LSN / SeqVal values be converted into a number than can be compared easily?
These are 10 bytes (80 bits) in size.

My project is in .Net 3.5

答:
Didn't need to use any of the above in the end. Ony of my collegues solved the problem in the end (Thanks Tony Broodie). The way to do this was to compare to seqval, then take+1. Simples.</p>

```<code>SqlExecutor.ExecuteReader(cnn,
string.Format("SELECT {0} , __$start_lsn, __$seqval , __$update_mask " +
    "FROM cdc.fn_cdc_get_all_changes_{1}(@startLsn,@endLsn,'all update old') cdc {2} " +
    "where __$operation = {3} ORDER BY __$start_lsn, __$seqval", columns,
    captureInstance, joins, (int)operation),
    reader =>
    {
        if (reader != null)
            items.Add(createEntity(reader));
    }, 5, 60, new SqlParameter("@startLsn", lsn),
              new SqlParameter("@endLsn", endLsn));
});
startLsn = lsn;
seqVal = sequence;
var startIndex = sequence == null ? 0 :
  items.FindIndex(0, item => item.Lsn.SequenceEqual(lsn)
    && item.Seqval.SequenceEqual(sequence)) + 1; // <---- Look here. See the +1
return items.Skip(startIndex).ToList();
</code>```

Body:
In SQL its easy as it supports the binary(10) LSN values for comparison:

SELECT *, __$start_lsn, __$seqval
FROM cdc.fn_cdc_get_all_changes_dbo_sometable(@startLsn, @endLsn, 'all update old')
WHERE __$seqval > @seqval
ORDER BY __$start_lsn, __$seqval

In C# it's more difficult:

byte[] mySeqval = ...
foreach(var row in cdcData)
{
    if(row.seqval > mySeqval) // Cannot perform this
        ...
}

Can the LSN / SeqVal values be converted into a number than can be compared easily?
These are 10 bytes (80 bits) in size.

My project is in .Net 3.5

Body:
Didn't need to use any of the above in the end. Ony of my collegues solved the problem in the end (Thanks Tony Broodie). The way to do this was to compare to seqval, then take+1. Simples.

SqlExecutor.ExecuteReader(cnn,
string.Format("SELECT {0} , __$start_lsn, __$seqval , __$update_mask " +
    "FROM cdc.fn_cdc_get_all_changes_{1}(@startLsn,@endLsn,'all update old') cdc {2} " +
    "where __$operation = {3} ORDER BY __$start_lsn, __$seqval", columns,
    captureInstance, joins, (int)operation),
    reader =>
    {
        if (reader != null)
            items.Add(createEntity(reader));
    }, 5, 60, new SqlParameter("@startLsn", lsn),
              new SqlParameter("@endLsn", endLsn));
});
startLsn = lsn;
seqVal = sequence;
var startIndex = sequence == null ? 0 :
  items.FindIndex(0, item => item.Lsn.SequenceEqual(lsn)
    && item.Seqval.SequenceEqual(sequence)) + 1; // <---- Look here. See the +1
return items.Skip(startIndex).ToList();


问:
When i press my spinner i see my data, but when i try to select it, it doesn't set the data?
I am trying to make a spinner which takes data from a Realtime Firebase Database. I extract the data just fine in my log statements and i also see my data when i press my dropdown. But when i try to select something in my spinner it doesn't set the data. Also when i try to call my getSelectedItem() method it gives me the error java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference

In the logs i write there is no null values, therefore i am quite confused as to why i am getting this kind of error

```<code>
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

import com.example.bankapp.BankAccount;
import com.example.bankapp.R;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

public class TransferOwnAccount extends AppCompatActivity {

    private Spinner accountFrom, accountTo;
    private EditText transferAmount;
    private FirebaseDatabase database;
    ArrayList<BankAccount> accounts = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transfer_own_account);
        init();
        loadAccounts();

    }

    public void transferMoney(View view) {
        Log.d("grinern", "olool"+accountFrom.getSelectedItem().toString());
    }

    public void loadAccounts() {
        Intent getIntent = getIntent();
        String userCPR = getIntent.getStringExtra("CPR");
        DatabaseReference dbref = database.getReference("usersbankaccounts/" + userCPR);
        dbref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot data : dataSnapshot.getChildren()) {
                    DatabaseReference bankaccounts = database.getReference("bankaccounts/" + data.getKey());
                    Log.d("grinern", data.getKey());
                    bankaccounts.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                            BankAccount bankAccount = dataSnapshot.getValue(BankAccount.class);
                            accounts.add(bankAccount);
                            Log.d("grinern", ""+accounts);
                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError databaseError) {

                        }
                    });
                }
                Log.d("grinern", ""+accounts);

                ArrayAdapter<BankAccount> adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, accounts);
                accountFrom.setAdapter(adapter);
                accountTo.setAdapter(adapter);
                adapter.notifyDataSetChanged();

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

    }

    public void init() {
        this.accountFrom = findViewById(R.id.transferFromSpinner);
        this.accountTo = findViewById(R.id.transferToSpinner);
        this.transferAmount = findViewById(R.id.transferAmount);
        this.database = FirebaseDatabase.getInstance();

    }
}
</code>```

It should select whatever i press in my dropdown spinner and print that in my log which is called in my transferMoney() method

Below is my layout file:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background"
    tools:context=".TransferOwnAccount">

    <Button
        android:id="@+id/transferButton"
        style="@style/Widget.AppCompat.Button.ButtonBar.AlertDialog"
        android:layout_width="100dp"
        android:layout_height="48dp"
        android:layout_marginTop="80dp"
        android:layout_marginBottom="8dp"
        android:background="@drawable/contrast_background"
        android:text="@string/transfer"
        android:textColor="#FFFFFF"
        android:typeface="serif"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.501"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/transferToSpinner"
        app:layout_constraintVertical_bias="0.006"
        tools:targetApi="lollipop" />

    <TextView
        android:id="@+id/transferToTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="56dp"
        android:text="@string/transfer_to"
        android:textColor="#FFFFFF"
        android:textSize="18sp"
        app:fontFamily="serif"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/transferFromSpinner" />

    <TextView
        android:id="@+id/transferFromTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="44dp"
        android:text="@string/transfer_from"
        android:textColor="#FFFFFF"
        android:textSize="18sp"
        app:fontFamily="serif"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/transferAmount" />

    <TextView
        android:id="@+id/transferTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="44dp"
        android:text="@string/transfer_money"
        android:textColor="#F9FAF9"
        android:textSize="24sp"
        app:fontFamily="serif"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/transferAmount"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="99dp"
        android:autofillHints=""
        android:ems="10"
        android:hint="@string/choose_amount"
        android:inputType="textPersonName"
        android:text="@string/choose_amount"
        android:textColor="#FFFFFF"
        android:typeface="serif"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/transferTitle"
        tools:targetApi="o" />

    <Spinner
        android:id="@+id/transferFromSpinner"
        android:layout_width="288dp"
        android:layout_height="32dp"
        android:layout_marginTop="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.504"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/transferFromTitle" />

    <Spinner
        android:id="@+id/transferToSpinner"
        android:layout_width="288dp"
        android:layout_height="32dp"
        android:layout_marginTop="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/transferToTitle" />
</android.support.constraint.ConstraintLayout>
</code>```

Below is the JSON from my Firebase Database.

```<code>{
  "bankaccounts" : {
    "126" : {
      "accNumber" : "126",
      "balance" : 0,
      "title" : "Default"
    },
    "127" : {
      "accNumber" : "127",
      "balance" : 0,
      "title" : "Budget"
    },
    "128" : {
      "accNumber" : "128",
      "balance" : 0,
      "title" : "Pension"
    }
  },
  "nextNumber" : "128",
  "users" : {
    "1111111111" : {
      "address" : "qwe",
      "cpr" : "1111111111",
      "email" : "qwe",
      "firstname" : "qwe",
      "lastname" : "qwe",
      "password" : "111111",
      "phonenumber" : "793"
    }
  },
  "usersbankaccounts" : {
    "1111111111" : {
      "126" : "Default Account",
      "127" : "Budget Account",
      "128" : "Pension Account"
    }
  }
}
</code>```

答:
You need to change your bankaccounts arraylist to static (To make sure its the same even if the state changes)

And then I moved the adapter as a field and initialized it in the init method, Check the code I provided:

```<code>package com.example.bankapp;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

import com.example.bankapp.BankAccount;
import com.example.bankapp.R;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

public class TransferOwnAccount extends AppCompatActivity {

    private Spinner accountFrom, accountTo;
    private EditText transferAmount;
    private FirebaseDatabase database;
    static  ArrayList<BankAccount> accounts = new ArrayList<>();
    ArrayAdapter<BankAccount> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transfer_own_account);
        init();
        loadAccounts();

    }

    public void transferMoney(View view) {
        Log.d("test", "olool" + accountFrom.getSelectedItem().toString());
    }

    public void loadAccounts() {
        Intent getIntent = getIntent();
        String userCPR = getIntent.getStringExtra("CPR");
        DatabaseReference dbref = database.getReference("usersbankaccounts/" + userCPR);
        dbref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot data : dataSnapshot.getChildren()) {
                    DatabaseReference bankaccounts = database.getReference("bankaccounts/" + data.getKey());
                    Log.d("test", data.getKey());
                    bankaccounts.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                            BankAccount bankAccount = dataSnapshot.getValue(BankAccount.class);
                            accounts.add(bankAccount);
                            adapter.notifyDataSetChanged();

                            Log.d("test", "" + accounts);
                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError databaseError) {

                        }
                    });
                }
                Log.d("test", "" + accounts);

                adapter.notifyDataSetChanged();

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

    }

    public void init() {
        this.adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, accounts);
        this.accountFrom = findViewById(R.id.transferFromSpinner);
        this.accountTo = findViewById(R.id.transferToSpinner);
        this.transferAmount = findViewById(R.id.transferAmount);
        this.database = FirebaseDatabase.getInstance();
        this.accountFrom.setAdapter(adapter);
        this.accountTo.setAdapter(adapter);

    }
}
</code>```

Then you need to make sure you have a toString() method in your bankaccount

```<code> @Override
    public String toString() {
        return title + "--- " +accNumber + "  " + balance ;
    }
</code>```

This should do the trick :)

Body:
I am trying to make a spinner which takes data from a Realtime Firebase Database. I extract the data just fine in my log statements and i also see my data when i press my dropdown. But when i try to select something in my spinner it doesn't set the data. Also when i try to call my getSelectedItem() method it gives me the error java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference

In the logs i write there is no null values, therefore i am quite confused as to why i am getting this kind of error

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

import com.example.bankapp.BankAccount;
import com.example.bankapp.R;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

public class TransferOwnAccount extends AppCompatActivity {

    private Spinner accountFrom, accountTo;
    private EditText transferAmount;
    private FirebaseDatabase database;
    ArrayList<BankAccount> accounts = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transfer_own_account);
        init();
        loadAccounts();

    }

    public void transferMoney(View view) {
        Log.d("grinern", "olool"+accountFrom.getSelectedItem().toString());
    }

    public void loadAccounts() {
        Intent getIntent = getIntent();
        String userCPR = getIntent.getStringExtra("CPR");
        DatabaseReference dbref = database.getReference("usersbankaccounts/" + userCPR);
        dbref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot data : dataSnapshot.getChildren()) {
                    DatabaseReference bankaccounts = database.getReference("bankaccounts/" + data.getKey());
                    Log.d("grinern", data.getKey());
                    bankaccounts.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                            BankAccount bankAccount = dataSnapshot.getValue(BankAccount.class);
                            accounts.add(bankAccount);
                            Log.d("grinern", ""+accounts);
                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError databaseError) {

                        }
                    });
                }
                Log.d("grinern", ""+accounts);

                ArrayAdapter<BankAccount> adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, accounts);
                accountFrom.setAdapter(adapter);
                accountTo.setAdapter(adapter);
                adapter.notifyDataSetChanged();

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

    }

    public void init() {
        this.accountFrom = findViewById(R.id.transferFromSpinner);
        this.accountTo = findViewById(R.id.transferToSpinner);
        this.transferAmount = findViewById(R.id.transferAmount);
        this.database = FirebaseDatabase.getInstance();

    }
}

It should select whatever i press in my dropdown spinner and print that in my log which is called in my transferMoney() method

Below is my layout file:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background"
    tools:context=".TransferOwnAccount">

    <Button
        android:id="@+id/transferButton"
        style="@style/Widget.AppCompat.Button.ButtonBar.AlertDialog"
        android:layout_width="100dp"
        android:layout_height="48dp"
        android:layout_marginTop="80dp"
        android:layout_marginBottom="8dp"
        android:background="@drawable/contrast_background"
        android:text="@string/transfer"
        android:textColor="#FFFFFF"
        android:typeface="serif"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.501"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/transferToSpinner"
        app:layout_constraintVertical_bias="0.006"
        tools:targetApi="lollipop" />

    <TextView
        android:id="@+id/transferToTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="56dp"
        android:text="@string/transfer_to"
        android:textColor="#FFFFFF"
        android:textSize="18sp"
        app:fontFamily="serif"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/transferFromSpinner" />

    <TextView
        android:id="@+id/transferFromTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="44dp"
        android:text="@string/transfer_from"
        android:textColor="#FFFFFF"
        android:textSize="18sp"
        app:fontFamily="serif"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/transferAmount" />

    <TextView
        android:id="@+id/transferTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="44dp"
        android:text="@string/transfer_money"
        android:textColor="#F9FAF9"
        android:textSize="24sp"
        app:fontFamily="serif"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/transferAmount"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="99dp"
        android:autofillHints=""
        android:ems="10"
        android:hint="@string/choose_amount"
        android:inputType="textPersonName"
        android:text="@string/choose_amount"
        android:textColor="#FFFFFF"
        android:typeface="serif"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/transferTitle"
        tools:targetApi="o" />

    <Spinner
        android:id="@+id/transferFromSpinner"
        android:layout_width="288dp"
        android:layout_height="32dp"
        android:layout_marginTop="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.504"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/transferFromTitle" />

    <Spinner
        android:id="@+id/transferToSpinner"
        android:layout_width="288dp"
        android:layout_height="32dp"
        android:layout_marginTop="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/transferToTitle" />
</android.support.constraint.ConstraintLayout>

Below is the JSON from my Firebase Database.

{
  "bankaccounts" : {
    "126" : {
      "accNumber" : "126",
      "balance" : 0,
      "title" : "Default"
    },
    "127" : {
      "accNumber" : "127",
      "balance" : 0,
      "title" : "Budget"
    },
    "128" : {
      "accNumber" : "128",
      "balance" : 0,
      "title" : "Pension"
    }
  },
  "nextNumber" : "128",
  "users" : {
    "1111111111" : {
      "address" : "qwe",
      "cpr" : "1111111111",
      "email" : "qwe",
      "firstname" : "qwe",
      "lastname" : "qwe",
      "password" : "111111",
      "phonenumber" : "793"
    }
  },
  "usersbankaccounts" : {
    "1111111111" : {
      "126" : "Default Account",
      "127" : "Budget Account",
      "128" : "Pension Account"
    }
  }
}

Body:
You need to change your bankaccounts arraylist to static (To make sure its the same even if the state changes)

And then I moved the adapter as a field and initialized it in the init method, Check the code I provided:

package com.example.bankapp;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

import com.example.bankapp.BankAccount;
import com.example.bankapp.R;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

public class TransferOwnAccount extends AppCompatActivity {

    private Spinner accountFrom, accountTo;
    private EditText transferAmount;
    private FirebaseDatabase database;
    static  ArrayList<BankAccount> accounts = new ArrayList<>();
    ArrayAdapter<BankAccount> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transfer_own_account);
        init();
        loadAccounts();

    }

    public void transferMoney(View view) {
        Log.d("test", "olool" + accountFrom.getSelectedItem().toString());
    }

    public void loadAccounts() {
        Intent getIntent = getIntent();
        String userCPR = getIntent.getStringExtra("CPR");
        DatabaseReference dbref = database.getReference("usersbankaccounts/" + userCPR);
        dbref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot data : dataSnapshot.getChildren()) {
                    DatabaseReference bankaccounts = database.getReference("bankaccounts/" + data.getKey());
                    Log.d("test", data.getKey());
                    bankaccounts.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                            BankAccount bankAccount = dataSnapshot.getValue(BankAccount.class);
                            accounts.add(bankAccount);
                            adapter.notifyDataSetChanged();

                            Log.d("test", "" + accounts);
                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError databaseError) {

                        }
                    });
                }
                Log.d("test", "" + accounts);

                adapter.notifyDataSetChanged();

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

    }

    public void init() {
        this.adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, accounts);
        this.accountFrom = findViewById(R.id.transferFromSpinner);
        this.accountTo = findViewById(R.id.transferToSpinner);
        this.transferAmount = findViewById(R.id.transferAmount);
        this.database = FirebaseDatabase.getInstance();
        this.accountFrom.setAdapter(adapter);
        this.accountTo.setAdapter(adapter);

    }
}

Then you need to make sure you have a toString() method in your bankaccount

 @Override
    public String toString() {
        return title + "--- " +accNumber + "  " + balance ;
    }

This should do the trick :)


问:
How to use "and" with conditions in Python?
I am trying to create a subset of data based on conditions of a certain column in the original data set. It works fine with only one condition (For example, data[TNT]<10000, but it doesn't work if I want to limit it within a range (data[TNT]>10000 and data[TNT]<25000.

#group2= 10k<TNT<25k
group2_b =  data['TNT']>10000 and data['TNT']<=25000
group2 = data[group2_b]
```

<p>The error message is:</p>

<blockquote>
```ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
```

答:
Try to add parentheses:

```<code>group2_b = (data['TNT']>10000) and (data['TNT']<=25000)
</code>```

Or use method:

```<code>group2_b = data['TNT'].gt(10000) & data['TNT'].le(25000)
</code>```

or use between:

```<code>group2_b = data['TNT'].between(10000,25000)
</code>```

Body:
I am trying to create a subset of data based on conditions of a certain column in the original data set. It works fine with only one condition (For example, data[TNT]<10000, but it doesn't work if I want to limit it within a range (data[TNT]>10000 and data[TNT]<25000.

#group2= 10k<TNT<25k
group2_b =  data['TNT']>10000 and data['TNT']<=25000
group2 = data[group2_b]

The error message is:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Body:
Try to add parentheses:

group2_b = (data['TNT']>10000) and (data['TNT']<=25000)

Or use method:

group2_b = data['TNT'].gt(10000) & data['TNT'].le(25000)

or use between:

group2_b = data['TNT'].between(10000,25000)


问:
For `case class Cc(a: Int, b: Int) extends MyTraitA`, where does `MyTraitA` appear with `Product` and `Serializable` traits?
Because of inheritance linearization in Scala, I would like to understand how traits I specify for a case class are ordered relative to the two traits automatically generated and added by the Scala compiler; i.e. Product with Serializable (and disappointingly, it's not ProductN[...] as of 2.12).

I've searched through pretty thoroughly and I haven't found it directly addressed. Given the following:

```<code>case class Cc(a: Int, b: Int) extends MyTraitA with MyTraitB
</code>```

Following the Scala compiler automatic code generation, which of these is the correct assumption about the resulting inheritance ordering?

case class Cc(a: Int, b: Int) extends MyTraitA with MyTraitB with Product with Serializable

case class Cc(a: Int, b: Int) extends Product with Serializable with MyTraitA with MyTraitB

And then, I have an additional question. What undesirable or unexpected effects could occur if I were to explicitly extend Product2[...] to the case class? Here are the two above pieces of code repeated with Product2[...] inserted:

case class Cc(a: Int, b: Int) extends MyTraitA with MyTraitB with Product2[Int, Int] with Product with Serializable

case class Cc(a: Int, b: Int) extends Product with Serializable with MyTraitA with MyTraitB with Product2[Int, Int]

IOW, is there any sort of undesirable interactions because both Product and Product2 appear together?

答:
Thanks to deep reading a link provided in a comment by Bogdan Vakulenko, the explicit answer to the first question is item 2:

```<code>case class Cc(a: Int, b: Int) extends Product with Serializable with MyTraitA with MyTraitB
</code>```

And thanks, again, to Bogdan Vakulenko, the answer to the second question is nothing undesirable should occur when adding the Product2[Int, Int] trait given it extends the Product trait.

There is a bonus answer which is very interesting. If it is desired to push the compiler generated interfaces to the back of the trait inheritance ordering, it's required the compiler generated interfaces instead be explicitly defined. And there are several ways to do this.

The first and simplest is to change the original code which appeared like this (no reference to Product nor Serializable and have the compiler automatically generate them):

```<code>case class Cc(a: Int, b: Int) extends MyTraitA with MyTraitB
</code>```

to appear like this (explicitly defining Product and Serializable at the tail of the trait list):

```<code>case class Cc(a: Int, b: Int) extends MyTraitA with MyTraitB with Product with Serializable
</code>```

The second option is to add Product with Serializable to both/either of MyTraitA and/or MyTraitB as such:

```<code>trait MyTraitA extends Product with Serializable
trait MyTraitB extends Product with Serializable
case class Cc(a: Int, b: Int) extends MyTraitA with MyTraitB
</code>```

This technique also results in desirable trait ordering.

```<code>case class Cc(a: Int, b: Int) extends MyTraitA with MyTraitB with Product with Serializable
</code>```

Finally, integrating Product2[Int, Int] is as simple as explicitly defining everything knowing any overlaps will be automatically resolved via the excellent multiple inheritance resolution strategies provided by default within the Scala compiler:

```<code>case class Cc(a: Int, b: Int) extends MyTraitA with MyTraitB with Product2[Int, Int] with Product with Serializable {
  override def _1: Int = a
  override def _2: Int = b
}
</code>```

Body:
Because of inheritance linearization in Scala, I would like to understand how traits I specify for a case class are ordered relative to the two traits automatically generated and added by the Scala compiler; i.e. Product with Serializable (and disappointingly, it's not ProductN[...] as of 2.12).

I've searched through pretty thoroughly and I haven't found it directly addressed. Given the following:

case class Cc(a: Int, b: Int) extends MyTraitA with MyTraitB

Following the Scala compiler automatic code generation, which of these is the correct assumption about the resulting inheritance ordering?

case class Cc(a: Int, b: Int) extends MyTraitA with MyTraitB with Product with Serializable

case class Cc(a: Int, b: Int) extends Product with Serializable with MyTraitA with MyTraitB

And then, I have an additional question. What undesirable or unexpected effects could occur if I were to explicitly extend Product2[...] to the case class? Here are the two above pieces of code repeated with Product2[...] inserted:

case class Cc(a: Int, b: Int) extends MyTraitA with MyTraitB with Product2[Int, Int] with Product with Serializable

case class Cc(a: Int, b: Int) extends Product with Serializable with MyTraitA with MyTraitB with Product2[Int, Int]

IOW, is there any sort of undesirable interactions because both Product and Product2 appear together?

Body:
Thanks to deep reading a link provided in a comment by Bogdan Vakulenko, the explicit answer to the first question is item 2:

case class Cc(a: Int, b: Int) extends Product with Serializable with MyTraitA with MyTraitB

And thanks, again, to Bogdan Vakulenko, the answer to the second question is nothing undesirable should occur when adding the Product2[Int, Int] trait given it extends the Product trait.

There is a bonus answer which is very interesting. If it is desired to push the compiler generated interfaces to the back of the trait inheritance ordering, it's required the compiler generated interfaces instead be explicitly defined. And there are several ways to do this.

The first and simplest is to change the original code which appeared like this (no reference to Product nor Serializable and have the compiler automatically generate them):

case class Cc(a: Int, b: Int) extends MyTraitA with MyTraitB

to appear like this (explicitly defining Product and Serializable at the tail of the trait list):

case class Cc(a: Int, b: Int) extends MyTraitA with MyTraitB with Product with Serializable

The second option is to add Product with Serializable to both/either of MyTraitA and/or MyTraitB as such:

trait MyTraitA extends Product with Serializable
trait MyTraitB extends Product with Serializable
case class Cc(a: Int, b: Int) extends MyTraitA with MyTraitB

This technique also results in desirable trait ordering.

case class Cc(a: Int, b: Int) extends MyTraitA with MyTraitB with Product with Serializable

Finally, integrating Product2[Int, Int] is as simple as explicitly defining everything knowing any overlaps will be automatically resolved via the excellent multiple inheritance resolution strategies provided by default within the Scala compiler:

case class Cc(a: Int, b: Int) extends MyTraitA with MyTraitB with Product2[Int, Int] with Product with Serializable {
  override def _1: Int = a
  override def _2: Int = b
}


问:
Can you align only a part of the text in a textbox?
I wanna generate a ranking for teams that are in a list based on their points. How can i format so the names are all aligned left and their points are aligned right in the textbox?

```<code>//Generating ranking
private void Grid_Loaded(object sender, RoutedEventArgs e)
        {
            teams = teams.OrderByDescending(o => o.Points).ToList();
            for (int i = 0; i < teams.Count; i++)
            {
                rankingTextBox.Text += $"{i + 1}.  {teams[i].Name} {teams[i].Points}\n";
            }
        }
</code>```

Now i get this:

Team  10

secondteam  5

thirdTeam  2

But i should be like this without dots:

Team.............10

secondteam...5

thirdTeam.......2

Thank you

答:
this may work:    </p>

```<code>private string SameSize(int Maxsize, string team)
{
        if (team.Length < Maxsize)
            return SameSize(Maxsize, team + ".");
        else
            return team;
}

var maxlength = teams.OrderByDescending(x => x.Name.Length).First().Length + 4;

rankingTextBox.Text += $"{i + 1}.  {SameSize(maxlength,teams[i].Name)} {teams[i].Points}\n";
</code>```

Body:
I wanna generate a ranking for teams that are in a list based on their points. How can i format so the names are all aligned left and their points are aligned right in the textbox?

//Generating ranking
private void Grid_Loaded(object sender, RoutedEventArgs e)
        {
            teams = teams.OrderByDescending(o => o.Points).ToList();
            for (int i = 0; i < teams.Count; i++)
            {
                rankingTextBox.Text += $"{i + 1}.  {teams[i].Name} {teams[i].Points}\n";
            }
        }

Now i get this:

Team  10

secondteam  5

thirdTeam  2

But i should be like this without dots:

Team.............10

secondteam...5

thirdTeam.......2

Thank you

Body:
this may work:

private string SameSize(int Maxsize, string team)
{
        if (team.Length < Maxsize)
            return SameSize(Maxsize, team + ".");
        else
            return team;
}

var maxlength = teams.OrderByDescending(x => x.Name.Length).First().Length + 4;

rankingTextBox.Text += $"{i + 1}.  {SameSize(maxlength,teams[i].Name)} {teams[i].Points}\n";


问:
Web Scraping - I need to login LinkedIn in order to webscrape (scrapy)
I am currently creating a web scraper for Linkedin but LinkedIn blocks my bot from scraping data because i am not logged in into any account. My goal is basically to scrape any job offering made by companies but my question is primarly on the logging in aspect of the code.

I am on Python 3.X using scrapy and formrequest.

I therefore looked online for the solution the formrequest package seemed to be the answer i needed. However, after several attempts it's still not working.

```<code>import scrapy
from scrapy.http import FormRequest
from scrapy.utils.response import open_in_browser
from ..items import LinkedinItem

class LinkedinSpiderSpider(scrapy.Spider):
    name = 'linkedin_spider'
    start_urls = ['https://www.linkedin.com/login']

    def parse(self, response):
        token = response.css('form input::attr(value)').extract_first()
        print(token)
        return FormRequest.from_response(response, formdata={
            'csrf_token': token,
            'username': 'XXX@gmail.com',
            'password': 'XXX'
        }, callback=self.start_scraping)

    def start_scraping(self, response):
        open_in_browser(response)
        items = LinkedinItem()
        all_div_quotes = response.css('div.quote')

        for quotes in all_div_quotes:
            Job_offers = response.css('.disabled').css('::text').extract()
            company = response.css('.job-card-search__company-name-link').css('::text').extract()
            information = response.css('.job-card-search__description-snippet').css('::text').extract()

            items['Job_offers'] = Job_offers
            items['company'] = company
            items['information'] = information

            yield items
</code>```

I added the open_in_browser package in order to verify if i was logged in properly and the browser opens to the login screen and it's wrritten: please enter an email adress

I expect my browser to open to the home page with my account logged in.

Thank you

答:
While I can't provide an answer to your original question, I can tell you that what you're doing is against LinkedIn's software extensions policy.

In order to protect our members' data and our website, we don't permit the use of any third party software, including "crawlers", bots, browser plug-ins, or browser extensions (also called "add-ons"), that scrapes, modifies the appearance of, or automates activity on LinkedIn's website.

Be careful here. Not only do many websites employ methods to protect against scraping data, but some (LinkedIn included) have been to known to take developers to court over this kind of thing.

For a safe, legal way to do what you're trying to do, check out LinkedIn's API page.

Body:
I am currently creating a web scraper for Linkedin but LinkedIn blocks my bot from scraping data because i am not logged in into any account. My goal is basically to scrape any job offering made by companies but my question is primarly on the logging in aspect of the code.

I am on Python 3.X using scrapy and formrequest.

I therefore looked online for the solution the formrequest package seemed to be the answer i needed. However, after several attempts it's still not working.

import scrapy
from scrapy.http import FormRequest
from scrapy.utils.response import open_in_browser
from ..items import LinkedinItem

class LinkedinSpiderSpider(scrapy.Spider):
    name = 'linkedin_spider'
    start_urls = ['https://www.linkedin.com/login']

    def parse(self, response):
        token = response.css('form input::attr(value)').extract_first()
        print(token)
        return FormRequest.from_response(response, formdata={
            'csrf_token': token,
            'username': 'XXX@gmail.com',
            'password': 'XXX'
        }, callback=self.start_scraping)

    def start_scraping(self, response):
        open_in_browser(response)
        items = LinkedinItem()
        all_div_quotes = response.css('div.quote')

        for quotes in all_div_quotes:
            Job_offers = response.css('.disabled').css('::text').extract()
            company = response.css('.job-card-search__company-name-link').css('::text').extract()
            information = response.css('.job-card-search__description-snippet').css('::text').extract()

            items['Job_offers'] = Job_offers
            items['company'] = company
            items['information'] = information

            yield items

I added the open_in_browser package in order to verify if i was logged in properly and the browser opens to the login screen and it's wrritten: please enter an email adress

I expect my browser to open to the home page with my account logged in.

Thank you


问:
Eclipselink NamedNativeQuery pass column name as parameter and not a value
Trying to pass column name as parameter but JPA sets it as a value surrounding it with single quotes.

```<code>@NamedNativeQueries({
    @NamedNativeQuery(
            name = "Genre.findAllLocalized",
            query = "SELECT "
                    + " CASE "
                    + "     WHEN ? IS NULL THEN genre_default"
                    + "     ELSE ? "
                    + " END localized_genre "
                    + "FROM genre ORDER BY localized_genre")
})
</code>```

Then:

```<code>List<String> res = em.createNamedQuery("Genre.findAllLocalized")
                .setParameter(1, colName)
                .setParameter(2, colName)
                .getResultList();
</code>```

The problem is that the column names being passed are taken as values so the result will return result list with repeated values of "col_name" instead of selecting the value of the column passed as parameter.

Is this achievable?

答:
Basically it makes no sense to create a prepared query like this, how would you name that query anyway: "*"? So the short answer is: no.

But you could create named queries dynamically if this matches your requirement:

```<code>String colName = "colName";
String query = "SELECT WHEN " + colName + " IS NULL THEN genre_default";
Query query = entitymanager.createQuery(query);
</code>```

Probably using a criteria builder is more the way you want to use JPA (code from https://en.wikibooks.org/wiki/Java_Persistence/Criteria):

```<code>// Select the employees and the mailing addresses that have the same address.
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery criteriaQuery = criteriaBuilder.createQuery();
Root employee = criteriaQuery.from(Employee.class);
Root address = criteriaQuery.from(MailingAddress.class);
criteriaQuery.multiselect(employee, address);

criteriaQuery.where( criteriaBuilder.equal(employee.get("address"), address.get("address"));
Query query = entityManager.createQuery(criteriaQuery);
List<Object[]> result = query.getResultList();
</code>```

Body:
Trying to pass column name as parameter but JPA sets it as a value surrounding it with single quotes.

@NamedNativeQueries({
    @NamedNativeQuery(
            name = "Genre.findAllLocalized",
            query = "SELECT "
                    + " CASE "
                    + "     WHEN ? IS NULL THEN genre_default"
                    + "     ELSE ? "
                    + " END localized_genre "
                    + "FROM genre ORDER BY localized_genre")
})

Then:

List<String> res = em.createNamedQuery("Genre.findAllLocalized")
                .setParameter(1, colName)
                .setParameter(2, colName)
                .getResultList();

The problem is that the column names being passed are taken as values so the result will return result list with repeated values of "col_name" instead of selecting the value of the column passed as parameter.

Is this achievable?

Body:
Basically it makes no sense to create a prepared query like this, how would you name that query anyway: "*"? So the short answer is: no.

But you could create named queries dynamically if this matches your requirement:

String colName = "colName";
String query = "SELECT WHEN " + colName + " IS NULL THEN genre_default";
Query query = entitymanager.createQuery(query);

Probably using a criteria builder is more the way you want to use JPA (code from https://en.wikibooks.org/wiki/Java_Persistence/Criteria):

// Select the employees and the mailing addresses that have the same address.
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery criteriaQuery = criteriaBuilder.createQuery();
Root employee = criteriaQuery.from(Employee.class);
Root address = criteriaQuery.from(MailingAddress.class);
criteriaQuery.multiselect(employee, address);

criteriaQuery.where( criteriaBuilder.equal(employee.get("address"), address.get("address"));
Query query = entityManager.createQuery(criteriaQuery);
List<Object[]> result = query.getResultList();


问:
mongoose push to array
I need to push an object into an array into the database, but I get an error. What am I doing wrong ? I found such a topic Push items into mongo array via mongoose but can not properly apply
..................................................................................................................................

```<code>habalka.files.push({_id: "tata", destination: "Harry"});
    habalka.save((res) => {
      console.log(res)
    });
</code>```

when I try this code i get this answer

MongooseError: document must have an _id before saving

database

```<code>{
 "_id": "78935e75-86c0-47c2-a76d-2b52a0a71e7c",
    "files": [
        {
            "_id": "67e848e5-7fb0-480b-a1d3-f3a09d1b57f7",
            "destination": "./uploads/78935e75-86c0-47c2-a76d-2b52a0a71e7c",
            "filename": "67e848e5-7fb0-480b-a1d3-f3a09d1b57f7.mp3",
            "path": "uploads\\78935e75-86c0-47c2-a76d-2b52a0a71e7c\\67e848e5-7fb0-480b-a1d3-f3a09d1b57f7.mp3",
            "folder": "78935e75-86c0-47c2-a76d-2b52a0a71e7c",
            "info": {
                "size": 12120000,
                "mimetype": "audio/mp3",
                "encoding": "7bit",
                "originalname": "Попрошайка Евгений Владимирович из ФАСП. Выпуск 10.mp3",
                "fieldname": "selectedFile"
            },
            "date": {
                "$date": "2019-05-23T01:07:27.122Z"
            }
        }
    ],
    "date": {
        "$date": "2019-05-23T01:07:27.123Z"
    },
    "__v": 0
}
</code>```

Schema

```<code>const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const HabalkaSchema = new Schema({
  _id: {
    type: String
  },
  files: [
    {
      _id: {
        type: String
      },
      destination: {
        type: String
      },
      filename: {
        type: String
      },
      path: {
        type: String
      },
      folder: {
        type: String
      },
      info: {
        size: {
          type: Number
        },
        mimetype: {
          type: String
        },
        encoding: {
          type: String
        },
        originalname: {
          type: String
        },
        fieldname: {
          type: String
        },
      },
      date: {
        type: Date,
        default: Date.now
      }
    }
  ],
  date: {
    type: Date,
    default: Date.now
  }
});
module.exports = Habalka = mongoose.model('habalka', HabalkaSchema);
</code>```

request

```<code>let Habalka = habalka.findOne({_id: "78935e75-86c0-47c2-a76d-2b52a0a71e7c"});
Habalka.files.push({destination: "Harry"});
Habalka.save();
</code>```

答:
I believe your issue is pushing to destination when it should be files

I would try

```<code>habalka.update(
{_id: "78935e75-86c0-47c2-a76d-2b52a0a71e7c"},
{$push: { files: {destination: "Harry"} }
);
</code>```

Title: mongoose push to array

Body:
I need to push an object into an array into the database, but I get an error. What am I doing wrong ? I found such a topic Push items into mongo array via mongoose but can not properly apply
..................................................................................................................................

habalka.files.push({_id: "tata", destination: "Harry"});
    habalka.save((res) => {
      console.log(res)
    });

when I try this code i get this answer

MongooseError: document must have an _id before saving

database

{
 "_id": "78935e75-86c0-47c2-a76d-2b52a0a71e7c",
    "files": [
        {
            "_id": "67e848e5-7fb0-480b-a1d3-f3a09d1b57f7",
            "destination": "./uploads/78935e75-86c0-47c2-a76d-2b52a0a71e7c",
            "filename": "67e848e5-7fb0-480b-a1d3-f3a09d1b57f7.mp3",
            "path": "uploads\\78935e75-86c0-47c2-a76d-2b52a0a71e7c\\67e848e5-7fb0-480b-a1d3-f3a09d1b57f7.mp3",
            "folder": "78935e75-86c0-47c2-a76d-2b52a0a71e7c",
            "info": {
                "size": 12120000,
                "mimetype": "audio/mp3",
                "encoding": "7bit",
                "originalname": "Попрошайка Евгений Владимирович из ФАСП. Выпуск 10.mp3",
                "fieldname": "selectedFile"
            },
            "date": {
                "$date": "2019-05-23T01:07:27.122Z"
            }
        }
    ],
    "date": {
        "$date": "2019-05-23T01:07:27.123Z"
    },
    "__v": 0
}

Schema

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const HabalkaSchema = new Schema({
  _id: {
    type: String
  },
  files: [
    {
      _id: {
        type: String
      },
      destination: {
        type: String
      },
      filename: {
        type: String
      },
      path: {
        type: String
      },
      folder: {
        type: String
      },
      info: {
        size: {
          type: Number
        },
        mimetype: {
          type: String
        },
        encoding: {
          type: String
        },
        originalname: {
          type: String
        },
        fieldname: {
          type: String
        },
      },
      date: {
        type: Date,
        default: Date.now
      }
    }
  ],
  date: {
    type: Date,
    default: Date.now
  }
});
module.exports = Habalka = mongoose.model('habalka', HabalkaSchema);

request

let Habalka = habalka.findOne({_id: "78935e75-86c0-47c2-a76d-2b52a0a71e7c"});
Habalka.files.push({destination: "Harry"});
Habalka.save();

Body:
I believe your issue is pushing to destination when it should be files

I would try

habalka.update(
{_id: "78935e75-86c0-47c2-a76d-2b52a0a71e7c"},
{$push: { files: {destination: "Harry"} }
);