问:
Get only JSON string as output without any html
I am developing a webiste in ASP.NET. On one of the pages page named menu.aspx, with the help of a certain login, I am getting the output in this format

foo({"1":"Jeff","2":"Mik","5":"Tom"});

I am using this code to get the output on the JSON form.

```<code>outputText += Convert.ToString(k.GetValue(0));
            for (Int32 i = 1; i < k.Length; i++)
            {
                outputText += "," + Convert.ToString(k.GetValue(i));
            }
            //
            outputText += "}" +");";
            Response.Clear();
            Response.Write(outputText);
            Response.ContentType = "application/json";
</code>```

However, I must get the output only in simple JSON on the page without any HTML.

For eg: Here's the screenshot showing the source of the output page. http://i.stack.imgur.com/faUtY.jpg

Notice that it has only the JSON string as the output.

And here's the screenshot showing the output page source (with HTML). http://i.stack.imgur.com/gIxzR.jpg  .This HTML is what I have to remove. How can do I do this?
The full code of menu.aspx.cs is putup here. http://pastebin.com/M14Srrgf

答: It seems like your JSON output HTTP call should be in a different request.  You could first load the HTML page and then from the HTML page make an AJAX call to your server to get the JSON by itself.</p>

Body:
I am developing a webiste in ASP.NET. On one of the pages page named menu.aspx, with the help of a certain login, I am getting the output in this format

foo({"1":"Jeff","2":"Mik","5":"Tom"});

I am using this code to get the output on the JSON form.

outputText += Convert.ToString(k.GetValue(0));
            for (Int32 i = 1; i < k.Length; i++)
            {
                outputText += "," + Convert.ToString(k.GetValue(i));
            }
            //
            outputText += "}" +");";
            Response.Clear();
            Response.Write(outputText);
            Response.ContentType = "application/json";

However, I must get the output only in simple JSON on the page without any HTML.

For eg: Here's the screenshot showing the source of the output page. http://i.stack.imgur.com/faUtY.jpg

Notice that it has only the JSON string as the output.

And here's the screenshot showing the output page source (with HTML). http://i.stack.imgur.com/gIxzR.jpg  .This HTML is what I have to remove. How can do I do this?
The full code of menu.aspx.cs is putup here. http://pastebin.com/M14Srrgf


来源: stackexchange

问:
How can I see all packages that depend on a certain package with PIP?
I would like to see a list of packages that depend on a certain package with PIP. That is, given django, I would like to see django-cms, django-filer, because I have these packages installed and they all have django as dependency.

答:
I know there's already an accepted answer here, but really, it seems to me that what you want is to use pipdeptree:</p>

```<code>pip install pipdeptree
pipdeptree --help

pipdeptree -r -p django
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I know there's already an accepted answer here, but really, it seems to me that what you want is to use pipdeptree:

pip install pipdeptree
pipdeptree --help

pipdeptree -r -p django


问:
Retrofit Null Response onSuccess Method
I was following this tutorial in YouTube for Retrofit for sending objects in a post request but encounter an error on emulator with a null response onResponse method.

Problem:

Main Activity:

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

private EditText mName, mEmail, mAge, mTopics;
private Button mButton;

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

    mName = findViewById(R.id.editText);
    mEmail = findViewById(R.id.editText2);
    mAge = findViewById(R.id.editText3);
    mTopics = findViewById(R.id.editText4);
    mButton = findViewById(R.id.button);

    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            User user = new User(
                    mName.getText().toString(),
                    mEmail.getText().toString(),
                    Integer.parseInt(mAge.getText().toString()),
                    mTopics.getText().toString().split(",")
            );

            //Added proof its not a NPE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            Log.d("Main", mName.getText().toString() +
                            mName.getText().toString()+ Integer.parseInt(mAge.getText().toString()) +
                            Integer.parseInt(mAge.getText().toString()) +mTopics.getText().toString().split(","));

            sendNetworkRequest(user);
        }
    });

}

private void sendNetworkRequest(User user) {
    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl("http://10.0.2.2:3000/api/users/")
            .addConverterFactory(GsonConverterFactory.create());

    Retrofit retrofit = builder.build();
    UserClient client = retrofit.create(UserClient.class);
    Call<User> call = client.createAccount(user);
    call.enqueue(new Callback<User>() {
        @Override
        public void onResponse(Call<User> call, Response<User> response) {
            Toast.makeText(MainActivity.this, "Success UserID = "+ response.body(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call<User> call, Throwable t) {
            Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_SHORT).show();
        }
    });

}
</code>```

}

Proof of NOT NPE:

UserClient:

```<code>public interface UserClient {

    @POST("api/users")
    Call<User> createAccount(@Body User user);
}
</code>```

User:

```<code>public class User {

private Integer id;
private int age;
private String name, email;
private String [] topics;

public Integer getId() {
    return id;
}

public User(String name, String email, int age,  String[] topics) {
    this.age = age;
    this.name = name;
    this.email = email;
    this.topics = topics;
}
</code>```

Node.JS

App.js

```<code>const express = require('express');
const bodyParser = require('body-parser');
const routes = require('./routes/api');
const mongoose = require('mongoose');

const app = express();

mongoose.connect('mongodb://localhost/user1',  { useMongoClient: true });
mongoose.Promise = global.Promise;

app.use(bodyParser.json());
app.use('/api', routes);

app.listen(process.env.port || 3000, function(){
    console.log('Using PORT 3000');
});
</code>```

Api.js:

```<code>const express = require('express');
const router = express.Router();
const User = require('../models/user');

router.get('/users', function(req, res, next){
    res.send({type: "GET"});
});

router.post('/users', function(req, res, err){
    User.create(req.body).then(function(user){
        res.send(user);
    });
});

module.exports = router;
</code>```

User.js

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

const UserSchema = new Schema({
    name: {
        type: String
    },
    email: {
        type: String
    },
    age: {
        type: Number
    },
    topics: {
        type: String
    }
});

const User = mongoose.model('user', UserSchema);

module.exports = User;
</code>```

What I have tried:

I have tried changing the BASE_URL the local ip address of my machine using 'ipconfig' on my terminal. = 'http://192.168.X.X:3000/api/users/'

Use Headers and FormURLEncoded in the UserClient = @Headers("Content-Type: application/json") | @FormUrlEncoded.

Used postman to check responses, which successfully happen.

Checked Robomongo for verification/

Postman:

Get Request

Post Request

Robomongo

答:
Maybe you are doing a bad request?

Try to add a check for null in onResponse() and access the raw response like this response.errorBody.string()

Title: Retrofit Null Response onSuccess Method

Body:
I was following this tutorial in YouTube for Retrofit for sending objects in a post request but encounter an error on emulator with a null response onResponse method.

Problem:

Main Activity:

public class MainActivity extends AppCompatActivity {

private EditText mName, mEmail, mAge, mTopics;
private Button mButton;

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

    mName = findViewById(R.id.editText);
    mEmail = findViewById(R.id.editText2);
    mAge = findViewById(R.id.editText3);
    mTopics = findViewById(R.id.editText4);
    mButton = findViewById(R.id.button);

    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            User user = new User(
                    mName.getText().toString(),
                    mEmail.getText().toString(),
                    Integer.parseInt(mAge.getText().toString()),
                    mTopics.getText().toString().split(",")
            );

            //Added proof its not a NPE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            Log.d("Main", mName.getText().toString() +
                            mName.getText().toString()+ Integer.parseInt(mAge.getText().toString()) +
                            Integer.parseInt(mAge.getText().toString()) +mTopics.getText().toString().split(","));

            sendNetworkRequest(user);
        }
    });

}

private void sendNetworkRequest(User user) {
    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl("http://10.0.2.2:3000/api/users/")
            .addConverterFactory(GsonConverterFactory.create());

    Retrofit retrofit = builder.build();
    UserClient client = retrofit.create(UserClient.class);
    Call<User> call = client.createAccount(user);
    call.enqueue(new Callback<User>() {
        @Override
        public void onResponse(Call<User> call, Response<User> response) {
            Toast.makeText(MainActivity.this, "Success UserID = "+ response.body(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call<User> call, Throwable t) {
            Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_SHORT).show();
        }
    });

}

}

Proof of NOT NPE:

UserClient:

public interface UserClient {

    @POST("api/users")
    Call<User> createAccount(@Body User user);
}

User:

public class User {

private Integer id;
private int age;
private String name, email;
private String [] topics;

public Integer getId() {
    return id;
}

public User(String name, String email, int age,  String[] topics) {
    this.age = age;
    this.name = name;
    this.email = email;
    this.topics = topics;
}

Node.JS

App.js

const express = require('express');
const bodyParser = require('body-parser');
const routes = require('./routes/api');
const mongoose = require('mongoose');

const app = express();

mongoose.connect('mongodb://localhost/user1',  { useMongoClient: true });
mongoose.Promise = global.Promise;

app.use(bodyParser.json());
app.use('/api', routes);

app.listen(process.env.port || 3000, function(){
    console.log('Using PORT 3000');
});

Api.js:

const express = require('express');
const router = express.Router();
const User = require('../models/user');

router.get('/users', function(req, res, next){
    res.send({type: "GET"});
});

router.post('/users', function(req, res, err){
    User.create(req.body).then(function(user){
        res.send(user);
    });
});

module.exports = router;

User.js

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

const UserSchema = new Schema({
    name: {
        type: String
    },
    email: {
        type: String
    },
    age: {
        type: Number
    },
    topics: {
        type: String
    }
});

const User = mongoose.model('user', UserSchema);

module.exports = User;

What I have tried:

I have tried changing the BASE_URL the local ip address of my machine using 'ipconfig' on my terminal. = 'http://192.168.X.X:3000/api/users/'

Use Headers and FormURLEncoded in the UserClient = @Headers("Content-Type: application/json") | @FormUrlEncoded.

Used postman to check responses, which successfully happen.

Checked Robomongo for verification/

Postman:

Get Request

Post Request

Robomongo


问:
How to find the second minimum number without using arrays or loops
I tried to write a program that receive from the user 5 integers and print the second minimum number.

Here is a sample of what I've tried:

```<code>#include <iostream>
using namespace std;
int main () {
int a,b,c,d,e;
cin>>a>>b>>c>>d>>e;
if (a>b && a<c && a<d && a<e)
    cout<<a<<endl;
if (b>a && b<c && b<d && b<e)
    cout<<b<<endl;
if (c>a && c<b && c<d && c<e)
    cout<<c<<endl;
if (d>a && d<b && d<c && d<e)
    cout <<d<<endl;
if (e>a && e<b && e<c && e<d)
cout <<e<<endl;
return 0;

}
</code>```

When I enter 1 2 3 4 5 it prints the second minimum, but when I enter

5 4 3 2 1 Nothing will print on the screen. What am I doing wrong with this? Is there any other way to write my program?

答:
This task can be fulfilled using one-pass algorithm. There is no need to use any collections (arrays, sets or anything).

This one-pass algorithm is memory efficient - it does not require storing all elements in collection (and wasting memory) and will work even with large number of elements when other solutions fail with out of memory.

General idea of this algorithm is like this:

take each number in order

you need two variables to store minimum and second minimum numbers from all already seen numbers.

when you get number you need to test it with current minumum to find if it is new minimum number.

if it is store it as minimum, store old minimum in second minimumnumber

otherwise check if it is less than second minimum number.

if it is store it as second minimum number.

now second minimum number contains answer for all already seen numbers.

repeat while there numbers that was not seen.

After investigating all numbers second minimum contain the answer.

Here is implementation with c++17 (link to wandbox):

```<code>#include <iostream>
#include <optional>

