问:
C++ How to make a numbered list only as big as the number of things in my vector
I want to make a numbered list for the contents of my vector that will shrink or increase depending on how many things are in the vector, since the user will be able to add or delete contents in the vector at will.

In this project, the user can select from a menu to edit the vector by 1. Adding a book, 2. Showing a list of all the books in the vector, and 3. Deleting a book. The function seen below is option 3, delete a book. As you can see I have set up 'y' to be the user selection that gets erased, all I need now is a way to list the books (contents of my vector bookCollection) in a numbered list for the user.

```<code>int delBook(vector<string> *bookCollection)
{
    int y;
    for (vector<string>::iterator bIter = bookCollection->begin(); bIter < bookCollection->end(); bIter++)
    {
        if (bookCollection->at(y+1) == *bIter)
        {
            bookCollection->erase(bIter);
        }
    }
}
</code>```

I want the delete selection to look something like this in the console:

"Book One"

"Book Two"

"Book Three"

"Book Four"

Enter the number of the book you want to delete: "4"

But can shrink or increase based on how many strings have been added to the vector, so next time the user selects "3. Delete a Book" it shows:

"Book One"

"Book Two"

"Book Three"

Enter the number of the book you want to delete:

I'm still very new to programming so forgive me if none of this made sense, still learning the lingo.

答:
There are many methods for displaying and processing menus.

Here is a table driven approach:

```<code>struct Menu_Item
{
  const char * menu_text;
  void (*processing_function)(); // Pointer to processing function
};

void Process_Hello()
{
   std::cout << "Hello\n";
}

static const Menu_Entry menu_1[] =
{
  {"Print Hello", Process_Hello},
};
const size_t menu_1_item_count =
sizeof(menu_1) / sizeof(menu_1[0]);

void Menu_Processor(Menu_Entry const * const p_menu,
                    size_t item_count)
{
  for (unsigned int i = 0; i < item_count; ++i)
  {
    std::cout << (i + 1) << p_menu[i].menu_text << "\n";
  }
  unsigned int selection;
  std::cin >> selection;
  // Process the selection:
  (p_menu[selection - 1])();
}
</code>```

This method is nice because you can insert or remove entries into the table without having to change the code.  It can be improved, but this one demonstrates the concept of a table driven menu system.

Body:
I want to make a numbered list for the contents of my vector that will shrink or increase depending on how many things are in the vector, since the user will be able to add or delete contents in the vector at will.

In this project, the user can select from a menu to edit the vector by 1. Adding a book, 2. Showing a list of all the books in the vector, and 3. Deleting a book. The function seen below is option 3, delete a book. As you can see I have set up 'y' to be the user selection that gets erased, all I need now is a way to list the books (contents of my vector bookCollection) in a numbered list for the user.

int delBook(vector<string> *bookCollection)
{
    int y;
    for (vector<string>::iterator bIter = bookCollection->begin(); bIter < bookCollection->end(); bIter++)
    {
        if (bookCollection->at(y+1) == *bIter)
        {
            bookCollection->erase(bIter);
        }
    }
}

I want the delete selection to look something like this in the console:

"Book One"

"Book Two"

"Book Three"

"Book Four"

Enter the number of the book you want to delete: "4"

But can shrink or increase based on how many strings have been added to the vector, so next time the user selects "3. Delete a Book" it shows:

"Book One"

"Book Two"

"Book Three"

Enter the number of the book you want to delete:

I'm still very new to programming so forgive me if none of this made sense, still learning the lingo.

Body:
There are many methods for displaying and processing menus.

Here is a table driven approach:

struct Menu_Item
{
  const char * menu_text;
  void (*processing_function)(); // Pointer to processing function
};

void Process_Hello()
{
   std::cout << "Hello\n";
}

static const Menu_Entry menu_1[] =
{
  {"Print Hello", Process_Hello},
};
const size_t menu_1_item_count =
sizeof(menu_1) / sizeof(menu_1[0]);

void Menu_Processor(Menu_Entry const * const p_menu,
                    size_t item_count)
{
  for (unsigned int i = 0; i < item_count; ++i)
  {
    std::cout << (i + 1) << p_menu[i].menu_text << "\n";
  }
  unsigned int selection;
  std::cin >> selection;
  // Process the selection:
  (p_menu[selection - 1])();
}

This method is nice because you can insert or remove entries into the table without having to change the code.  It can be improved, but this one demonstrates the concept of a table driven menu system.


来源: stackexchange

问:
Changing application.properties in AWS for a Spring Boot webapp
I've made a spring project using Boot. the project runs fine locally. It's a simple webapp connected to a mysql database. The configuration path is:

src/main/resources/application.properties

With parameters like this:

```<code>spring.datasource.url = xxx
spring.datasource.username = xxx
spring.datasource.password = xxx
</code>```

Now, I've deployed the app in AWS without problems. I've configured the database already but when the app tries to start I'm getting this error:

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

I guess that is using my local configuratión file that was packed in the war file. Now, how can I change those values in the AWS? O do I need to pack the war with the correct application.properties in that server?

Thanks!

答:
Please read this:

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

There are several methods of setting configuration outside your JARs resource, pick the one that works for you.

ContentLicense: CC BY-SA 3.0

Body:
I've made a spring project using Boot. the project runs fine locally. It's a simple webapp connected to a mysql database. The configuration path is:

src/main/resources/application.properties

With parameters like this:

spring.datasource.url = xxx
spring.datasource.username = xxx
spring.datasource.password = xxx

Now, I've deployed the app in AWS without problems. I've configured the database already but when the app tries to start I'm getting this error:

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

I guess that is using my local configuratión file that was packed in the war file. Now, how can I change those values in the AWS? O do I need to pack the war with the correct application.properties in that server?

Thanks!


问:
Adobe InDesign XML import with XSL Stylesheet
I'm new to Adobe InDesign and have a basic question about importing XML data with an associated XSL style sheet to create a PDF document.

Essentially I have a XML & XSL file that display correctly as a webpage, but I would like to convert the webpage into a PDF document while retaining the internal hyperlinks contained in the XML.

There's two parts to this question:

Firstly, can I use the same style sheet and XML file that is use for HTML web display for InDesign?  The reason I asked is because I went through the motions with the import XML hoping that it would work with minimal effort, but only came up with the XSL display in the document, so obviously something went wrong but with my limited understanding I don't know what.  Is the style sheet incompatible?

Secondly, would the hyperlinks be retained?

Many thanks!

答:
It's a bit hard to state anything here. In the situation where the current xsl file would work with InDesign as it, there are peculiarities in both worlds that won't save you from some efforts. HTML tags won't be interpreted by InDesign.
,  or  for exemple will only be nodes without specific meanings.

Layout concerns in InDesign will imply that you attach paragraph and character styles to tags or that you add namespaced attributes in the incoming XML with XSLT. Something that you didn't do in your current XSLT.
Of course, any CSS you attached in the HTML file is useless with InDesign.

So basically, you have two choices. First one is to write another XSL for InDesign that will allow to import the XML file smoothly within InDesign. Or to not use InDesign at all and have a look at XSL:FO which can convert XML to PDF through XSLT.


问:
Git asking for password from command line
I setup git and gitosis on a server to manage my repos.  It's working properly for the initial shell account I set it up with, i.e. I can run:

```<code>git clone git@MYSERVER:gitosis-admin.git
</code>```

But when I try to use the separate accounts I've created (via gitosis.conf) it keeps asking for a password:

```<code>git clone johndoe@MYSERVER:gitosis-admin.git
</code>```

I setup the SSH key and pushed a copy to the keydir on the server.  This question seems to address the same problem, but the solution given is for tortoisegit.

Git keeps asking for password

How do I tell git to use the ssh key instead of asking for a password?

答:
You don't use your user name, you always say:

```<code>git clone git@MYSERVER:<repository>
</code>```

Gitosis associates your name in its config file with the name of your key on the server. That is, you have lines like

```<code>[group users]
members = johndoe janeroe
writable = repo1 repo2
</code>```

in gitosis.conf, and files johndoe.pub, janedoe.pub in gitosis-admin/keydir; gitosis will use the appropriate key for the user but you always use "git" as the user in the URL. That's because it's always using the "git" account.

ContentLicense: CC BY-SA 2.5

Body:
I setup git and gitosis on a server to manage my repos.  It's working properly for the initial shell account I set it up with, i.e. I can run:

git clone git@MYSERVER:gitosis-admin.git

But when I try to use the separate accounts I've created (via gitosis.conf) it keeps asking for a password:

git clone johndoe@MYSERVER:gitosis-admin.git

I setup the SSH key and pushed a copy to the keydir on the server.  This question seems to address the same problem, but the solution given is for tortoisegit.

Git keeps asking for password

How do I tell git to use the ssh key instead of asking for a password?

Body:
You don't use your user name, you always say:

git clone git@MYSERVER:<repository>

Gitosis associates your name in its config file with the name of your key on the server. That is, you have lines like

[group users]
members = johndoe janeroe
writable = repo1 repo2

in gitosis.conf, and files johndoe.pub, janedoe.pub in gitosis-admin/keydir; gitosis will use the appropriate key for the user but you always use "git" as the user in the URL. That's because it's always using the "git" account.


问:
raise NeedDownloadError('Need ffmpeg exe. ' NeedDownloadError: Need ffmpeg exe)
I'm trying to execute a call to an unofficial Instagram API python library, after several errors for dependencies needed I fixed, I'm stuck at this one.</p>

