问:
Bootstrap 4 Dropdown Menu not working?
I copied the official Bootstrap 4 example for dropdown menus but it is not working, that is nothing is dropped down.</p>

```<code><li class="nav-item dropdown">
    <a class="nav-link dropdown-toggle" href="#" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a>
    <div class="dropdown-menu" aria-labelledby="dropdown01">
    <a class="dropdown-item" href="#">Action</a>
    <a class="dropdown-item" href="#">Another action</a>
    <a class="dropdown-item" href="#">Something else here</a>
  </div>
</li>
</code>```

答:
A simple answer is to replace this line:

```<code><script type="text/javascript" src="your_directory/bootstrap.min.js"></script>
</code>```

for this other:

```<code><script type="text/javascript" src="your_directory/bootstrap.bundle.min.js"></script>
</code>```

Title: Bootstrap 4 Dropdown Menu not working?

Body:
I copied the official Bootstrap 4 example for dropdown menus but it is not working, that is nothing is dropped down.

    Dropdown

    Action
    Another action
    Something else here

Body:
A simple answer is to replace this line:

<script type="text/javascript" src="your_directory/bootstrap.min.js"></script>

for this other:

<script type="text/javascript" src="your_directory/bootstrap.bundle.min.js"></script>


来源: stackexchange

问:
npm install if package.json was modified
TL;DR: Is there a way to have npm install run automatically before running any npm script if your package.json has been modified?

Problem Scenario

You pull or checkout a branch that updated package.json. You run npm run my-script. my-script depends on a package that has newly been added to package.json. my-script fails. You wonder why. Before flipping over your desk you run npm install just to be sure. my-script runs successfully. You don't need a new desk.

I know that build / task runner tools like gradle make sure that your dependencies are up-to-date before running a task. I has always been a (minor) pain point that npm doesn't do it. I stumbled over two solutions that I don't particluarly like.

Non-Ideal Solution: make

Instead of relying on npm scripts in your package.json to run commands you use make and make use of its integrated dependency tracking with the following trick:

```<code># Smart install: Only executes if package.json's
# modification date is later than node_module's

node_modules: package.json
    npm install
    @rm -f node_modules/.modified
    @touch -m node_modules/.modified

install: node_modules
</code>```

Source: https://mattandre.ws/2016/05/make-for-hipsters/

The problem is that you know have to rely on make to run scripts and lose certain advantages of npm scripts such as conveniently referring to other scripts and running scripts in parallel (npm-run-all). It's also harder to work with others if they don't know make or have problems running it (Windows). It's an archaic tool outside of the node/npm ecosystem and too costly just for this smart install advantage.

Non-Ideal Solution: Git hook

Another way is to add a post-merge git hook.

The problem is that this solution is local to the repository and can't be easily shared. npm install will only be run automatically on git merges. When you change package.json in any other way you still have to remember running npm install. Admittedly, that's a minor point in practice. Nonetheless, it would be nice to never have to think about running npm install at all when you want to run a script.

Source: https://davidwalsh.name/git-hook-npm-install-package-json-modified

Ideal Solution

I'd like to define my package.json in a way similar to:

```<code>{
  "scripts": {
    "pre-run": "npm-smart-install",
    "my-script": "…"
  },
  "dependencies": {
    "npm-smart-install": "1.0.0"
  }
}
</code>```

npm-smart-install is a hypothetical npm package that I wish existed. pre-run is a hypothetical npm-scripts lifecycle hook. When I run npm run my-script and package.json has been modified since the last run of any script, run npm install before running my-script.

To repeat: Is there a way to have npm install run automatically before running any npm script if your package.json has been modified without relying on tools outside the npm ecosystem?

答:
You can create a custom script that will run your smart install.

smart-install.sh file

```<code>#!/usr/bin/env bash

changedFiles="$(git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD)"

checkForChangedFiles() {
    echo "$changedFiles" | grep --quiet "$1" && eval "$2"
}

packageJsonHasChanged() {
  echo "Changes to package.json detected, installing updates"
  npm i
}

checkForChangedFiles package.json packageJsonHasChanged
</code>```