int main()
{
    int a, b, c, d, e;
    std::cin >> a >> b >> c >> d >> e;

    // you can find second minimal number while going through each number once
    auto find_current_answer = [minimum = std::optional<int>{}, next_to_minimum = std::optional<int>{}](int next) mutable {
        // when receiving next number
        // 1. check if it is new minimum
        if (!minimum || minimum > next) {
            // move values like this: next_to_minimum <- minimum <- next
            next_to_minimum = std::exchange(minimum, next);
        }
        // 2. else check if it is new next_to_minimum
        else if (!next_to_minimum || next_to_minimum > next) {
            next_to_minimum = next;
        }
        // 3. return current answer
        return next_to_minimum;
    };

    // repeat as much as you like
    find_current_answer(a);
    find_current_answer(b);
    find_current_answer(c);
    find_current_answer(d);
    // store answer that is interesting to you
    auto result = find_current_answer(e);

    // if it has value - it is the answer
    if (result) {
        std::cout << "Answer: " << *result << '\n';
    }
    else {
        std::cout << "Not enough numbers!\n";
    }
}
</code>```

Body:
I tried to write a program that receive from the user 5 integers and print the second minimum number.

Here is a sample of what I've tried:

#include <iostream>
using namespace std;
int main () {
int a,b,c,d,e;
cin>>a>>b>>c>>d>>e;
if (a>b && a<c && a<d && a<e)
    cout<<a<<endl;
if (b>a && b<c && b<d && b<e)
    cout<<b<<endl;
if (c>a && c<b && c<d && c<e)
    cout<<c<<endl;
if (d>a && d<b && d<c && d<e)
    cout <<d<<endl;
if (e>a && e<b && e<c && e<d)
cout <<e<<endl;
return 0;

}

When I enter 1 2 3 4 5 it prints the second minimum, but when I enter

5 4 3 2 1 Nothing will print on the screen. What am I doing wrong with this? Is there any other way to write my program?

Body:
This task can be fulfilled using one-pass algorithm. There is no need to use any collections (arrays, sets or anything).

This one-pass algorithm is memory efficient - it does not require storing all elements in collection (and wasting memory) and will work even with large number of elements when other solutions fail with out of memory.

General idea of this algorithm is like this:

take each number in order

you need two variables to store minimum and second minimum numbers from all already seen numbers.

when you get number you need to test it with current minumum to find if it is new minimum number.

if it is store it as minimum, store old minimum in second minimumnumber

otherwise check if it is less than second minimum number.

if it is store it as second minimum number.

now second minimum number contains answer for all already seen numbers.

repeat while there numbers that was not seen.

After investigating all numbers second minimum contain the answer.

Here is implementation with c++17 (link to wandbox):

#include <iostream>
#include <optional>

int main()
{
    int a, b, c, d, e;
    std::cin >> a >> b >> c >> d >> e;

    // you can find second minimal number while going through each number once
    auto find_current_answer = [minimum = std::optional<int>{}, next_to_minimum = std::optional<int>{}](int next) mutable {
        // when receiving next number
        // 1. check if it is new minimum
        if (!minimum || minimum > next) {
            // move values like this: next_to_minimum <- minimum <- next
            next_to_minimum = std::exchange(minimum, next);
        }
        // 2. else check if it is new next_to_minimum
        else if (!next_to_minimum || next_to_minimum > next) {
            next_to_minimum = next;
        }
        // 3. return current answer
        return next_to_minimum;
    };

    // repeat as much as you like
    find_current_answer(a);
    find_current_answer(b);
    find_current_answer(c);
    find_current_answer(d);
    // store answer that is interesting to you
    auto result = find_current_answer(e);

    // if it has value - it is the answer
    if (result) {
        std::cout << "Answer: " << *result << '\n';
    }
    else {
        std::cout << "Not enough numbers!\n";
    }
}


问:
VueJS not creating Input Fields
Anyone know why when I click on the addEditNewPOEntry it does not create a new row of empty inputs for the user to fill out?

```<code><div class="row" v-for="po in task.pos" :key="po.purchase_order">
    <div class="col-12 col-sm-6">
        <div class="form-group">
            <label class="control-label" for="po_number">Order Number:</label>
            <input id="po_number" class="form-control" type="text" placeholder="Purchase Order" v-model="po.purchase_order" :key="po.id">
        </div>
    </div>
    <div class="col-12 col-sm-6">
        <div class="form-group">
            <label class="control-label" for="po_amount">Order: Amount:</label>
            <input id="po_amount" class="form-control" type="text" placeholder="Purchase Amount" v-model="po.po_amount" :key="">
        </div>
    </div>
</div>
<div class="form-group">
    <button class="btn btn-success btn-xs mb5 text-white" @click.prevent="addEditNewPOEntry(task)"><i class="fa fa-plus"></i> Add PO</button>
    <button class="btn btn-warning btn-block btn-xs" v-on:click.prevent="saveEdit(task)">Done</button>
</div>

addEditNewPOEntry: function (task) {
    task.pos.push({purchase_order: ' ', po_amount: ''});
},
</code>```

Here is the included data attached to the vue model.

```<code>data:
    tasks:Array[1]
        0:Object
           id:40
           name:"Test Name"
           pos:Array[2]
               0:Object
               1:Object
          purchase_order:"[{\"purchase_order\":\"afdasfd\",\"po_amount\":\"32.00\"}]"
</code>```

答:
Unfortunately we can't see the structure of your data, so I can't say for certain, but your issue is likely due to Vue list/object change detection caveats. Mutated objects/arrays may require replacement with a clone in order to ensure that the changes are detected correctly so that re-rendering may be triggered.

Edit

Given the structure of your data, I suspect that the issue is as I described. You're modifying a piece of data that is structured (roughly) as array => object => array. I'm honestly not sure which parts of this structure need to be forcefully detected, but the following lines would force the entire set of data to have its changes detected:

```<code>var this_vue_instance = this;
this_vue_instance.tasks.forEach(function(task, task_index) {
    task.pos.forEach(function(po, po_index) {
        task.pos[po_index] = Object.assign({}, po); //forces individual po object to update
    });
    task.pos = task.pos.slice(); //forces pos array to update
    this_vue_instance.tasks[task_index] = Object.assign({}, task); //forces individual task object to update
});
this_vue_instance.tasks = this_vue_instance.tasks.slice(); //forces tasks array to update
</code>```

This is an incredibly inefficient way to force change detections, some of these steps are probably unnecessary, and I really don't recommend this approach if you can avoid it, but feel free to toy around with it and see if it makes things work. This is meant more to be an instructive experiment to help you narrow down the issue, understand the Vue object/list change detection caveats, and aid in further researching solutions. You're absolutely welcome to use the solution if it works, but be aware of potential performance issues on larger data sets.

Title: VueJS not creating Input Fields

Body:
Anyone know why when I click on the addEditNewPOEntry it does not create a new row of empty inputs for the user to fill out?

            Order Number:
            <input id="po_number" class="form-control" type="text" placeholder="Purchase Order" v-model="po.purchase_order" :key="po.id">

            Order: Amount:
            <input id="po_amount" class="form-control" type="text" placeholder="Purchase Amount" v-model="po.po_amount" :key="">

    <button class="btn btn-success btn-xs mb5 text-white" @click.prevent="addEditNewPOEntry(task)"> Add PO</button>
    <button class="btn btn-warning btn-block btn-xs" v-on:click.prevent="saveEdit(task)">Done</button>

addEditNewPOEntry: function (task) {
    task.pos.push({purchase_order: ' ', po_amount: ''});
},

Here is the included data attached to the vue model.

data:
    tasks:Array[1]
        0:Object
           id:40
           name:"Test Name"
           pos:Array[2]
               0:Object
               1:Object
          purchase_order:"[{\"purchase_order\":\"afdasfd\",\"po_amount\":\"32.00\"}]"

Body:
Unfortunately we can't see the structure of your data, so I can't say for certain, but your issue is likely due to Vue list/object change detection caveats. Mutated objects/arrays may require replacement with a clone in order to ensure that the changes are detected correctly so that re-rendering may be triggered.

Edit

Given the structure of your data, I suspect that the issue is as I described. You're modifying a piece of data that is structured (roughly) as array => object => array. I'm honestly not sure which parts of this structure need to be forcefully detected, but the following lines would force the entire set of data to have its changes detected:

var this_vue_instance = this;
this_vue_instance.tasks.forEach(function(task, task_index) {
    task.pos.forEach(function(po, po_index) {
        task.pos[po_index] = Object.assign({}, po); //forces individual po object to update
    });
    task.pos = task.pos.slice(); //forces pos array to update
    this_vue_instance.tasks[task_index] = Object.assign({}, task); //forces individual task object to update
});
this_vue_instance.tasks = this_vue_instance.tasks.slice(); //forces tasks array to update

This is an incredibly inefficient way to force change detections, some of these steps are probably unnecessary, and I really don't recommend this approach if you can avoid it, but feel free to toy around with it and see if it makes things work. This is meant more to be an instructive experiment to help you narrow down the issue, understand the Vue object/list change detection caveats, and aid in further researching solutions. You're absolutely welcome to use the solution if it works, but be aware of potential performance issues on larger data sets.

ContentLicense: CC BY-SA 4.0


问:
Java Configuration vs Component Scan Annotations
Java configuration allows us to manage bean creation within a configuration file. Annotated @Component, @Service classes used with component scanning does the same. However, I'm concerned about using these two mechanisms at the same time.

Should Java configuration and annotated component scans be avoided in the same project? I ask because the result is unclear in the following scenario:

```<code>@Configuration
public class MyConfig {
    @Bean
    public Foo foo() {
        return new Foo(500);
    }
}

...

@Component
public class Foo {
    private int value;

    public Foo() {
    }
    public Foo(int value) {
        this.value = value;
    }
}

...

public class Consumer {
    @Autowired
    Foo foo;