```<code> File "C:\Users\Pablo\Desktop\txts_pys_phps_programacion\Instagram-API-python-master\InstagramAPI.py", line 15, in <module>
    from moviepy.editor import VideoFileClip
  File "C:\Python27\lib\site-packages\moviepy\editor.py", line 22, in <module>
    from .video.io.VideoFileClip import VideoFileClip
  File "C:\Python27\lib\site-packages\moviepy\video\io\VideoFileClip.py", line 3, in <module>
    from moviepy.video.VideoClip import VideoClip
  File "C:\Python27\lib\site-packages\moviepy\video\VideoClip.py", line 20, in <module>
    from .io.ffmpeg_writer import ffmpeg_write_image, ffmpeg_write_video
  File "C:\Python27\lib\site-packages\moviepy\video\io\ffmpeg_writer.py", line 15, in <module>
    from moviepy.config import get_setting
  File "C:\Python27\lib\site-packages\moviepy\config.py", line 38, in <module>
    FFMPEG_BINARY = get_exe()
  File "C:\Python27\lib\site-packages\imageio\plugins\ffmpeg.py", line 86, in get_exe
    raise NeedDownloadError('Need ffmpeg exe. '
NeedDownloadError: Need ffmpeg exe. You can download it by calling:
  imageio.plugins.ffmpeg.download()
</code>```

答:
on mac,
this is the best way to install ffmpeg.
Open terminal and type.

```<code>$ brew install ffmpeg
</code>```

you will be seeing it get installed.

```<code>==> Installing dependencies for ffmpeg: lame, x264, xvid
</code>```