Then if you have husky you can add that to the post-checkout hook or any hook you like. If you don't have husky, you can also add it directly to the scripts which essentially do the same thing.

.huskyrc file

```<code>{
  "hooks": {
    "post-checkout": "npm run smart-install"
  }
}
</code>```

package.json file

```<code>"scripts": {
  ...
  "smart-install": "bash ./bin/smart-install.sh",
}
</code>```

Either way it's a good idea to create a npm script to run smart-install

ContentLicense: CC BY-SA 4.0

Body:
TL;DR: Is there a way to have npm install run automatically before running any npm script if your package.json has been modified?

Problem Scenario

You pull or checkout a branch that updated package.json. You run npm run my-script. my-script depends on a package that has newly been added to package.json. my-script fails. You wonder why. Before flipping over your desk you run npm install just to be sure. my-script runs successfully. You don't need a new desk.

I know that build / task runner tools like gradle make sure that your dependencies are up-to-date before running a task. I has always been a (minor) pain point that npm doesn't do it. I stumbled over two solutions that I don't particluarly like.

Non-Ideal Solution: make

Instead of relying on npm scripts in your package.json to run commands you use make and make use of its integrated dependency tracking with the following trick:

# Smart install: Only executes if package.json's
# modification date is later than node_module's

node_modules: package.json
    npm install
    @rm -f node_modules/.modified
    @touch -m node_modules/.modified

install: node_modules

Source: https://mattandre.ws/2016/05/make-for-hipsters/

The problem is that you know have to rely on make to run scripts and lose certain advantages of npm scripts such as conveniently referring to other scripts and running scripts in parallel (npm-run-all). It's also harder to work with others if they don't know make or have problems running it (Windows). It's an archaic tool outside of the node/npm ecosystem and too costly just for this smart install advantage.

Non-Ideal Solution: Git hook

Another way is to add a post-merge git hook.

The problem is that this solution is local to the repository and can't be easily shared. npm install will only be run automatically on git merges. When you change package.json in any other way you still have to remember running npm install. Admittedly, that's a minor point in practice. Nonetheless, it would be nice to never have to think about running npm install at all when you want to run a script.

Source: https://davidwalsh.name/git-hook-npm-install-package-json-modified

Ideal Solution

I'd like to define my package.json in a way similar to:

{
  "scripts": {
    "pre-run": "npm-smart-install",
    "my-script": "…"
  },
  "dependencies": {
    "npm-smart-install": "1.0.0"
  }
}

npm-smart-install is a hypothetical npm package that I wish existed. pre-run is a hypothetical npm-scripts lifecycle hook. When I run npm run my-script and package.json has been modified since the last run of any script, run npm install before running my-script.

To repeat: Is there a way to have npm install run automatically before running any npm script if your package.json has been modified without relying on tools outside the npm ecosystem?

Body:
You can create a custom script that will run your smart install.

smart-install.sh file

#!/usr/bin/env bash

changedFiles="$(git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD)"

checkForChangedFiles() {
    echo "$changedFiles" | grep --quiet "$1" && eval "$2"
}

packageJsonHasChanged() {
  echo "Changes to package.json detected, installing updates"
  npm i
}

checkForChangedFiles package.json packageJsonHasChanged

Then if you have husky you can add that to the post-checkout hook or any hook you like. If you don't have husky, you can also add it directly to the scripts which essentially do the same thing.

.huskyrc file

{
  "hooks": {
    "post-checkout": "npm run smart-install"
  }
}

package.json file

"scripts": {
  ...
  "smart-install": "bash ./bin/smart-install.sh",
}

Either way it's a good idea to create a npm script to run smart-install


问:
How to Convert system.windows.controls.image to byte[]
I need to convert System.Windows.Controls.Image to byte[].

How to do it ?

答:
```<code>System.Windows.Controls.Image img = new System.Windows.Controls.Image();
var uri = new Uri("pack://application:,,,/Images/myImage.jpg");
img.Source = new BitmapImage(uri);
byte[] arr;
using (MemoryStream ms = new MemoryStream())
{
      var bmp = img.Source as BitmapImage;
      JpegBitmapEncoder encoder = new JpegBitmapEncoder();
      encoder.Frames.Add(BitmapFrame.Create(bmp));
      encoder.Save(ms);
      arr = ms.ToArray();
}
</code>```

