问:
refactoring assistance with reducing some array data objects in JavaScript
I need to reduce data in profiles array in a way such that the final object groups the data in profile obj based on the favorite movie and the users that liked/favorited the movie.
I want something like:

```<code>{
 'Forrest Gump': ["Nicholas Lain"],
 'Planet Earth 1': ["Jane Jones", "Matthew Johnson"]
}
</code>```

from the following data objects:

```<code>const profiles = [
      {
        id: 1,
        userID: '1',
        favoriteMovieID: '1',
      },
      {
        id: 2,
        userID: '2',
        favoriteMovieID: '1',
      },
      {
        id: 3,
        userID: '4',
        favoriteMovieID: '5',
      }
    ];

    const users = {
      1: {
        id: 1,
        name: 'Jane Cruz',
        userName: 'coder',
      },
      2: {
        id: 2,
        name: 'Matthew Johnson',
        userName: 'mpage',
      }
    };

    const movies = {
      1: {
        id: 1,
        name: 'Planet Earth 1',
      },
      2: {
        id: 2,
        name: 'Selma',
      }
    };
</code>```

I need some ideas in refactoring the following code for it to go back to the users and movies object to grab their names from the IDs I have captured below. Instead of IDs, I need to capture the names.

```<code>profiles.reduce(function (acc, obj) {
    let key = obj['favoriteMovieID']
    if (!acc[key]) {
      acc[key] = []
    }
    acc[key].push(obj.userID)
    return acc
  }, {})
</code>```

答:
Here is one technique, doing a fold on the profiles, grabbing the movie and person names inside the parameters, and then simply writing a new accumulator with that data.  Note that there is a potential performance problem with this, as described in Rich Snapp's excellent article.  If that causes you an actual issue, it's easy enough to change this to mutate the accumulator.

I added some additional data to show what happens when the user or the movie isn't in the appropriate lists.  If that cannot ever happen, you can simplify the name and person declarations a bit.  But I wouldn't recommend it, as things that "can never happen" in fact regularly do happen.

const groupNamesByMovie = (profiles, users, movies) =>
  profiles .reduce ((
    a, {userID, favoriteMovieID}, _, __,
    {name} = movies [favoriteMovieID] || {name: 'Unknown Movie'},
    {name: person} = users [userID] || {name: 'Unknown Person'}
  ) => ({
    ...a,
    [name]: [... (a [name] || []), person]
  }), {})

const profiles = [{id: 1, userID: "1", favoriteMovieID: "1"}, {id: 2, userID: "2", favoriteMovieID: "1"}, {id: 3, userID: "4", favoriteMovieID: "5"}, {id: 4, userID: "6", favoriteMovieID: "5"}, {id: 5, userID: "5", favoriteMovieID: "7"}]
const users = {1: {id: 1, name: "Jane Cruz", userName: "coder"}, 2: {id: 2, name: "Matthew Johnson", userName: "mpage"}, 4: {id: 4, name: "Nicholas Lain", userName: "nlain"}, 5: {id: 5, name: "Fred Flintstone", userName: "bedrock1"}}
const movies = {1: {id: 1, name: 'Planet Earth 1'}, 2: {id: 2, name: 'Selma'}, 5: {id: 5, name: 'Forrest Gump'}}

console .log (
  groupNamesByMovie (profiles, users, movies)
)```
</div>
</div>
</p>

<p>Note that the arguments <code>_</code> and <code>__</code> are just meant to be placeholders, since we don't care about <code>reduce</code>'s <code>index</code> and <code>array</code> parameters.</p>

<h2>Update</h2>

<p>There was a request for clarification.  For comparison, here's a more imperative version of this same idea:</p>

<pre class="lang-js prettyprint-override"><code>const getNamesByMovie = (profiles, users, movies) =>
  profiles .reduce ((acc, {userID, favoriteMovieID}) => {
    const movie = movies [favoriteMovieID]
    const name = movie ? movie.name : 'Unknown Movie'
    const user = users [userID]
    const person = user ? user.name : 'Unknown Person'
    const fans = acc [name] || []
    return {
      ... acc,
      [name]: [... fans, person]
    }

  }, {})
</code>```

And if you wanted to avoid that potential performance problem, you could replace the return statement with something like this:

    acc [name] = fans
    fans .push (person)
    return acc
```

Either of these does the same sort of thing as the original above.  I choose that initial style because I don't like mutating the accumulator object, preferring to always create a new version... and because I prefer working with expressions over statements.  But this style does take some getting used to.

You also asked how we passed additional parameters to the reduce callback.  We don't.  Instead we define some additional parameters and initialize them based on the earlier parameters.

Body:
I need to reduce data in profiles array in a way such that the final object groups the data in profile obj based on the favorite movie and the users that liked/favorited the movie.
I want something like:

{
 'Forrest Gump': ["Nicholas Lain"],
 'Planet Earth 1': ["Jane Jones", "Matthew Johnson"]
}

from the following data objects:

const profiles = [
      {
        id: 1,
        userID: '1',
        favoriteMovieID: '1',
      },
      {
        id: 2,
        userID: '2',
        favoriteMovieID: '1',
      },
      {
        id: 3,
        userID: '4',
        favoriteMovieID: '5',
      }
    ];

    const users = {
      1: {
        id: 1,
        name: 'Jane Cruz',
        userName: 'coder',
      },
      2: {
        id: 2,
        name: 'Matthew Johnson',
        userName: 'mpage',
      }
    };

    const movies = {
      1: {
        id: 1,
        name: 'Planet Earth 1',
      },
      2: {
        id: 2,
        name: 'Selma',
      }
    };

I need some ideas in refactoring the following code for it to go back to the users and movies object to grab their names from the IDs I have captured below. Instead of IDs, I need to capture the names.

profiles.reduce(function (acc, obj) {
    let key = obj['favoriteMovieID']
    if (!acc[key]) {
      acc[key] = []
    }
    acc[key].push(obj.userID)
    return acc
  }, {})

Body:
Here is one technique, doing a fold on the profiles, grabbing the movie and person names inside the parameters, and then simply writing a new accumulator with that data.  Note that there is a potential performance problem with this, as described in Rich Snapp's excellent article.  If that causes you an actual issue, it's easy enough to change this to mutate the accumulator.

I added some additional data to show what happens when the user or the movie isn't in the appropriate lists.  If that cannot ever happen, you can simplify the name and person declarations a bit.  But I wouldn't recommend it, as things that "can never happen" in fact regularly do happen.

const groupNamesByMovie = (profiles, users, movies) =>
  profiles .reduce ((
    a, {userID, favoriteMovieID}, _, __,
    {name} = movies [favoriteMovieID] || {name: 'Unknown Movie'},
    {name: person} = users [userID] || {name: 'Unknown Person'}
  ) => ({
    ...a,
    [name]: [... (a [name] || []), person]
  }), {})

const profiles = [{id: 1, userID: "1", favoriteMovieID: "1"}, {id: 2, userID: "2", favoriteMovieID: "1"}, {id: 3, userID: "4", favoriteMovieID: "5"}, {id: 4, userID: "6", favoriteMovieID: "5"}, {id: 5, userID: "5", favoriteMovieID: "7"}]
const users = {1: {id: 1, name: "Jane Cruz", userName: "coder"}, 2: {id: 2, name: "Matthew Johnson", userName: "mpage"}, 4: {id: 4, name: "Nicholas Lain", userName: "nlain"}, 5: {id: 5, name: "Fred Flintstone", userName: "bedrock1"}}
const movies = {1: {id: 1, name: 'Planet Earth 1'}, 2: {id: 2, name: 'Selma'}, 5: {id: 5, name: 'Forrest Gump'}}

console .log (
  groupNamesByMovie (profiles, users, movies)
)

Note that the arguments _ and __ are just meant to be placeholders, since we don't care about reduce's index and array parameters.

Update

There was a request for clarification.  For comparison, here's a more imperative version of this same idea:

const getNamesByMovie = (profiles, users, movies) =>
  profiles .reduce ((acc, {userID, favoriteMovieID}) => {
    const movie = movies [favoriteMovieID]
    const name = movie ? movie.name : 'Unknown Movie'
    const user = users [userID]
    const person = user ? user.name : 'Unknown Person'
    const fans = acc [name] || []
    return {
      ... acc,
      [name]: [... fans, person]
    }

  }, {})

And if you wanted to avoid that potential performance problem, you could replace the return statement with something like this:

    acc [name] = fans
    fans .push (person)
    return acc

Either of these does the same sort of thing as the original above.  I choose that initial style because I don't like mutating the accumulator object, preferring to always create a new version... and because I prefer working with expressions over statements.  But this style does take some getting used to.

You also asked how we passed additional parameters to the reduce callback.  We don't.  Instead we define some additional parameters and initialize them based on the earlier parameters.


来源: stackexchange

问:
How to implement Dump as the one provided by LinqPad?
Given (new [] {"a", "b"}).Dump(), LinqPad provides some very useful print results.

It seems that this extension method is a short hand for Console.WriteLine.

Question> how to implement this dump for myself?

答:
With a lot of hard work.

Dump is not a shortcut for Console.WriteLine; it's an extremely complicated recursive method which turns arbitrary object graphs into HTML, with special support for collections, DataTables, Images, and a couple of other types.

It also has special output code to format collections of complex objects into tables, and to prevent recursive expansion.

ContentLicense: CC BY-SA 3.0


问:
Is it possible to add a json in the properties an element?
I have a json like this:

```<code>    Map<String, dynamic> optionsContainer() {
      return {
        "color": Colors.red,
        "height": MediaQuery.of(context).size.height * 0.40,
        "margin": EdgeInsets.all(10)
      };
    }
.
.
.
 Container(
  child:Text("mytext"),
  optionsContainer(),
 )