    ...
}
</code>```

So, in the above situation, will the Consumer get a Foo instance with a 500 value or 0 value? I've tested locally and it appears that the Java configured Foo (with value 500) is created consistently. However, I'm concerned that my testing isn't thorough enough to be conclusive.

What is the real answer? Using both Java config and component scanning on @Component beans of the same type seems like a bad thing.

答:
In general, there is nothing wrong with component scanning and explicit bean definitions in the same application context. I tend to use component scanning where possible, and create the few beans that need more setup with @Bean methods.

There is no upside to include classes in the component scan when you create beans of their type explicitly. Component scanning can easily be targeted at certain classes and packages. If you design your packages accordingly, you can component scan only the packages without "special" bean classes (or else use more advanced filters on scanning).

In a quick look I didn't find any clear information about bean definition precedence in such a case. Typically there is a deterministic and fairly stable order in which these are processed, but if it is not documented it maybe could change in some future Spring version.

Body:
Java configuration allows us to manage bean creation within a configuration file. Annotated @Component, @Service classes used with component scanning does the same. However, I'm concerned about using these two mechanisms at the same time.

Should Java configuration and annotated component scans be avoided in the same project? I ask because the result is unclear in the following scenario:

@Configuration
public class MyConfig {
    @Bean
    public Foo foo() {
        return new Foo(500);
    }
}

...

@Component
public class Foo {
    private int value;

    public Foo() {
    }
    public Foo(int value) {
        this.value = value;
    }
}

...

public class Consumer {
    @Autowired
    Foo foo;

    ...
}

So, in the above situation, will the Consumer get a Foo instance with a 500 value or 0 value? I've tested locally and it appears that the Java configured Foo (with value 500) is created consistently. However, I'm concerned that my testing isn't thorough enough to be conclusive.

What is the real answer? Using both Java config and component scanning on @Component beans of the same type seems like a bad thing.


问:
How to split a huge folder?
We have a folder on Windows that's ... huge. I ran "dir > list.txt". The command lost response after 1.5 hours. The output file is about 200 MB. It shows there're at least 2.8 million files. I know the situation is stupid but let's focus the problem itself. If I have such a folder, how can I split it to some "manageable" sub-folders? Surprisingly all the solutions I have come up with all involve getting all the files in the folder at some point, which is a no-no in my case. Any suggestions?

Thank Keith Hill and Mehrdad. I accepted Keith's answer because that's exactly what I wanted to do but I couldn't quite get PS working quickly.

With Mehrdad's tip, I wrote this little program. It took 7+ hours to move 2.8 million files. So the initial dir command did finish. But somehow it didn't return to console.

```<code>namespace SplitHugeFolder
{
    class Program
    {
        static void Main(string[] args)
        {
            var destination = args[1];

            if (!Directory.Exists(destination))
                Directory.CreateDirectory(destination);

            var di = new DirectoryInfo(args[0]);

            var batchCount = int.Parse(args[2]);
            int currentBatch = 0;

            string targetFolder = GetNewSubfolder(destination);

            foreach (var fileInfo in di.EnumerateFiles())
            {
                if (currentBatch == batchCount)
                {
                    Console.WriteLine("New Batch...");
                    currentBatch = 0;
                    targetFolder = GetNewSubfolder(destination);
                }

                var source = fileInfo.FullName;
                var target = Path.Combine(targetFolder, fileInfo.Name);
                File.Move(source, target);
                currentBatch++;
            }
        }

        private static string GetNewSubfolder(string parent)
        {
            string newFolder;
            do
            {
                newFolder = Path.Combine(parent, Path.GetRandomFileName());
            } while (Directory.Exists(newFolder));
            Directory.CreateDirectory(newFolder);
            return newFolder;
        }
    }
}
</code>```

答:
How about starting with this:
    cmd /c dir /b > list.txt

That should get you a list of all the file names.

If you're doing "dir > list.txt" from a powershell prompt, get-childitem is aliased as "dir". Get-childitem has known issues enumerating large directories, and the object collections it returns can get huge.

ContentLicense: CC BY-SA 2.5

Title: How to split a huge folder?

Body:
We have a folder on Windows that's ... huge. I ran "dir > list.txt". The command lost response after 1.5 hours. The output file is about 200 MB. It shows there're at least 2.8 million files. I know the situation is stupid but let's focus the problem itself. If I have such a folder, how can I split it to some "manageable" sub-folders? Surprisingly all the solutions I have come up with all involve getting all the files in the folder at some point, which is a no-no in my case. Any suggestions?

Thank Keith Hill and Mehrdad. I accepted Keith's answer because that's exactly what I wanted to do but I couldn't quite get PS working quickly.

With Mehrdad's tip, I wrote this little program. It took 7+ hours to move 2.8 million files. So the initial dir command did finish. But somehow it didn't return to console.

namespace SplitHugeFolder
{
    class Program
    {
        static void Main(string[] args)
        {
            var destination = args[1];

            if (!Directory.Exists(destination))
                Directory.CreateDirectory(destination);

            var di = new DirectoryInfo(args[0]);

            var batchCount = int.Parse(args[2]);
            int currentBatch = 0;

            string targetFolder = GetNewSubfolder(destination);

            foreach (var fileInfo in di.EnumerateFiles())
            {
                if (currentBatch == batchCount)
                {
                    Console.WriteLine("New Batch...");
                    currentBatch = 0;
                    targetFolder = GetNewSubfolder(destination);
                }

                var source = fileInfo.FullName;
                var target = Path.Combine(targetFolder, fileInfo.Name);
                File.Move(source, target);
                currentBatch++;
            }
        }

        private static string GetNewSubfolder(string parent)
        {
            string newFolder;
            do
            {
                newFolder = Path.Combine(parent, Path.GetRandomFileName());
            } while (Directory.Exists(newFolder));
            Directory.CreateDirectory(newFolder);
            return newFolder;
        }
    }
}


问:
"Fuzzy Lookup" add in results
Using Excel 2010, and the Microsoft "Fuzzy Lookup" add in to compare a column out of 2 worksheets. First worksheet has around 48,000 rows (x 3 columns), second worksheet has around 23,000 rows (x 5 columns). The "Fuzzy Lookup" is comparing one column from each & returning a similarity between the two.

The fuzzy lookup appears to run without a problem, and the results - in most cases - appear to be correct. For example:

W2-NK22/16 in one worksheet shows to have a 0.97 similarity to W2NK2216.

But not in all cases. Some that I expected to have some degree of similarity, instead have 0.000 returned by the Add-In. For example:

```<code>761689700000
</code>```

should have some degree of similarity to:

```<code>761689700000EN4239
</code>```

but the Fuzzy Lookup add in returns 0.000 for it. Both fields are formatted as text.  Neither have spaces before or after them, and the first 12 characters are identical.

I have uninstalled & reinstalled the add-in, and have used the default settings.  The only other Fuzzy Lookup settings I have changed were in Configure --> Global -- UseApproximateIndexing. I have set it to both False and True which have had no impact.

I have hundreds of examples like the one above that show 0.000 similarity, but upon inspection appear to be very similar.  Rows before & after them show various degrees of similarity.

Any thoughts or ideas as to why this doesn't appear to function correctly, or a better way to do this approximate match would be appreciated.

答:
Trying to add content even though this case is 2 years old. Hopefully someone else can use it.

For Transformations, Tokenization, etc - look in the same folder where Fuzzy Lookup is installed. There is an example file there called Portfolio.xlsx and a corresponding Readme.docx file. Those are very helpful. Frankly the documentation on the Fuzzy Lookup add-in is terrible (but it is free). The Readme file talks about an entitlement called "EditTransformationProvider" that might help this kind of problem.

I've implemented Fuzzy on a couple processes at my work and we have saved hundreds of man-hours when working in Excel. It's no joke.

Title: "Fuzzy Lookup" add in results

Body:
Using Excel 2010, and the Microsoft "Fuzzy Lookup" add in to compare a column out of 2 worksheets. First worksheet has around 48,000 rows (x 3 columns), second worksheet has around 23,000 rows (x 5 columns). The "Fuzzy Lookup" is comparing one column from each & returning a similarity between the two.

The fuzzy lookup appears to run without a problem, and the results - in most cases - appear to be correct. For example:

W2-NK22/16 in one worksheet shows to have a 0.97 similarity to W2NK2216.

But not in all cases. Some that I expected to have some degree of similarity, instead have 0.000 returned by the Add-In. For example:

761689700000

should have some degree of similarity to:

761689700000EN4239

but the Fuzzy Lookup add in returns 0.000 for it. Both fields are formatted as text.  Neither have spaces before or after them, and the first 12 characters are identical.

I have uninstalled & reinstalled the add-in, and have used the default settings.  The only other Fuzzy Lookup settings I have changed were in Configure --> Global -- UseApproximateIndexing. I have set it to both False and True which have had no impact.

I have hundreds of examples like the one above that show 0.000 similarity, but upon inspection appear to be very similar.  Rows before & after them show various degrees of similarity.

Any thoughts or ideas as to why this doesn't appear to function correctly, or a better way to do this approximate match would be appreciated.


问:
Received length differs from sent length
I am using an Android app to send a base64 encoded string to a CherryPy server. The Android code works like this:

```<code>URL url = new URL("http://foo.bar/blabla");

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "application/octet-stream");
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(base64s.length());

OutputStream out = new BufferedOutputStream(conn.getOutputStream());
out.write(base64s.getBytes());
</code>```

So, you'd say the amount of bytes sent equals the amount of bytes in the Content-Length header. However, in Python, when I run this:

```<code>cl = cherrypy.request.headers['Content-Length']
rawbody = cherrypy.request.body.read()

print "{} bytes, {}".format(len(rawbody), cl)
</code>```

The numbers cl and len(rawbody) are different.

How can that be?

答: Maybe you forgot to close the stream with out.close(); ?

Body:
I am using an Android app to send a base64 encoded string to a CherryPy server. The Android code works like this:

URL url = new URL("http://foo.bar/blabla");

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "application/octet-stream");
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(base64s.length());

OutputStream out = new BufferedOutputStream(conn.getOutputStream());
out.write(base64s.getBytes());

So, you'd say the amount of bytes sent equals the amount of bytes in the Content-Length header. However, in Python, when I run this:

cl = cherrypy.request.headers['Content-Length']
rawbody = cherrypy.request.body.read()

print "{} bytes, {}".format(len(rawbody), cl)

The numbers cl and len(rawbody) are different.

How can that be?


问:
Python download youtube with specific filename
I'm trying to download youtube videos with pytube this way:

```<code>from pytube import YouTube
YouTube('http://youtube.com/watch?v=9bZkp7q19f0').streams.first().download()
</code>```

but the file will have the same name as the original video name. How do I specify a custom filename?

答:
UPDATE:

The feature is now added. Do this:

```<code>YouTube('http://youtube.com/watch?v=9bZkp7q19f0')
    .streams.first()
    .download(filename='filename')
</code>```

Old answer:

This is not possible in the current latest (v7.0.18) release. The feature has been added, but no new release has been released since then. If you want to have this feature, you need to download the pytube repository: https://github.com/NFicano/pytube

If you have done so, you can use YouTube('http://youtube.com/watch?v=9bZkp7q19f0').streams.first().download(filename='filename')

It will automatically add the filename extension, so you don't have to include that.

I found it by reading the source. There, I found the declaration of the function download in the file streams.py:

```<code>def download(self, output_path=None, filename=None):
</code>```

So you can obviously also specify a path.

For a good workaround, see landogardner's answer.

Body:
I'm trying to download youtube videos with pytube this way:

from pytube import YouTube
YouTube('http://youtube.com/watch?v=9bZkp7q19f0').streams.first().download()

but the file will have the same name as the original video name. How do I specify a custom filename?

Body:
UPDATE:

The feature is now added. Do this:

YouTube('http://youtube.com/watch?v=9bZkp7q19f0')
    .streams.first()
    .download(filename='filename')

Old answer:

This is not possible in the current latest (v7.0.18) release. The feature has been added, but no new release has been released since then. If you want to have this feature, you need to download the pytube repository: https://github.com/NFicano/pytube

If you have done so, you can use YouTube('http://youtube.com/watch?v=9bZkp7q19f0').streams.first().download(filename='filename')

It will automatically add the filename extension, so you don't have to include that.

I found it by reading the source. There, I found the declaration of the function download in the file streams.py:

def download(self, output_path=None, filename=None):

So you can obviously also specify a path.

For a good workaround, see landogardner's answer.


问:
Symfony3 fosuserbundle form for admin with group
i use Symfony3.3 and want to make a form for the admin administration. The user should be have a group and the group sould have the roles for the backend access.
The form for groups (name and roles) i finished and the form for the admins (name, passwort...) is finish too.
The admin will be find and have the group. If i load the admin it have the arraycollection with the groups.

Here my classes
admin:

```<code>class Admin extends BaseUser
{
    /**
     * @ORM\Id()
     * @ORM\Column(name="idAdmin", type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     * @ORM\Column(type="string", length=255, options={"default":NULL})
     */
    protected $style;

    /**
     * @ORM\ManyToMany(targetEntity="AdminBundle\Entity\AdminGroup")
     * @ORM\JoinTable(
     *     name="admin_has_group",
     *     joinColumns={
     *         @ORM\JoinColumn(name="idAdmin", referencedColumnName="idAdmin")
     *     },
     *     inverseJoinColumns={
     *         @ORM\JoinColumn(name="idGroup", referencedColumnName="idGroup")
     *     }
     * )
     */
    protected $groups;

    /**
     * @return string
     */
    public function getStyle()
    {
        return $this->style;
    }

    /**
     * @param string $style
     */
    public function setStyle($style)
    {
        $this->style = $style;

        return $this;
    }

    public function setGroups($groups)
    {

        $this->groups = $groups;

        return $this;
    }

    public function getGroups()
    {
        return $this->groups;
    }
}
</code>```

groups

```<code>class AdminGroup extends BaseGroup
{
    /**
     * @var int
     * @ORM\Id
     * @ORM\Column(name="idGroup", type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * Group constructor.
     *
     * @param string $name
     * @param array  $roles
     */
    public function __construct($name = '', $roles = array())
    {
        parent::__construct($name, $roles);
    }
}
</code>```

form generation

```<code>$admin = $this->getDoctrine()->getRepository(Admin::class)->find(1);
$admingroupList = $this->getDoctrine()->getRepository(AdminGroup::class)->findAll();
$form  = $this->createFormBuilder($admin)
    ->add("username", TextType::class)
    ->add('plainPassword', PasswordType::class, $passwordSettings)
    ->add(
        'groups', ChoiceType::class, [
        'required' => false,
        'multiple' => true,
        'choices'  => $admingroupList,
    ])
    ->add('save', SubmitType::class, ['label' => 'Save'])->getForm()->createView();