ContentLicense: CC BY-SA 2.5


问:
filtering an array of object based on string array
my problem might not be as challenging as some other similar questions but they were a little to much for me.

I have an array of objects that I need to filter by name against a string array of names, if the names match I want to remove the object with the name that matches

so like the following:

```<code>nameObjects = [{name: 'name3', value: 'some val'},{name: 'name1', value:'some other val'}]
names = ['name1','name2','name3']
</code>```

I've tried the following just using for loops but I'm sure that there is a quicker (and correct lol) filter method that works

```<code>         for(i=0; i < this.names.length; i++){
            for(j=0; j < this.nameObjects.length; j++){

              if(this.names[i] === this.nameObjects[j].name){
                this.files.splice(i,this.nameObjects[j])
              }
            }
          }
</code>```

also sorry for the poor logic ^

答:
const nameObjects = [
    { name: "name3", value: "some val" },
    { name: "name1", value: "some other val" },
];
const names = ["name1", "name2"];

const result = nameObjects.filter(obj => !names.includes(obj.name));

console.log(result);```

Body:
my problem might not be as challenging as some other similar questions but they were a little to much for me.

I have an array of objects that I need to filter by name against a string array of names, if the names match I want to remove the object with the name that matches

so like the following:

nameObjects = [{name: 'name3', value: 'some val'},{name: 'name1', value:'some other val'}]
names = ['name1','name2','name3']

I've tried the following just using for loops but I'm sure that there is a quicker (and correct lol) filter method that works

         for(i=0; i < this.names.length; i++){
            for(j=0; j < this.nameObjects.length; j++){

              if(this.names[i] === this.nameObjects[j].name){
                this.files.splice(i,this.nameObjects[j])
              }
            }
          }

also sorry for the poor logic ^


问:
Calculating follower growth over time for each influencer
I have a table with influencers and their follower counter for each day:

```<code>influencer_id |     date     |    followers
     1        | 2020-05-29   |      7361
     1        | 2020-05-28   |      7234
                    ...
     2        | 2020-05-29   |       82
     2        | 2020-05-28   |       85
                    ...
     3        | 2020-05-29   |      3434
     3        | 2020-05-28   |      2988
     3        | 2020-05-27   |      2765
                    ...
</code>```

Let's say I want to calculate how many followers each individual influencer has gained in the last 7 days and get the following table:

```<code>influencer_id |                       growth
     1        |  <num followers last day - num followers first day>
     2        |                         "
     3        |                         "
</code>```

As a first attempt I did this:

```<code>SELECT influencer_id,
      (MAX(followers) - MIN(followers)) AS growth
FROM influencer_follower_daily
WHERE date < '2020-05-30'
AND date >= '2020-05-23'
GROUP BY influencer_id;
</code>```

This works and shows the growth over the week for each influencer. But it assumes the follower count always increases and people never unfollow!

So is there a way to achieve what I want using an SQL query over the original table? Or will I have to generate a completely new table using a FOR loop that calculates a +/- follower change column between each date?

答:
Postgres doesn't have a first()/last() aggregation function.  One method is:

```<code>SELECT DISTINCT influencer_id,
       ( FIRST_VALUE(followers) OVER (PARTITION BY influencer_id ORDER BY DATE DESC) -
         FIRST_VALUE(followers) OVER (PARTITION BY influencer_id ORDER BY DATE ASC)
       ) as growth
FROM influencer_follower_daily
WHERE date < '2020-05-30' AND date >= '2020-05-23';
</code>```

Another alternative is to use arrays:

```<code>SELECT influencer_id,
       ( ARRAY_AGG(followers ORDER BY DATE DESC) )[1] -
         ARRAY_AGG(followers ORDER BY DATE ASC) )[1]
       ) as growth