Body:
I'm trying to execute a call to an unofficial Instagram API python library, after several errors for dependencies needed I fixed, I'm stuck at this one.

 File "C:\Users\Pablo\Desktop\txts_pys_phps_programacion\Instagram-API-python-master\InstagramAPI.py", line 15, in <module>
    from moviepy.editor import VideoFileClip
  File "C:\Python27\lib\site-packages\moviepy\editor.py", line 22, in <module>
    from .video.io.VideoFileClip import VideoFileClip
  File "C:\Python27\lib\site-packages\moviepy\video\io\VideoFileClip.py", line 3, in <module>
    from moviepy.video.VideoClip import VideoClip
  File "C:\Python27\lib\site-packages\moviepy\video\VideoClip.py", line 20, in <module>
    from .io.ffmpeg_writer import ffmpeg_write_image, ffmpeg_write_video
  File "C:\Python27\lib\site-packages\moviepy\video\io\ffmpeg_writer.py", line 15, in <module>
    from moviepy.config import get_setting
  File "C:\Python27\lib\site-packages\moviepy\config.py", line 38, in <module>
    FFMPEG_BINARY = get_exe()
  File "C:\Python27\lib\site-packages\imageio\plugins\ffmpeg.py", line 86, in get_exe
    raise NeedDownloadError('Need ffmpeg exe. '
NeedDownloadError: Need ffmpeg exe. You can download it by calling:
  imageio.plugins.ffmpeg.download()

Body:
on mac,
this is the best way to install ffmpeg.
Open terminal and type.

$ brew install ffmpeg

you will be seeing it get installed.

==> Installing dependencies for ffmpeg: lame, x264, xvid


问:
App module disappeared in android studio
I had app module running on my android studio project until I pressed delete by mistake. I am now unable to run my project as it doesn't detect app module.

I can see app folder in project view (containing build, libs, src folders) but I don't see it in android view or configuration setting where it says

I have an old apk file of the project.

I shared my project on github.
Please help me get my module back so that I can run my project.

答:
I had this same issue, twice now. The first time, a full clean/rebuild did the trick. The second time, this didn't work. What did resolve the problem was opening the settings.gradle file and copying everything, then removing it to leave an empty file. Then save and resync Gradle. This failed, but then I pasted the old contents back into the file and did a resync again, which then fixed the issue.

Not sure what the problem was in the first place, but this worked for me so I figured I'd share.


问:
Retrieving dates from foreign table based on form values
I have a form where I can allocate course runs for the next work year. So I have 3 basic courses (Course1, Course2, Course3). Each of these courses have several course runs every year; data about the course is stored in a separate table called CourseRuns (with each course having its own table).

So what I would like to do is to retrieve dates from my CourseRuns table. So if my form is populated as such:

```<code>Course1: Run 2
Course2: Run 1
Course3: -
</code>```

I want to see the course dates for the course runs that were selected in the form.

If possible, I'd also like to know if it is possible to use the course dates to validate the record (I do not want clashing allocated course dates)

答: In the on-current event you can call a routine that refreshes read-only labels/textboxes that display the information you refer to. In the after-update events for the course fields you would call this routine again. The routine itself would take the primary key from the course1 / course2 / course3 textbox/comboboxes (whatever they are) and do a dlookup() on the CourseRuns table with appropriate filters. Take resulting values from the DLookup() and place them in your read-only FYI fields. If you find yourself doing many DLookups() and the code starts bogging down, I believe you'll find a more efficient solution with a recordset approach, but in practice I doubt that will prove necessary.</p>

Body:
I have a form where I can allocate course runs for the next work year. So I have 3 basic courses (Course1, Course2, Course3). Each of these courses have several course runs every year; data about the course is stored in a separate table called CourseRuns (with each course having its own table).

So what I would like to do is to retrieve dates from my CourseRuns table. So if my form is populated as such:

Course1: Run 2
Course2: Run 1
Course3: -

I want to see the course dates for the course runs that were selected in the form.

If possible, I'd also like to know if it is possible to use the course dates to validate the record (I do not want clashing allocated course dates)


问:
React-native props.navigation.navigate undefined
I really can't get my navigation to work. My navigation works in DrawerNavigator menu but it does not work in components. I've tried everything but there must be something I still do not understand.

I always get an error: "TypeError: undefined is not an object (evaluating'_this.props.navigation')"

This is my View:

import React from 'react';
import { Provider } from 'react-redux';
import configureStore from '../../store/configure-store';
import StoresListContainer from '../../packages/stores/containers/list-container';

const store = configureStore({});

const Stores = () => {
  return (
    <Provider store={store}>
      <StoresListContainer navigation={this.props.navigation} />
    </Provider>
  );
};

export default Stores;```
</div>
</div>
</p>

<p>This is my Component:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
  View,
  Text,
  ActivityIndicator,
  FlatList,
  Image,
  TouchableNativeFeedback,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import Styles from './styles';
import Theme from '../../../config/theme';

type Props = {
  error: boolean,
  loading: boolean,
  data: Object,
  fetchData: Function,
};

class ListComponent extends Component<Props> {

  constructor(props) {
    super(props);
    this.goToPage = this.goToPage.bind(this);
  }

  componentDidMount() {
    this.props.fetchData();
  }

  goToPage(param) {
    this.props.navigation.navigate(param);
  }

  render() {
    const hasData = Object.keys(this.props.data).length;
    const errorMessage = () => {
      return (
        <Text>Ops! Ocorreu um erro ao carregar os dados.</Text>
      );
    };

    const renderData = (item) => {
      return (
        <TouchableNativeFeedback contact={item} onPress={() => this.goToPage('Store')}>
          <View style={Styles.renderData}>
            <View style={{ flex: 0 }}>
              <Image style={Styles.renderDataPicture} source={{ uri: item.item.image }} />
            </View>
            <View style={{ flex: 2 }}>
              <Text style={Styles.renderDataTitle}>{ item.item.fantasy_name }</Text>
              <Text style={Styles.renderDataSubtitle}>{ item.item.location }</Text>
            </View>
            <View style={Styles.renderDataItemIconContainer}>
              <Icon name="chevron-right" style={Styles.renderDataItemIcon} />
            </View>
          </View>
        </TouchableNativeFeedback>
      );
    };

    const renderLoading = () => {
      return (
        <View style={Styles.renderLoading}>
          <ActivityIndicator color={Theme.color.secondary} size="large" />
          <Text style={Theme.text}>Aguarde</Text>
        </View>
      );
    };

    const getData = (data) => {
      return (
        <FlatList data={data} renderItem={renderData} keyExtractor={(item, index) => index} />
      );
    };

    return (
      <View style={Styles.container}>
        { this.props.loading ? renderLoading() : null }
        { this.props.error ? errorMessage() : null }
        { hasData ? getData(this.props.data) : null }
      </View>
    );
  }
}

export default ListComponent;</code>```

答:
You are using a functional stateless component instead of a class, therefore you need to drop the this.

```<code>const Stores = (props) => {
  return (
    <Provider store={store}>
      <StoresListContainer navigation={props.navigation} />
    </Provider>
  );
};

// ES6 Class
class Stores extends Component {
  render(){
    return (
      <Provider store={store}>
        <StoresListContainer navigation={this.props.navigation} />
      </Provider>
    );
  }
}
</code>```

Body:
I really can't get my navigation to work. My navigation works in DrawerNavigator menu but it does not work in components. I've tried everything but there must be something I still do not understand.

I always get an error: "TypeError: undefined is not an object (evaluating'_this.props.navigation')"

This is my View:

import React from 'react';
import { Provider } from 'react-redux';
import configureStore from '../../store/configure-store';
import StoresListContainer from '../../packages/stores/containers/list-container';

const store = configureStore({});

const Stores = () => {
  return (
    <Provider store={store}>
      <StoresListContainer navigation={this.props.navigation} />
    </Provider>
  );
};

export default Stores;

This is my Component:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
  View,
  Text,
  ActivityIndicator,
  FlatList,
  Image,
  TouchableNativeFeedback,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import Styles from './styles';
import Theme from '../../../config/theme';

type Props = {
  error: boolean,
  loading: boolean,
  data: Object,
  fetchData: Function,
};

class ListComponent extends Component<Props> {

  constructor(props) {
    super(props);
    this.goToPage = this.goToPage.bind(this);
  }

  componentDidMount() {
    this.props.fetchData();
  }

  goToPage(param) {
    this.props.navigation.navigate(param);
  }

  render() {
    const hasData = Object.keys(this.props.data).length;
    const errorMessage = () => {
      return (
        <Text>Ops! Ocorreu um erro ao carregar os dados.</Text>
      );
    };

    const renderData = (item) => {
      return (
        <TouchableNativeFeedback contact={item} onPress={() => this.goToPage('Store')}>
          <View style={Styles.renderData}>
            <View style={{ flex: 0 }}>
              <Image style={Styles.renderDataPicture} source={{ uri: item.item.image }} />
            </View>
            <View style={{ flex: 2 }}>
              <Text style={Styles.renderDataTitle}>{ item.item.fantasy_name }</Text>
              <Text style={Styles.renderDataSubtitle}>{ item.item.location }</Text>
            </View>
            <View style={Styles.renderDataItemIconContainer}>
              <Icon name="chevron-right" style={Styles.renderDataItemIcon} />
            </View>
          </View>
        </TouchableNativeFeedback>
      );
    };

    const renderLoading = () => {
      return (
        <View style={Styles.renderLoading}>
          <ActivityIndicator color={Theme.color.secondary} size="large" />
          <Text style={Theme.text}>Aguarde</Text>
        </View>
      );
    };

    const getData = (data) => {
      return (
        <FlatList data={data} renderItem={renderData} keyExtractor={(item, index) => index} />
      );
    };

    return (
      <View style={Styles.container}>
        { this.props.loading ? renderLoading() : null }
        { this.props.error ? errorMessage() : null }
        { hasData ? getData(this.props.data) : null }
      </View>
    );
  }
}

export default ListComponent;

Body:
You are using a functional stateless component instead of a class, therefore you need to drop the this.

const Stores = (props) => {
  return (
    <Provider store={store}>
      <StoresListContainer navigation={props.navigation} />
    </Provider>
  );
};

// ES6 Class
class Stores extends Component {
  render(){
    return (
      <Provider store={store}>
        <StoresListContainer navigation={this.props.navigation} />
      </Provider>
    );
  }
}


问:
Unable to stateSave with custom regex implementation of the search() API
I enabled regex filtering in the following manner since the default is false -

```<code>$(document).ready(
    function() {
        var table = $('#companies').DataTable({
            stateSave: true,
            stateDuration: 0, //force the use of Local Storage
            // other code for 'dom' & 'buttons' properties
        });

        table.search($(this).val(), true, true, true).draw();
    });
</code>```

However, stateSave, which was previously working fine to restore the search parameter upon page refresh has stopped working. It still remembers to sort the columns which makes me think that it is not working for search since the regex filter is being implemented externally.

This answer mentions the use of state.loaded() but a comment beneath it says that it is a sloppy hack and stateSave should be used instead. Another similar question went unanswered.

So, how can I save the search parameter with a custom implementation of the search() API?

EDIT - Obfuscated fiddle with the JavaScript intact but all the JSP code removed.

答:
Based on this answer and Prashant's suggestion, I was able to use state.loaded() to save the search term and populate the search box upon reload, as shown below -

```<code>$(document).ready(
    function() {
        var table = $('#companies').DataTable({
            stateSave: true,
            stateDuration: 0, //force the use of Local Storage
            // other code for 'dom' & 'buttons' properties
        });
        if (searchText !== null && searchText !== "") {
            table.search(searchText.search, true, true, true).draw();
        } else {
            table.search($(this).val(), true, true, true).draw();
        }
    });

$(document).on('init.dt', function(e, settings) {
    var api = new $.fn.dataTable.Api(settings);
    var state = api.state.loaded();
    searchText = state.search;
});
</code>```

Body:
I enabled regex filtering in the following manner since the default is false -

$(document).ready(
    function() {
        var table = $('#companies').DataTable({
            stateSave: true,
            stateDuration: 0, //force the use of Local Storage
            // other code for 'dom' & 'buttons' properties
        });

        table.search($(this).val(), true, true, true).draw();
    });

However, stateSave, which was previously working fine to restore the search parameter upon page refresh has stopped working. It still remembers to sort the columns which makes me think that it is not working for search since the regex filter is being implemented externally.

This answer mentions the use of state.loaded() but a comment beneath it says that it is a sloppy hack and stateSave should be used instead. Another similar question went unanswered.

So, how can I save the search parameter with a custom implementation of the search() API?

EDIT - Obfuscated fiddle with the JavaScript intact but all the JSP code removed.

Body:
Based on this answer and Prashant's suggestion, I was able to use state.loaded() to save the search term and populate the search box upon reload, as shown below -

$(document).ready(
    function() {
        var table = $('#companies').DataTable({
            stateSave: true,
            stateDuration: 0, //force the use of Local Storage
            // other code for 'dom' & 'buttons' properties
        });
        if (searchText !== null && searchText !== "") {
            table.search(searchText.search, true, true, true).draw();
        } else {
            table.search($(this).val(), true, true, true).draw();
        }
    });

$(document).on('init.dt', function(e, settings) {
    var api = new $.fn.dataTable.Api(settings);
    var state = api.state.loaded();
    searchText = state.search;
});


问:
Heroku Rails - 500 Internal Server Error
When I post something in my Rails app (locally), it works perfectly. However, when I deploy it on Herokuapp, it breaks. Here is what I have:

```<code>#Gemfile

# Use sqlite3 as the database for Active Record
gem 'sqlite3', group: :development
gem 'pg', '0.18.1', group: :production
gem 'rails_12factor', group: :production

#database.yml

production:
<<: *default
adapter: postgresql
database: db/production.sqlite3
</code>```

I then proceeded to deploy my app to Heroku like this:

```<code>git add .
git commit -m "comment"
git push heroku master
heroku run rake db:migrate
heroku run rake db:seed
</code>```

I've checked my version using the following:

```<code>heroku run rake db:version
>> Current version: 20171103035018
rake db:version
>> Current version: 20171103035018
</code>```

Finally, here is my controller where I perform a create action:

```<code>#suggestions_controller.rb

def create
    @suggestion = Suggestion.new(suggestion_params)

    if @suggestion.save
        flash[:notice] = "Suggestion successfully posted!"
        redirect_to root_path
    else
        flash[:error] = "Suggestion failed to post!"
        redirect_to root_path
    end
end

private
    def suggestion_params
        params.require(:suggestion).permit(:suggester, :ip, :suggestion_type, :title, :body)
    end
</code>```

I tried this on my localhost and it creates just fine, but when I deploy it on Heroku, it displays this error:

I'm pretty certain I did everything correctly and I have no idea what's breaking here.

Thanks for any help.

Edit: I just got a lead to the problem. It says that my created_at is null.

ActiveRecord::NotNullViolation (PG::NotNullViolation: ERROR:  null value in column "created_at" violates not-null constraint

I'm researching on the web now to see how I can fix this problem.

答:
I figured out the problem. It was indeed this particular error message:

ActiveRecord::NotNullViolation (PG::NotNullViolation: ERROR:  null value in column "created_at" violates not-null constraint

I had to add this line of code to my suggestions_controller.rb

```<code>def create
    Suggestion.record_timestamps = true; #added this line of code
    ... #other logic
end
</code>```

When I upvote and downvote a post, I don't want it to update the timestamps such as this:

```<code>def upvote
    Suggestion.record_timestamps = false;
    ... #other logic
end
</code>```

I redeployed my app and it works fine now.

Body:
When I post something in my Rails app (locally), it works perfectly. However, when I deploy it on Herokuapp, it breaks. Here is what I have:

#Gemfile

# Use sqlite3 as the database for Active Record
gem 'sqlite3', group: :development
gem 'pg', '0.18.1', group: :production
gem 'rails_12factor', group: :production

#database.yml

production:
<<: *default
adapter: postgresql
database: db/production.sqlite3

I then proceeded to deploy my app to Heroku like this:

git add .
git commit -m "comment"
git push heroku master
heroku run rake db:migrate
heroku run rake db:seed

I've checked my version using the following:

heroku run rake db:version
>> Current version: 20171103035018
rake db:version
>> Current version: 20171103035018

Finally, here is my controller where I perform a create action:

#suggestions_controller.rb

def create
    @suggestion = Suggestion.new(suggestion_params)

    if @suggestion.save
        flash[:notice] = "Suggestion successfully posted!"
        redirect_to root_path
    else
        flash[:error] = "Suggestion failed to post!"
        redirect_to root_path
    end
end

private
    def suggestion_params
        params.require(:suggestion).permit(:suggester, :ip, :suggestion_type, :title, :body)
    end

I tried this on my localhost and it creates just fine, but when I deploy it on Heroku, it displays this error:

I'm pretty certain I did everything correctly and I have no idea what's breaking here.

Thanks for any help.

Edit: I just got a lead to the problem. It says that my created_at is null.

ActiveRecord::NotNullViolation (PG::NotNullViolation: ERROR:  null value in column "created_at" violates not-null constraint

I'm researching on the web now to see how I can fix this problem.

Body:
I figured out the problem. It was indeed this particular error message:

ActiveRecord::NotNullViolation (PG::NotNullViolation: ERROR:  null value in column "created_at" violates not-null constraint

I had to add this line of code to my suggestions_controller.rb

def create
    Suggestion.record_timestamps = true; #added this line of code
    ... #other logic
end

When I upvote and downvote a post, I don't want it to update the timestamps such as this:

def upvote
    Suggestion.record_timestamps = false;
    ... #other logic
end

I redeployed my app and it works fine now.


问:
Use Gulp To Copy File Into Directory Named After Filename
I have the following files

```<code>assets
---views
------pages
---------some_page.ejs
---------another_page.ejs
</code>```

When I build these ejs files, I want them to go into the following file structure

```<code>public
---some_page
------index.html
---another_page
------index.html
</code>```

My gulp file contains the following build command:

```<code>gulp.task('build-html', function() {
return gulp.src('assets/views/pages/*.ejs')
    .pipe(ejs())
    .pipe(gulp.dest('public/???')); // WHAT DO I ADD HERE TO MAKE ABOVE WORK?
});
</code>```

I'm totally stumped what I need to add into the gulp.dest function to achieve the above.

答:
Solved with gulp-rename package:

```<code>gulp.task('build-html', function() {
return gulp.src('assets/views/pages/*.ejs')
    .pipe(ejs())
    .pipe(rename(function (path) {
       path.dirname += "/" + path.basename;
       path.basename = "index";
    }))
    .pipe(gulp.dest('public/'));
});
</code>```

Body:
I have the following files

assets
---views
------pages
---------some_page.ejs
---------another_page.ejs

When I build these ejs files, I want them to go into the following file structure

public
---some_page
------index.html
---another_page
------index.html

My gulp file contains the following build command:

gulp.task('build-html', function() {
return gulp.src('assets/views/pages/*.ejs')
    .pipe(ejs())
    .pipe(gulp.dest('public/???')); // WHAT DO I ADD HERE TO MAKE ABOVE WORK?
});

I'm totally stumped what I need to add into the gulp.dest function to achieve the above.

Body:
Solved with gulp-rename package:

gulp.task('build-html', function() {
return gulp.src('assets/views/pages/*.ejs')
    .pipe(ejs())
    .pipe(rename(function (path) {
       path.dirname += "/" + path.basename;
       path.basename = "index";
    }))
    .pipe(gulp.dest('public/'));
});


问:
Upload image -> canvas -> image - sizing issues
I use file reader to read a user uploaded image, I size the canvas to the width and height of the image.

```<code>var img = new Image();
img.src = e.target.result;
var canvas = $('#test-canvas')[0];
$('#test-canvas').width(img.width);
$('#test-canvas').height(img.height);
</code>```

I then draw the image on to the canvas.

```<code>var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0 canvas.width, canvas.height);
</code>```

I then add the canvas to an image

```<code>var uploadImageObj = $('<img id="upload-img">');
uploadImageObj.attr('src', canvas.toDataURL());
uploadImageObj.appendTo('.template');
</code>```

Later I plan to add reading exif data, and will rotate the image accordingly.

The problem I am having is that the image is always the default canvas size (300 x 150) - why? I need it to be the same size as the uploaded image?

答:
```<code><div class="row">
        <canvas hidden="hidden" id="canvas" width="1280" height="720" >
        </canvas>
</div>
</code>```

Body:
I use file reader to read a user uploaded image, I size the canvas to the width and height of the image.

var img = new Image();
img.src = e.target.result;
var canvas = $('#test-canvas')[0];
$('#test-canvas').width(img.width);
$('#test-canvas').height(img.height);

I then draw the image on to the canvas.

var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0 canvas.width, canvas.height);

I then add the canvas to an image

var uploadImageObj = $('');
uploadImageObj.attr('src', canvas.toDataURL());
uploadImageObj.appendTo('.template');

Later I plan to add reading exif data, and will rotate the image accordingly.

The problem I am having is that the image is always the default canvas size (300 x 150) - why? I need it to be the same size as the uploaded image?


问:
How to export test results in MSTest using cake script?
I am using VS 2017 professional (version 15.2) with platform of Asp.net core (version 1.1). I am using a testing framework of MSTest (which is in the internal template of asp.net core). I try to use the cake script for running the test cases written in MSTest using the cake script, I need to export test results like passed and failed test case count.

```<code>     MSTest("./Tests/*.UnitTests.dll");
</code>```

When I run this code in cake test execution should be finished but I need detailed test results.

Can anyone please suggest how to export the results of test cases?

答:
Look at the documentation for the MSTest cake Alias.

2 of the overloads accept a MSTestSettings argument, doc.

MSTest(ICakeContext, IEnumerable<FilePath>, MSTestSettings) - Runs all MSTest unit tests in the specified assemblies.

MSTest(ICakeContext, string, MSTestSettings)- Runs all MSTest unit tests in the assemblies matching the specified pattern.

This argument has a string property ResultsFile where you can set the location for the results to be written, doc.

Body:
I am using VS 2017 professional (version 15.2) with platform of Asp.net core (version 1.1). I am using a testing framework of MSTest (which is in the internal template of asp.net core). I try to use the cake script for running the test cases written in MSTest using the cake script, I need to export test results like passed and failed test case count.

     MSTest("./Tests/*.UnitTests.dll");

When I run this code in cake test execution should be finished but I need detailed test results.

Can anyone please suggest how to export the results of test cases?


问:
NullReferenceException when adding InMemoryRandomAccessStream to list
```<code>        private List<InMemoryRandomAccessStream> undoStreamList;
        InMemoryRandomAccessStream tempStream = new InMemoryRandomAccessStream();
        await inkCanvas.InkPresenter.StrokeContainer.SaveAsync(tempStream);
        undoStreamList.Add(tempStream);
        state++;
</code>```

This code returns a NullReferenceException on the penultimate line, how do I fix it?

I also tried changing the penultimate line to undoStreamList.Add(new InMemoryRandomAccessStream); but it didn't work.

答:
It looks like your list has not been initialized:

```<code>// Initialize this either inline or inside the constructor...
private List<InMemoryRandomAccessStream> undoStreamList = new List<InMemoryRandomAccessStream>();

InMemoryRandomAccessStream tempStream = new InMemoryRandomAccessStream();
await inkCanvas.InkPresenter.StrokeContainer.SaveAsync(tempStream);
undoStreamList.Add(tempStream);
state++;
</code>```

This is the only possible reason for that line throwing an exception!

Body:
        private List<InMemoryRandomAccessStream> undoStreamList;
        InMemoryRandomAccessStream tempStream = new InMemoryRandomAccessStream();
        await inkCanvas.InkPresenter.StrokeContainer.SaveAsync(tempStream);
        undoStreamList.Add(tempStream);
        state++;

This code returns a NullReferenceException on the penultimate line, how do I fix it?

I also tried changing the penultimate line to undoStreamList.Add(new InMemoryRandomAccessStream); but it didn't work.

Body:
It looks like your list has not been initialized:

// Initialize this either inline or inside the constructor...
private List<InMemoryRandomAccessStream> undoStreamList = new List<InMemoryRandomAccessStream>();

InMemoryRandomAccessStream tempStream = new InMemoryRandomAccessStream();
await inkCanvas.InkPresenter.StrokeContainer.SaveAsync(tempStream);
undoStreamList.Add(tempStream);
state++;

This is the only possible reason for that line throwing an exception!


问:
Migrating Sharepoint online onedrive content
How to migrate sharepoint online (Office 365) one drive content of a user to another through powershell?</p>

答:
Have a look at this script on TechNet. It has some restrictions listed, but it should give you a good starting point.

https://gallery.technet.microsoft.com/office/Copy-OneDrive-files-f1c751e7

Here is some of the essential information from the page:

There are a few things to keep in mind:

This could take a while. Each file or folder takes at least a second or two to process. If your departing user has tens of thousands
  of files, and time is not on your side, you may want to use another
  method.

It uses your connection. It downloads the files before uploading them to the other user’s OneDrive. If your connection is slow, and
  you’re moving large files you might want to leave this running on a
  cloud hosted server.

It can’t move files larger than 250MB A limitation of this PowerShell module is that it can’t send files larger than 250MB to
  SharePoint. This script will make a note of these files and export a
  list of them to c:\temp\largefiles.txt in case you want to move them
  manually.

No Two Factor Authentication This script doesn’t work with multifactor authentication on the admin account. You may want to
  create a temporary admin without MFA for this purpose.

Prerequisites For this script to work, you’ll need to install the
  following PowerShell Modules:

SharePoint Online Management Shell The SharePoint Online Management
  Shell is used to modify the permissions on the users’ OneDrive site
  collections.

Download and install it here:
  https://www.microsoft.com/en-au/download/details.aspx?id=35588

SharePoint PnP Powershell Module The SharePoint PnP Powershell module
  provides the cmdlets we’ll use to transfer the files and folders
  between OneDrive accounts.

To install it, open a PowerShell window as an administrator and run
  the following cmdlet:

```<code>Install-Module SharePointPnPPowerShellOnline -Force
</code>```

MSOnline V1 Powershell Module You’ll also need the MSOnline V1
  PowerShell Module for this script.

To install it, open a PowerShell window as an administrator and run
  the following cmdlet:

```<code>Install-Module MSOnline -Force
</code>```

And the script itself:

```<code>$departinguser = Read-Host "Enter departing user's email"
$destinationuser = Read-Host "Enter destination user's email"
$globaladmin = Read-Host "Enter the username of your Global Admin account"
$credentials = Get-Credential -Credential $globaladmin
Connect-MsolService -Credential $credentials

$InitialDomain = Get-MsolDomain | Where-Object {$_.IsInitial -eq $true}

$SharePointAdminURL = "https://$($InitialDomain.Name.Split(".")[0])-admin.sharepoint.com"

$departingUserUnderscore = $departinguser -replace "[^a-zA-Z]", "_"
$destinationUserUnderscore = $destinationuser -replace "[^a-zA-Z]", "_"

$departingOneDriveSite = "https://$($InitialDomain.Name.Split(".")[0])-my.sharepoint.com/personal/$departingUserUnderscore"
$destinationOneDriveSite = "https://$($InitialDomain.Name.Split(".")[0])-my.sharepoint.com/personal/$destinationUserUnderscore"
Write-Host "`nConnecting to SharePoint Online" -ForegroundColor Blue
Connect-SPOService -Url $SharePointAdminURL -Credential $credentials

Write-Host "`nAdding $globaladmin as site collection admin on both OneDrive site collections" -ForegroundColor Blue
# Set current admin as a Site Collection Admin on both OneDrive Site Collections
Set-SPOUser -Site $departingOneDriveSite -LoginName $globaladmin -IsSiteCollectionAdmin $true
Set-SPOUser -Site $destinationOneDriveSite -LoginName $globaladmin -IsSiteCollectionAdmin $true

Write-Host "`nConnecting to $departinguser's OneDrive via SharePoint Online PNP module" -ForegroundColor Blue

Connect-PnPOnline -Url $departingOneDriveSite -Credentials $credentials

Write-Host "`nGetting display name of $departinguser" -ForegroundColor Blue
# Get name of departing user to create folder name.
$departingOwner = Get-PnPSiteCollectionAdmin | Where-Object {$_.loginname -match $departinguser}

# If there's an issue retrieving the departing user's display name, set this one.
if ($departingOwner -contains $null) {
    $departingOwner = @{
        Title = "Departing User"
    }
}

# Define relative folder locations for OneDrive source and destination
$departingOneDrivePath = "/personal/$departingUserUnderscore/Documents"
$destinationOneDrivePath = "/personal/$destinationUserUnderscore/Documents/$($departingOwner.Title)'s Files"
$destinationOneDriveSiteRelativePath = "Documents/$($departingOwner.Title)'s Files"

Write-Host "`nGetting all items from $($departingOwner.Title)" -ForegroundColor Blue
# Get all items from source OneDrive
$items = Get-PnPListItem -List Documents -PageSize 1000

$largeItems = $items | Where-Object {[long]$_.fieldvalues.SMTotalFileStreamSize -ge 261095424 -and $_.FileSystemObjectType -contains "File"}
if ($largeItems) {
    $largeexport = @()
    foreach ($item in $largeitems) {
        $largeexport += "$(Get-Date) - Size: $([math]::Round(($item.FieldValues.SMTotalFileStreamSize / 1MB),2)) MB Path: $($item.FieldValues.FileRef)"
        Write-Host "File too large to copy: $($item.FieldValues.FileRef)" -ForegroundColor DarkYellow
    }
    $largeexport | Out-file C:\temp\largefiles.txt -Append
    Write-Host "A list of files too large to be copied from $($departingOwner.Title) have been exported to C:\temp\LargeFiles.txt" -ForegroundColor Yellow
}

$rightSizeItems = $items | Where-Object {[long]$_.fieldvalues.SMTotalFileStreamSize -lt 261095424 -or $_.FileSystemObjectType -contains "Folder"}

Write-Host "`nConnecting to $destinationuser via SharePoint PNP PowerShell module" -ForegroundColor Blue
Connect-PnPOnline -Url $destinationOneDriveSite -Credentials $credentials

Write-Host "`nFilter by folders" -ForegroundColor Blue
# Filter by Folders to create directory structure
$folders = $rightSizeItems | Where-Object {$_.FileSystemObjectType -contains "Folder"}

Write-Host "`nCreating Directory Structure" -ForegroundColor Blue
foreach ($folder in $folders) {
    $path = ('{0}{1}' -f $destinationOneDriveSiteRelativePath, $folder.fieldvalues.FileRef).Replace($departingOneDrivePath, '')
    Write-Host "Creating folder in $path" -ForegroundColor Green
    $newfolder = Ensure-PnPFolder -SiteRelativePath $path
}

Write-Host "`nCopying Files" -ForegroundColor Blue
$files = $rightSizeItems | Where-Object {$_.FileSystemObjectType -contains "File"}
$fileerrors = ""
foreach ($file in $files) {

    $destpath = ("$destinationOneDrivePath$($file.fieldvalues.FileDirRef)").Replace($departingOneDrivePath, "")
    Write-Host "Copying $($file.fieldvalues.FileLeafRef) to $destpath" -ForegroundColor Green
    $newfile = Copy-PnPFile -SourceUrl $file.fieldvalues.FileRef -TargetUrl $destpath -OverwriteIfAlreadyExists -Force -ErrorVariable errors -ErrorAction SilentlyContinue
    $fileerrors += $errors
}
$fileerrors | Out-File c:\temp\fileerrors.txt

# Remove Global Admin from Site Collection Admin role for both users
Write-Host "`nRemoving $globaladmin from OneDrive site collections" -ForegroundColor Blue
Set-SPOUser -Site $departingOneDriveSite -LoginName $globaladmin -IsSiteCollectionAdmin $false
Set-SPOUser -Site $destinationOneDriveSite -LoginName $globaladmin -IsSiteCollectionAdmin $false
Write-Host "`nComplete!" -ForegroundColor Green
</code>```

Body:
Have a look at this script on TechNet. It has some restrictions listed, but it should give you a good starting point.

https://gallery.technet.microsoft.com/office/Copy-OneDrive-files-f1c751e7

Here is some of the essential information from the page:

There are a few things to keep in mind:

This could take a while. Each file or folder takes at least a second or two to process. If your departing user has tens of thousands
  of files, and time is not on your side, you may want to use another
  method.

It uses your connection. It downloads the files before uploading them to the other user’s OneDrive. If your connection is slow, and
  you’re moving large files you might want to leave this running on a
  cloud hosted server.

It can’t move files larger than 250MB A limitation of this PowerShell module is that it can’t send files larger than 250MB to
  SharePoint. This script will make a note of these files and export a
  list of them to c:\temp\largefiles.txt in case you want to move them
  manually.

No Two Factor Authentication This script doesn’t work with multifactor authentication on the admin account. You may want to
  create a temporary admin without MFA for this purpose.

Prerequisites For this script to work, you’ll need to install the
  following PowerShell Modules:

SharePoint Online Management Shell The SharePoint Online Management
  Shell is used to modify the permissions on the users’ OneDrive site
  collections.

Download and install it here:
  https://www.microsoft.com/en-au/download/details.aspx?id=35588

SharePoint PnP Powershell Module The SharePoint PnP Powershell module
  provides the cmdlets we’ll use to transfer the files and folders
  between OneDrive accounts.

To install it, open a PowerShell window as an administrator and run
  the following cmdlet:

Install-Module SharePointPnPPowerShellOnline -Force

MSOnline V1 Powershell Module You’ll also need the MSOnline V1
  PowerShell Module for this script.

To install it, open a PowerShell window as an administrator and run
  the following cmdlet:

Install-Module MSOnline -Force

And the script itself:

$departinguser = Read-Host "Enter departing user's email"
$destinationuser = Read-Host "Enter destination user's email"
$globaladmin = Read-Host "Enter the username of your Global Admin account"
$credentials = Get-Credential -Credential $globaladmin
Connect-MsolService -Credential $credentials

$InitialDomain = Get-MsolDomain | Where-Object {$_.IsInitial -eq $true}

$SharePointAdminURL = "https://$($InitialDomain.Name.Split(".")[0])-admin.sharepoint.com"

$departingUserUnderscore = $departinguser -replace "[^a-zA-Z]", "_"
$destinationUserUnderscore = $destinationuser -replace "[^a-zA-Z]", "_"

$departingOneDriveSite = "https://$($InitialDomain.Name.Split(".")[0])-my.sharepoint.com/personal/$departingUserUnderscore"
$destinationOneDriveSite = "https://$($InitialDomain.Name.Split(".")[0])-my.sharepoint.com/personal/$destinationUserUnderscore"
Write-Host "`nConnecting to SharePoint Online" -ForegroundColor Blue
Connect-SPOService -Url $SharePointAdminURL -Credential $credentials

Write-Host "`nAdding $globaladmin as site collection admin on both OneDrive site collections" -ForegroundColor Blue
# Set current admin as a Site Collection Admin on both OneDrive Site Collections
Set-SPOUser -Site $departingOneDriveSite -LoginName $globaladmin -IsSiteCollectionAdmin $true
Set-SPOUser -Site $destinationOneDriveSite -LoginName $globaladmin -IsSiteCollectionAdmin $true

Write-Host "`nConnecting to $departinguser's OneDrive via SharePoint Online PNP module" -ForegroundColor Blue

Connect-PnPOnline -Url $departingOneDriveSite -Credentials $credentials

Write-Host "`nGetting display name of $departinguser" -ForegroundColor Blue
# Get name of departing user to create folder name.
$departingOwner = Get-PnPSiteCollectionAdmin | Where-Object {$_.loginname -match $departinguser}

# If there's an issue retrieving the departing user's display name, set this one.
if ($departingOwner -contains $null) {
    $departingOwner = @{
        Title = "Departing User"
    }
}

# Define relative folder locations for OneDrive source and destination
$departingOneDrivePath = "/personal/$departingUserUnderscore/Documents"
$destinationOneDrivePath = "/personal/$destinationUserUnderscore/Documents/$($departingOwner.Title)'s Files"
$destinationOneDriveSiteRelativePath = "Documents/$($departingOwner.Title)'s Files"

Write-Host "`nGetting all items from $($departingOwner.Title)" -ForegroundColor Blue
# Get all items from source OneDrive
$items = Get-PnPListItem -List Documents -PageSize 1000

$largeItems = $items | Where-Object {[long]$_.fieldvalues.SMTotalFileStreamSize -ge 261095424 -and $_.FileSystemObjectType -contains "File"}
if ($largeItems) {
    $largeexport = @()
    foreach ($item in $largeitems) {
        $largeexport += "$(Get-Date) - Size: $([math]::Round(($item.FieldValues.SMTotalFileStreamSize / 1MB),2)) MB Path: $($item.FieldValues.FileRef)"
        Write-Host "File too large to copy: $($item.FieldValues.FileRef)" -ForegroundColor DarkYellow
    }
    $largeexport | Out-file C:\temp\largefiles.txt -Append
    Write-Host "A list of files too large to be copied from $($departingOwner.Title) have been exported to C:\temp\LargeFiles.txt" -ForegroundColor Yellow
}

$rightSizeItems = $items | Where-Object {[long]$_.fieldvalues.SMTotalFileStreamSize -lt 261095424 -or $_.FileSystemObjectType -contains "Folder"}

Write-Host "`nConnecting to $destinationuser via SharePoint PNP PowerShell module" -ForegroundColor Blue
Connect-PnPOnline -Url $destinationOneDriveSite -Credentials $credentials

Write-Host "`nFilter by folders" -ForegroundColor Blue
# Filter by Folders to create directory structure
$folders = $rightSizeItems | Where-Object {$_.FileSystemObjectType -contains "Folder"}

Write-Host "`nCreating Directory Structure" -ForegroundColor Blue
foreach ($folder in $folders) {
    $path = ('{0}{1}' -f $destinationOneDriveSiteRelativePath, $folder.fieldvalues.FileRef).Replace($departingOneDrivePath, '')
    Write-Host "Creating folder in $path" -ForegroundColor Green
    $newfolder = Ensure-PnPFolder -SiteRelativePath $path
}

Write-Host "`nCopying Files" -ForegroundColor Blue
$files = $rightSizeItems | Where-Object {$_.FileSystemObjectType -contains "File"}
$fileerrors = ""
foreach ($file in $files) {

    $destpath = ("$destinationOneDrivePath$($file.fieldvalues.FileDirRef)").Replace($departingOneDrivePath, "")
    Write-Host "Copying $($file.fieldvalues.FileLeafRef) to $destpath" -ForegroundColor Green
    $newfile = Copy-PnPFile -SourceUrl $file.fieldvalues.FileRef -TargetUrl $destpath -OverwriteIfAlreadyExists -Force -ErrorVariable errors -ErrorAction SilentlyContinue
    $fileerrors += $errors
}
$fileerrors | Out-File c:\temp\fileerrors.txt

# Remove Global Admin from Site Collection Admin role for both users
Write-Host "`nRemoving $globaladmin from OneDrive site collections" -ForegroundColor Blue
Set-SPOUser -Site $departingOneDriveSite -LoginName $globaladmin -IsSiteCollectionAdmin $false
Set-SPOUser -Site $destinationOneDriveSite -LoginName $globaladmin -IsSiteCollectionAdmin $false
Write-Host "`nComplete!" -ForegroundColor Green


问:
Spring maven - run specific tests (via annotations or maven profile)
Using a Spring maven context, I would like to run specific tests based on a maven profile. I would like to have an easy way of tagging the test groups. If possible I would like to use the annotations.
Which options are there, like maven command line parameters, maven profiles specification, etc.

Say I have the following tests:

Example:

```<code>// annotation("integration")
public class GeopointFormatterTest {
    @Test
    public void testIntegration1() {  ...  }
    @Test
    public void testIntegration2() {  ...  }
</code>```

Annotations like @Profile (which is for creating beans) and @ActiveProfile (which is for selecting specific profiles for creating beans) cannot be used for selecting tests, of course. All tests just run for statements like:

mvn clean install -Pdevelopment

mvn clean install -Pdevelopment -Dspring.profiles.active=acceptance

mvn clean install -Pdevelopment -Dspring.profiles.active=integration

As suggested, I used also @IfProfileValue. This is a good way for selecting tests based on system property values. System property values can be overruled by a CustomProfileValueSource class, like in: @ProfileValueSourceConfiguration(CustomProfileValueSource.class)

EDIT and ALTERNATIVE

The GREAT answers below focus on JUnit's @Category mechanism. Thanks to all!

A different approach is via these steps: [1] set a property within a maven profile and [2] use the property to skip tests via the  of the standard surefire test plugin.

[1] Setting the properties via a profile:

```<code><profiles>
    <profile>
        <id>integrationtests</id>
        <properties>
            <integration.skip>false</integration.skip>
            <acceptance.skip>true</acceptance.skip>
        </properties>
    </profile>
    ... other profiles
</code>```

[2] Using the properties in the surefire test plugin to skip tests.

```<code><build>
   <plugins>
      <plugin>
         <!-- Run the integration test-->
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-surefire-plugin</artifactId>
         <version>${surefire.plugin.version}</version>
         <configuration>
            <skipTests>${acceptance.skip}</skipTests>
</code>```

Start in maven: mvn clean install –Pintegrationtests

答:
You will probably need to categorize your tests using the @Category annotation. A complete example has been provided in the Surefire documentation provided here - search for the string Using JUnit Categories.

Assuming that you have categorized your tests accordingly, you will now be able to setup one or more profiles in your maven build which will trigger these tests as per the category

```<code><profiles>
    <profile>
        <id>slow-tests</id>
        <build>
            <plugins>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.11</version>
                    <configuration>
                        <groups>com.mycompany.SlowTests</groups>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>
    <profile>
        <id>fast-tests</id>
        <build>
            <plugins>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.11</version>
                    <configuration>
                        <groups>com.mycompany.FastTests</groups>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>
</code>```

You can specify one or more profiles on the command line when running the tests.

```<code>mvn test -Pslow-tests,fast-tests
</code>```

Body:
Using a Spring maven context, I would like to run specific tests based on a maven profile. I would like to have an easy way of tagging the test groups. If possible I would like to use the annotations.
Which options are there, like maven command line parameters, maven profiles specification, etc.

Say I have the following tests:

Example:

// annotation("integration")
public class GeopointFormatterTest {
    @Test
    public void testIntegration1() {  ...  }
    @Test
    public void testIntegration2() {  ...  }

Annotations like @Profile (which is for creating beans) and @ActiveProfile (which is for selecting specific profiles for creating beans) cannot be used for selecting tests, of course. All tests just run for statements like:

mvn clean install -Pdevelopment

mvn clean install -Pdevelopment -Dspring.profiles.active=acceptance

mvn clean install -Pdevelopment -Dspring.profiles.active=integration

As suggested, I used also @IfProfileValue. This is a good way for selecting tests based on system property values. System property values can be overruled by a CustomProfileValueSource class, like in: @ProfileValueSourceConfiguration(CustomProfileValueSource.class)

EDIT and ALTERNATIVE

The GREAT answers below focus on JUnit's @Category mechanism. Thanks to all!

A different approach is via these steps: [1] set a property within a maven profile and [2] use the property to skip tests via the  of the standard surefire test plugin.

[1] Setting the properties via a profile:

<profiles>
    <profile>
        <id>integrationtests</id>
        <properties>
            <integration.skip>false</integration.skip>
            <acceptance.skip>true</acceptance.skip>
        </properties>
    </profile>
    ... other profiles

[2] Using the properties in the surefire test plugin to skip tests.

<build>
   <plugins>
      <plugin>

         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-surefire-plugin</artifactId>
         <version>${surefire.plugin.version}</version>
         <configuration>
            <skipTests>${acceptance.skip}</skipTests>

Start in maven: mvn clean install –Pintegrationtests

Body:
You will probably need to categorize your tests using the @Category annotation. A complete example has been provided in the Surefire documentation provided here - search for the string Using JUnit Categories.

Assuming that you have categorized your tests accordingly, you will now be able to setup one or more profiles in your maven build which will trigger these tests as per the category

<profiles>
    <profile>
        <id>slow-tests</id>
        <build>
            <plugins>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.11</version>
                    <configuration>
                        <groups>com.mycompany.SlowTests</groups>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>
    <profile>
        <id>fast-tests</id>
        <build>
            <plugins>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.11</version>
                    <configuration>
                        <groups>com.mycompany.FastTests</groups>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>

You can specify one or more profiles on the command line when running the tests.

mvn test -Pslow-tests,fast-tests


问:
Installing flyway CLI gives command not found
I try to run flyway repair on my server, but I have a problem installing the cli.
i extracted it on the server and i am at ~/flyway/flyway-4.2.0$ but it says command not found. Am I missing something? (Java is installed)

Manual only says this

答:
Try running the command as ./flyway repair

It appears you are on a linux server and it is necessary to run the command this way (see https://unix.stackexchange.com/questions/4430/why-do-we-use-to-execute-a-file). The Flyway docs are for a windows cmd prompt.


问:
Communicate between MainActivity and a Fragment
Hello Stackoverflow community, I looked at a lot of examples but I just can't apply it to my code. So I have the following code:

```<code>public class Profile extends AppCompatActivity {

private ViewPager mPager_profile;
private static final int NUM_PAGES = 3;
private PagerAdapter mPagerAdapter_profile;

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

    // set up the slider
    mPager_profile = (ViewPager) findViewById(R.id.pager_profile);
    mPagerAdapter_profile = new ScreenSlidePagerAdapter_profile(getSupportFragmentManager());
    mPager_profile.setAdapter(mPagerAdapter_profile);
    // bottom dots
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout_profile);
    tabLayout.setupWithViewPager(mPager_profile, true);

    Intent intent = getIntent();
    String[] data = intent.getStringArrayExtra("data");

}

// some code here
...

private class ScreenSlidePagerAdapter_profile extends
FragmentStatePagerAdapter {
    public ScreenSlidePagerAdapter_profile(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position){
            case 0:
                return new event_slide();
            case 1:
                return new profile_slide();
            case 2:
                return new option_slide();
            default:
                return null;

        }
    }

    @Override
    public int getCount() {
        return NUM_PAGES;
    }
}
</code>```

}

and the following code is my event_slide.java fragment:

```<code>public class event_slide extends android.support.v4.app.Fragment{

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance){
        ViewGroup eventView = (ViewGroup)inflater.inflate(R.layout.login_event, container, false);

        return eventView;
    }
}
</code>```

My question is: How can I pass the String array called "data" to my Fragment event_slide and than apply for example (String -->)data[0] to one of the TextView's, for example findViewById(R.id.textView9).setText(data[0]). I am new to android development, so please keep it simple.

Thanks in advance :)

答:
The easiest way would be (but not the best):

```<code>public class EventSlide extends android.support.v4.app.Fragment{

    public String arg1;

    public EventSlide(String arg1){
        this.arg1 = arg1;
    }

    // Override OnCreate method, initialize your textView and set your text there
}
</code>```

I recomend you take a look to newInstance pattern.

Body:
Hello Stackoverflow community, I looked at a lot of examples but I just can't apply it to my code. So I have the following code:

public class Profile extends AppCompatActivity {

private ViewPager mPager_profile;
private static final int NUM_PAGES = 3;
private PagerAdapter mPagerAdapter_profile;

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

    // set up the slider
    mPager_profile = (ViewPager) findViewById(R.id.pager_profile);
    mPagerAdapter_profile = new ScreenSlidePagerAdapter_profile(getSupportFragmentManager());
    mPager_profile.setAdapter(mPagerAdapter_profile);
    // bottom dots
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout_profile);
    tabLayout.setupWithViewPager(mPager_profile, true);

    Intent intent = getIntent();
    String[] data = intent.getStringArrayExtra("data");

}

// some code here
...

private class ScreenSlidePagerAdapter_profile extends
FragmentStatePagerAdapter {
    public ScreenSlidePagerAdapter_profile(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position){
            case 0:
                return new event_slide();
            case 1:
                return new profile_slide();
            case 2:
                return new option_slide();
            default:
                return null;

        }
    }

    @Override
    public int getCount() {
        return NUM_PAGES;
    }
}

}

and the following code is my event_slide.java fragment:

public class event_slide extends android.support.v4.app.Fragment{

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance){
        ViewGroup eventView = (ViewGroup)inflater.inflate(R.layout.login_event, container, false);

        return eventView;
    }
}