</code>```

I get an error when I try to assign it to the properties of an element, in this case a container

Is there any way of doing this?

I am getting this error:

"Too many positional arguments: 0 expected, but 1 found.
Try removing the extra positional arguments, or specifying the name for named arguments."

my idea is to recycle code and define these properties in a class so as not to repeat them again.

NOTE: I don't do this with a theme because this is only for one class within my app I don't want it to overwrite the other styles.

答:
If you know all possible keys in map, you can extract values and pass them as usual named parameters:

```<code>final options = optionsContainer();
</code>```

```<code>Container(
  color: options["color"],
  height: options["height"],
  margin: options["margin"],
)
</code>```

Alternatively you can make a class for container data and use it instead of map which gives compile-time types check:

```<code>class ContainerData {
  final Color color;
  final double height;
  final EdgeInsets margin;

  ContainerData({
    @required this.color,
    @required this.height,
    @required this.margin,
  });
}
</code>```

```<code>ContainerData getOptions() {
  return ContainerData(
    color: Colors.red,
    height: MediaQuery.of(context).size.height * 0.40,
    margin: EdgeInsets.all(10),
  );
}
</code>```

```<code>final options = getOptions();
</code>```

```<code>Container(
  color: options.color,
  height: options.height,
  margin: options.margin,
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a json like this:

    Map<String, dynamic> optionsContainer() {
      return {
        "color": Colors.red,
        "height": MediaQuery.of(context).size.height * 0.40,
        "margin": EdgeInsets.all(10)
      };
    }
.
.
.
 Container(
  child:Text("mytext"),
  optionsContainer(),
 )

I get an error when I try to assign it to the properties of an element, in this case a container

Is there any way of doing this?

I am getting this error:

"Too many positional arguments: 0 expected, but 1 found.
Try removing the extra positional arguments, or specifying the name for named arguments."

my idea is to recycle code and define these properties in a class so as not to repeat them again.

NOTE: I don't do this with a theme because this is only for one class within my app I don't want it to overwrite the other styles.

Body:
If you know all possible keys in map, you can extract values and pass them as usual named parameters:

final options = optionsContainer();

Container(
  color: options["color"],
  height: options["height"],
  margin: options["margin"],
)

Alternatively you can make a class for container data and use it instead of map which gives compile-time types check:

class ContainerData {
  final Color color;
  final double height;
  final EdgeInsets margin;

  ContainerData({
    @required this.color,
    @required this.height,
    @required this.margin,
  });
}

ContainerData getOptions() {
  return ContainerData(
    color: Colors.red,
    height: MediaQuery.of(context).size.height * 0.40,
    margin: EdgeInsets.all(10),
  );
}

final options = getOptions();

Container(
  color: options.color,
  height: options.height,
  margin: options.margin,
)


问:
Memory Leak in C#
Is it ever possible in a managed system to leak memory when you make sure that all handles, things that implement IDispose are disposed?

Would there be cases where some variables are left out?

答:
I don't think C++ style memory leaks are possible.  The garbage collector should account for those.  It is possible to create a static object that aggregates object references even though the objects are never used again.  Something like this:

```<code>public static class SomethingFactory
{
    private static List<Something> listOfSomethings = new List<Something>();

    public static Something CreateSomething()
    {
        var something = new Something();
        listOfSomethings.Add(something);
        return something;
    }
}
</code>```

That's an obviously stupid example, but it would be the equivalent of a managed runtime memory leak.

OwnerDisplayName: Joan Venge

ContentLicense: CC BY-SA 2.5

Title: Memory Leak in C#

LastEditorDisplayName: strager

Body:
I don't think C++ style memory leaks are possible.  The garbage collector should account for those.  It is possible to create a static object that aggregates object references even though the objects are never used again.  Something like this:

public static class SomethingFactory
{
    private static List<Something> listOfSomethings = new List<Something>();

    public static Something CreateSomething()
    {
        var something = new Something();
        listOfSomethings.Add(something);
        return something;
    }
}

That's an obviously stupid example, but it would be the equivalent of a managed runtime memory leak.

OwnerDisplayName: Michael Meadows


问:
Reading a binary file in C: ftell returns results that sometimes are off by one
I'm trying to read a binary file that is in the following format:

number of images [4-byte int]

width [4-byte int]

    height [4-byte int]

    grayscale data [width * height bytes]

    (more elements of the same type)

That's the first function being called:

```<code>int process_file(const char *filename) {
    FILE *input_file = fopen(filename, "r");

    //Get number of images
    unsigned int number_of_images = read_int_from_file(input_file);

    //Allocate memory for all images
    struct image *images = malloc(sizeof(struct image) * number_of_images);

    read_images(images, number_of_images, input_file)
}
</code>```

Here's the image structure for anyone wondering:

```<code>struct image {
    unsigned int width;
    unsigned int height;
    unsigned char *data;
};
</code>```

And that's what read_int_from_file does:

```<code>static unsigned int read_int_from_file(FILE *file) {
    unsigned char chars[4];
    if (fread(&chars, sizeof(char), 4, file) != 4) {
        fprintf(stderr, "Couldn't read enough bytes!\n");
        return 0;
    }
    //Calculations follow that return right numbers
    return out;
}
</code>```

That's the rest:

```<code>static int read_images(struct image *images, unsigned int number_of_images, FILE * file) {
    struct image *current_image = images;

    int i;
    for (i = 0; i < number_of_images; i++) {
        read_image(current_image++, file)
    }

    return EXIT_SUCCESS;
}

static int read_image(struct image *image, FILE *file) {
    static long int expected_position = 4;

    if (ftell(file) != expected_position) {
        fprintf(stderr, "Reading @ %lu when should be @ %lu!",
                ftell(file), expected_position);
        exit(EXIT_FAILURE);
    }

    unsigned int width = read_int_from_file(file);
    unsigned int height = read_int_from_file(file);

    unsigned int size = width * height;

    unsigned char *data = malloc(sizeof(char) * size);
    if (data) {
        if (fread(data, sizeof(char), size, file) != size) {
            exit(EXIT_FAILURE);
        }

        image->width = width;
        image->height = height;
        image->data = data;

        expected_position += 2 * 4 + width * height;
        return EXIT_SUCCESS;
    } else {
        exit(EXIT_FAILURE);
    }
}
</code>```

The problem is that the file pointer is sometimes going ahead when it shouldn't do so, i.e. I'm hitting ftell(file) != expected_position. I'm getting it after a good amount of successful reads, but some good time before the end, too.

Does anyone have any idea why that may be? I mean, even if the numbers were wrong, that shouldn't happen, should it? Thanks!

答:
You need to open the binary file as such:</p>

```<code>//                                   v
FILE *input_file = fopen(filename, "rb");
</code>```

Body:
I'm trying to read a binary file that is in the following format:

number of images [4-byte int]

width [4-byte int]

    height [4-byte int]

    grayscale data [width * height bytes]

    (more elements of the same type)

That's the first function being called:

int process_file(const char *filename) {
    FILE *input_file = fopen(filename, "r");

    //Get number of images
    unsigned int number_of_images = read_int_from_file(input_file);

    //Allocate memory for all images
    struct image *images = malloc(sizeof(struct image) * number_of_images);

    read_images(images, number_of_images, input_file)
}

Here's the image structure for anyone wondering:

struct image {
    unsigned int width;
    unsigned int height;
    unsigned char *data;
};

And that's what read_int_from_file does:

static unsigned int read_int_from_file(FILE *file) {
    unsigned char chars[4];
    if (fread(&chars, sizeof(char), 4, file) != 4) {
        fprintf(stderr, "Couldn't read enough bytes!\n");
        return 0;
    }
    //Calculations follow that return right numbers
    return out;
}

That's the rest:

static int read_images(struct image *images, unsigned int number_of_images, FILE * file) {
    struct image *current_image = images;

    int i;
    for (i = 0; i < number_of_images; i++) {
        read_image(current_image++, file)
    }

    return EXIT_SUCCESS;
}

static int read_image(struct image *image, FILE *file) {
    static long int expected_position = 4;

    if (ftell(file) != expected_position) {
        fprintf(stderr, "Reading @ %lu when should be @ %lu!",
                ftell(file), expected_position);
        exit(EXIT_FAILURE);
    }

    unsigned int width = read_int_from_file(file);
    unsigned int height = read_int_from_file(file);

    unsigned int size = width * height;

    unsigned char *data = malloc(sizeof(char) * size);
    if (data) {
        if (fread(data, sizeof(char), size, file) != size) {
            exit(EXIT_FAILURE);
        }

        image->width = width;
        image->height = height;
        image->data = data;

        expected_position += 2 * 4 + width * height;
        return EXIT_SUCCESS;
    } else {
        exit(EXIT_FAILURE);
    }
}

The problem is that the file pointer is sometimes going ahead when it shouldn't do so, i.e. I'm hitting ftell(file) != expected_position. I'm getting it after a good amount of successful reads, but some good time before the end, too.

Does anyone have any idea why that may be? I mean, even if the numbers were wrong, that shouldn't happen, should it? Thanks!

Body:
You need to open the binary file as such:

//                                   v
FILE *input_file = fopen(filename, "rb");


问:
SpringBoot - making jar files - No auto configuration classes found in META-INF/spring.factories
Everything was working fine when starting my app using IntelliJ. But when I made a fat jar and executed it with

```<code>java -jar myapp.jar
</code>```

I got this:

```<code>16:37:44.194 [main] ERROR org.springframework.boot.SpringApplication - Application startup failed
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [pl.mypackage.Main]; nested exception is java.lang.IllegalArgumentException: No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.
        at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:489)
        at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:191)
        at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:321)
        at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243)
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:273)
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:98)
        at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:681)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:523)
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:369)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:313)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1185)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1174)
        at pl.mypackage.Main.main(Main.java:39)
Caused by: java.lang.IllegalArgumentException: No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.
        at org.springframework.util.Assert.notEmpty(Assert.java:276)
        at org.springframework.boot.autoconfigure.EnableAutoConfigurationImportSelector.getCandidateConfigurations(EnableAutoConfigurationImportSelector.java:145)
        at org.springframework.boot.autoconfigure.EnableAutoConfigurationImportSelector.selectImports(EnableAutoConfigurationImportSelector.java:84)
        at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:481)
        ... 14 common frames omitted
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [pl.mypackage.Main]; nested exception is java.lang.IllegalArgumentException: No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.
        at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:489)
        at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:191)
        at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:321)
        at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243)
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:273)
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:98)
        at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:681)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:523)
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:369)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:313)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1185)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1174)
        at pl.mypackage.Main.main(Main.java:39)
Caused by: java.lang.IllegalArgumentException: No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.
        at org.springframework.util.Assert.notEmpty(Assert.java:276)
        at org.springframework.boot.autoconfigure.EnableAutoConfigurationImportSelector.getCandidateConfigurations(EnableAutoConfigurationImportSelector.java:145)
        at org.springframework.boot.autoconfigure.EnableAutoConfigurationImportSelector.selectImports(EnableAutoConfigurationImportSelector.java:84)
        at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:481)
        ... 14 more
</code>```

It looks like it doesn't found auto configuration classes in META-INF/spring.factories. How to add it, and what should be the content of this file?

答:
Alternatively, you can use this;  </p>

```<code>click -> run as maven clean
      -> run as maven install

and your jar in /yourProjectFolder/target/yourProjectName-0.0.1-SNAPSHOT.jar

java -jar yourProjectName-0.0.1-SNAPSHOT.jar
</code>```

Body:
Everything was working fine when starting my app using IntelliJ. But when I made a fat jar and executed it with

java -jar myapp.jar

I got this:

16:37:44.194 [main] ERROR org.springframework.boot.SpringApplication - Application startup failed
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [pl.mypackage.Main]; nested exception is java.lang.IllegalArgumentException: No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.
        at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:489)
        at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:191)
        at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:321)
        at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243)
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:273)
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:98)
        at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:681)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:523)
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:369)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:313)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1185)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1174)
        at pl.mypackage.Main.main(Main.java:39)