FROM influencer_follower_daily
WHERE date < '2020-05-30' AND date >= '2020-05-23'
GROUP BY influencer_id;
</code>```

Body:
I have a table with influencers and their follower counter for each day:

influencer_id |     date     |    followers
     1        | 2020-05-29   |      7361
     1        | 2020-05-28   |      7234
                    ...
     2        | 2020-05-29   |       82
     2        | 2020-05-28   |       85
                    ...
     3        | 2020-05-29   |      3434
     3        | 2020-05-28   |      2988
     3        | 2020-05-27   |      2765
                    ...

Let's say I want to calculate how many followers each individual influencer has gained in the last 7 days and get the following table:

influencer_id |                       growth
     1        |  <num followers last day - num followers first day>
     2        |                         "
     3        |                         "

As a first attempt I did this:

SELECT influencer_id,
      (MAX(followers) - MIN(followers)) AS growth
FROM influencer_follower_daily
WHERE date < '2020-05-30'
AND date >= '2020-05-23'
GROUP BY influencer_id;

This works and shows the growth over the week for each influencer. But it assumes the follower count always increases and people never unfollow!

So is there a way to achieve what I want using an SQL query over the original table? Or will I have to generate a completely new table using a FOR loop that calculates a +/- follower change column between each date?

Body:
Postgres doesn't have a first()/last() aggregation function.  One method is:

SELECT DISTINCT influencer_id,
       ( FIRST_VALUE(followers) OVER (PARTITION BY influencer_id ORDER BY DATE DESC) -
         FIRST_VALUE(followers) OVER (PARTITION BY influencer_id ORDER BY DATE ASC)
       ) as growth
FROM influencer_follower_daily
WHERE date < '2020-05-30' AND date >= '2020-05-23';

Another alternative is to use arrays:

SELECT influencer_id,
       ( ARRAY_AGG(followers ORDER BY DATE DESC) )[1] -
         ARRAY_AGG(followers ORDER BY DATE ASC) )[1]
       ) as growth
FROM influencer_follower_daily
WHERE date < '2020-05-30' AND date >= '2020-05-23'
GROUP BY influencer_id;


问:
E349: No identifier Under Cursor
Every time I switch back to vim window, it shows the list, if current cursor on an empty line, it shows error: E349: No identifier Under Cursor.

答:
According to https://unix.stackexchange.com/a/480138 ,
it is the FocusIn/FocusOut mode that can be disabled with:

```<code>echo -ne '\e[?1004l'
</code>```

I encountered this problem when I would lose an ssh connection, so tmux on the remote server that enabled FocusIn/FocusOut mode would not be able to disable it. If I opened a vim on my local machine, vim would receive those events. If the FocusIn/FocusOut mode is not the default for your terminal, you can also disable it with:

```<code>reset
</code>```

ContentLicense: CC BY-SA 3.0

Title: E349: No identifier Under Cursor

Body:
According to https://unix.stackexchange.com/a/480138 ,
it is the FocusIn/FocusOut mode that can be disabled with:

echo -ne '\e[?1004l'

I encountered this problem when I would lose an ssh connection, so tmux on the remote server that enabled FocusIn/FocusOut mode would not be able to disable it. If I opened a vim on my local machine, vim would receive those events. If the FocusIn/FocusOut mode is not the default for your terminal, you can also disable it with:

reset


问:
Mouse not drawing in pyglet
My custom mouse image is not showing up in pyglet. It loads normally(When you create the window outside a class), but when i make the window in a class and try yo add the custom mouse cursor nothing happens

```<code>class x:
    def __init__(self):
        self.game_window = pyglet.window.Window()
        self.on_mouse_press = self.game_window.event(self.on_mouse_press)

        self.game_cursor = pyglet.image.load('image.png')
        self.cursor = pyglet.window.ImageMouseCursor(self.game_cursor, 50, 70)
        self.game_window.set_mouse_cursor(self.cursor)