My question is: How can I pass the String array called "data" to my Fragment event_slide and than apply for example (String -->)data[0] to one of the TextView's, for example findViewById(R.id.textView9).setText(data[0]). I am new to android development, so please keep it simple.

Thanks in advance :)

Body:
The easiest way would be (but not the best):

public class EventSlide extends android.support.v4.app.Fragment{

    public String arg1;

    public EventSlide(String arg1){
        this.arg1 = arg1;
    }

    // Override OnCreate method, initialize your textView and set your text there
}

I recomend you take a look to newInstance pattern.


问:
Sorting a vector of custom objects with const member
I would like to sort a vector holding objects of a class with a const member variable.

Unfortunately, I get an error stating that there is "no matching function for call to "swap"".

When I remove the const keyword for id, then std::sort() works with both the overloaded operator<() and the custom compare function.

Why is this the case? Can I in general not sort objects belonging to a class with a const member variable?

```<code>#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct A
{
    const int id;
    A(int id) : id(id) {}
    bool operator<(const A &other) const
    {
        return id < other.id;
    }
};

bool cmp(const A &lhs, const A &rhs)
{
    return lhs.id < rhs.id;
}

int main()
{
    vector<A> vec;
    vec.emplace_back(3);
    vec.emplace_back(0);
    vec.emplace_back(2);
    vec.emplace_back(1);
    std::sort(vec.begin(), vec.end());
    std::sort(vec.begin(), vec.end(), cmp);
}
</code>```