Caused by: java.lang.IllegalArgumentException: No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.
        at org.springframework.util.Assert.notEmpty(Assert.java:276)
        at org.springframework.boot.autoconfigure.EnableAutoConfigurationImportSelector.getCandidateConfigurations(EnableAutoConfigurationImportSelector.java:145)
        at org.springframework.boot.autoconfigure.EnableAutoConfigurationImportSelector.selectImports(EnableAutoConfigurationImportSelector.java:84)
        at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:481)
        ... 14 common frames omitted
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [pl.mypackage.Main]; nested exception is java.lang.IllegalArgumentException: No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.
        at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:489)
        at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:191)
        at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:321)
        at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243)
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:273)
        at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:98)
        at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:681)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:523)
        at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759)
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:369)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:313)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1185)
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1174)
        at pl.mypackage.Main.main(Main.java:39)
Caused by: java.lang.IllegalArgumentException: No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.
        at org.springframework.util.Assert.notEmpty(Assert.java:276)
        at org.springframework.boot.autoconfigure.EnableAutoConfigurationImportSelector.getCandidateConfigurations(EnableAutoConfigurationImportSelector.java:145)
        at org.springframework.boot.autoconfigure.EnableAutoConfigurationImportSelector.selectImports(EnableAutoConfigurationImportSelector.java:84)
        at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:481)
        ... 14 more

It looks like it doesn't found auto configuration classes in META-INF/spring.factories. How to add it, and what should be the content of this file?

Body:
Alternatively, you can use this;

click -> run as maven clean
      -> run as maven install

and your jar in /yourProjectFolder/target/yourProjectName-0.0.1-SNAPSHOT.jar

java -jar yourProjectName-0.0.1-SNAPSHOT.jar


答:
this snippet will do the job; the result will be an array of arrays you are looking for; it could be written in more complex way using reduce() but I prefer more readable version:

let result = [];
rows.forEach( row => {
  row.forEach( (item,index) => {
    if(result[index]){
      result[index].push(item)
    }else{
      result[index] = [item]
    }
  })
})
```

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let  rows = [
    [
      "stravi/aa",
      "202001",
      "59",
      "51",
      "2558.98",
      "0.5358894453719162",
      "1.9204668112983725",
      "140",
      "2.3466309084813943"
    ],
    [
      "stravi/ab",
      "202003",
      "3591",
      "349",
      "2246.09",
      "0.41838214",
      "3.57603358",
      "50",
      "4.82115474"
    ],
    [
      "stravi/ac",
      "202007",
      "3354",
      "25",
      "1975.76",
      "0.74220667708",
      "1.12321555541",
      "11",
      "0.9324532454"
    ]
  ];

let result = [];
rows.forEach( row => {
  row.forEach( (item,index) => {
    if(result[index]){
      result[index].push(item)
    }else{
      result[index] = [item]
    }
  })
})
console.log(result)</code>```

Title: Split nested arrays in typescript

Body:
From service I got below response:

 "rows": [
    [
      "stravi/aa",
      "202001",
      "59",
      "51",
      "2558.98",
      "0.5358894453719162",
      "1.9204668112983725",
      "140",
      "2.3466309084813943"
    ],
    [
      "stravi/ab",
      "202003",
      "3591",
      "349",
      "2246.09",
      "0.41838214",
      "3.57603358",
      "50",
      "4.82115474"
    ],
    [
      "stravi/ac",
      "202007",
      "3354",
      "25",
      "1975.76",
      "0.74220667708",
      "1.12321555541",
      "11",
      "0.9324532454"
    ]
  ]

I would like to split below nested arrays to 9 arrays - when in 1 array will be 1 row from each of array, in 2 array -> second row etc. =>