</code>```

I have tried printing every one of the lines of code (for mouse image loading)

When i print - self.game_cursor = pyglet.image.load('image.png') - This is the result:
ImageData 85x82

When i print - self.cursor = pyglet.window.ImageMouseCursor(self.game_cursor, 50, 70) - This is the result:
pyglet.window.ImageMouseCursor object at 0x7f4dad76b390

When i print - self.game_window.set_mouse_cursor(self.cursor) - This is the result:
None

How do I fix make the mouse show?

答:
According to pyglet documentation for ImageMouseCursor class link method draw(x, y) is abstract. So I've tried sub-classing ImageMouseCursor and implementing draw method like this:

```<code>    import pyglet
    pyglet.resource.path = ['resources']
    pyglet.resource.reindex()

    # subclass definition
    class GameMouse(pyglet.window.ImageMouseCursor):
        # class initialization
        def __init__(self):
            self.game_cursor = pyglet.resource.image('game_cursor.png')
            super().__init__(self.game_cursor, 0, 34)
        # method override
        def draw(self, x, y):
            self.game_cursor.blit(x, y)
</code>```

However, this will not work if gl blending is not enabled. gl blending is needed to display alpha channels. I've managed to enable it by sub-classing Window class, and using glEnable / glBlendFunc functions. This is the part of the code that does as described:

```<code>    # subclass definition:
    class GameApp(pyglet.window.Window):
        # class initialization
        def __init__(self):
            super(GameApp, self).__init__()
            pyglet.gl.glEnable(pyglet.gl.GL_BLEND)
            pyglet.gl.glBlendFunc(pyglet.gl.GL_SRC_ALPHA,
                                  pyglet.gl.GL_ONE_MINUS_SRC_ALPHA)

</code>```

Hope this helps

Title: Mouse not drawing in pyglet

Body:
My custom mouse image is not showing up in pyglet. It loads normally(When you create the window outside a class), but when i make the window in a class and try yo add the custom mouse cursor nothing happens

class x:
    def __init__(self):
        self.game_window = pyglet.window.Window()
        self.on_mouse_press = self.game_window.event(self.on_mouse_press)

        self.game_cursor = pyglet.image.load('image.png')
        self.cursor = pyglet.window.ImageMouseCursor(self.game_cursor, 50, 70)
        self.game_window.set_mouse_cursor(self.cursor)

I have tried printing every one of the lines of code (for mouse image loading)

When i print - self.game_cursor = pyglet.image.load('image.png') - This is the result:
ImageData 85x82

When i print - self.cursor = pyglet.window.ImageMouseCursor(self.game_cursor, 50, 70) - This is the result:
pyglet.window.ImageMouseCursor object at 0x7f4dad76b390

When i print - self.game_window.set_mouse_cursor(self.cursor) - This is the result:
None

How do I fix make the mouse show?

Body:
According to pyglet documentation for ImageMouseCursor class link method draw(x, y) is abstract. So I've tried sub-classing ImageMouseCursor and implementing draw method like this:

    import pyglet
    pyglet.resource.path = ['resources']
    pyglet.resource.reindex()

    # subclass definition
    class GameMouse(pyglet.window.ImageMouseCursor):
        # class initialization
        def __init__(self):
            self.game_cursor = pyglet.resource.image('game_cursor.png')
            super().__init__(self.game_cursor, 0, 34)
        # method override
        def draw(self, x, y):
            self.game_cursor.blit(x, y)

However, this will not work if gl blending is not enabled. gl blending is needed to display alpha channels. I've managed to enable it by sub-classing Window class, and using glEnable / glBlendFunc functions. This is the part of the code that does as described:

    # subclass definition:
    class GameApp(pyglet.window.Window):
        # class initialization
        def __init__(self):
            super(GameApp, self).__init__()
            pyglet.gl.glEnable(pyglet.gl.GL_BLEND)
            pyglet.gl.glBlendFunc(pyglet.gl.GL_SRC_ALPHA,
                                  pyglet.gl.GL_ONE_MINUS_SRC_ALPHA)

Hope this helps


问:
Unrecognised javascript syntax
I have come across a particular javascript code while looking into RxJs documentation.

```<code>import { of } from 'rxjs';
import { map } from 'rxjs/operators';