答:
Well, the way that sort is going to be implemented is that it will swap objects as needed. A class with a const member and no copy or move assignment operators is not going to be "swappable".

I would probably make the id member private and non-const. Then I'd have it accessed via a getter (but not providing a setter). Making it logically const, but the class would be copyable.

Something like this:

```<code>class A {
public:
    A(int id) : id_(id) {}

    bool operator<(const A &other) const {
        return id_ < other.id_;
    }

    int id() const { return id_; }

private:
    int id_;
};
</code>```

Body:
I would like to sort a vector holding objects of a class with a const member variable.

Unfortunately, I get an error stating that there is "no matching function for call to "swap"".

When I remove the const keyword for id, then std::sort() works with both the overloaded operator<() and the custom compare function.

Why is this the case? Can I in general not sort objects belonging to a class with a const member variable?

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct A
{
    const int id;
    A(int id) : id(id) {}
    bool operator<(const A &other) const
    {
        return id < other.id;
    }
};

bool cmp(const A &lhs, const A &rhs)
{
    return lhs.id < rhs.id;
}

int main()
{
    vector vec;
    vec.emplace_back(3);
    vec.emplace_back(0);
    vec.emplace_back(2);
    vec.emplace_back(1);
    std::sort(vec.begin(), vec.end());
    std::sort(vec.begin(), vec.end(), cmp);
}