</code>```

save form

```<code>$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {

    $user = $form->getData();

    $em->persist($user);
    $em->flush();

    ....
}
</code>```

The first problem is that i have in the overview only display the id's in the select.
The second problem is that i submit the form (with selected groups) symfony crashed with the following message

Call to a member function contains() on array

I try to convert the grouplist to an normal array they will be crashed at the save the data

Expected argument of type "FOS\UserBundle\Model\GroupInterface", "integer" given

I dont know that i sould do to make a simple symfony form with the admin data and group selection... i dont find any example for a form with fosuserbundle...

Have someone an idea what i can to without manipulate the fosuserbundle entites or the symfonycode?

If you need more source, tell me with part :)

Editing 10.12.17
I try to convert the ChoosenArray into this format

```<code>$list = [
'user' => 0,
'admin' => 1
];
</code>```

but than it will be broken at

```<code>$form->handleRequest($request);
</code>```

with the error:

Expected argument of type "FOS\UserBundle\Model\GroupInterface", "integer" given

答:
I do not think the data returned from

```<code> $admingroupList = $this->getDoctrine()->getRepository(AdminGroup::class)->findAll();
</code>```

Will work as you want it too. choices wants something like this

```<code>'choices' => [
    'Admin' => 'admin',
    'User' => 'user'
]
</code>```

Where the key of the array is the name the user sees, and the value of the array is the value used in the <option>.

You probably need to manipulate the $admingroupList array to mimic the demo array above. Or write your own query in the AdminGroup Repo to return a pre-formatted array for use with a Symfony form.

Body:
i use Symfony3.3 and want to make a form for the admin administration. The user should be have a group and the group sould have the roles for the backend access.
The form for groups (name and roles) i finished and the form for the admins (name, passwort...) is finish too.
The admin will be find and have the group. If i load the admin it have the arraycollection with the groups.

Here my classes
admin:

class Admin extends BaseUser
{
    /**
     * @ORM\Id()
     * @ORM\Column(name="idAdmin", type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     * @ORM\Column(type="string", length=255, options={"default":NULL})
     */
    protected $style;

    /**
     * @ORM\ManyToMany(targetEntity="AdminBundle\Entity\AdminGroup")
     * @ORM\JoinTable(
     *     name="admin_has_group",
     *     joinColumns={
     *         @ORM\JoinColumn(name="idAdmin", referencedColumnName="idAdmin")
     *     },
     *     inverseJoinColumns={
     *         @ORM\JoinColumn(name="idGroup", referencedColumnName="idGroup")
     *     }
     * )
     */
    protected $groups;

    /**
     * @return string
     */
    public function getStyle()
    {
        return $this->style;
    }

    /**
     * @param string $style
     */
    public function setStyle($style)
    {
        $this->style = $style;

        return $this;
    }

    public function setGroups($groups)
    {

        $this->groups = $groups;

        return $this;
    }

    public function getGroups()
    {
        return $this->groups;
    }
}

groups

class AdminGroup extends BaseGroup
{
    /**
     * @var int
     * @ORM\Id
     * @ORM\Column(name="idGroup", type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * Group constructor.
     *
     * @param string $name
     * @param array  $roles
     */
    public function __construct($name = '', $roles = array())
    {
        parent::__construct($name, $roles);
    }
}

form generation

$admin = $this->getDoctrine()->getRepository(Admin::class)->find(1);
$admingroupList = $this->getDoctrine()->getRepository(AdminGroup::class)->findAll();
$form  = $this->createFormBuilder($admin)
    ->add("username", TextType::class)
    ->add('plainPassword', PasswordType::class, $passwordSettings)
    ->add(
        'groups', ChoiceType::class, [
        'required' => false,
        'multiple' => true,
        'choices'  => $admingroupList,
    ])
    ->add('save', SubmitType::class, ['label' => 'Save'])->getForm()->createView();

save form

$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {

    $user = $form->getData();

    $em->persist($user);
    $em->flush();

    ....
}

The first problem is that i have in the overview only display the id's in the select.
The second problem is that i submit the form (with selected groups) symfony crashed with the following message

Call to a member function contains() on array

I try to convert the grouplist to an normal array they will be crashed at the save the data

Expected argument of type "FOS\UserBundle\Model\GroupInterface", "integer" given

I dont know that i sould do to make a simple symfony form with the admin data and group selection... i dont find any example for a form with fosuserbundle...

Have someone an idea what i can to without manipulate the fosuserbundle entites or the symfonycode?

If you need more source, tell me with part :)

Editing 10.12.17
I try to convert the ChoosenArray into this format

$list = [
'user' => 0,
'admin' => 1
];

but than it will be broken at

$form->handleRequest($request);

with the error:

Expected argument of type "FOS\UserBundle\Model\GroupInterface", "integer" given

Body:
I do not think the data returned from

 $admingroupList = $this->getDoctrine()->getRepository(AdminGroup::class)->findAll();

Will work as you want it too. choices wants something like this

'choices' => [
    'Admin' => 'admin',
    'User' => 'user'
]

Where the key of the array is the name the user sees, and the value of the array is the value used in the <option>.

You probably need to manipulate the $admingroupList array to mimic the demo array above. Or write your own query in the AdminGroup Repo to return a pre-formatted array for use with a Symfony form.


问:
NumberFormatter - ObjectiveC
How do I create a number formatter for formatting large numbers with commas?

For example, 2389378.289 should become 2,389,378.289

Note that there is not always three decimal places, nor is there always a decimal at all. Please use NSNumberFormatter.

Thanks!

答:
```<code>NSNumberFormatter *fmt = [[[NSNumberFormatter alloc] init] autorelease];
[fmt setAlwaysShowsDecimalSeparator:NO];
[fmt setFormat:@"#,##0.###"];
NSLog(@"%@",[fmt stringFromNumber:[NSNumber numberWithFloat:35.424252]]);
NSLog(@"%@",[fmt stringFromNumber:[NSNumber numberWithFloat:21.3]]);
NSLog(@"%@",[fmt stringFromNumber:[NSNumber numberWithFloat:10392425]]);
</code>```

The format Chuck gave you supports up to 3 decimal places.  If you have a number with less than 3 they just don't show up.  Chuck is also correct that you want to take a look at the Unicode number format guide, it is invaluable for number formatting issues.

Title: NumberFormatter - ObjectiveC

Body:
NSNumberFormatter *fmt = [[[NSNumberFormatter alloc] init] autorelease];
[fmt setAlwaysShowsDecimalSeparator:NO];
[fmt setFormat:@"#,##0.###"];
NSLog(@"%@",[fmt stringFromNumber:[NSNumber numberWithFloat:35.424252]]);
NSLog(@"%@",[fmt stringFromNumber:[NSNumber numberWithFloat:21.3]]);
NSLog(@"%@",[fmt stringFromNumber:[NSNumber numberWithFloat:10392425]]);

The format Chuck gave you supports up to 3 decimal places.  If you have a number with less than 3 they just don't show up.  Chuck is also correct that you want to take a look at the Unicode number format guide, it is invaluable for number formatting issues.


问:
RxJS switchMap and different observables
New to Angular and RxJS, trying to understand this a bit... my app reacts to a UI event and that results in making a call out to a HTTP service that returns an Observable.  I subscribe to it like so:

```<code>this.myXYZService.search(query)
  .map(r => { // some code })
  .subscribe(r => { //some code });
</code>```

Say that event triggers again and it results in making a second call out to the same HTTP service that will return a brand new Observable BEFORE the 1st call finishes.

Now, as I understand it I can use switchMap instead of map to discard the old Observable and operate on the new Observable?  Or am I understanding this incorrectly?  And what happens if the second event triggers after the 1st event is already in the subscribe part of the chain? In this case it will no longer switch?  And since JS is synchronous wouldn't the entire 1st chain execute anyway before the 2nd event even starts processing its chain?

I guess I am confused by the whole thing because the instances of the Observables are different - how does Rx keep track which call to switch?? Is it by the function name? Say I have 2 separate blocks of code:

```<code>this.myXYZService.search('abcd')
  .map(r => { // some code })
  .subscribe(r => { //some code });

this.myXYZService.search('efgh')
  .map(r => { // some code })
  .subscribe(r => { //some code });
</code>```

if I use switchMap on both of the above what exactly happens? Does the second call cancel out the first?

答:
switchMap cancels the previous inner observable when the outer observable emits. For example

```<code>Observable.fromEvent(inputEl, 'keydown') // outer observable
    .switchMap(event => {
        let value = event.value;

        return this.myXYZService.search(value); // inner observable
    })
    .subscribe(res => {
        // some code
    });
</code>```

In this case, every time the outer observable (fromEvent) emits (on keydown of input element), the inner observable (myXYZService.search) is called and the previous inner observable is cancelled.

Body:
New to Angular and RxJS, trying to understand this a bit... my app reacts to a UI event and that results in making a call out to a HTTP service that returns an Observable.  I subscribe to it like so:

this.myXYZService.search(query)
  .map(r => { // some code })
  .subscribe(r => { //some code });

Say that event triggers again and it results in making a second call out to the same HTTP service that will return a brand new Observable BEFORE the 1st call finishes.

Now, as I understand it I can use switchMap instead of map to discard the old Observable and operate on the new Observable?  Or am I understanding this incorrectly?  And what happens if the second event triggers after the 1st event is already in the subscribe part of the chain? In this case it will no longer switch?  And since JS is synchronous wouldn't the entire 1st chain execute anyway before the 2nd event even starts processing its chain?

I guess I am confused by the whole thing because the instances of the Observables are different - how does Rx keep track which call to switch?? Is it by the function name? Say I have 2 separate blocks of code:

this.myXYZService.search('abcd')
  .map(r => { // some code })
  .subscribe(r => { //some code });

this.myXYZService.search('efgh')
  .map(r => { // some code })
  .subscribe(r => { //some code });

if I use switchMap on both of the above what exactly happens? Does the second call cancel out the first?

Body:
switchMap cancels the previous inner observable when the outer observable emits. For example

Observable.fromEvent(inputEl, 'keydown') // outer observable
    .switchMap(event => {
        let value = event.value;

        return this.myXYZService.search(value); // inner observable
    })
    .subscribe(res => {
        // some code
    });

In this case, every time the outer observable (fromEvent) emits (on keydown of input element), the inner observable (myXYZService.search) is called and the previous inner observable is cancelled.


问:
In-place Python dictionary inverse
The task that I wanted to see if possible to solve is, swapping key,value pairs of a dictionary (in Python), with an in-place calculation, without additional data-structures (Only a constant number of extra variables). It seems rather impossible (in a finite world), but I'm open to hear suggestions on solving it.

I've seen a few posts about in-place dictionary inverse in python, and I've found one common thing between all of the solutions.
The following dictionary won't be properly inversed:

```<code>dict = {'b':'a','a':'c','c':123}
</code>```

The reason for that is, when swapping the first argument, we overwrite 'a''s actual value (The values are unique, the keys are unique, but that doesn't mean there isn't a value that is the same as an already existing key)

NOTES:

1) The dictionary given as an example has hashable values.

2) The key/values can be of any data-type. Not necessarily strings.

I'd love to hear ways to solve it, I've thought of one but it only works if we have infinite memory, which obviously is not true.

EDIT:

1) My Idea was, changing the dictionary such that I add a constant number of underscores ("_") to the beginning of each key entry. The number of underscores is determined based on the keys, if some key has X underscores, I'll add X+1 underscores (max_underscores_of_key_in_prefix+1).
To work around objects in the keys, I'll make a wrapper class for that.
I have tried my best explaining my intuition, but I am not sure this is practical.

2) @Mark Ransom's solution works perfectly, but if anyone has an other algorithmic solution to the problem, I'd still love to hear it out!
I mark this question as solved because it is solved, but again, other solutions are more than welcome :-)

答:
Obviously for this to be possible, both keys and values must be hashable. This means that none of your keys or values can be a list. We can take advantage of this to know which dictionary elements have been already processed.

Since you can't iterate and modify a dictionary at the same time, we must start over every time we swap a key/value. That makes this very slow, an O(n^2) operation.

```<code>def invert_dict(d):
    done = False
    while not done:
        done = True
        for key, val in d.items():
            if isinstance(val, list):
                if len(val) > 1:
                    d[key] = [val[1]]
                    val = val[0]
            else:
                del d[key]
            if not isinstance(val, list):
                if val in d:
                    d[val] = [d[val], key]
                else:
                    d[val] = [key]
                done = False
                break
    for key, val in d.items():
        d[key] = val[0]
</code>```

Title: In-place Python dictionary inverse

Body:
The task that I wanted to see if possible to solve is, swapping key,value pairs of a dictionary (in Python), with an in-place calculation, without additional data-structures (Only a constant number of extra variables). It seems rather impossible (in a finite world), but I'm open to hear suggestions on solving it.

I've seen a few posts about in-place dictionary inverse in python, and I've found one common thing between all of the solutions.
The following dictionary won't be properly inversed:

dict = {'b':'a','a':'c','c':123}

The reason for that is, when swapping the first argument, we overwrite 'a''s actual value (The values are unique, the keys are unique, but that doesn't mean there isn't a value that is the same as an already existing key)

NOTES:

1) The dictionary given as an example has hashable values.

2) The key/values can be of any data-type. Not necessarily strings.

I'd love to hear ways to solve it, I've thought of one but it only works if we have infinite memory, which obviously is not true.

EDIT:

1) My Idea was, changing the dictionary such that I add a constant number of underscores ("_") to the beginning of each key entry. The number of underscores is determined based on the keys, if some key has X underscores, I'll add X+1 underscores (max_underscores_of_key_in_prefix+1).
To work around objects in the keys, I'll make a wrapper class for that.
I have tried my best explaining my intuition, but I am not sure this is practical.

2) @Mark Ransom's solution works perfectly, but if anyone has an other algorithmic solution to the problem, I'd still love to hear it out!
I mark this question as solved because it is solved, but again, other solutions are more than welcome :-)

Body:
Obviously for this to be possible, both keys and values must be hashable. This means that none of your keys or values can be a list. We can take advantage of this to know which dictionary elements have been already processed.

Since you can't iterate and modify a dictionary at the same time, we must start over every time we swap a key/value. That makes this very slow, an O(n^2) operation.

def invert_dict(d):
    done = False
    while not done:
        done = True
        for key, val in d.items():
            if isinstance(val, list):
                if len(val) > 1:
                    d[key] = [val[1]]
                    val = val[0]
            else:
                del d[key]
            if not isinstance(val, list):
                if val in d:
                    d[val] = [d[val], key]
                else:
                    d[val] = [key]
                done = False
                break
    for key, val in d.items():
        d[key] = val[0]


答:
You would want something like...

searchTerms.switchMap(
  searchTerm => this.myXYZService.search(searchTerm)
).subscribe(...)

As soon as a new search term arrives then any in-progress search calls will be ignored / discarded.  I wouldn't use the word cancelled because the call still goes out.  However, their result will be ignored.

If the first request returns before the second search term is emitted then it will be sent to the subscription.  If it doesn't then it will not.

Title: RxJS switchMap and different observables


问:
Angular2 Cli installation problems
I want to give a shot at angular 2 so I'm working to install angular2 cli now, but when I install it and then run ng new newapp , it awkwardly opens the command line and says something about 'mg' (not even 'ng').

Here's what happens when I run 'ng new myapp'

I'm running sudo npm install -g angular-cli@latest which gives the following output:

```<code>npm WARN engine angular-cli@1.0.0-beta.19-3: wanted: {"node":">= 4.1.0","npm":">= 3.0.0"} (current: {"node":"4.6.1","npm":"2.15.9"})
npm WARN engine @ngtools/webpack@1.1.4: wanted: {"node":">= 4.1.0","npm":">= 3.0.0"} (current: {"node":"4.6.1","npm":"2.15.9"})
npm WARN engine @angular-cli/ast-tools@1.0.7: wanted: {"node":">= 4.1.0","npm":">= 3.0.0"} (current: {"node":"4.6.1","npm":"2.15.9"})
npm WARN optional dep failed, continuing fsevents@1.0.15
npm WARN deprecated graceful-fs@1.2.3: graceful-fs v3.0.0 and before will fail on node releases >= v7.0. Please update to graceful-fs@^4.0.0 as soon as possible. Use 'npm ls graceful-fs' to find it in the tree.

> execSync@1.0.2 install /home/user/.npm-packages/lib/node_modules/angular-cli/node_modules/angular2-template-loader/node_modules/codecov/node_modules/execSync
> node install.js

[execsync v1.0.2] Attempting to compile native extensions.
[execSync v1.0.2]
    Native code compile failed!!
npm WARN deprecated tough-cookie@2.2.2: ReDoS vulnerability parsing Set-Cookie https://nodesecurity.io/advisories/130
npm WARN deprecated minimatch@0.3.0: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated minimatch@2.0.10: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue

> node-zopfli@2.0.1 install /home/user/.npm-packages/lib/node_modules/angular-cli/node_modules/compression-webpack-plugin/node_modules/node-zopfli
> node-pre-gyp install --fallback-to-build

node-pre-gyp ERR! Tried to download(403): https://node-zopfli.s3.amazonaws.com/Release/zopfli-v2.0.1-node-v46-linux-x64.tar.gz
node-pre-gyp ERR! Pre-built binaries not found for node-zopfli@2.0.1 and node@4.6.1 (node-v46 ABI) (falling back to source compile with node-gyp)
make: Entering directory '/home/user/.npm-packages/lib/node_modules/angular-cli/node_modules/compression-webpack-plugin/node_modules/node-zopfli/build'
  CXX(target) Release/obj.target/zopfli/src/zopfli-binding.o
  CXX(target) Release/obj.target/zopfli/src/png/zopflipng.o
  CC(target) Release/obj.target/zopfli/zopfli/src/zopfli/blocksplitter.o
  CC(target) Release/obj.target/zopfli/zopfli/src/zopfli/cache.o
  CC(target) Release/obj.target/zopfli/zopfli/src/zopfli/deflate.o
  CC(target) Release/obj.target/zopfli/zopfli/src/zopfli/gzip_container.o
  CC(target) Release/obj.target/zopfli/zopfli/src/zopfli/hash.o
  CC(target) Release/obj.target/zopfli/zopfli/src/zopfli/katajainen.o
  CC(target) Release/obj.target/zopfli/zopfli/src/zopfli/lz77.o
In file included from ../zopfli/src/zopfli/lz77.c:21:0:
../zopfli/src/zopfli/symbols.h:38:12: warning: ‘ZopfliGetDistExtraBits’ defined but not used [-Wunused-function]
 static int ZopfliGetDistExtraBits(int dist) {
            ^
../zopfli/src/zopfli/symbols.h:61:12: warning: ‘ZopfliGetDistExtraBitsValue’ defined but not used [-Wunused-function]
 static int ZopfliGetDistExtraBitsValue(int dist) {
            ^
../zopfli/src/zopfli/symbols.h:138:12: warning: ‘ZopfliGetLengthExtraBits’ defined but not used [-Wunused-function]
 static int ZopfliGetLengthExtraBits(int l) {
            ^
../zopfli/src/zopfli/symbols.h:161:12: warning: ‘ZopfliGetLengthExtraBitsValue’ defined but not used [-Wunused-function]
 static int ZopfliGetLengthExtraBitsValue(int l) {
            ^
../zopfli/src/zopfli/symbols.h:222:12: warning: ‘ZopfliGetLengthSymbolExtraBits’ defined but not used [-Wunused-function]
 static int ZopfliGetLengthSymbolExtraBits(int s) {
            ^
../zopfli/src/zopfli/symbols.h:231:12: warning: ‘ZopfliGetDistSymbolExtraBits’ defined but not used [-Wunused-function]
 static int ZopfliGetDistSymbolExtraBits(int s) {
            ^
  CC(target) Release/obj.target/zopfli/zopfli/src/zopfli/squeeze.o
In file included from ../zopfli/src/zopfli/squeeze.c:28:0:
../zopfli/src/zopfli/symbols.h:61:12: warning: ‘ZopfliGetDistExtraBitsValue’ defined but not used [-Wunused-function]
 static int ZopfliGetDistExtraBitsValue(int dist) {
            ^
../zopfli/src/zopfli/symbols.h:161:12: warning: ‘ZopfliGetLengthExtraBitsValue’ defined but not used [-Wunused-function]
 static int ZopfliGetLengthExtraBitsValue(int l) {
            ^
../zopfli/src/zopfli/symbols.h:222:12: warning: ‘ZopfliGetLengthSymbolExtraBits’ defined but not used [-Wunused-function]
 static int ZopfliGetLengthSymbolExtraBits(int s) {
            ^
../zopfli/src/zopfli/symbols.h:231:12: warning: ‘ZopfliGetDistSymbolExtraBits’ defined but not used [-Wunused-function]
 static int ZopfliGetDistSymbolExtraBits(int s) {
            ^
  CC(target) Release/obj.target/zopfli/zopfli/src/zopfli/tree.o
  CC(target) Release/obj.target/zopfli/zopfli/src/zopfli/util.o
  CC(target) Release/obj.target/zopfli/zopfli/src/zopfli/zlib_container.o
  CC(target) Release/obj.target/zopfli/zopfli/src/zopfli/zopfli_lib.o
  CXX(target) Release/obj.target/zopfli/zopfli/src/zopflipng/zopflipng_lib.o
  CXX(target) Release/obj.target/zopfli/zopfli/src/zopflipng/lodepng/lodepng.o
  CXX(target) Release/obj.target/zopfli/zopfli/src/zopflipng/lodepng/lodepng_util.o
  SOLINK_MODULE(target) Release/obj.target/zopfli.node
  COPY Release/zopfli.node
  COPY /home/user/.npm-packages/lib/node_modules/angular-cli/node_modules/compression-webpack-plugin/node_modules/node-zopfli/lib/binding/node-v46-linux-x64/zopfli.node
  TOUCH Release/obj.target/action_after_build.stamp
make: Leaving directory '/home/user/.npm-packages/lib/node_modules/angular-cli/node_modules/compression-webpack-plugin/node_modules/node-zopfli/build'
npm WARN optional dep failed, continuing fsevents@1.0.15
npm WARN deprecated lodash-node@2.4.1: This package is discontinued. Use lodash@^4.0.0.
|
> node-sass@3.11.2 install /home/user/.npm-packages/lib/node_modules/angular-cli/node_modules/node-sass
> node scripts/install.js

Start downloading binary at https://github.com/sass/node-sass/releases/download/v3.11.2/linux-x64-46_binding.node
Binary downloaded and installed at /home/user/.npm-packages/lib/node_modules/angular-cli/node_modules/node-sass/vendor/linux-x64-46/binding.node

> node-sass@3.11.2 postinstall /home/user/.npm-packages/lib/node_modules/angular-cli/node_modules/node-sass
> node scripts/build.js

"/home/user/.npm-packages/lib/node_modules/angular-cli/node_modules/node-sass/vendor/linux-x64-46/binding.node" exists.
 testing binary.
Binary is fine; exiting.
/home/user/.npm-packages/bin/ng -> /home/user/.npm-packages/lib/node_modules/angular-cli/bin/ng
angular-cli@1.0.0-beta.19-3 /home/user/.npm-packages/lib/node_modules/angular-cli
├── ember-cli-string-utils@1.0.0
├── json-loader@0.5.4
├── raw-loader@0.5.1
├── expose-loader@0.7.1
├── script-loader@0.7.0
├── symlink-or-copy@1.1.6
├── fs.realpath@1.0.0
├── rimraf@2.5.4
├── @angular-cli/base-href-webpack@1.0.6
├── denodeify@1.2.1
├── exit@0.1.2
├── karma-sourcemap-loader@0.3.7 (graceful-fs@4.1.10)
├── @ngtools/webpack@1.1.4
├── parse5@2.2.3
├── chalk@1.1.3 (escape-string-regexp@1.0.5, ansi-styles@2.2.1, supports-color@2.0.0, strip-ansi@3.0.1, has-ansi@2.0.0)
├── file-loader@0.8.5 (loader-utils@0.2.16)
├── url-loader@0.5.7 (mime@1.2.11, loader-utils@0.2.16)
├── opn@4.0.1 (object-assign@4.1.0, pinkie-promise@2.0.1)
├── style-loader@0.13.1 (loader-utils@0.2.16)
├── sass-loader@3.2.3 (object-assign@4.1.0, async@1.5.2, loader-utils@0.2.16)
├── silent-error@1.0.1 (debug@2.2.0)
├── zone.js@0.6.26
├── @angular/platform-server@2.1.2
├── fs-extra@0.30.0 (path-is-absolute@1.0.1, klaw@1.3.1, graceful-fs@4.1.10, jsonfile@2.4.0)
├── glob@7.1.1 (path-is-absolute@1.0.1, inherits@2.0.3, inflight@1.0.6, once@1.4.0, minimatch@3.0.3)
├── ts-loader@0.8.2 (object-assign@2.1.1, arrify@1.0.1, semver@5.3.0, colors@1.1.2, loader-utils@0.2.16, enhanced-resolve@0.9.1)
├── tslint-loader@2.1.5 (object-assign@4.1.0, strip-json-comments@1.0.4, loader-utils@0.2.16, mkdirp@0.5.1)
├── stylus-loader@2.3.1 (loader-utils@0.2.16, when@3.6.4)
├── shelljs@0.7.5 (interpret@1.0.1, rechoir@0.6.2)
├── less-loader@2.2.3 (loader-utils@0.2.16)
├── webpack-merge@0.14.1 (lodash.isequal@4.4.0, lodash.merge@3.3.2, lodash.isplainobject@3.2.0, lodash.find@3.2.1)
├── resolve@1.1.7
├── source-map-loader@0.1.5 (async@0.9.2, loader-utils@0.2.16, source-map@0.1.43)
├── exports-loader@0.6.3 (loader-utils@0.2.16, source-map@0.1.43)
├── webpack-md5-hash@0.0.5 (md5@2.2.1)
├── offline-plugin@3.4.2 (deep-extend@0.4.1, loader-utils@0.2.16, es6-promise@3.3.1, minimatch@3.0.3, ejs@2.5.2)
├── enhanced-resolve@2.3.0 (object-assign@4.1.0, graceful-fs@4.1.10, tapable@0.2.4, memory-fs@0.3.0)
├── postcss-loader@0.9.1 (loader-utils@0.2.16, postcss@5.2.5)
├── @angular/compiler-cli@2.1.2 (minimist@1.2.0, reflect-metadata@0.1.8)
├── npm-run-all@3.1.1 (object-assign@4.1.0, pinkie-promise@2.0.1, read-pkg-up@1.0.1, shell-quote@1.6.1, minimatch@3.0.3, cross-spawn@4.0.2, ps-tree@1.1.0, read-pkg@1.1.0, string.prototype.padend@3.0.0)
├── @angular/common@2.1.2
├── @angular/platform-browser@2.1.2
├── leek@0.0.21 (debug@2.2.0, lodash.assign@3.2.0, rsvp@3.3.3, request@2.78.0)
├── sourcemap-istanbul-instrumenter-loader@0.2.0 (object-assign@4.1.0, loader-utils@0.2.16, istanbul@0.4.5)
├── istanbul-instrumenter-loader@0.2.0 (object-assign@4.1.0, loader-utils@0.2.16, istanbul@0.4.5)
├── webpack-dev-server@2.1.0-beta.9 (connect-history-api-fallback@1.3.0, strip-ansi@3.0.1, supports-color@3.1.2, opn@4.0.2, compression@1.6.2, express@4.14.0, webpack-dev-middleware@1.8.4, spdy@3.4.4, http-proxy-middleware@0.17.2, chokidar@1.6.1, sockjs@0.3.18, serve-index@1.8.0, sockjs-client@1.1.1, yargs@4.8.1)
├── angular2-template-loader@0.5.0 (loader-utils@0.2.16, codecov@1.0.1)
├── stylus@0.54.5 (css-parse@1.7.0, debug@2.2.0, mkdirp@0.5.1, glob@7.0.6, source-map@0.1.43, sax@0.5.8)
├── html-webpack-plugin@2.24.1 (toposort@1.0.0, loader-utils@0.2.16, bluebird@3.4.6, html-minifier@3.1.0, pretty-error@2.0.2)
├── handlebars@4.0.5 (async@1.5.2, source-map@0.4.4, optimist@0.6.1, uglify-js@2.7.4)
├── typescript@2.0.7
├── common-tags@1.3.1 (babel-runtime@6.18.0)
├── awesome-typescript-loader@2.2.4 (object-assign@4.1.0, colors@1.1.2, loader-utils@0.2.16, source-map-support@0.4.6)
├── remap-istanbul@0.6.4 (amdefine@1.0.0, source-map@0.5.6, through2@2.0.1, gulp-util@3.0.7, istanbul@0.4.3)
├── @angular/tsc-wrapped@0.3.0 (tsickle@0.1.7)
├── compression-webpack-plugin@0.3.2 (async@0.2.10, webpack-sources@0.1.2, node-zopfli@2.0.1)
├── tslint@3.15.1 (colors@1.1.2, diff@2.2.3, optimist@0.6.1, findup-sync@0.3.0, underscore.string@3.3.4)
├── @angular/core@2.1.2
├── @angular/compiler@2.1.2
├── string-replace-loader@1.0.5 (loader-utils@0.2.16, lodash@3.10.1)
├── webpack@2.1.0-beta.25 (object-assign@4.1.0, interpret@1.0.1, tapable@0.2.4, async@1.5.2, clone@1.0.2, supports-color@3.1.2, loader-utils@0.2.16, loader-runner@2.2.0, source-map@0.5.6, mkdirp@0.5.1, acorn@3.3.0, memory-fs@0.3.0, webpack-sources@0.1.2, uglify-js@2.7.4, watchpack@1.1.0, ajv@4.8.2, yargs@4.8.1, node-libs-browser@1.0.0)
├── karma-webpack@1.8.0 (async@0.9.2, loader-utils@0.2.16, source-map@0.1.43, webpack-dev-middleware@1.8.4, lodash@3.10.1)
├── protractor@3.3.0 (jasminewd2@0.0.9, q@1.4.1, adm-zip@0.4.7, source-map-support@0.4.6, glob@6.0.4, optimist@0.6.1, saucelabs@1.0.1, jasmine@2.4.1, request@2.67.0, selenium-webdriver@2.52.0)
├── typedoc@0.4.5 (progress@1.1.8, marked@0.3.6, minimatch@3.0.3, typedoc-default-themes@0.4.0, typescript@1.8.10, highlight.js@9.8.0)
├── css-loader@0.23.1 (postcss-modules-extract-imports@1.0.1, object-assign@4.1.0, loader-utils@0.2.16, postcss-modules-values@1.2.2, css-selector-tokenizer@0.5.4, source-list-map@0.1.6, lodash.camelcase@3.0.1, postcss-modules-scope@1.0.2, postcss-modules-local-by-default@1.1.1, postcss@5.2.5, cssnano@3.8.0)
├── less@2.7.1 (graceful-fs@4.1.10, mime@1.3.4, image-size@0.5.0, source-map@0.5.6, errno@0.1.4, mkdirp@0.5.1, promise@7.1.1)
├── lodash@4.16.6
├── core-js@2.4.1
├── rxjs@5.0.0-beta.12 (symbol-observable@1.0.4)
├── @angular-cli/ast-tools@1.0.7 (rxjs@5.0.0-beta.11)
├── node-sass@3.11.2 (get-stdin@4.0.1, lodash.assign@4.2.0, lodash.clonedeep@4.5.0, async-foreach@0.1.3, in-publish@2.0.0, nan@2.4.0, mkdirp@0.5.1, cross-spawn@3.0.1, gaze@1.1.2, npmlog@4.0.0, meow@3.7.0, request@2.78.0, sass-graph@2.1.2, node-gyp@3.4.0)
└── ember-cli@2.5.0 (ember-cli-test-info@1.0.0, ember-cli-path-utils@1.0.0, ember-cli-is-package-missing@1.0.0, clean-base-url@1.0.0, ember-cli-normalize-entity-name@1.0.0, get-caller-file@1.0.2, fs-monitor-stack@1.1.1, git-repo-info@1.3.1, broccoli-funnel-reducer@1.0.0, ember-cli-valid-component-name@1.0.0, ember-cli-get-component-path-option@1.0.0, is-git-url@0.2.3, escape-string-regexp@1.0.5, promise-map-series@0.2.3, isbinaryfile@2.0.4, broccoli-plugin@1.2.2, broccoli-source@1.1.0, exists-sync@0.0.3, semver@5.3.0, filesize@3.3.0, inflection@1.10.0, bower-endpoint-parser@0.2.2, broccoli-viz@2.0.1, node-modules-path@1.0.1, through@2.3.8, amd-name-resolver@0.0.5, broccoli-sane-watcher@1.1.5, walk-sync@0.2.7, node-uuid@1.4.7, portfinder@1.0.9, nopt@3.0.6, debug@2.2.0, http-proxy@1.15.2, minimatch@3.0.3, readline2@0.1.1, diff@2.2.3, temp@0.8.3, findup@0.1.5, morgan@1.7.0, glob@7.0.3, configstore@2.1.0, fs-tree-diff@0.4.4, broccoli-funnel@1.0.9, rsvp@3.3.3, merge-defaults@0.2.1, ora@0.2.3, mkdirp@0.5.1, broccoli-kitchen-sink-helpers@0.3.1, quick-temp@0.1.5, fs-extra@0.26.7, compression@1.6.2, sane@1.4.1, findup-sync@0.2.1, express@4.14.0, broccoli-config-replace@1.1.2, inquirer@0.12.0, cpr@0.4.2, tree-sync@1.1.4, broccoli-merge-trees@1.1.4, yam@0.0.18, ember-router-generator@1.2.2, ember-cli-broccoli@0.16.9, broccoli-config-loader@1.0.0, tiny-lr@0.2.1, broccoli-concat@2.3.8, markdown-it@4.3.0, markdown-it-terminal@0.0.3, testem@1.13.0, ember-cli-preprocess-registry@2.0.0, core-object@0.0.2, bower-config@1.4.0, broccoli-babel-transpiler@5.6.1, bower@1.7.9, npm@2.14.21)
</code>```

Trying to debug it, I tried the minimatch installaton by running  sudo npm install -g minimatch@3.0.2, which gives me this output.

```<code>minimatch@3.0.2 /home/user/.npm-packages/lib/node_modules/minimatch
└── brace-expansion@1.1.6 (balanced-match@0.4.2, concat-map@0.0.1)
</code>```

But when I do  npm minimatch -v   it gives me this 2.15.9

Any suggestions?

答: It should be npm install @angular/cli -g not angular/cli. I also recommended not using '@latest'. Uninstall all with: npm uninstall angular/cli then run npm install -g @angular/cli. Should work for you.

Title: Angular2 Cli installation problems

Body:
I want to give a shot at angular 2 so I'm working to install angular2 cli now, but when I install it and then run ng new newapp , it awkwardly opens the command line and says something about 'mg' (not even 'ng').

Here's what happens when I run 'ng new myapp'

I'm running sudo npm install -g angular-cli@latest which gives the following output:

npm WARN engine angular-cli@1.0.0-beta.19-3: wanted: {"node":">= 4.1.0","npm":">= 3.0.0"} (current: {"node":"4.6.1","npm":"2.15.9"})
npm WARN engine @ngtools/webpack@1.1.4: wanted: {"node":">= 4.1.0","npm":">= 3.0.0"} (current: {"node":"4.6.1","npm":"2.15.9"})
npm WARN engine @angular-cli/ast-tools@1.0.7: wanted: {"node":">= 4.1.0","npm":">= 3.0.0"} (current: {"node":"4.6.1","npm":"2.15.9"})
npm WARN optional dep failed, continuing fsevents@1.0.15
npm WARN deprecated graceful-fs@1.2.3: graceful-fs v3.0.0 and before will fail on node releases >= v7.0. Please update to graceful-fs@^4.0.0 as soon as possible. Use 'npm ls graceful-fs' to find it in the tree.

> execSync@1.0.2 install /home/user/.npm-packages/lib/node_modules/angular-cli/node_modules/angular2-template-loader/node_modules/codecov/node_modules/execSync
> node install.js

[execsync v1.0.2] Attempting to compile native extensions.
[execSync v1.0.2]
    Native code compile failed!!
npm WARN deprecated tough-cookie@2.2.2: ReDoS vulnerability parsing Set-Cookie https://nodesecurity.io/advisories/130
npm WARN deprecated minimatch@0.3.0: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated minimatch@2.0.10: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue

> node-zopfli@2.0.1 install /home/user/.npm-packages/lib/node_modules/angular-cli/node_modules/compression-webpack-plugin/node_modules/node-zopfli
> node-pre-gyp install --fallback-to-build

node-pre-gyp ERR! Tried to download(403): https://node-zopfli.s3.amazonaws.com/Release/zopfli-v2.0.1-node-v46-linux-x64.tar.gz
node-pre-gyp ERR! Pre-built binaries not found for node-zopfli@2.0.1 and node@4.6.1 (node-v46 ABI) (falling back to source compile with node-gyp)
make: Entering directory '/home/user/.npm-packages/lib/node_modules/angular-cli/node_modules/compression-webpack-plugin/node_modules/node-zopfli/build'
  CXX(target) Release/obj.target/zopfli/src/zopfli-binding.o
  CXX(target) Release/obj.target/zopfli/src/png/zopflipng.o
  CC(target) Release/obj.target/zopfli/zopfli/src/zopfli/blocksplitter.o
  CC(target) Release/obj.target/zopfli/zopfli/src/zopfli/cache.o
  CC(target) Release/obj.target/zopfli/zopfli/src/zopfli/deflate.o
  CC(target) Release/obj.target/zopfli/zopfli/src/zopfli/gzip_container.o
  CC(target) Release/obj.target/zopfli/zopfli/src/zopfli/hash.o
  CC(target) Release/obj.target/zopfli/zopfli/src/zopfli/katajainen.o
  CC(target) Release/obj.target/zopfli/zopfli/src/zopfli/lz77.o
In file included from ../zopfli/src/zopfli/lz77.c:21:0:
../zopfli/src/zopfli/symbols.h:38:12: warning: ‘ZopfliGetDistExtraBits’ defined but not used [-Wunused-function]
 static int ZopfliGetDistExtraBits(int dist) {
            ^
../zopfli/src/zopfli/symbols.h:61:12: warning: ‘ZopfliGetDistExtraBitsValue’ defined but not used [-Wunused-function]
 static int ZopfliGetDistExtraBitsValue(int dist) {
            ^
../zopfli/src/zopfli/symbols.h:138:12: warning: ‘ZopfliGetLengthExtraBits’ defined but not used [-Wunused-function]
 static int ZopfliGetLengthExtraBits(int l) {
            ^
../zopfli/src/zopfli/symbols.h:161:12: warning: ‘ZopfliGetLengthExtraBitsValue’ defined but not used [-Wunused-function]
 static int ZopfliGetLengthExtraBitsValue(int l) {
            ^
../zopfli/src/zopfli/symbols.h:222:12: warning: ‘ZopfliGetLengthSymbolExtraBits’ defined but not used [-Wunused-function]
 static int ZopfliGetLengthSymbolExtraBits(int s) {
            ^
../zopfli/src/zopfli/symbols.h:231:12: warning: ‘ZopfliGetDistSymbolExtraBits’ defined but not used [-Wunused-function]
 static int ZopfliGetDistSymbolExtraBits(int s) {
            ^
  CC(target) Release/obj.target/zopfli/zopfli/src/zopfli/squeeze.o
In file included from ../zopfli/src/zopfli/squeeze.c:28:0:
../zopfli/src/zopfli/symbols.h:61:12: warning: ‘ZopfliGetDistExtraBitsValue’ defined but not used [-Wunused-function]
 static int ZopfliGetDistExtraBitsValue(int dist) {
            ^
../zopfli/src/zopfli/symbols.h:161:12: warning: ‘ZopfliGetLengthExtraBitsValue’ defined but not used [-Wunused-function]
 static int ZopfliGetLengthExtraBitsValue(int l) {
            ^
../zopfli/src/zopfli/symbols.h:222:12: warning: ‘ZopfliGetLengthSymbolExtraBits’ defined but not used [-Wunused-function]
 static int ZopfliGetLengthSymbolExtraBits(int s) {
            ^
../zopfli/src/zopfli/symbols.h:231:12: warning: ‘ZopfliGetDistSymbolExtraBits’ defined but not used [-Wunused-function]
 static int ZopfliGetDistSymbolExtraBits(int s) {
            ^
  CC(target) Release/obj.target/zopfli/zopfli/src/zopfli/tree.o
  CC(target) Release/obj.target/zopfli/zopfli/src/zopfli/util.o
  CC(target) Release/obj.target/zopfli/zopfli/src/zopfli/zlib_container.o
  CC(target) Release/obj.target/zopfli/zopfli/src/zopfli/zopfli_lib.o
  CXX(target) Release/obj.target/zopfli/zopfli/src/zopflipng/zopflipng_lib.o
  CXX(target) Release/obj.target/zopfli/zopfli/src/zopflipng/lodepng/lodepng.o
  CXX(target) Release/obj.target/zopfli/zopfli/src/zopflipng/lodepng/lodepng_util.o
  SOLINK_MODULE(target) Release/obj.target/zopfli.node
  COPY Release/zopfli.node
  COPY /home/user/.npm-packages/lib/node_modules/angular-cli/node_modules/compression-webpack-plugin/node_modules/node-zopfli/lib/binding/node-v46-linux-x64/zopfli.node
  TOUCH Release/obj.target/action_after_build.stamp
make: Leaving directory '/home/user/.npm-packages/lib/node_modules/angular-cli/node_modules/compression-webpack-plugin/node_modules/node-zopfli/build'
npm WARN optional dep failed, continuing fsevents@1.0.15
npm WARN deprecated lodash-node@2.4.1: This package is discontinued. Use lodash@^4.0.0.
|
> node-sass@3.11.2 install /home/user/.npm-packages/lib/node_modules/angular-cli/node_modules/node-sass
> node scripts/install.js

Start downloading binary at https://github.com/sass/node-sass/releases/download/v3.11.2/linux-x64-46_binding.node
Binary downloaded and installed at /home/user/.npm-packages/lib/node_modules/angular-cli/node_modules/node-sass/vendor/linux-x64-46/binding.node

> node-sass@3.11.2 postinstall /home/user/.npm-packages/lib/node_modules/angular-cli/node_modules/node-sass
> node scripts/build.js

"/home/user/.npm-packages/lib/node_modules/angular-cli/node_modules/node-sass/vendor/linux-x64-46/binding.node" exists.
 testing binary.
Binary is fine; exiting.
/home/user/.npm-packages/bin/ng -> /home/user/.npm-packages/lib/node_modules/angular-cli/bin/ng
angular-cli@1.0.0-beta.19-3 /home/user/.npm-packages/lib/node_modules/angular-cli
├── ember-cli-string-utils@1.0.0
├── json-loader@0.5.4
├── raw-loader@0.5.1
├── expose-loader@0.7.1
├── script-loader@0.7.0
├── symlink-or-copy@1.1.6
├── fs.realpath@1.0.0
├── rimraf@2.5.4
├── @angular-cli/base-href-webpack@1.0.6
├── denodeify@1.2.1
├── exit@0.1.2
├── karma-sourcemap-loader@0.3.7 (graceful-fs@4.1.10)
├── @ngtools/webpack@1.1.4
├── parse5@2.2.3
├── chalk@1.1.3 (escape-string-regexp@1.0.5, ansi-styles@2.2.1, supports-color@2.0.0, strip-ansi@3.0.1, has-ansi@2.0.0)
├── file-loader@0.8.5 (loader-utils@0.2.16)
├── url-loader@0.5.7 (mime@1.2.11, loader-utils@0.2.16)
├── opn@4.0.1 (object-assign@4.1.0, pinkie-promise@2.0.1)
├── style-loader@0.13.1 (loader-utils@0.2.16)
├── sass-loader@3.2.3 (object-assign@4.1.0, async@1.5.2, loader-utils@0.2.16)
├── silent-error@1.0.1 (debug@2.2.0)
├── zone.js@0.6.26
├── @angular/platform-server@2.1.2
├── fs-extra@0.30.0 (path-is-absolute@1.0.1, klaw@1.3.1, graceful-fs@4.1.10, jsonfile@2.4.0)
├── glob@7.1.1 (path-is-absolute@1.0.1, inherits@2.0.3, inflight@1.0.6, once@1.4.0, minimatch@3.0.3)
├── ts-loader@0.8.2 (object-assign@2.1.1, arrify@1.0.1, semver@5.3.0, colors@1.1.2, loader-utils@0.2.16, enhanced-resolve@0.9.1)
├── tslint-loader@2.1.5 (object-assign@4.1.0, strip-json-comments@1.0.4, loader-utils@0.2.16, mkdirp@0.5.1)
├── stylus-loader@2.3.1 (loader-utils@0.2.16, when@3.6.4)
├── shelljs@0.7.5 (interpret@1.0.1, rechoir@0.6.2)
├── less-loader@2.2.3 (loader-utils@0.2.16)
├── webpack-merge@0.14.1 (lodash.isequal@4.4.0, lodash.merge@3.3.2, lodash.isplainobject@3.2.0, lodash.find@3.2.1)
├── resolve@1.1.7
├── source-map-loader@0.1.5 (async@0.9.2, loader-utils@0.2.16, source-map@0.1.43)
├── exports-loader@0.6.3 (loader-utils@0.2.16, source-map@0.1.43)
├── webpack-md5-hash@0.0.5 (md5@2.2.1)
├── offline-plugin@3.4.2 (deep-extend@0.4.1, loader-utils@0.2.16, es6-promise@3.3.1, minimatch@3.0.3, ejs@2.5.2)
├── enhanced-resolve@2.3.0 (object-assign@4.1.0, graceful-fs@4.1.10, tapable@0.2.4, memory-fs@0.3.0)
├── postcss-loader@0.9.1 (loader-utils@0.2.16, postcss@5.2.5)
├── @angular/compiler-cli@2.1.2 (minimist@1.2.0, reflect-metadata@0.1.8)
├── npm-run-all@3.1.1 (object-assign@4.1.0, pinkie-promise@2.0.1, read-pkg-up@1.0.1, shell-quote@1.6.1, minimatch@3.0.3, cross-spawn@4.0.2, ps-tree@1.1.0, read-pkg@1.1.0, string.prototype.padend@3.0.0)
├── @angular/common@2.1.2
├── @angular/platform-browser@2.1.2
├── leek@0.0.21 (debug@2.2.0, lodash.assign@3.2.0, rsvp@3.3.3, request@2.78.0)
├── sourcemap-istanbul-instrumenter-loader@0.2.0 (object-assign@4.1.0, loader-utils@0.2.16, istanbul@0.4.5)
├── istanbul-instrumenter-loader@0.2.0 (object-assign@4.1.0, loader-utils@0.2.16, istanbul@0.4.5)
├── webpack-dev-server@2.1.0-beta.9 (connect-history-api-fallback@1.3.0, strip-ansi@3.0.1, supports-color@3.1.2, opn@4.0.2, compression@1.6.2, express@4.14.0, webpack-dev-middleware@1.8.4, spdy@3.4.4, http-proxy-middleware@0.17.2, chokidar@1.6.1, sockjs@0.3.18, serve-index@1.8.0, sockjs-client@1.1.1, yargs@4.8.1)
├── angular2-template-loader@0.5.0 (loader-utils@0.2.16, codecov@1.0.1)
├── stylus@0.54.5 (css-parse@1.7.0, debug@2.2.0, mkdirp@0.5.1, glob@7.0.6, source-map@0.1.43, sax@0.5.8)
├── html-webpack-plugin@2.24.1 (toposort@1.0.0, loader-utils@0.2.16, bluebird@3.4.6, html-minifier@3.1.0, pretty-error@2.0.2)
├── handlebars@4.0.5 (async@1.5.2, source-map@0.4.4, optimist@0.6.1, uglify-js@2.7.4)
├── typescript@2.0.7
├── common-tags@1.3.1 (babel-runtime@6.18.0)
├── awesome-typescript-loader@2.2.4 (object-assign@4.1.0, colors@1.1.2, loader-utils@0.2.16, source-map-support@0.4.6)
├── remap-istanbul@0.6.4 (amdefine@1.0.0, source-map@0.5.6, through2@2.0.1, gulp-util@3.0.7, istanbul@0.4.3)
├── @angular/tsc-wrapped@0.3.0 (tsickle@0.1.7)
├── compression-webpack-plugin@0.3.2 (async@0.2.10, webpack-sources@0.1.2, node-zopfli@2.0.1)
├── tslint@3.15.1 (colors@1.1.2, diff@2.2.3, optimist@0.6.1, findup-sync@0.3.0, underscore.string@3.3.4)
├── @angular/core@2.1.2
├── @angular/compiler@2.1.2
├── string-replace-loader@1.0.5 (loader-utils@0.2.16, lodash@3.10.1)
├── webpack@2.1.0-beta.25 (object-assign@4.1.0, interpret@1.0.1, tapable@0.2.4, async@1.5.2, clone@1.0.2, supports-color@3.1.2, loader-utils@0.2.16, loader-runner@2.2.0, source-map@0.5.6, mkdirp@0.5.1, acorn@3.3.0, memory-fs@0.3.0, webpack-sources@0.1.2, uglify-js@2.7.4, watchpack@1.1.0, ajv@4.8.2, yargs@4.8.1, node-libs-browser@1.0.0)
├── karma-webpack@1.8.0 (async@0.9.2, loader-utils@0.2.16, source-map@0.1.43, webpack-dev-middleware@1.8.4, lodash@3.10.1)
├── protractor@3.3.0 (jasminewd2@0.0.9, q@1.4.1, adm-zip@0.4.7, source-map-support@0.4.6, glob@6.0.4, optimist@0.6.1, saucelabs@1.0.1, jasmine@2.4.1, request@2.67.0, selenium-webdriver@2.52.0)
├── typedoc@0.4.5 (progress@1.1.8, marked@0.3.6, minimatch@3.0.3, typedoc-default-themes@0.4.0, typescript@1.8.10, highlight.js@9.8.0)
├── css-loader@0.23.1 (postcss-modules-extract-imports@1.0.1, object-assign@4.1.0, loader-utils@0.2.16, postcss-modules-values@1.2.2, css-selector-tokenizer@0.5.4, source-list-map@0.1.6, lodash.camelcase@3.0.1, postcss-modules-scope@1.0.2, postcss-modules-local-by-default@1.1.1, postcss@5.2.5, cssnano@3.8.0)
├── less@2.7.1 (graceful-fs@4.1.10, mime@1.3.4, image-size@0.5.0, source-map@0.5.6, errno@0.1.4, mkdirp@0.5.1, promise@7.1.1)
├── lodash@4.16.6
├── core-js@2.4.1
├── rxjs@5.0.0-beta.12 (symbol-observable@1.0.4)
├── @angular-cli/ast-tools@1.0.7 (rxjs@5.0.0-beta.11)
├── node-sass@3.11.2 (get-stdin@4.0.1, lodash.assign@4.2.0, lodash.clonedeep@4.5.0, async-foreach@0.1.3, in-publish@2.0.0, nan@2.4.0, mkdirp@0.5.1, cross-spawn@3.0.1, gaze@1.1.2, npmlog@4.0.0, meow@3.7.0, request@2.78.0, sass-graph@2.1.2, node-gyp@3.4.0)
└── ember-cli@2.5.0 (ember-cli-test-info@1.0.0, ember-cli-path-utils@1.0.0, ember-cli-is-package-missing@1.0.0, clean-base-url@1.0.0, ember-cli-normalize-entity-name@1.0.0, get-caller-file@1.0.2, fs-monitor-stack@1.1.1, git-repo-info@1.3.1, broccoli-funnel-reducer@1.0.0, ember-cli-valid-component-name@1.0.0, ember-cli-get-component-path-option@1.0.0, is-git-url@0.2.3, escape-string-regexp@1.0.5, promise-map-series@0.2.3, isbinaryfile@2.0.4, broccoli-plugin@1.2.2, broccoli-source@1.1.0, exists-sync@0.0.3, semver@5.3.0, filesize@3.3.0, inflection@1.10.0, bower-endpoint-parser@0.2.2, broccoli-viz@2.0.1, node-modules-path@1.0.1, through@2.3.8, amd-name-resolver@0.0.5, broccoli-sane-watcher@1.1.5, walk-sync@0.2.7, node-uuid@1.4.7, portfinder@1.0.9, nopt@3.0.6, debug@2.2.0, http-proxy@1.15.2, minimatch@3.0.3, readline2@0.1.1, diff@2.2.3, temp@0.8.3, findup@0.1.5, morgan@1.7.0, glob@7.0.3, configstore@2.1.0, fs-tree-diff@0.4.4, broccoli-funnel@1.0.9, rsvp@3.3.3, merge-defaults@0.2.1, ora@0.2.3, mkdirp@0.5.1, broccoli-kitchen-sink-helpers@0.3.1, quick-temp@0.1.5, fs-extra@0.26.7, compression@1.6.2, sane@1.4.1, findup-sync@0.2.1, express@4.14.0, broccoli-config-replace@1.1.2, inquirer@0.12.0, cpr@0.4.2, tree-sync@1.1.4, broccoli-merge-trees@1.1.4, yam@0.0.18, ember-router-generator@1.2.2, ember-cli-broccoli@0.16.9, broccoli-config-loader@1.0.0, tiny-lr@0.2.1, broccoli-concat@2.3.8, markdown-it@4.3.0, markdown-it-terminal@0.0.3, testem@1.13.0, ember-cli-preprocess-registry@2.0.0, core-object@0.0.2, bower-config@1.4.0, broccoli-babel-transpiler@5.6.1, bower@1.7.9, npm@2.14.21)

Trying to debug it, I tried the minimatch installaton by running  sudo npm install -g minimatch@3.0.2, which gives me this output.

minimatch@3.0.2 /home/user/.npm-packages/lib/node_modules/minimatch
└── brace-expansion@1.1.6 (balanced-match@0.4.2, concat-map@0.0.1)

But when I do  npm minimatch -v   it gives me this 2.15.9

Any suggestions?


问:
Can attributes inside a tag have an extra space, is it semantically correct?
This could be a stupid question, but i'm at the design phase where everything is checked for semantics correctness.

For example, when having this

```<code><a href="..." id="page" <?php if (false) echo 'name="test"'; ?> class="pageWidth">
</code>```

...i believe it produces:

```<code><a href="..." id="page"  class="pageWidth">
</code>```

... notice there is a an extra space between the id attribute and the class attribute.

Now, the stupid semantic question: is this semantically correct? Can attributes have extra space and not matter at all?

答:
According to w3.org:

Attributes must be separated from each other by one or more space characters.

So, including an extra space between two attributes is still valid HTML.

But I don't think that formatting affects semantics of the markup, per se.

That being said, it would not be difficult to remove the extra space if you prefer.

I sometimes use a ternary operator to generate output like that:

```<code><a href="..." id="page"<?= false ? ' name="test"' : '' ?> class="pageWidth">
</code>```

Body:
This could be a stupid question, but i'm at the design phase where everything is checked for semantics correctness.

For example, when having this

<a href="..." id="page" <?php if (false) echo 'name="test"'; ?> class="pageWidth">

...i believe it produces:

... notice there is a an extra space between the id attribute and the class attribute.

Now, the stupid semantic question: is this semantically correct? Can attributes have extra space and not matter at all?

Body:
According to w3.org:

Attributes must be separated from each other by one or more space characters.

So, including an extra space between two attributes is still valid HTML.

But I don't think that formatting affects semantics of the markup, per se.

That being said, it would not be difficult to remove the extra space if you prefer.

I sometimes use a ternary operator to generate output like that:

<a href="..." id="page"<?= false ? ' name="test"' : '' ?> class="pageWidth">