map(x => x * x)(of(1, 2, 3)).subscribe((v) => console.log(`value: ${v}`));
</code>```

I understand what it does but I have not come across this syntax before as far as I remember. Which syntax is this?

EDIT:

I was confused about the part map(x => x * x)(of(1, 2, 3)). @Olian04 nicely explains that map() is an higher order function. map() returns an function which is passed the parameter of(1, 2, 3)

答:
Since you didn't specify exactly which part of the snipped was confusing you, I'll do a quick breakdown of the code excluding the imports:

x => x*x is an arrow function. Its the same as function(x){return x*x;}

map is a higher order function that takes a function as its argument map(f). It also returns a function fMap = map(f)

fMap is a function that takes an observable as an argument, and
returns an observable where each value has had the function f applied on it fObs = fMap(obs)

of is a function that takes any number of arguments, and returns an observable that will emit those arguments as events to subscribers obs = of(1, 2, 3)

fObs.subscribe is a higher order function that takes a function as its argument and registers it as an event subscriber

`value: ${v}` is a string literal template which is the same as doing 'value: ' + String(v)

OwnerDisplayName: Arnab Das

Title: Unrecognised javascript syntax

Body:
I have come across a particular javascript code while looking into RxJs documentation.

import { of } from 'rxjs';
import { map } from 'rxjs/operators';

map(x => x * x)(of(1, 2, 3)).subscribe((v) => console.log(`value: ${v}`));

I understand what it does but I have not come across this syntax before as far as I remember. Which syntax is this?

EDIT:

I was confused about the part map(x => x * x)(of(1, 2, 3)). @Olian04 nicely explains that map() is an higher order function. map() returns an function which is passed the parameter of(1, 2, 3)


问:
CSS media not working on a set of devices
I have written media queries for a project i am working on. The whole devices on my chrome are working fine on samsung, pixel and I-phones but not working on Infinix and tecno phones. These are media queries i used:

```<code>@media (max-width: 320px)
@media (min-width: 360px) and (max-width: 384px)
@media (max-width: 768px)
</code>```

All the devices on my chrome device emulator is working fine but when i check with mt infinix and tecno phones, it doesnt work fine. Check the screenshots for tecno for infinix for samsung for iphone
The navigation is showing well in the last two but not in the first two

答:
As checked in your screenshots,

Problem seems not in media query, But with cross browser support of your css codes.

Did you flexbox or any other css3 methods ? if yes, then add css autoprefixer codes for browser fallbacks.

You can also use some online tool like pleeease.io to get browser autoprefixer codes.

Body:
I have written media queries for a project i am working on. The whole devices on my chrome are working fine on samsung, pixel and I-phones but not working on Infinix and tecno phones. These are media queries i used:

@media (max-width: 320px)
@media (min-width: 360px) and (max-width: 384px)
@media (max-width: 768px)

All the devices on my chrome device emulator is working fine but when i check with mt infinix and tecno phones, it doesnt work fine. Check the screenshots for tecno for infinix for samsung for iphone
The navigation is showing well in the last two but not in the first two


答:
You should not mutate the array while you are looping over it.

You can simply use Array.prototype.filter with Array.prototype.includes to get the desired result

const nameObjects = [{name: 'name3', value: 'some val'},{name: 'name1', value:'some other val'}];
const names = ['name2','name3'];
const res = nameObjects.filter(obj => !names.includes(obj.name));
console.log(res);```

Title: filtering an array of object based on string array


问:
Creating OpenAI Gym Environment from Map Data
I am just starting out with reinforcement learning and trying to create a custom environment with OpenAI gym. However, I am stumped with trying to create an environment (with roads and intersections) from map data, say Google Maps. </p>

<p>Would appreciate any help I can get. </p>

答: The best way that I have found would be to use osmnx to have your map data ready in a graph format. It allows easy access of nodes that make up a street map in a graph or geopandas form. This data can then be used to drive the game logic. With regards to rendering, external rendering tools like PyGame can then be used. </p>

Body:
I am just starting out with reinforcement learning and trying to create a custom environment with OpenAI gym. However, I am stumped with trying to create an environment (with roads and intersections) from map data, say Google Maps.

Would appreciate any help I can get.