Body:
Well, the way that sort is going to be implemented is that it will swap objects as needed. A class with a const member and no copy or move assignment operators is not going to be "swappable".

I would probably make the id member private and non-const. Then I'd have it accessed via a getter (but not providing a setter). Making it logically const, but the class would be copyable.

Something like this:

class A {
public:
    A(int id) : id_(id) {}

    bool operator<(const A &other) const {
        return id_ < other.id_;
    }

    int id() const { return id_; }

private:
    int id_;
};


问:
Calculate broadcast by IP and mask
i'm trying to calculate broadcast address by logic OR and NOT with specified ip and mask, but the func return me smth strange. Why?

```<code> IP = '192.168.32.16'
 MASK = '255.255.0.0'

 def get_ID(ip, mask):
    ip = ip.split('.')
    mask = mask.split('.')
    ip = [int(bin(int(octet)), 2) for octet in ip]
    mask = [int(bin(int(octet)), 2) for octet in mask]
    subnet = [str(int(bin(ioctet & moctet), 2)) for ioctet, moctet in zip(ip, mask)]
    host = [str(int(bin(ioctet & ~moctet), 2)) for ioctet, moctet in zip(ip, mask)]
    broadcast = [str(int(bin(ioctet | ~moctet), 2)) for ioctet, moctet in zip(ip, mask)] # a mistake, i guess
    print('Subnet: {0}'.format('.'.join(subnet)))
    print('Host: {0}'.format('.'.join(host)))
    print('Broadcast address: {0}'.format('.'.join(broadcast)))
</code>```