["stravi/aa", "stravi/ab", "stravi/ac"]
[202001", "202003","202006"]

etc.

I am trying to it by using splitted, map, filter... But still I got mess...

Body:
this snippet will do the job; the result will be an array of arrays you are looking for; it could be written in more complex way using reduce() but I prefer more readable version:

let result = [];
rows.forEach( row => {
  row.forEach( (item,index) => {
    if(result[index]){
      result[index].push(item)
    }else{
      result[index] = [item]
    }
  })
})

let  rows = [
    [
      "stravi/aa",
      "202001",
      "59",
      "51",
      "2558.98",
      "0.5358894453719162",
      "1.9204668112983725",
      "140",
      "2.3466309084813943"
    ],
    [
      "stravi/ab",
      "202003",
      "3591",
      "349",
      "2246.09",
      "0.41838214",
      "3.57603358",
      "50",
      "4.82115474"
    ],
    [
      "stravi/ac",
      "202007",
      "3354",
      "25",
      "1975.76",
      "0.74220667708",
      "1.12321555541",
      "11",
      "0.9324532454"
    ]
  ];

let result = [];
rows.forEach( row => {
  row.forEach( (item,index) => {
    if(result[index]){
      result[index].push(item)
    }else{
      result[index] = [item]
    }
  })
})
console.log(result)


问:
Form Validation not working for name input box
I am trying to get the input box border for my name to change to red while displaying a message under neath it when the value is "". I am doing all of this in JavaScript.  However, when I test it out, nothing happens. I checked the console and nothing is broken.  Was wondering if someone could help me out and see where my error is.

<form id="customer_form" onsubmit="return customerFormValidation(this)" action="">

Billing Address

         Full Name
        <input type="text" id="firstname" name="firstname" placeholder="John M. Doe">
         Email
        <input type="text" id="email" name="email" placeholder="john@example.com">
         Phone #
        <input type="text" id="phone" name="phone" placeholder="(123)-456-7890">
         Address
        <input type="text" id="address" name="address" placeholder="542 W. 15th Street">
         City
        <input type="text" id="city" name="city" placeholder="New York">

            State
            <input type="text" id="state" name="state" placeholder="NY">

            Zip
            <input type="text" id="zip" name="zip" placeholder="10001">

</form>
<button class="fa orange btn" type="submit" id="customerBtn">Next</button>

```

答:
The problem is that your submit button is outside your form, so it can't trigger the form's submit event.

If you put the button inside the form, it works.

<form id="customer_form" onsubmit="return customerFormValidation(this)" action="">

Billing Address

         Full Name
        <input type="text" id="firstname" name="firstname" placeholder="John M. Doe">
         Email
        <input type="text" id="email" name="email" placeholder="john@example.com">
         Phone #
        <input type="text" id="phone" name="phone" placeholder="(123)-456-7890">
         Address
        <input type="text" id="address" name="address" placeholder="542 W. 15th Street">
         City
        <input type="text" id="city" name="city" placeholder="New York">

            State
            <input type="text" id="state" name="state" placeholder="NY">

            Zip
            <input type="text" id="zip" name="zip" placeholder="10001">

    <button class="fa orange btn" type="submit" id="customerBtn">Next</button>
</form>

```

Regards.

Body:
The problem is that your submit button is outside your form, so it can't trigger the form's submit event.

If you put the button inside the form, it works.

<form id="customer_form" onsubmit="return customerFormValidation(this)" action="">
    <h1 style="text-align: center">Billing Address</h1>
    <div class="row">
        <label for="fname"><i class="fa fa-user"></i> Full Name</label>
        <input type="text" id="firstname" name="firstname" placeholder="John M. Doe">
        <label for="email"><i class="fa fa-envelope"></i> Email</label>
        <input type="text" id="email" name="email" placeholder="john@example.com">
        <label for="phone"><i class="fa fa-address-card-o"></i> Phone #</label>
        <input type="text" id="phone" name="phone" placeholder="(123)-456-7890">
        <label for="adr"><i class="fa fa-address-card-o"></i> Address</label>
        <input type="text" id="address" name="address" placeholder="542 W. 15th Street">
        <label for="city"><i class="fa fa-institution"></i> City</label>
        <input type="text" id="city" name="city" placeholder="New York">

        <div class="col-50">
            <label for="state">State</label>
            <input type="text" id="state" name="state" placeholder="NY">
        </div>
        <div class="col-50">
            <label for="zip">Zip</label>
            <input type="text" id="zip" name="zip" placeholder="10001">
        </div>

    </div>
    <button class="fa orange btn" type="submit" id="customerBtn">Next</button>
</form>

<script>
 function customerFormValidation() {
        reason = "";
        reason += validateName(customer_form.firstname);

        console.log(reason);
        if (reason.length > 0) {
            return false;
        } else {
            return false;
        }
    }

    function validateName(firstname) {
        var error = "";
        if (firstname.value == "") {
            document.getElementById("firstname").style.display = "block";
            document.getElementById("firstname").innerText = "Please enter your name";
            document.getElementById("firstname").style.borderColor = "red";
            document.getElementById("firstname").focus();
        } else {
            firstname.style.background = 'White';
            document.getElementById('firstname').innerHTML = "";
        }
        return error;
    }

</script>

Regards.


问:
Warnings as Errors versus Deprecated Attribute in Visual Studio
We like the Warnings as Errors setting as we have a policy of not checking in code with warnings and this is the only effective way we have found to enforce it.

We also like to use the Obsolete attribute to flag methods that should not be used any more.

Problem is that adding a Obsolete attribute to a method or class immediately causes tons of projects to not build (not to mention problems if a .NET API call is deprecated).

Does anyone have a good solution to this?

We want a visible, hard-to-ignore indicator that you are using a deprecated API but that does not cause the build to fail. We want to see the warnings in the IDE and in CI builds.

答: As explained here /sdl (Enable Additional Security Checks), if you switch off SDL the compiler will treat it as a warning.</p>


问:
Python3: Why is my else statement activating regardless of multiple if statements being true
```<code>tweet = ''
tweet = input('Enter a tweet (160 characters or less):\n')

if len(tweet) <= 160:
    if 'LOL' in tweet:
        print('Laugh out loud')
    if 'BFN' in tweet:
        print('Bye for now')
    if 'BRB' in tweet:
        print('Be right back')
    if 'IRL' in tweet:
        print('In real life')
    if 'FTW' in tweet:
        print('For the win')
    if 'LMFAO' in tweet:
        print('Laugh my F**king a** off')
    if 'LMAO' in tweet:
        print('Laugh my a** off')
    else:
        print('You didn\'t use any abbreviations')
elif len(tweet) == 0:
    print('Wow, such empty')
elif len(tweet) > 160:
    print('Your tweet is over 160 characters')
</code>```

So, for example if I run this program and input:
LOL BRB

The output is:
Laugh out loud
Be right back
You didn't use any abbreviations

Whereas the output I want for that input is:
Laugh out loud
Be right back

As far as I can tell the indentation is correct. Also we haven't gone over the 'break' or 'enumerate' functions, so we are not expected to use these to attain the desired result.

Thank you for the help!!

This is the code in working order after everyone's help:

```<code>tweet = ''
tweet = input('Enter a tweet (160 characters or less):\n')

tweet_abbrev = False

if len(tweet) <= 160:
    if 'LOL' in tweet:
        tweet_abbrev = True
        print('Laugh out loud')
    if 'BFN' in tweet:
        tweet_abbrev = True
        print('Bye for now')
    if 'BRB' in tweet:
        tweet_abbrev = True
        print('Be right back')
    if 'IRL' in tweet:
        tweet_abbrev = True
        print('In real life')
    if 'FTW' in tweet:
        tweet_abbrev = True
        print('For the win')
    if 'LMFAO' in tweet:
        tweet_abbrev = True
        print('Laugh my F**king a** off')
    if 'LMAO' in tweet:
        tweet_abbrev = True
        print('Laugh my a** off')
    if not tweet_abbrev:
        print('You didn\'t use any abbreviations')
if len(tweet) == 0:
    print('Wow, such empty')
elif len(tweet) > 160:
    print('Your tweet is over 160 characters')
</code>```

Thank you everyone for the quick responses!!!

答:
It's because your last if statement does a check and defaults to "You didn't use any abbreviations" if it isn't true.

You don't want all your statements to be elif because then it will only resolve to the first check that is true. You want to check them all individually and print the corresponding statement if it is true.

You're just missing one thing: the check that sees if your string doesn't use any abbreviations. Try this.

```<code>tweet = ''
tweet = input('Enter a tweet (160 characters or less):\n')

if len(tweet) <= 160:
    if 'LOL' in tweet:
        print('Laugh out loud')
    if 'BFN' in tweet:
        print('Bye for now')
    if 'BRB' in tweet:
        print('Be right back')
    if 'IRL' in tweet:
        print('In real life')
    if 'FTW' in tweet:
        print('For the win')
    if 'LMFAO' in tweet:
        print('Laugh my F**king a** off')
    if 'LMAO' in tweet:
        print('Laugh my a** off')
    if {Insert check to see if there are any abbreviations}:
        print('You didn\'t use any abbreviations')
elif len(tweet) == 0:
    print('Wow, such empty')
elif len(tweet) > 160:
    print('Your tweet is over 160 characters')
</code>```

And just replace {Insert check to see if there are any abbreviations} with a valid check. To try it out immediately, you can just do if '\'' in tweet:

Body:
tweet = ''
tweet = input('Enter a tweet (160 characters or less):\n')

if len(tweet) <= 160:
    if 'LOL' in tweet:
        print('Laugh out loud')
    if 'BFN' in tweet:
        print('Bye for now')
    if 'BRB' in tweet:
        print('Be right back')
    if 'IRL' in tweet:
        print('In real life')
    if 'FTW' in tweet:
        print('For the win')
    if 'LMFAO' in tweet:
        print('Laugh my F**king a** off')
    if 'LMAO' in tweet:
        print('Laugh my a** off')
    else:
        print('You didn\'t use any abbreviations')
elif len(tweet) == 0:
    print('Wow, such empty')
elif len(tweet) > 160:
    print('Your tweet is over 160 characters')

So, for example if I run this program and input:
LOL BRB

The output is:
Laugh out loud
Be right back
You didn't use any abbreviations

Whereas the output I want for that input is:
Laugh out loud
Be right back

As far as I can tell the indentation is correct. Also we haven't gone over the 'break' or 'enumerate' functions, so we are not expected to use these to attain the desired result.

Thank you for the help!!

This is the code in working order after everyone's help:

tweet = ''
tweet = input('Enter a tweet (160 characters or less):\n')

tweet_abbrev = False

if len(tweet) <= 160:
    if 'LOL' in tweet:
        tweet_abbrev = True
        print('Laugh out loud')
    if 'BFN' in tweet:
        tweet_abbrev = True
        print('Bye for now')
    if 'BRB' in tweet:
        tweet_abbrev = True
        print('Be right back')
    if 'IRL' in tweet:
        tweet_abbrev = True
        print('In real life')
    if 'FTW' in tweet:
        tweet_abbrev = True
        print('For the win')
    if 'LMFAO' in tweet:
        tweet_abbrev = True
        print('Laugh my F**king a** off')
    if 'LMAO' in tweet:
        tweet_abbrev = True
        print('Laugh my a** off')
    if not tweet_abbrev:
        print('You didn\'t use any abbreviations')
if len(tweet) == 0:
    print('Wow, such empty')
elif len(tweet) > 160:
    print('Your tweet is over 160 characters')

Thank you everyone for the quick responses!!!

Body:
It's because your last if statement does a check and defaults to "You didn't use any abbreviations" if it isn't true.

You don't want all your statements to be elif because then it will only resolve to the first check that is true. You want to check them all individually and print the corresponding statement if it is true.

You're just missing one thing: the check that sees if your string doesn't use any abbreviations. Try this.

tweet = ''
tweet = input('Enter a tweet (160 characters or less):\n')

if len(tweet) <= 160:
    if 'LOL' in tweet:
        print('Laugh out loud')
    if 'BFN' in tweet:
        print('Bye for now')
    if 'BRB' in tweet:
        print('Be right back')
    if 'IRL' in tweet:
        print('In real life')
    if 'FTW' in tweet:
        print('For the win')
    if 'LMFAO' in tweet:
        print('Laugh my F**king a** off')
    if 'LMAO' in tweet:
        print('Laugh my a** off')
    if {Insert check to see if there are any abbreviations}:
        print('You didn\'t use any abbreviations')
elif len(tweet) == 0:
    print('Wow, such empty')
elif len(tweet) > 160:
    print('Your tweet is over 160 characters')

And just replace {Insert check to see if there are any abbreviations} with a valid check. To try it out immediately, you can just do if '\'' in tweet:


问:
How to change the offset of an view using onTapGesture?
I am trying to move a view when it is being tapped. But unfortunately nothing happens. How do I toggle the position of it using the offset y axis?</p>

```<code>    struct Test: View {
    @State var cards : [Card] = [Card(), Card(), Card(), Card(), Card(), Card()]

    var body: some View {
        VStack {
            ZStack (alignment: .top){
                ForEach (0..<cards.count) { i in
                    RoundedRectangle(cornerRadius: 10).frame(width: 250, height: 150)
                        .foregroundColor(Color.random).offset(y: self.cards[i].isFocus ? CGFloat(500) : CGFloat(i*50))
                        .zIndex(Double(i))
                        .onTapGesture {
                            self.cards[i].isFocus.toggle() // now the touched Card should move to an offset of y: 500, but nothing happens
                        }
                }
            }
            Spacer()
        }

    }
}

struct Card :Identifiable{
    @State var isFocus :Bool = false
    var id  = UUID()

}

struct Test_Previews: PreviewProvider {
    static var previews: some View {
        Test()
    }
}

extension Color {
    static var random: Color {
        return Color(red: .random(in: 0...1),
                     green: .random(in: 0...1),
                     blue: .random(in: 0...1))
    }
}
</code>```

答:
I see your code and I am sorry to say but its wrong in many aspects. I would recommend you to go through SwiftUI basics and understand how and when we use @State, @ObservedObject, @Binding etc. Also always try to break your Views into the smallest components.
Below is the code which I think fulfills your requirement.</p>

```<code>struct Test: View {
    var cards : [Card] = [Card(), Card(), Card(), Card(), Card(), Card()]

    var body: some View {

        VStack {
            ZStack (alignment: .top){
                ForEach (0..<cards.count) { i in
                    CardView(card: self.cards[i], i: i)
                }
            }
            Spacer()
        }
    }
}

struct CardView: View {

    @ObservedObject var card: Card
    let i: Int

    var body: some View {

       RoundedRectangle(cornerRadius: 10).frame(width: 250, height: 150)
            .foregroundColor(Color.random)
            .offset(y: card.isFocus ? CGFloat(500) : CGFloat(i*10))
            .zIndex(Double(i))
            .onTapGesture {
                withAnimation {
                  self.card.isFocus.toggle()
                }
        }
    }
}

class Card: ObservableObject{
    @Published var isFocus: Bool = false
    var id  = UUID()

}
</code>```

Body:
I am trying to move a view when it is being tapped. But unfortunately nothing happens. How do I toggle the position of it using the offset y axis?

    struct Test: View {
    @State var cards : [Card] = [Card(), Card(), Card(), Card(), Card(), Card()]

    var body: some View {
        VStack {
            ZStack (alignment: .top){
                ForEach (0..<cards.count) { i in
                    RoundedRectangle(cornerRadius: 10).frame(width: 250, height: 150)
                        .foregroundColor(Color.random).offset(y: self.cards[i].isFocus ? CGFloat(500) : CGFloat(i*50))
                        .zIndex(Double(i))
                        .onTapGesture {
                            self.cards[i].isFocus.toggle() // now the touched Card should move to an offset of y: 500, but nothing happens
                        }
                }
            }
            Spacer()
        }

    }
}

struct Card :Identifiable{
    @State var isFocus :Bool = false
    var id  = UUID()

}

struct Test_Previews: PreviewProvider {
    static var previews: some View {
        Test()
    }
}

extension Color {
    static var random: Color {
        return Color(red: .random(in: 0...1),
                     green: .random(in: 0...1),
                     blue: .random(in: 0...1))
    }
}

Body:
I see your code and I am sorry to say but its wrong in many aspects. I would recommend you to go through SwiftUI basics and understand how and when we use @State, @ObservedObject, @Binding etc. Also always try to break your Views into the smallest components.
Below is the code which I think fulfills your requirement.

struct Test: View {
    var cards : [Card] = [Card(), Card(), Card(), Card(), Card(), Card()]

    var body: some View {

        VStack {
            ZStack (alignment: .top){
                ForEach (0..<cards.count) { i in
                    CardView(card: self.cards[i], i: i)
                }
            }
            Spacer()
        }
    }
}

struct CardView: View {

    @ObservedObject var card: Card
    let i: Int

    var body: some View {

       RoundedRectangle(cornerRadius: 10).frame(width: 250, height: 150)
            .foregroundColor(Color.random)
            .offset(y: card.isFocus ? CGFloat(500) : CGFloat(i*10))
            .zIndex(Double(i))
            .onTapGesture {
                withAnimation {
                  self.card.isFocus.toggle()
                }
        }
    }
}

class Card: ObservableObject{
    @Published var isFocus: Bool = false
    var id  = UUID()

}


问:
JavaScript createElement("h4") parses, creates text node, but doesn't create H4 element
I'm trying to have a for loop create H4 tags containing text, followed by some paragraph text, then repeat.

Here's what I've done:

```<code>var results = document.getElementById("results"); //refers to a <p> in html file
var stopper = 29;

for(i=0; i <= stopper; i++) {
    var elementDate = document.createElement("h4");
    elementDate.appendChild(document.createTextNode("Text gathered from an array"));
    results.appendChild(elementDate);
    results.innerText += "Paragraph text";
}
</code>```

I also tried elementDate.innerText = "..." but I'm getting the same problem:

Instead of creating an H4 and appending the text, it just appends the text straight to
. The H4 is never created and there are no errors in the log.

答:
When you do

```<code>results.innerText += "Paragraph text";
</code>```

What this does is:

Extracts the current innerText of the element, resulting in a plain string (no HTML tags)

Concatenates "Paragraph text" onto the end of that string

Sets that new string to be the new innerText of the element (no HTML tags)

So, the
 gets lost. (innerText should not be used in almost all situations anyway)

Use insertAdjacentText instead:

var results = document.getElementById("results"); //refers to a
 in html file
var stopper = 29;

for(i=0; i <= stopper; i++) {
    var elementDate = document.createElement("h4");
    elementDate.appendChild(document.createTextNode("Some text which would be gathered from an array"));
    results.appendChild(elementDate);
    results.insertAdjacentText('beforeend', "Paragraph text");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="results"></p></code>```

(You might be tempted to do .innerHTML +=, but that would allow for arbitrary code execution, in addition to corrupting existing nodes in the container, which would be inelegant and would effectively deattach any event listeners attached to them)

Body:
I'm trying to have a for loop create H4 tags containing text, followed by some paragraph text, then repeat.

Here's what I've done:

var results = document.getElementById("results"); //refers to a
 in html file
var stopper = 29;

for(i=0; i <= stopper; i++) {
    var elementDate = document.createElement("h4");
    elementDate.appendChild(document.createTextNode("Text gathered from an array"));
    results.appendChild(elementDate);
    results.innerText += "Paragraph text";
}

I also tried elementDate.innerText = "..." but I'm getting the same problem:

Instead of creating an H4 and appending the text, it just appends the text straight to
. The H4 is never created and there are no errors in the log.

Body:
When you do

results.innerText += "Paragraph text";

What this does is:

Extracts the current innerText of the element, resulting in a plain string (no HTML tags)

Concatenates "Paragraph text" onto the end of that string

Sets that new string to be the new innerText of the element (no HTML tags)

So, the <h4> gets lost. (innerText should not be used in almost all situations anyway)

Use insertAdjacentText instead:

var results = document.getElementById("results"); //refers to a <p> in html file
var stopper = 29;

for(i=0; i <= stopper; i++) {
    var elementDate = document.createElement("h4");
    elementDate.appendChild(document.createTextNode("Some text which would be gathered from an array"));
    results.appendChild(elementDate);
    results.insertAdjacentText('beforeend', "Paragraph text");
}

<p id="results"></p>

(You might be tempted to do .innerHTML +=, but that would allow for arbitrary code execution, in addition to corrupting existing nodes in the container, which would be inelegant and would effectively deattach any event listeners attached to them)


问:
Get data from nested arrays two layers deep based on sub-index
I have this json schema

"header": {
        "self": {},
        "items": [
            {
                "_id": "5ec7e61979ec9914ecefc539",
                "title": "Test",
                "root": "true",
                "alignment": "left",
                "page": "test",
                "translate": "",
                "toggle": "",
                "icon": "",
                "IsActive": 1,
                "submenu": [
                    {
                        "_id": "5ece913a353a71309084768d",
                        "title": "Sub Test",
                        "bullet": "dot",
                        "page": "test",
                        "translate": "MENU.TEST1",
                        "icon": "flaticon-stes-3",
                        "IsActive": 1
                    },
                    {
                        "_id": "5ece935d79972f0390997179",
                        "title": "Sub Test",
                        "bullet": "dot",
                        "page": "test",
                        "translate": "MENU.TEST2",
                        "icon": "flaticon-stes-3",
                        "IsActive": 1
                    }
                ]
            }
        ]
    }```
</div>
</div>
</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>// Index based on a previous query
this.db.collection('AssetData').find({"header.items.$.submenu.[0]._id":ObjectID("5ece913a353a71309084768d"));

//Tried with elemMatch
this.db.collection('AssetData').find(
                                {
                                "header.items": {
                                    $elemMatch:{
                                        "submenu": {
                                            $elemMatch:{
                                            "_id":ObjectID("5ece913a353a71309084768d")
                                            }
                                        }
                                    }
                                }
                               });</code>```

And I am wanting to retrieve one of the sub-menu object data based on the _id from the sub-menu, but I'm having trouble retrieving it.

I'm not sure If I could use an index of the second array from another query to obtain the data, or if there's another way that I'm missing like elem match.

I am using MongoDB 3.5.6.

What would be the best way to retrieve this?

答:
```<code>// Index based on a previous query
this.db.collection('AssetData').find({"header.items.$.submenu.[0]._id":ObjectID("5ece913a353a71309084768d")});

//Tried with elemMatch
this.db.collection('AssetData').find(
                                {
                                "header.items": {
                                    $elemMatch:{
                                        "submenu": {
                                            $elemMatch:{
                                            "_id":ObjectID("5ece913a353a71309084768d")
                                            }
                                        }
                                    }
                                }
                               }).exec(function(err, item) {
console.log(item);
// here you can retrieve the stock from item, as you wish
                               });
</code>```

hopefully it will help you

Body:
I have this json schema

"header": {
        "self": {},
        "items": [
            {
                "_id": "5ec7e61979ec9914ecefc539",
                "title": "Test",
                "root": "true",
                "alignment": "left",
                "page": "test",
                "translate": "",
                "toggle": "",
                "icon": "",
                "IsActive": 1,
                "submenu": [
                    {
                        "_id": "5ece913a353a71309084768d",
                        "title": "Sub Test",
                        "bullet": "dot",
                        "page": "test",
                        "translate": "MENU.TEST1",
                        "icon": "flaticon-stes-3",
                        "IsActive": 1
                    },
                    {
                        "_id": "5ece935d79972f0390997179",
                        "title": "Sub Test",
                        "bullet": "dot",
                        "page": "test",
                        "translate": "MENU.TEST2",
                        "icon": "flaticon-stes-3",
                        "IsActive": 1
                    }
                ]
            }
        ]
    }

// Index based on a previous query
this.db.collection('AssetData').find({"header.items.$.submenu.[0]._id":ObjectID("5ece913a353a71309084768d"));

//Tried with elemMatch
this.db.collection('AssetData').find(
                                {
                                "header.items": {
                                    $elemMatch:{
                                        "submenu": {
                                            $elemMatch:{
                                            "_id":ObjectID("5ece913a353a71309084768d")
                                            }
                                        }
                                    }
                                }
                               });

And I am wanting to retrieve one of the sub-menu object data based on the _id from the sub-menu, but I'm having trouble retrieving it.

I'm not sure If I could use an index of the second array from another query to obtain the data, or if there's another way that I'm missing like elem match.

I am using MongoDB 3.5.6.

What would be the best way to retrieve this?

Body:
// Index based on a previous query
this.db.collection('AssetData').find({"header.items.$.submenu.[0]._id":ObjectID("5ece913a353a71309084768d")});

//Tried with elemMatch
this.db.collection('AssetData').find(
                                {
                                "header.items": {
                                    $elemMatch:{
                                        "submenu": {
                                            $elemMatch:{
                                            "_id":ObjectID("5ece913a353a71309084768d")
                                            }
                                        }
                                    }
                                }
                               }).exec(function(err, item) {
console.log(item);
// here you can retrieve the stock from item, as you wish
                               });

hopefully it will help you


问:
Getting null argument when implementing N-tiers architecture with Autofac
I created this simple WebAPI project containing the following library class

Coordination (ServiceLayer)

Domain (BusinessLayer)

Data (DataLayer)

Dtos (Dtos for webapi)

Basically WebAPI project calls(reference) Dtos, and Coordination. Coordination Calls Domain and Domain call Data.

This is what my structure look like.

My issues is implementing Dependency Injection using Autofac. I can call the Coordination layer, when i try to call the domain layer this is where it get confused.

This is how I defined my registertype

```<code>public class AutofacWebapiConfig
    {

        public static IContainer Container;

        public static void Initialize(HttpConfiguration config)
        {
            Initialize(config, RegisterServices(new ContainerBuilder()));
        }

        public static void Initialize(HttpConfiguration config, IContainer container)
        {
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }

        private static IContainer RegisterServices(ContainerBuilder builder)
        {
            //Register your Web API controllers.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            builder.RegisterAssemblyTypes(Assembly.Load(nameof(Coordination)))
              .Where(t => t.Namespace.Contains("Services"))
              .As(t => t.GetInterfaces().FirstOrDefault(i => i.Name == "I" + t.Name));

            builder.RegisterAssemblyTypes(Assembly.Load(nameof(Domain)))
              .Where(j => j.Namespace.Contains("Domain"))
              .As(j => j.GetInterfaces().FirstOrDefault(i => i.Name == "I" + j.Name));

            //Set the dependency resolver to be Autofac.
            Container = builder.Build();

            return Container;
        }

    }
</code>```

A few issues occurs. First it doesn't know how to find Domain, because in theory WebAPI does not talk to the Domain layer.

I did add it as a reference but now i get a null argument error. ServiceType cannot be null.

Nothing that jumps out of me from the service implementation

```<code> public class StudentService : IStudentService
    {
        private readonly IStudentDomain studentDomain;
        public StudentService(IStudentDomain _studentDomain)
        {
            this.studentDomain = _studentDomain;
        }

        public async Task<StudentDto> GetStudentByID(string id)
        {
            var test = this.studentDomain.getStudentByID(id);
        }
}
</code>```

And here is my domain implementation

```<code>    public class StudentDomain : IStudentDomain
    {

        public StudentDomain()
        {

        }

        /// <summary>
        /// Return student
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        StudentEntity IStudentDomain.getStudentByID(string id)
        {
            StudentEntity student = new StudentEntity("dd", "aa", "ddd");
            return student;
        }
    }
</code>```

This is the error I keep getting

I am sorry my os is french, but its just mean the value is null.
Full stack error

```<code>System.ArgumentNullException
  HResult=0x80004003
  Message=La valeur ne peut pas être null.
Nom du paramètre : serviceType
  Source=Autofac
  StackTrace:
   at Autofac.Core.TypedService..ctor(Type serviceType)
   at Autofac.RegistrationExtensions.<>c__DisplayClass14_0`3.<As>b__0(Type t)
   at Autofac.RegistrationExtensions.<>c__DisplayClass13_0`3.<As>b__0(Type t)
   at Autofac.Features.Scanning.ScanningRegistrationExtensions.<>c__DisplayClass8_0`3.<As>b__0(Type t, IRegistrationBuilder`3 rb)
   at Autofac.Features.Scanning.ScanningRegistrationExtensions.ScanTypes(IEnumerable`1 types, IComponentRegistryBuilder cr, IRegistrationBuilder`3 rb)
   at Autofac.Features.Scanning.ScanningRegistrationExtensions.ScanAssemblies(IEnumerable`1 assemblies, IComponentRegistryBuilder cr, IRegistrationBuilder`3 rb)
   at Autofac.Features.Scanning.ScanningRegistrationExtensions.<>c__DisplayClass0_0.<RegisterAssemblyTypes>b__0(IComponentRegistryBuilder cr)
   at Autofac.ContainerBuilder.Build(IComponentRegistryBuilder componentRegistry, Boolean excludeDefaultModules)
   at Autofac.ContainerBuilder.Build(ContainerBuildOptions options)
   at CB.WebAPI.App_Start.AutofacWebapiConfig.RegisterServices(ContainerBuilder builder) in C:\source\repos\CB.WebAPI\CB.WebAPI\App_Start\AutofacWebapiConfig.cs:line 43
   at CB.WebAPI.App_Start.AutofacWebapiConfig.Initialize(HttpConfiguration config) in C:\source\repos\CB.WebAPI\CB.WebAPI\App_Start\AutofacWebapiConfig.cs:line 21
   at CB.WebAPI.App_Start.Bootstrapper.Run() in C:\source\repos\CB.WebAPI\CB.WebAPI\App_Start\Bootstrapper.cs:line 14
   at CB.WebAPI.WebApiApplication.Application_Start() in C:\source\repos\CB.WebAPI\CB.WebAPI\Global.asax.cs:line 18
</code>```

Here I am adding the global.asax.cs file. Line 18 is my bootstrapper.run();

```<code>    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            Bootstrapper.Run();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
</code>```

答:
It seems that there is an issue with registering Domain because StudentEntity does not have corresponding interface and .As(j => j.GetInterfaces().FirstOrDefault(i => i.Name == "I" + j.Name)) will fail to find one for it.

If you don't want to manually add all types with interfaces try this:

```<code>builder.RegisterAssemblyTypes(typeof(StudentDomain).Assembly)
          .Where(j => j.Namespace.Contains("Domain"))
          .AsImplementedInterfaces()
</code>```

Possibly you will want/need to distinguish between types with interfaces and without them, you can try next approach:

```<code>builder.RegisterAssemblyTypes(typeof(StudentDomain).Assembly)
          .Where(j => j.Namespace.Contains("Domain") && j.GetInterfaces().Any())
          .AsImplementedInterfaces()

builder.RegisterAssemblyTypes(typeof(StudentDomain).Assembly)
          .Where(j => j.Namespace.Contains("Domain") && !j.GetInterfaces().Any())
          .AsSelf();
</code>```

P.S.

Also I would recommend to change all Assembly.Load(nameof(SOME_NAME)) to typeof(TYPE_NAME).Assembly, I think it is more readable and obvious.

Body:
I created this simple WebAPI project containing the following library class

Coordination (ServiceLayer)

Domain (BusinessLayer)

Data (DataLayer)

Dtos (Dtos for webapi)

Basically WebAPI project calls(reference) Dtos, and Coordination. Coordination Calls Domain and Domain call Data.

This is what my structure look like.

My issues is implementing Dependency Injection using Autofac. I can call the Coordination layer, when i try to call the domain layer this is where it get confused.

This is how I defined my registertype

public class AutofacWebapiConfig
    {

        public static IContainer Container;

        public static void Initialize(HttpConfiguration config)
        {
            Initialize(config, RegisterServices(new ContainerBuilder()));
        }

        public static void Initialize(HttpConfiguration config, IContainer container)
        {
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }

        private static IContainer RegisterServices(ContainerBuilder builder)
        {
            //Register your Web API controllers.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            builder.RegisterAssemblyTypes(Assembly.Load(nameof(Coordination)))
              .Where(t => t.Namespace.Contains("Services"))
              .As(t => t.GetInterfaces().FirstOrDefault(i => i.Name == "I" + t.Name));

            builder.RegisterAssemblyTypes(Assembly.Load(nameof(Domain)))
              .Where(j => j.Namespace.Contains("Domain"))
              .As(j => j.GetInterfaces().FirstOrDefault(i => i.Name == "I" + j.Name));

            //Set the dependency resolver to be Autofac.
            Container = builder.Build();

            return Container;
        }

    }

A few issues occurs. First it doesn't know how to find Domain, because in theory WebAPI does not talk to the Domain layer.

I did add it as a reference but now i get a null argument error. ServiceType cannot be null.

Nothing that jumps out of me from the service implementation

 public class StudentService : IStudentService
    {
        private readonly IStudentDomain studentDomain;
        public StudentService(IStudentDomain _studentDomain)
        {
            this.studentDomain = _studentDomain;
        }

        public async Task<StudentDto> GetStudentByID(string id)
        {
            var test = this.studentDomain.getStudentByID(id);
        }
}

And here is my domain implementation

    public class StudentDomain : IStudentDomain
    {

        public StudentDomain()
        {

        }

        ///
        /// Return student
        ///
        /// <param name="id"></param>
        /// <returns></returns>
        StudentEntity IStudentDomain.getStudentByID(string id)
        {
            StudentEntity student = new StudentEntity("dd", "aa", "ddd");
            return student;
        }
    }

This is the error I keep getting

I am sorry my os is french, but its just mean the value is null.
Full stack error

System.ArgumentNullException
  HResult=0x80004003
  Message=La valeur ne peut pas être null.
Nom du paramètre : serviceType
  Source=Autofac
  StackTrace:
   at Autofac.Core.TypedService..ctor(Type serviceType)
   at Autofac.RegistrationExtensions.<>c__DisplayClass14_0`3.<As>b__0(Type t)
   at Autofac.RegistrationExtensions.<>c__DisplayClass13_0`3.<As>b__0(Type t)
   at Autofac.Features.Scanning.ScanningRegistrationExtensions.<>c__DisplayClass8_0`3.<As>b__0(Type t, IRegistrationBuilder`3 rb)
   at Autofac.Features.Scanning.ScanningRegistrationExtensions.ScanTypes(IEnumerable`1 types, IComponentRegistryBuilder cr, IRegistrationBuilder`3 rb)
   at Autofac.Features.Scanning.ScanningRegistrationExtensions.ScanAssemblies(IEnumerable`1 assemblies, IComponentRegistryBuilder cr, IRegistrationBuilder`3 rb)
   at Autofac.Features.Scanning.ScanningRegistrationExtensions.<>c__DisplayClass0_0.<RegisterAssemblyTypes>b__0(IComponentRegistryBuilder cr)
   at Autofac.ContainerBuilder.Build(IComponentRegistryBuilder componentRegistry, Boolean excludeDefaultModules)
   at Autofac.ContainerBuilder.Build(ContainerBuildOptions options)
   at CB.WebAPI.App_Start.AutofacWebapiConfig.RegisterServices(ContainerBuilder builder) in C:\source\repos\CB.WebAPI\CB.WebAPI\App_Start\AutofacWebapiConfig.cs:line 43
   at CB.WebAPI.App_Start.AutofacWebapiConfig.Initialize(HttpConfiguration config) in C:\source\repos\CB.WebAPI\CB.WebAPI\App_Start\AutofacWebapiConfig.cs:line 21
   at CB.WebAPI.App_Start.Bootstrapper.Run() in C:\source\repos\CB.WebAPI\CB.WebAPI\App_Start\Bootstrapper.cs:line 14
   at CB.WebAPI.WebApiApplication.Application_Start() in C:\source\repos\CB.WebAPI\CB.WebAPI\Global.asax.cs:line 18

Here I am adding the global.asax.cs file. Line 18 is my bootstrapper.run();

    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            Bootstrapper.Run();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }

Body:
It seems that there is an issue with registering Domain because StudentEntity does not have corresponding interface and .As(j => j.GetInterfaces().FirstOrDefault(i => i.Name == "I" + j.Name)) will fail to find one for it.

If you don't want to manually add all types with interfaces try this:

builder.RegisterAssemblyTypes(typeof(StudentDomain).Assembly)
          .Where(j => j.Namespace.Contains("Domain"))
          .AsImplementedInterfaces()

Possibly you will want/need to distinguish between types with interfaces and without them, you can try next approach:

builder.RegisterAssemblyTypes(typeof(StudentDomain).Assembly)
          .Where(j => j.Namespace.Contains("Domain") && j.GetInterfaces().Any())
          .AsImplementedInterfaces()

builder.RegisterAssemblyTypes(typeof(StudentDomain).Assembly)
          .Where(j => j.Namespace.Contains("Domain") && !j.GetInterfaces().Any())
          .AsSelf();

P.S.

Also I would recommend to change all Assembly.Load(nameof(SOME_NAME)) to typeof(TYPE_NAME).Assembly, I think it is more readable and obvious.


问:
how do I pip install on the command prompt? "fatal error in launcher"
C:\Users\Utente>pip install
Fatal error in launcher: Unable to create process using '"c:\users\utente\appdata\local\programs\python\python38\python.exe"  "C:\Users\Utente\Python\Python38-32\Scripts\pip.exe" install'

Why do I get a Fatal error in launcher while installing pip on command prompt?

Kindly help me  with this error "c:\users\utente\appdata\local\programs\python\python38\python.exe"

答: You need to install python and pip comes with it (in the bin folder). The pip install expects the name of the python library after that. For example pip install pandas. This is why you are getting the error.


问:
Python: How to Create chucks of data contain X byte for each time
I am trying to write a simple function that take a data in hex format. However, the idea is I want to use for loop with round() so that each time the loop will print only 2KB (2048) of data (only 2048 byte for each time),

This is what I did, but did not work.

```<code>data = "4d5a90000300000004000000fff........"

def function_x(x):
    for i in range(0,int(round(len(data)/2048))):
        data_chunk = data[i*2047:(i+1)*2047]
        ....
        ....
        ....
        ....
</code>```

UPDATE: To make my question clear for you, I will provide some details. I am using Postgresql, Large objects specifically, However, to update this object or insert any new data on it, you must keep this note in you mind, which is mentioned in their documentation

The amount of data per page is defined to be LOBLKSIZE (which is currently BLCKSZ/4, or typically 2 kB "2048").

so I wrote this simple code to fit with their requirements, just do not know what is the the right numbers must be written instead of (?) marks that i put

for i in range(0,int(round(len(data)/??))):  > to divide the code into x number of pages, each page must contain 2048 byte only > data[i*??:(i+1)*??]

NOTE: if i == 0 because the first page must be updated not inserted according to their docs

here is the full code

```<code>data = "4d5a90000300000004000000fff........"
loid = 14697

def function_x(x):
        for i in range(0,int(round(len(data)/??))):
    data_chunk = data[i*??:(i+1)*??]
    if i == 0:
        sql = "UPDATE PG_LARGEOBJECT SET data=decode('%s', 'hex') where loid=%d and pageno=%d" % (data_chunk, loid, i)
    else:
        sql = "INSERT PG_LARGEOBJECT SET data=decode('%s', 'hex') where loid=%d and pageno=%d" % (data_chunk, loid, i)
        ....
        ....
        ....
        ....
</code>```

答:
A list comprehension would fit. The code below will create a list with all of the chunks and then print them one by one.

```<code>chunks = [data[i:i+2048] for i in range(0, len(data), 2048)]
print(*chunks, sep='\n')
</code>```

You could also turn this into a single line (se below), but I prefer the method above, since it's easier to understand what is happening.

```<code>print(*[data[i:i+2048] for i in range(0, len(data), 2048)], sep='\n')
</code>```

UPDATE:
If you want to check things about the list items, you could simply do this:

```<code>for i, chunk in enumerate([data[i:i+2048] for i in range(0, len(data), 2048)]):
  if i == 0:
    ...
  else:
    ...
</code>```

I hope I understood the update question and that this will help.

Body:
I am trying to write a simple function that take a data in hex format. However, the idea is I want to use for loop with round() so that each time the loop will print only 2KB (2048) of data (only 2048 byte for each time),

This is what I did, but did not work.

data = "4d5a90000300000004000000fff........"

def function_x(x):
    for i in range(0,int(round(len(data)/2048))):
        data_chunk = data[i*2047:(i+1)*2047]
        ....
        ....
        ....
        ....

UPDATE: To make my question clear for you, I will provide some details. I am using Postgresql, Large objects specifically, However, to update this object or insert any new data on it, you must keep this note in you mind, which is mentioned in their documentation

The amount of data per page is defined to be LOBLKSIZE (which is currently BLCKSZ/4, or typically 2 kB "2048").

so I wrote this simple code to fit with their requirements, just do not know what is the the right numbers must be written instead of (?) marks that i put

for i in range(0,int(round(len(data)/??))):  > to divide the code into x number of pages, each page must contain 2048 byte only > data[i*??:(i+1)*??]

NOTE: if i == 0 because the first page must be updated not inserted according to their docs

here is the full code

data = "4d5a90000300000004000000fff........"
loid = 14697

def function_x(x):
        for i in range(0,int(round(len(data)/??))):
    data_chunk = data[i*??:(i+1)*??]
    if i == 0:
        sql = "UPDATE PG_LARGEOBJECT SET data=decode('%s', 'hex') where loid=%d and pageno=%d" % (data_chunk, loid, i)
    else:
        sql = "INSERT PG_LARGEOBJECT SET data=decode('%s', 'hex') where loid=%d and pageno=%d" % (data_chunk, loid, i)
        ....
        ....
        ....
        ....

Body:
A list comprehension would fit. The code below will create a list with all of the chunks and then print them one by one.

chunks = [data[i:i+2048] for i in range(0, len(data), 2048)]
print(*chunks, sep='\n')

You could also turn this into a single line (se below), but I prefer the method above, since it's easier to understand what is happening.

print(*[data[i:i+2048] for i in range(0, len(data), 2048)], sep='\n')

UPDATE:
If you want to check things about the list items, you could simply do this:

for i, chunk in enumerate([data[i:i+2048] for i in range(0, len(data), 2048)]):
  if i == 0:
    ...
  else:
    ...

I hope I understood the update question and that this will help.


问:
EJB entity beans JAR & RESTeasy
I am having trouble getting my entity beans to connect correctly to MySQL. Here's my set up:

JBOSS: 6

UBUNTU: 11.04

EJB: 3.1

I am currently trying to access entity beans via a JNDI remote call to a JARed session bean in the root of my EAR file.

My Entity beans map correctly to my database and work in one EAR file however I want to use the same entity beans in another EAR file in the same container so I have JARed my entity beans and I pull them into my second EAR file using my build script. I am pulling the exact same persistance.xml file as my first EAR file and it points to the same data source XML in the root of my deploy directory. I can define my persistence context and access my entity beans without error and I can compile and deploy my JBoss server without any exceptions. However I get this error when I try to access the entity beans after the container has deployed:

```<code>java.lang.IllegalArgumentException: org.hibernate.hql.ast.QuerySyntaxException: User is not mapped [SELECT u FROM User u WHERE u.accountId=:accountId]
</code>```

This is the query I am using:

```<code>List<User> users = entityManager.createQuery("SELECT u FROM User u WHERE u.accountId=:accountId")
        .setParameter("accountId", accountId)
        .getResultList();
</code>```

Can anyone tell me if:

there is an issue with JARing entity beans

does RESTeasy need some special config to deal with entity beans

is it even possible to use JARed entity beans

could there be a config conflict if I am accessing the same datasource using two separate instances of the same entity beans in the same container

Thanks in advance for any help with this. I am really stuck.

ADDED (20/05/2011):

So I have now consolidated my entity and session beans into one jar and have altered the persistence.xml so include the auto detect property suggested by Nayan below:

```<code><property name="hibernate.archive.autodetection" value="class"/>
</code>```

but to no avail. I have the JAR registered in my application.xml and have added the JAR to the classpath in my build script.

Would it make any sense to put the JAR file into the root of the deploy directory and try to access it from there?

答: The issue was with the location of my persistence.xml file. I have the persistence.xml file in a JAR with my sessions beans not with my entity beans where it was needed. Problem solved!</p>

Title: EJB entity beans JAR & RESTeasy

Body:
I am having trouble getting my entity beans to connect correctly to MySQL. Here's my set up:

JBOSS: 6

UBUNTU: 11.04

EJB: 3.1

I am currently trying to access entity beans via a JNDI remote call to a JARed session bean in the root of my EAR file.

My Entity beans map correctly to my database and work in one EAR file however I want to use the same entity beans in another EAR file in the same container so I have JARed my entity beans and I pull them into my second EAR file using my build script. I am pulling the exact same persistance.xml file as my first EAR file and it points to the same data source XML in the root of my deploy directory. I can define my persistence context and access my entity beans without error and I can compile and deploy my JBoss server without any exceptions. However I get this error when I try to access the entity beans after the container has deployed:

java.lang.IllegalArgumentException: org.hibernate.hql.ast.QuerySyntaxException: User is not mapped [SELECT u FROM User u WHERE u.accountId=:accountId]

This is the query I am using:

List<User> users = entityManager.createQuery("SELECT u FROM User u WHERE u.accountId=:accountId")
        .setParameter("accountId", accountId)
        .getResultList();

Can anyone tell me if:

there is an issue with JARing entity beans

does RESTeasy need some special config to deal with entity beans

is it even possible to use JARed entity beans

could there be a config conflict if I am accessing the same datasource using two separate instances of the same entity beans in the same container

Thanks in advance for any help with this. I am really stuck.

ADDED (20/05/2011):

So I have now consolidated my entity and session beans into one jar and have altered the persistence.xml so include the auto detect property suggested by Nayan below:

<property name="hibernate.archive.autodetection" value="class"/>

but to no avail. I have the JAR registered in my application.xml and have added the JAR to the classpath in my build script.

Would it make any sense to put the JAR file into the root of the deploy directory and try to access it from there?


问:
Creating a dateRange Scala, Joda, Java
I have spent hours trying to make this next piece of code work.

import org.joda.time.{DateTime, Period}

def dateRange(from: DateTime, to: DateTime, step: Period): Iterator[DateTime]      =Iterator.iterate(from)(_.plus(step)).takeWhile(!_.isAfter(to))

val range = {
dateRange(new DateTime(2012, 06, 30).minusYears(5), new DateTime(2000, 06, 30),new Period.months(6))
}
```

<p>I'm trying to set up a date range array that steps through from 2000 to 2012 in 6 month increments. The problem that I am facing is the following error.</p>

```Exception in thread "main" java.lang.IllegalArgumentException: No instant converter found for type: scala.Tuple3
at    org.joda.time.convert.ConverterManager.getInstantConverter(ConverterManager.java:165)
at org.joda.time.base.BaseDateTime.<init>(BaseDateTime.java:169)
at org.joda.time.DateTime.<init>(DateTime.java:241)
at tester.MomentumAlgo$class.$init$(MomentumAlgo.scala:154)
at tester.RunMomentumAlgo$$anon$1.<init>(RunMomentumAlgo.scala:86)
at tester.RunMomentumAlgo$.main(RunMomentumAlgo.scala:86)
at tester.RunMomentumAlgo.main(RunMomentumAlgo.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
```

I seems to be something to do with the last Period.months() part, however I have no idea how to fix it. The Tuple3 error I have no idea about.

If someone can give me a different solution, that would also be great. I want a list of dates from 2000 to 2012, every 6 months.

Any questions welcome. I thought this would be a common piece of code, but there isn't much on the net about it.

Thanks in advance.

答:
I came up with this simple solution:

def generateDateRange(from: LocalDate, to: LocalDate): List[Date] = {
    if(from.compareTo(to) > 0) Nil
    from :: generateDateRange(from.plusDays(1), to)
}
```

We recursively build a list of dates by prepending the start of the range to the new range which starts a day later.

Title: Creating a dateRange Scala, Joda, Java

Body:
I have spent hours trying to make this next piece of code work.

import org.joda.time.{DateTime, Period}

def dateRange(from: DateTime, to: DateTime, step: Period): Iterator[DateTime]      =Iterator.iterate(from)(_.plus(step)).takeWhile(!_.isAfter(to))

val range = {
dateRange(new DateTime(2012, 06, 30).minusYears(5), new DateTime(2000, 06, 30),new Period.months(6))
}

I'm trying to set up a date range array that steps through from 2000 to 2012 in 6 month increments. The problem that I am facing is the following error.

Exception in thread "main" java.lang.IllegalArgumentException: No instant converter found for type: scala.Tuple3
at    org.joda.time.convert.ConverterManager.getInstantConverter(ConverterManager.java:165)
at org.joda.time.base.BaseDateTime.<init>(BaseDateTime.java:169)
at org.joda.time.DateTime.<init>(DateTime.java:241)
at tester.MomentumAlgo$class.$init$(MomentumAlgo.scala:154)
at tester.RunMomentumAlgo$$anon$1.<init>(RunMomentumAlgo.scala:86)
at tester.RunMomentumAlgo$.main(RunMomentumAlgo.scala:86)
at tester.RunMomentumAlgo.main(RunMomentumAlgo.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

I seems to be something to do with the last Period.months() part, however I have no idea how to fix it. The Tuple3 error I have no idea about.

If someone can give me a different solution, that would also be great. I want a list of dates from 2000 to 2012, every 6 months.

Any questions welcome. I thought this would be a common piece of code, but there isn't much on the net about it.

Thanks in advance.

Body:
I came up with this simple solution:

def generateDateRange(from: LocalDate, to: LocalDate): List[Date] = {
    if(from.compareTo(to) > 0) Nil
    from :: generateDateRange(from.plusDays(1), to)
}

We recursively build a list of dates by prepending the start of the range to the new range which starts a day later.


问:
std::stoi only converts first few characters
I am using stoi in one of my functions with the intent of converting a string of numbers into an integer. I was about halfway through a homework problem but then I ran into this. Oddly, if the number has an even number of characters, stoi only converts the first half. Any help would be greatly appreciated!

Code:

```<code>#include <fstream>
#include <vector>
#include <string>
using namespace std;
string start;
string endD;
int sDigit;
int eDigit;
int i;
vector<int> palindromes;

void construct(int layer, int digits, string prev)
{
    string temp = prev;
    if(layer > (digits % 2) + digits/2)
    {
        short a = (short) digits/2;
        for(int i = a; i >= 0; i--)
        {
            if(i == a && digits % 2 == 1)
            {
                continue;
            }
            else
            {
                temp.push_back(temp[i]);
            }
        }
        cout << temp << " " << stoi(temp) << endl; // Output is here
        palindromes.push_back(stoi(temp));
    }
    else if(layer == 1 && digits == sDigit)
    {
        for(int i = start[0] - '0'; i < 10; i++)
        {
            temp[0] = i + '0';
            construct(layer + 1, digits, temp);
        }
    }
    else if(layer == 1 && digits == eDigit)
    {
        for(int i = '1'; i <= endD[0]; i++)
        {
            temp[0] = i;
            construct(layer + 1, digits, temp);
            temp = prev;
        }
    }
    else if(layer == 1)
    {
        for(int i = 1; i < 10; i++)
        {
            temp[0] = '0' + i;
            construct(layer + 1, digits, temp);
            temp = prev;
        }
    }
    else
    {
        for(int i = 0; i < 10; i++)
        {
            temp.push_back(i + '0');
            construct(layer + 1, digits, temp);
            temp = prev;
        }
    }
}

int main()
{
    int startD, endDD;
    cin >> startD >> endDD;
    start = to_string(startD);
    endD = to_string(endDD);
    int tempS = startD;
    int tempE = endDD;
    while(tempS != 0)
    {
        tempS /= 10;
        sDigit++;
    }
    while(tempE != 0)
    {
        tempE /= 10;
        eDigit++;
    }
    for(int i = sDigit; i <= eDigit; i++)
    {
        construct(1, i, "x");
    }
    for(int i = 0; i < palindromes.size(); i++)
    {
        //cout << palindromes[i] << endl;
    }
}```

Input: 1 1000
Output:

```

答:
Your code has undefined behavior because in this line

```<code>temp.push_back(temp[i]);
</code>```

you are accessing temp out-of-bounds. You can see this by adding a line

```<code>std::cout << "check " << i << " " << temp.size() << "\n";
</code>```

just before that line.

Output will be (see here):

```<code>1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
check 1 1
check 0 2
1
...
</code>```

When the size is 1 the last valid index is 0. The problem is not with stoi but with the logic of your algorithm.

Body:
I am using stoi in one of my functions with the intent of converting a string of numbers into an integer. I was about halfway through a homework problem but then I ran into this. Oddly, if the number has an even number of characters, stoi only converts the first half. Any help would be greatly appreciated!

Code:

#include <fstream>
#include <vector>
#include <string>
using namespace std;
string start;
string endD;
int sDigit;
int eDigit;
int i;
vector<int> palindromes;

void construct(int layer, int digits, string prev)
{
    string temp = prev;
    if(layer > (digits % 2) + digits/2)
    {
        short a = (short) digits/2;
        for(int i = a; i >= 0; i--)
        {
            if(i == a && digits % 2 == 1)
            {
                continue;
            }
            else
            {
                temp.push_back(temp[i]);
            }
        }
        cout << temp << " " << stoi(temp) << endl; // Output is here
        palindromes.push_back(stoi(temp));
    }
    else if(layer == 1 && digits == sDigit)
    {
        for(int i = start[0] - '0'; i < 10; i++)
        {
            temp[0] = i + '0';
            construct(layer + 1, digits, temp);
        }
    }
    else if(layer == 1 && digits == eDigit)
    {
        for(int i = '1'; i <= endD[0]; i++)
        {
            temp[0] = i;
            construct(layer + 1, digits, temp);
            temp = prev;
        }
    }
    else if(layer == 1)
    {
        for(int i = 1; i < 10; i++)
        {
            temp[0] = '0' + i;
            construct(layer + 1, digits, temp);
            temp = prev;
        }
    }
    else
    {
        for(int i = 0; i < 10; i++)
        {
            temp.push_back(i + '0');
            construct(layer + 1, digits, temp);
            temp = prev;
        }
    }
}

int main()
{
    int startD, endDD;
    cin >> startD >> endDD;
    start = to_string(startD);
    endD = to_string(endDD);
    int tempS = startD;
    int tempE = endDD;
    while(tempS != 0)
    {
        tempS /= 10;
        sDigit++;
    }
    while(tempE != 0)
    {
        tempE /= 10;
        eDigit++;
    }
    for(int i = sDigit; i <= eDigit; i++)
    {
        construct(1, i, "x");
    }
    for(int i = 0; i < palindromes.size(); i++)
    {
        //cout << palindromes[i] << endl;
    }
}```

Input: 1 1000
Output:

Body:
Your code has undefined behavior because in this line

temp.push_back(temp[i]);

you are accessing temp out-of-bounds. You can see this by adding a line

std::cout << "check " << i << " " << temp.size() << "\n";

just before that line.

Output will be (see here):

1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
check 1 1
check 0 2
1
...

When the size is 1 the last valid index is 0. The problem is not with stoi but with the logic of your algorithm.


问:
What is the point of Node.js
Ok this is probably a little blunt and to the point, but what is the point/need for Node.js

I've noticed it mainly through CloudFoundry but just not too sure what its supposed to be doing. However I am guessing its probably something pretty big as why else would VMWare be supporting it.

Thanks in advance.

答:
Node.js is an event based,
  asynchronous I/O framework that uses
  Google's V8 JavaScript engine. Node.js
  is commonly used for heavy
  client-server JavaScript applications.

The node.js tag has some more background information to point you in the right direction:  https://stackoverflow.com/tags/node.js/info

Title: What is the point of Node.js