问:
Embedded documents and arrays reduce need for expensive joins in MongoDB

Embedded documents and arrays reduce need for expensive joins.

From: https://docs.mongodb.com/manual/introduction/

What does that sentence mean? What documents are called embedded documents? How do they are arrays reduce need for expensive joins?

答:
https://www.mongodb.com/blog/post/6-rules-of-thumb-for-mongodb-schema-design-part-1 would be a good read to understand embedding vs referencing techniques and what use cases they solve.

The quoted sentence itself says that nested documents are returned within a single fetch of the parent document which eliminates need to make fetches from multiple collections.

Nested / embedded / sub- documents are bson objects within an array property of the parent document. E.g.

```<code>{
    _id: 1,
    name: "the doc",
    refs: [
        {name: "embedded document 1"},
        {name: "subdocument 2"},
        {value: { another: ["nested", "document"]}}
    ]
}
</code>```

Compare it with references where refs are not embedded but stored in aseparate collection:

documents collection:

```<code>{
    _id: 1,
    name: "the doc",
}
</code>```

referenced docs collection:

```<code>{doc_id: 1, name: "embedded document 1"},
{doc_id: 1, name: "subdocument 2"},
{doc_id: 1, value: { another: ["nested", "document"]}}
</code>```

Fetching the doc with _id:1 and all referenced docs would require much more expensive query using aggregation framework with $lookup stage.

Body:
https://www.mongodb.com/blog/post/6-rules-of-thumb-for-mongodb-schema-design-part-1 would be a good read to understand embedding vs referencing techniques and what use cases they solve.

The quoted sentence itself says that nested documents are returned within a single fetch of the parent document which eliminates need to make fetches from multiple collections.

Nested / embedded / sub- documents are bson objects within an array property of the parent document. E.g.

{
    _id: 1,
    name: "the doc",
    refs: [
        {name: "embedded document 1"},
        {name: "subdocument 2"},
        {value: { another: ["nested", "document"]}}
    ]
}

Compare it with references where refs are not embedded but stored in aseparate collection:

documents collection:

{
    _id: 1,
    name: "the doc",
}

referenced docs collection:

{doc_id: 1, name: "embedded document 1"},
{doc_id: 1, name: "subdocument 2"},
{doc_id: 1, value: { another: ["nested", "document"]}}

Fetching the doc with _id:1 and all referenced docs would require much more expensive query using aggregation framework with $lookup stage.


问:
Why will my images/script not show up on asp.net mvc deployed site?
I have deployed an app to an IIS6 server.  For now, I'm using the wildcard mapping.  My app works perfectly fine on my development machine, but when I try to access it on the server, some pages work and some don't.

It is the scripts & images that are giving me the biggest problem.

I have a url http://localhost/sdev/home/index and the page comes up fine except the images and scripts don't load.  When I view source and look at the url I see:

```<code>../../Content/Images/logo.png
</code>```

If I try to navigate to that url, it tries to go to

```<code>http://localhost/content/images/logo.png
</code>```

instead of

```<code>http://localhost/sdev/content/images/logo.png
</code>```

The strange thing is that some pages work fine, such as:

```<code>http://localhost/sdev/ServiceCall/DivisionStep/ALB?type=fsr
</code>```

Any ideas on what I can do to fix this?  Yes, I have read Phil's instructions and thought I followed them correctly but maybe I missed something.

答:
i just wrote some helpers for images you can use.

(1) simply create a public static class called AppHelper with a using System.Web.Mvc; and add it to a folder in your MVC project called 'Helpers'.

(2) copy in these methods:

```<code>    public static string Image(this HtmlHelper helper,
        string classText, string sourcePath, string altText, string width, string height)
    {
        return Image(helper, classText, sourcePath, altText, width, height, null);
    }
</code>```