答:
-64 and 192 are actually the same value as 8-bit bytes.  You just need to mask the bytes with 0xff to get numbers in the more standard 0…255 range instead of the -128…127 range you have now.  Something like this:

```<code>broadcast = [(ioctet | ~moctet) & 0xff for ioctet, moctet in zip(ip, mask)]
</code>```

Title: Calculate broadcast by IP and mask

Body:
i'm trying to calculate broadcast address by logic OR and NOT with specified ip and mask, but the func return me smth strange. Why?

 IP = '192.168.32.16'
 MASK = '255.255.0.0'

 def get_ID(ip, mask):
    ip = ip.split('.')
    mask = mask.split('.')
    ip = [int(bin(int(octet)), 2) for octet in ip]
    mask = [int(bin(int(octet)), 2) for octet in mask]
    subnet = [str(int(bin(ioctet & moctet), 2)) for ioctet, moctet in zip(ip, mask)]
    host = [str(int(bin(ioctet & ~moctet), 2)) for ioctet, moctet in zip(ip, mask)]
    broadcast = [str(int(bin(ioctet | ~moctet), 2)) for ioctet, moctet in zip(ip, mask)] # a mistake, i guess
    print('Subnet: {0}'.format('.'.join(subnet)))
    print('Host: {0}'.format('.'.join(host)))
    print('Broadcast address: {0}'.format('.'.join(broadcast)))

Body:
-64 and 192 are actually the same value as 8-bit bytes.  You just need to mask the bytes with 0xff to get numbers in the more standard 0…255 range instead of the -128…127 range you have now.  Something like this:

broadcast = [(ioctet | ~moctet) & 0xff for ioctet, moctet in zip(ip, mask)]

ContentLicense: CC BY-SA 4.0


问:
Cannot connect to my mongoDB replicaset
I create a replicaset rs0 on which I have:

```<code>mongo1.mydomain.com
mongo2.mydomain.com
mongo3.mydomain.com
</code>```

Here is my rs.conf

```<code>rs0:PRIMARY> rs.conf()
{
        "_id" : "rs0",
        "version" : 3,
        "protocolVersion" : NumberLong(1),
        "members" : [
                {
                        "_id" : 0,
                        "host" : "mongo1.mydomain.com:27017",
                        "arbiterOnly" : false,
                        "buildIndexes" : true,
                        "hidden" : false,
                        "priority" : 1,
                        "tags" : {

                        },
                        "slaveDelay" : NumberLong(0),
                        "votes" : 1
                },
                {
                        "_id" : 1,
                        "host" : "mongo2.mydomain.com:27017",
                        "arbiterOnly" : false,
                        "buildIndexes" : true,
                        "hidden" : false,
                        "priority" : 1,
                        "tags" : {

                        },
                        "slaveDelay" : NumberLong(0),
                        "votes" : 1
                },
                {
                        "_id" : 2,
                        "host" : "mongo3.mydomain.com:27017",
                        "arbiterOnly" : false,
                        "buildIndexes" : true,
                        "hidden" : false,
                        "priority" : 1,
                        "tags" : {

                        },
                        "slaveDelay" : NumberLong(0),
                        "votes" : 1
                }
        ],
        "settings" : {
                "chainingAllowed" : true,
                "heartbeatIntervalMillis" : 2000,
                "heartbeatTimeoutSecs" : 10,
                "electionTimeoutMillis" : 10000,
                "catchUpTimeoutMillis" : 60000,
                "getLastErrorModes" : {

                },
                "getLastErrorDefaults" : {
                        "w" : 1,
                        "wtimeout" : 0
                },
                "replicaSetId" : ObjectId("5a0ca4fe5e8a441fcd6aa77d")
        }
}
</code>```