```<code>    public static string Image(this HtmlHelper helper,
        string classText, string sourcePath, string altText, string width, string height, object htmlAttributes)
    {
        StringBuilder sb = new StringBuilder();
        if (htmlAttributes != null)
            foreach (PropertyInfo p in htmlAttributes.GetType().GetProperties())
                sb.AppendFormat(@" {0}=""{1}""", p.Name, p.GetValue(htmlAttributes, null).ToString());

        if (htmlAttributes == null)
            return String.Format(@"<img{0} src=""{1}"" alt=""{2}"" width=""{3}"" height=""{4}"" />",
                String.IsNullOrEmpty(classText) ? String.Empty : String.Format(@" class=""{0}""", classText),
                (new UrlHelper(helper.ViewContext.RequestContext)).Content(sourcePath),
                altText, width, height);
        else
            return String.Format(@"<img{0} src=""{1}"" alt=""{2}"" width=""{3}"" height=""{4}""{5} />",
                String.IsNullOrEmpty(classText) ? String.Empty : String.Format(@" class=""{0}""", classText),
                (new UrlHelper(helper.ViewContext.RequestContext)).Content(sourcePath),
                altText, width, height, sb.ToString());
    }
</code>```

(3) ..and use like so:
<% =Html.Image("small_pic_border","~/Content/Images/Home/office2_137x139.jpg","principal headshot","137","139") %>

This method uses the Url.Content method that liammclennan mentioned. It should also force you into some good habbits: like using alternate text etc.

For scripts use:

OwnerDisplayName: Mike Roosa

Body:
I have deployed an app to an IIS6 server.  For now, I'm using the wildcard mapping.  My app works perfectly fine on my development machine, but when I try to access it on the server, some pages work and some don't.

It is the scripts & images that are giving me the biggest problem.

I have a url http://localhost/sdev/home/index and the page comes up fine except the images and scripts don't load.  When I view source and look at the url I see:

../../Content/Images/logo.png

If I try to navigate to that url, it tries to go to

http://localhost/content/images/logo.png

instead of

http://localhost/sdev/content/images/logo.png

The strange thing is that some pages work fine, such as:

http://localhost/sdev/ServiceCall/DivisionStep/ALB?type=fsr

Any ideas on what I can do to fix this?  Yes, I have read Phil's instructions and thought I followed them correctly but maybe I missed something.

Body:
i just wrote some helpers for images you can use.

(1) simply create a public static class called AppHelper with a using System.Web.Mvc; and add it to a folder in your MVC project called 'Helpers'.

(2) copy in these methods:

    public static string Image(this HtmlHelper helper,
        string classText, string sourcePath, string altText, string width, string height)
    {
        return Image(helper, classText, sourcePath, altText, width, height, null);
    }

    public static string Image(this HtmlHelper helper,
        string classText, string sourcePath, string altText, string width, string height, object htmlAttributes)
    {
        StringBuilder sb = new StringBuilder();
        if (htmlAttributes != null)
            foreach (PropertyInfo p in htmlAttributes.GetType().GetProperties())
                sb.AppendFormat(@" {0}=""{1}""", p.Name, p.GetValue(htmlAttributes, null).ToString());

        if (htmlAttributes == null)
            return String.Format(@"<img{0} src=""{1}"" alt=""{2}"" width=""{3}"" height=""{4}"" />",
                String.IsNullOrEmpty(classText) ? String.Empty : String.Format(@" class=""{0}""", classText),
                (new UrlHelper(helper.ViewContext.RequestContext)).Content(sourcePath),
                altText, width, height);
        else
            return String.Format(@"<img{0} src=""{1}"" alt=""{2}"" width=""{3}"" height=""{4}""{5} />",
                String.IsNullOrEmpty(classText) ? String.Empty : String.Format(@" class=""{0}""", classText),
                (new UrlHelper(helper.ViewContext.RequestContext)).Content(sourcePath),
                altText, width, height, sb.ToString());
    }

(3) ..and use like so:
<% =Html.Image("small_pic_border","~/Content/Images/Home/office2_137x139.jpg","principal headshot","137","139") %>

This method uses the Url.Content method that liammclennan mentioned. It should also force you into some good habbits: like using alternate text etc.

For scripts use:
<script type="text/javascript" src="<% =Url.Content("~/Scripts/mootools.js") %>"></script>

OwnerDisplayName: cottsak

LastEditorDisplayName: cottsak