Currently mongo3 is primary (I shutted down mongo1 which was the primary then restarted it)

Then I have a DB myDB for which a user (with dash) has been created (with read and write rights):

```<code>rs0:PRIMARY> use myDB
switched to db myDB
rs0:PRIMARY> db.auth("my-server-user", "Test1234");
1
rs0:PRIMARY>
</code>```

I now try to connect to my replicaset (all port are open for the moment to my servers) with URI but I get error:

```<code>MongoDB server version: 3.4.10
2017-11-15T22:13:01.241+0100 E QUERY    [thread1] Error: Authentication failed.
DB.prototype._authOrThrow@src/mongo/shell/db.js:1461:20
@(auth):6:1
@(auth):1:2
exception: login failed
</code>```

To connect I use:

```<code>mongo "mongodb://mongo1.mydomain.com:27017,mongo2.mydomain.com:27017,mongo3.mydomain.com:27017/myDB?replicaSet=rs0" --authenticationDatabase admin --username my-server-user --password Test1234
</code>```

Do you have an idea?

Thanks in advance

答:
Ok found by removing:

```<code>--authenticationDatabase admin
</code>```

I get:

```<code>mongo "mongodb://mongo1.mydomain.com:27017,mongo2.mydomain.com:27017,mongo3.mydomain.com:27017/myDB?replicaSet=rs0" --username my-server-user --password Test1234
</code>```

Title: Cannot connect to my mongoDB replicaset

Body:
I create a replicaset rs0 on which I have:

mongo1.mydomain.com
mongo2.mydomain.com
mongo3.mydomain.com

Here is my rs.conf

rs0:PRIMARY> rs.conf()
{
        "_id" : "rs0",
        "version" : 3,
        "protocolVersion" : NumberLong(1),
        "members" : [
                {
                        "_id" : 0,
                        "host" : "mongo1.mydomain.com:27017",
                        "arbiterOnly" : false,
                        "buildIndexes" : true,
                        "hidden" : false,
                        "priority" : 1,
                        "tags" : {

                        },
                        "slaveDelay" : NumberLong(0),
                        "votes" : 1
                },
                {
                        "_id" : 1,
                        "host" : "mongo2.mydomain.com:27017",
                        "arbiterOnly" : false,
                        "buildIndexes" : true,
                        "hidden" : false,
                        "priority" : 1,
                        "tags" : {

                        },
                        "slaveDelay" : NumberLong(0),
                        "votes" : 1
                },
                {
                        "_id" : 2,
                        "host" : "mongo3.mydomain.com:27017",
                        "arbiterOnly" : false,
                        "buildIndexes" : true,
                        "hidden" : false,
                        "priority" : 1,
                        "tags" : {

                        },
                        "slaveDelay" : NumberLong(0),
                        "votes" : 1
                }
        ],
        "settings" : {
                "chainingAllowed" : true,
                "heartbeatIntervalMillis" : 2000,
                "heartbeatTimeoutSecs" : 10,
                "electionTimeoutMillis" : 10000,
                "catchUpTimeoutMillis" : 60000,
                "getLastErrorModes" : {

                },
                "getLastErrorDefaults" : {
                        "w" : 1,
                        "wtimeout" : 0
                },
                "replicaSetId" : ObjectId("5a0ca4fe5e8a441fcd6aa77d")
        }
}

Currently mongo3 is primary (I shutted down mongo1 which was the primary then restarted it)

Then I have a DB myDB for which a user (with dash) has been created (with read and write rights):

rs0:PRIMARY> use myDB
switched to db myDB
rs0:PRIMARY> db.auth("my-server-user", "Test1234");
1
rs0:PRIMARY>

I now try to connect to my replicaset (all port are open for the moment to my servers) with URI but I get error:

MongoDB server version: 3.4.10
2017-11-15T22:13:01.241+0100 E QUERY    [thread1] Error: Authentication failed.
DB.prototype._authOrThrow@src/mongo/shell/db.js:1461:20
@(auth):6:1
@(auth):1:2
exception: login failed

To connect I use:

mongo "mongodb://mongo1.mydomain.com:27017,mongo2.mydomain.com:27017,mongo3.mydomain.com:27017/myDB?replicaSet=rs0" --authenticationDatabase admin --username my-server-user --password Test1234

Do you have an idea?

Thanks in advance

Body:
Ok found by removing:

--authenticationDatabase admin

I get:

mongo "mongodb://mongo1.mydomain.com:27017,mongo2.mydomain.com:27017,mongo3.mydomain.com:27017/myDB?replicaSet=rs0" --username my-server-user --password Test1234


问:
Create a function that outputs spending level based on money spent - Python
How do I create a function that says that for example if a person spends 100 dollars they are bronze, whereas if they spend between 100 dollars and 200 dollars they are silver?

I am trying to learn how to use user defined functions rather than loops, so would prefer no suggestions using loops.

Thanks

答:
Create a dictionary which maps the different increment keys to a value. Then you just need to calculate which key your 'amount_spent' is closest to and choose the value from the dictionary which this corresponds to</p>

```<code>def prestige_level(amount_spent):
    levels = {0: 'bronze',
              100: 'silver',
              200: 'gold'}

    key = min([x for x in levels if amount_spent >= x], key=lambda x: abs(x - amount_spent))
    return levels[key]

print(prestige_level(1))
>> bronze
print(prestige_level(100))
>> silver
print(prestige_level(101))
>> silver
print(prestige_level(199))
>> silver
print(prestige_level(200))
>> gold
print(prestige_level(201))
>> gold
print(prestige_level(1000))
>> gold
</code>```

Body:
Create a dictionary which maps the different increment keys to a value. Then you just need to calculate which key your 'amount_spent' is closest to and choose the value from the dictionary which this corresponds to

def prestige_level(amount_spent):
    levels = {0: 'bronze',
              100: 'silver',
              200: 'gold'}

    key = min([x for x in levels if amount_spent >= x], key=lambda x: abs(x - amount_spent))
    return levels[key]

print(prestige_level(1))
>> bronze
print(prestige_level(100))
>> silver
print(prestige_level(101))
>> silver
print(prestige_level(199))
>> silver
print(prestige_level(200))
>> gold
print(prestige_level(201))
>> gold
print(prestige_level(1000))
>> gold


问:
Python 3 Elif Indentation Error
I am working on a simple script in Python, and when I attempt to use an elif statement, it throws an error saying that it expected an indented block. I know this may be something simple, but I have tried everything and I am stuck, so anyone willing to help is welcome. Thank you in advance.

```<code>import math as m

mass = input("Enter the mass of the object (kg)")
i = 0
while i == 0:
  if type(mass)!= type(1.1):
    #mass = input("You have entered an incorrect value, please enter a numerical value.")

  elif type(mass) == type(1.1):
    print("test")
    break
</code>```

The full error message is below:

```<code>Traceback (most recent call last):
  File "python", line 9
    elif type(mass) == type(1.1):
       ^
IndentationError: expected an indented block
</code>```

答:
Your if is empty (as comments are ignored), therefore Python expects a statement to execute in the True case in the next not-commented line with a indentation.

Just put a pass in the if block, in order to fix this.

Title: Python 3 Elif Indentation Error

Body:
I am working on a simple script in Python, and when I attempt to use an elif statement, it throws an error saying that it expected an indented block. I know this may be something simple, but I have tried everything and I am stuck, so anyone willing to help is welcome. Thank you in advance.

import math as m

mass = input("Enter the mass of the object (kg)")
i = 0
while i == 0:
  if type(mass)!= type(1.1):
    #mass = input("You have entered an incorrect value, please enter a numerical value.")

  elif type(mass) == type(1.1):
    print("test")
    break

The full error message is below:

Traceback (most recent call last):
  File "python", line 9
    elif type(mass) == type(1.1):
       ^
IndentationError: expected an indented block


问:
bash: extract an attribute value between quotes using awk or sed(GNU grep is not an option)
I have a xml file with data like below

```<code><temp>
<a="something" total="50" b="something" total="0" c="something" total="20">
</temp>
</code>```

I need to get first value of total i.e, 50 but my sed solution is giving value of last occurrence of total i.e, 20

```<code>sed -n 's/.*total="\([^"]*\).*/\1/p' temp.xml
</code>```

output : 20

desired output: 50

I appreciate the help. Thank you

答:
Sample data file:

```<code>$ cat my.xml
<temp>
<a="something" total="50" b="something" total="0" c="something" total="20">
</temp>
</code>```

And a quick awk solution based on the limited data sample and sole requirement of retrieving the first total value:

```<code>$ awk -F'"' '/ total=/ { print $4}' my.xml
50
</code>```

-F'"' : define (input) field separator as a double quote

/ total=/ : only interested in lines that include the string ' total=', and then ...

print $4 : print the 4th field

Body:
I have a xml file with data like below

<temp>

</temp>

I need to get first value of total i.e, 50 but my sed solution is giving value of last occurrence of total i.e, 20

sed -n 's/.*total="\([^"]*\).*/\1/p' temp.xml

output : 20

desired output: 50

I appreciate the help. Thank you

Body:
Sample data file:

$ cat my.xml
<temp>
<a="something" total="50" b="something" total="0" c="something" total="20">
</temp>

And a quick awk solution based on the limited data sample and sole requirement of retrieving the first total value:

$ awk -F'"' '/ total=/ { print $4}' my.xml
50

-F'"' : define (input) field separator as a double quote

/ total=/ : only interested in lines that include the string ' total=', and then ...

print $4 : print the 4th field