问:
How do you run pre functions when creating a new document for the first time from a model with mongoose
This is quite a large schema, but I'm trying to handle validation of a list of ObjectId's myself because I don't want errors returned when the passed values are objects

```<code>var thingSchema = new Schema({

    // origin Id to relate states when new states are created
    thingId: { type: Schema.ObjectId, ref: 'thing' },
    hash: { type: String },

    // organzational properties
    title: { type: String },
    names: { type: [String] },
    realms: { type: [String], default: ["all", "things"] },

    // values
    text: { type: String },
    number: { type: Number },
    url: { type: String },
    json: { type: {} },
    list: { type: [] },
    boolean: { type: Boolean },
    binary: {
        data: { type: Buffer },
        // binary type .PNG .JPG for decoding if
        extension: { type: String }
    },

    // family relations | inventory of other things | child things | states
    things:     { type: [{ type: Schema.ObjectId, ref: 'thing' }], default: [] },
    parents:    { type: [{ type: Schema.ObjectId, ref: 'thing' }], default: [] },
    states:     { type: [{ type: Schema.ObjectId, ref: 'thing' }], default: [] },
    properties: { type: [{ type: Schema.ObjectId, ref: 'thing' }], default: [] }, // extendable schema support

    // ownership / privacy / access control / billing
    owner: { type: Schema.ObjectId, ref: 'entity' },
    owners: { type: [{ type: Schema.ObjectId, ref: 'entity' }] },
    payees: { type: [{ type: Schema.ObjectId, ref: 'entity' }] },

    // smart contract variable/dynamic pricing
    contract: {
        type: [{
            contractType: { type: String, required: true },
            thing: { type: Schema.ObjectId, ref: 'entity', required: true },
            amount: { type: Number, required: true, default: 1 },
            multiplier: { type: Number, required: true, default: 1 },
            unit: { type: String, required: true }
        }]
    },

    // meta data
    created: { type: Date, default: Date.now() },
    inception: { type: Date, default: Date.now() },
    age: { type: Number, default: 0 },
    lifetime: { type: Number, default: 0, min: 0, max: Infinity },
    location: { type: String },
    valueType: { type: String, enum: [
        String,
        Object,
        Number,
        Array,
        ]
    },

    // state meta data
    stateId: { type: String },
    stateCreated: { type: Date, default: Date.now() },

},{
    usePushEach: true
})

thingSchema.pre('validate', function(next){
    // custom validate passed properties, parents, things, and states to make sure they're not objects
    let validations = ['properties', 'things', 'parents', 'states']
    for(var i=0;i<validations.length;i++){
        for(var j=0;j<this[validations[i]].length;j++){
            console.log(this[validations[i]][j])
            console.log(i)
            console.log(j)
            if(!(this[validations[i]][j] instanceof Schema.ObjectId)){
                this[validations[i]].splice(j, 1)
                j--
            }
        }
    }
    next()
})

var thingModel = node.model('thing', thingSchema)
</code>```

But when I run

```<code>let thingModelled = new thingModel(JSON.parse(JSON.stringify(thing)))
</code>```

the pre hook isn't run, I can't tell if these pre hooks are only run on save functions?

Or how to get hooks run on model creations?

this is the error when running
    new thingModel(data)

```<code>ValidationError: properties: Cast to Array failed for value "[ { title: 'options',
4|agoraser |     list: [ 'editing', 'edited' ],
4|agoraser |     things: [],
4|agoraser |     properties: [] } ]" at path "properties"
4|agoraser |     at new ValidationError (/media/rick/hyper/Dropbox/host-root/var/www/nodes/agora/server/node_modules/mongoose/lib/error/validation.js:28:11)
4|agoraser |     at model.Document.invalidate (/media/rick/hyper/Dropbox/host-root/var/www/nodes/agora/server/node_modules/mongoose/lib/document.js:1658:32)
4|agoraser |     at model.Document.$set (/media/rick/hyper/Dropbox/host-root/var/www/nodes/agora/server/node_modules/mongoose/lib/document.js:760:10)
4|agoraser |     at model._handleIndex (/media/rick/hyper/Dropbox/host-root/var/www/nodes/agora/server/node_modules/mongoose/lib/document.js:590:14)
4|agoraser |     at model.Document.$set (/media/rick/hyper/Dropbox/host-root/var/www/nodes/agora/server/node_modules/mongoose/lib/document.js:550:24)
4|agoraser |     at model.Document (/media/rick/hyper/Dropbox/host-root/var/www/nodes/agora/server/node_modules/mongoose/lib/document.js:77:12)
4|agoraser |     at model.Model (/media/rick/hyper/Dropbox/host-root/var/www/nodes/agora/server/node_modules/mongoose/lib/model.js:55:12)
4|agoraser |     at new model (/media/rick/hyper/Dropbox/host-root/var/www/nodes/agora/server/node_modules/mongoose/lib/model.js:3879:13)
</code>```

答:
To validate some field before saveyou can use schemaName.path('fieldName').validate(function(value, done){....},"error message") this signature. This method is called pre save and if a validation rule is violated and save is aborted and the error is returned to your callback.

For example if you want to create a validation for states so can follow this

```<code>thingSchema.path('states').validate(function (value, done) {
  // your logic for validation
  // value will contain the value of state field
  if(validate) {
    return done(true);
  } else {
    return done(false);
  }
}, 'Invalid state');
</code>```

Body:
This is quite a large schema, but I'm trying to handle validation of a list of ObjectId's myself because I don't want errors returned when the passed values are objects

var thingSchema = new Schema({

    // origin Id to relate states when new states are created
    thingId: { type: Schema.ObjectId, ref: 'thing' },
    hash: { type: String },

    // organzational properties
    title: { type: String },
    names: { type: [String] },
    realms: { type: [String], default: ["all", "things"] },

    // values
    text: { type: String },
    number: { type: Number },
    url: { type: String },
    json: { type: {} },
    list: { type: [] },
    boolean: { type: Boolean },
    binary: {
        data: { type: Buffer },
        // binary type .PNG .JPG for decoding if
        extension: { type: String }
    },

    // family relations | inventory of other things | child things | states
    things:     { type: [{ type: Schema.ObjectId, ref: 'thing' }], default: [] },
    parents:    { type: [{ type: Schema.ObjectId, ref: 'thing' }], default: [] },
    states:     { type: [{ type: Schema.ObjectId, ref: 'thing' }], default: [] },
    properties: { type: [{ type: Schema.ObjectId, ref: 'thing' }], default: [] }, // extendable schema support

    // ownership / privacy / access control / billing
    owner: { type: Schema.ObjectId, ref: 'entity' },
    owners: { type: [{ type: Schema.ObjectId, ref: 'entity' }] },
    payees: { type: [{ type: Schema.ObjectId, ref: 'entity' }] },

    // smart contract variable/dynamic pricing
    contract: {
        type: [{
            contractType: { type: String, required: true },
            thing: { type: Schema.ObjectId, ref: 'entity', required: true },
            amount: { type: Number, required: true, default: 1 },
            multiplier: { type: Number, required: true, default: 1 },
            unit: { type: String, required: true }
        }]
    },

    // meta data
    created: { type: Date, default: Date.now() },
    inception: { type: Date, default: Date.now() },
    age: { type: Number, default: 0 },
    lifetime: { type: Number, default: 0, min: 0, max: Infinity },
    location: { type: String },
    valueType: { type: String, enum: [
        String,
        Object,
        Number,
        Array,
        ]
    },

    // state meta data
    stateId: { type: String },
    stateCreated: { type: Date, default: Date.now() },

},{
    usePushEach: true
})

thingSchema.pre('validate', function(next){
    // custom validate passed properties, parents, things, and states to make sure they're not objects
    let validations = ['properties', 'things', 'parents', 'states']
    for(var i=0;i<validations.length;i++){
        for(var j=0;j<this[validations[i]].length;j++){
            console.log(this[validations[i]][j])
            console.log(i)
            console.log(j)
            if(!(this[validations[i]][j] instanceof Schema.ObjectId)){
                this[validations[i]].splice(j, 1)
                j--
            }
        }
    }
    next()
})

var thingModel = node.model('thing', thingSchema)

But when I run

let thingModelled = new thingModel(JSON.parse(JSON.stringify(thing)))

the pre hook isn't run, I can't tell if these pre hooks are only run on save functions?

Or how to get hooks run on model creations?

this is the error when running
    new thingModel(data)

ValidationError: properties: Cast to Array failed for value "[ { title: 'options',
4|agoraser |     list: [ 'editing', 'edited' ],
4|agoraser |     things: [],
4|agoraser |     properties: [] } ]" at path "properties"
4|agoraser |     at new ValidationError (/media/rick/hyper/Dropbox/host-root/var/www/nodes/agora/server/node_modules/mongoose/lib/error/validation.js:28:11)
4|agoraser |     at model.Document.invalidate (/media/rick/hyper/Dropbox/host-root/var/www/nodes/agora/server/node_modules/mongoose/lib/document.js:1658:32)
4|agoraser |     at model.Document.$set (/media/rick/hyper/Dropbox/host-root/var/www/nodes/agora/server/node_modules/mongoose/lib/document.js:760:10)
4|agoraser |     at model._handleIndex (/media/rick/hyper/Dropbox/host-root/var/www/nodes/agora/server/node_modules/mongoose/lib/document.js:590:14)
4|agoraser |     at model.Document.$set (/media/rick/hyper/Dropbox/host-root/var/www/nodes/agora/server/node_modules/mongoose/lib/document.js:550:24)
4|agoraser |     at model.Document (/media/rick/hyper/Dropbox/host-root/var/www/nodes/agora/server/node_modules/mongoose/lib/document.js:77:12)
4|agoraser |     at model.Model (/media/rick/hyper/Dropbox/host-root/var/www/nodes/agora/server/node_modules/mongoose/lib/model.js:55:12)
4|agoraser |     at new model (/media/rick/hyper/Dropbox/host-root/var/www/nodes/agora/server/node_modules/mongoose/lib/model.js:3879:13)

Body:
To validate some field before saveyou can use schemaName.path('fieldName').validate(function(value, done){....},"error message") this signature. This method is called pre save and if a validation rule is violated and save is aborted and the error is returned to your callback.

For example if you want to create a validation for states so can follow this

thingSchema.path('states').validate(function (value, done) {
  // your logic for validation
  // value will contain the value of state field
  if(validate) {
    return done(true);
  } else {
    return done(false);
  }
}, 'Invalid state');


来源: stackexchange

问:
can i get realtime user login list in firebase?
I want to create an app that displays the list of users who are logged in realtime, and if the user closes the app it will automatically be deleted from the list of users who are logging .. can i make it in firebase, or what technology is suitable to make it.</p>

答:
Firebase does not return list of user logged in your app through api. You can see that list on Firebase Console.

Other than this, you can do this by implementing custom WebService that help you in login and store all credentials in database. So that you can easily get list of all logged in users through any api WebService.

ContentLicense: CC BY-SA 3.0


问:
Is it possible to load an image when I press a command without blocking the application?
How do I load an image without blocking the application at the press of a command?
For normal swing apps, there's the swingworker, is there something like that for J2ME also?</p>

答: Kick off a new thread in your command handler and load the image in that thread.  Or, if you do it a lot, have an Image Loader thread constantly running, which processes a queue of image loading requests, and add a request to that queue in your command handler.</p>

ContentLicense: CC BY-SA 2.5


问:
How to automatically close the execution of the `qemu` after end of process?
I want that the qemu window after opening and showing the output automatically closes after running pintOS

Like when i run the command pintos -- run alarm-multiple in tcsh shell, qemu displays that process begins ,then some alarm-notifications and then the process ends, but after that the qemu window won't close

I want to exit the window after successful completion of my system call.

答:
UPDATED:

The new solution

Here is another better solution that will work for both pintos run ... and make grade

add this line to devices/shutdown.c :: shutdown_power_off(void) before the loop.

```<code>outw( 0x604, 0x0 | 0x2000 );
</code>```

The old Solution

For the newer versions of qemu you need to run it with the option

```<code>-device isa-debug-exit
</code>```

Which exits on any write to an IO port, by default it's 0x501

i.e in your pintos project under the src/utils directory you will need to add one line to the pintos file in the run_qemu subroutine

```<code>sub run_qemu {
    print "warning: qemu doesn't support --terminal\n"
       if $vga eq 'terminal';
    print "warning: qemu doesn't support jitter\n"
       if defined $jitter;
    my (@cmd) = ('qemu-system-i386');

    push (@cmd, '-device', 'isa-debug-exit'); # <====== add this line
    ..
    ..
    push (@cmd, '-monitor', 'null') if $vga eq 'none' && $debug eq 'none';
    run_command (@cmd);
}
</code>```

and in shutdown.c file under the devices directory
add this line in the shutdown_power_off function after the for loop

```<code>for (p = s; *p != '\0'; p++)
    outb (0x8900, *p);

outb (0x501, 0x31); // <====== add this line
</code>```

Qemu's exit code is double the value plus one, so there is no way to exit cleanly. Use 0x31 which should result in a qemu exit code of 0x63

finally run pintos with -q option

```<code>pintos -q run alarm-multiple
</code>```

Note: this solution will not work for make grade see the comment below by @pranav3688  for a solution.

Body:
UPDATED:

The new solution

Here is another better solution that will work for both pintos run ... and make grade

add this line to devices/shutdown.c :: shutdown_power_off(void) before the loop.

outw( 0x604, 0x0 | 0x2000 );

The old Solution

For the newer versions of qemu you need to run it with the option

-device isa-debug-exit

Which exits on any write to an IO port, by default it's 0x501

i.e in your pintos project under the src/utils directory you will need to add one line to the pintos file in the run_qemu subroutine

sub run_qemu {
    print "warning: qemu doesn't support --terminal\n"
       if $vga eq 'terminal';
    print "warning: qemu doesn't support jitter\n"
       if defined $jitter;
    my (@cmd) = ('qemu-system-i386');

    push (@cmd, '-device', 'isa-debug-exit'); # <====== add this line
    ..
    ..
    push (@cmd, '-monitor', 'null') if $vga eq 'none' && $debug eq 'none';
    run_command (@cmd);
}

and in shutdown.c file under the devices directory
add this line in the shutdown_power_off function after the for loop

for (p = s; *p != '\0'; p++)
    outb (0x8900, *p);

outb (0x501, 0x31); // <====== add this line

Qemu's exit code is double the value plus one, so there is no way to exit cleanly. Use 0x31 which should result in a qemu exit code of 0x63

finally run pintos with -q option

pintos -q run alarm-multiple

Note: this solution will not work for make grade see the comment below by @pranav3688  for a solution.


问:
Codeigniter timespan does not work properly
My code like below :

```<code>$post_date = '2017-11-15 21:04:31';
$now = new DateTime();
$units = 7;
echo timespan($post_date, $now, $units);
</code>```

It return me this :

asked 47 Years, 10 Months, 2 Weeks, 1 Day, 23 Hours, 53 Minutes

where's 47 years coming from?

UPDATE

I want to calculate the difference between active time now since he has in the $post_date. For example $post_date = '2017-11-15 21:04:31'; it's should be 1 day, 8 hours, 9 minutes since he was posted.

how can I fix it?

答:
You can use diff.

Code

```<code>$post_date= new DateTime("2017-11-15 21:04:31");
$now = new DateTime();
$diff = $now->diff($post_date);
echo "Days: " . $diff->days . " Hours: " . $diff->h . " Minutes: " . $diff->i;
</code>```

OUTPUT:

```<code>Days: 1 Hours: 8 Minutes: 39
</code>```

For print_r result

```<code>echo"```";
print_r($diff);

DateInterval Object
(
    [y] => 0
    [m] => 0
    [d] => 1
    [h] => 8
    [i] => 39
    [s] => 22
    [weekday] => 0
    [weekday_behavior] => 0
    [first_last_day_of] => 0
    [invert] => 1
    [days] => 1
    [special_type] => 0
    [special_amount] => 0
    [have_weekday_relative] => 0
    [have_special_relative] => 0
)
```

Body:
My code like below :

$post_date = '2017-11-15 21:04:31';
$now = new DateTime();
$units = 7;
echo timespan($post_date, $now, $units);

It return me this :

asked 47 Years, 10 Months, 2 Weeks, 1 Day, 23 Hours, 53 Minutes

where's 47 years coming from?

UPDATE

I want to calculate the difference between active time now since he has in the $post_date. For example $post_date = '2017-11-15 21:04:31'; it's should be 1 day, 8 hours, 9 minutes since he was posted.

how can I fix it?

Body:
You can use diff.

Code

$post_date= new DateTime("2017-11-15 21:04:31");
$now = new DateTime();
$diff = $now->diff($post_date);
echo "Days: " . $diff->days . " Hours: " . $diff->h . " Minutes: " . $diff->i;

OUTPUT:

Days: 1 Hours: 8 Minutes: 39

For print_r result

echo"<pre>";
print_r($diff);

DateInterval Object
(
    [y] => 0
    [m] => 0
    [d] => 1
    [h] => 8
    [i] => 39
    [s] => 22
    [weekday] => 0
    [weekday_behavior] => 0
    [first_last_day_of] => 0
    [invert] => 1
    [days] => 1
    [special_type] => 0
    [special_amount] => 0
    [have_weekday_relative] => 0
    [have_special_relative] => 0
)


问:
Laravel 5 - Binding model from query string
I have the following URL:

/search?customer=my-customer-slug&q=foo

I wonder if there is a way to bind a Customer model into $request->customer, by searching from the Customer's slug.

Doing that when the URL is /search/{customer-slug} is very easy, but I don't know if I can do that with query strings.

答:
Although I don't see the advantage over using /search/{customer-slug}, you could use a middleware to achieve this.

Make a middleware to check for customer in the query string and assign it to the request. Then, you can attach this middleware to any route you expect to have a customer in the url.

```<code><?php

namespace App\Http\Middleware;

use App\Customer;
use Closure;

class CustomerQueryStringMiddleware
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        if ($request->filled('customer')) {

            $customer = Customer::where('slug', $request->customer)->firstOrFail();

            $request->merge(['customer' => $customer]);
        }

        return $next($request);
    }
}
</code>```

Body:
Although I don't see the advantage over using /search/{customer-slug}, you could use a middleware to achieve this.

Make a middleware to check for customer in the query string and assign it to the request. Then, you can attach this middleware to any route you expect to have a customer in the url.

<?php

namespace App\Http\Middleware;

use App\Customer;
use Closure;

class CustomerQueryStringMiddleware
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        if ($request->filled('customer')) {

            $customer = Customer::where('slug', $request->customer)->firstOrFail();

            $request->merge(['customer' => $customer]);
        }

        return $next($request);
    }
}


问:
Cannot select latest and not same data from mysql
I have value like this.

```<code>id  website   time
1   aaa.com   11.10
2   bbb.com   11.10
3   ccc.com   11.10
4   aaa.com   11.11
5   bbb.com   11.11
6   ccc.com   11.11
</code>```

I want to select latest and not same data in table. It should be .

```<code>4   aaa.com   11.11
5   bbb.com   11.11
6   ccc.com   11.11
</code>```

I query like this

```<code>"SELECT * FROM name GROUP BY website ORDER BY id DESC";
</code>```

It alway show DESC and ASC.

```<code>1   aaa.com   11.10
2   bbb.com   11.10
3   ccc.com   11.10
</code>```

How to select latest value with not same data ?

答:
Join to a subquery which finds the latest record for each website:

```<code>SELECT t1.*
FROM yourTable t1
INNER JOIN
(
    SELECT website, MAX(time) AS max_time
    FROM yourTable
    GROUP BY website
) t2
    ON t1.website = t2.website AND
       t1.time = t2.max_time;
</code>```

You are storing your times apparently in some text format.  This isn't desirable, and it would be better to store date times instead.  If the width of the time is always the same (5 telling from your sample data), then my query should work though.

Body:
I have value like this.

id  website   time
1   aaa.com   11.10
2   bbb.com   11.10
3   ccc.com   11.10
4   aaa.com   11.11
5   bbb.com   11.11
6   ccc.com   11.11

I want to select latest and not same data in table. It should be .

4   aaa.com   11.11
5   bbb.com   11.11
6   ccc.com   11.11

I query like this

"SELECT * FROM name GROUP BY website ORDER BY id DESC";

It alway show DESC and ASC.

1   aaa.com   11.10
2   bbb.com   11.10
3   ccc.com   11.10

How to select latest value with not same data ?

Body:
Join to a subquery which finds the latest record for each website:

SELECT t1.*
FROM yourTable t1
INNER JOIN
(
    SELECT website, MAX(time) AS max_time
    FROM yourTable
    GROUP BY website
) t2
    ON t1.website = t2.website AND
       t1.time = t2.max_time;

You are storing your times apparently in some text format.  This isn't desirable, and it would be better to store date times instead.  If the width of the time is always the same (5 telling from your sample data), then my query should work though.


问:
Android WebView: handling orientation changes
The issue is the performance following rotation. The WebView has to reload the page, which can be a bit tedious.

What's the best way of handling an orientation change without reloading the page from source each time?

答:
```<code>@Override
    protected void onSaveInstanceState(Bundle outState )
    {
        super.onSaveInstanceState(outState);
        webView.saveState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState)
    {
        super.onRestoreInstanceState(savedInstanceState);
        webView.restoreState(savedInstanceState);
    }
</code>```


问:
Manager object has no attribute 'save'
In my serializers.py I have a OrderCreateSerializer:

```<code>class OrderCreateSerializer(ModelSerializer):

    data_params = serializers.DictField()  # 根据产品数据模型不同而异

    class Meta:
        model = Order
        fields = (
            "product_describe",  # 产品描述 (购买xx产品 + 参数)
            "billing_type", # 计费类型 ("包年包月")
            "data_params",  # 数据
        )
    def create(self, validated_data):

        request = self.context.get("request")
        if request and hasattr(request, "user"):
            user = request.user

        validated_data["order_num"] = generateOrderNum(userid=user.id)
        validated_data["order_status"] = "未支付"
        validated_data["order_status"] = "未支付"

        data_dic = validated_data.pop("data_params") #

        # data_dic["data"]["profile"]

        validated_data["buytime"] = data_dic["data"]["buytime"]
        validated_data["count"] = data_dic["data"]["count"]
        validated_data["paytype"] = ""

        validated_data["cost"] = ""
        validated_data["account"] = user.account

        return Order.objects.save(**validated_data)  # this is the line 57
</code>```

When I save the validated_data, it report the bellow error:

Manager object has no attribute 'save'

My Order model is like bellow, there is many fields in it :

```<code>class Order(models.Model):
    """
    订单
    """
    order_num = models.CharField(max_length=128, unique=True)  # 订单编号
    order_status = models.CharField(max_length=12)  # 订单状态  "未支付"， "已支付，未完成"， "已完成"， "已经删除"，"其他"
    product_describe = models.TextField()  # 产品描述
    billing_type = models.CharField(max_length=16)  # 计费类型
    buytime = models.CharField(max_length=16)  # 比如：1月  永久
    count = models.IntegerField()  # 购买数量
    paytype = models.CharField(max_length=16)  # 支付方式（支付包，微信，xxx）
    cost = models.DecimalField(max_digits=8, decimal_places=2, default=0.00)  # 费用（需要花费多少钱）
    account = models.ForeignKey(to=Account) # 所属账户

    ctime = models.DateTimeField(auto_now_add=True)  # 创建时间
    uptime = models.DateTimeField(auto_now=True)  # 更新时间

    def __str__(self):
        return self.product_describe
    def __unicode__(self):
        return self.product_describe
</code>```

I don't know why there is the Manager object here.

答:
Order.objects is an instance of the Manager class. The save method is a method of the model class.

Try:Order(**validated_data).save()

Title: Manager object has no attribute 'save'

Body:
In my serializers.py I have a OrderCreateSerializer:

class OrderCreateSerializer(ModelSerializer):

    data_params = serializers.DictField()  # 根据产品数据模型不同而异

    class Meta:
        model = Order
        fields = (
            "product_describe",  # 产品描述 (购买xx产品 + 参数)
            "billing_type", # 计费类型 ("包年包月")
            "data_params",  # 数据
        )
    def create(self, validated_data):

        request = self.context.get("request")
        if request and hasattr(request, "user"):
            user = request.user

        validated_data["order_num"] = generateOrderNum(userid=user.id)
        validated_data["order_status"] = "未支付"
        validated_data["order_status"] = "未支付"

        data_dic = validated_data.pop("data_params") #

        # data_dic["data"]["profile"]

        validated_data["buytime"] = data_dic["data"]["buytime"]
        validated_data["count"] = data_dic["data"]["count"]
        validated_data["paytype"] = ""

        validated_data["cost"] = ""
        validated_data["account"] = user.account

        return Order.objects.save(**validated_data)  # this is the line 57

When I save the validated_data, it report the bellow error:

Manager object has no attribute 'save'

My Order model is like bellow, there is many fields in it :

class Order(models.Model):
    """
    订单
    """
    order_num = models.CharField(max_length=128, unique=True)  # 订单编号
    order_status = models.CharField(max_length=12)  # 订单状态  "未支付"， "已支付，未完成"， "已完成"， "已经删除"，"其他"
    product_describe = models.TextField()  # 产品描述
    billing_type = models.CharField(max_length=16)  # 计费类型
    buytime = models.CharField(max_length=16)  # 比如：1月  永久
    count = models.IntegerField()  # 购买数量
    paytype = models.CharField(max_length=16)  # 支付方式（支付包，微信，xxx）
    cost = models.DecimalField(max_digits=8, decimal_places=2, default=0.00)  # 费用（需要花费多少钱）
    account = models.ForeignKey(to=Account) # 所属账户

    ctime = models.DateTimeField(auto_now_add=True)  # 创建时间
    uptime = models.DateTimeField(auto_now=True)  # 更新时间

    def __str__(self):
        return self.product_describe
    def __unicode__(self):
        return self.product_describe

I don't know why there is the Manager object here.


问:
Conversation not happening in Amazon Echo
Hi My intent schema is like this:

```<code>{
  "intents": [
    {
      "slots": [
        {
          "name": "Literalslot",
          "type": "AMAZON.LITERAL"
        }
      ],
      "intent": "ConverseGenieIntent"
    },
    {
      "intent": "AMAZON.HelpIntent"
    },
    {
      "intent": "AMAZON.StopIntent"
    },
    {
      "intent": "AMAZON.CancelIntent"
    }
  ]
}
</code>```

And my utterances are:

```<code>ConverseGenieIntent {hello|Literalslot}
ConverseGenieIntent {validate payroll|Literalslot}
ConverseGenieIntent {no no|Literalslot}
ConverseGenieIntent {no|Literalslot}
ConverseGenieIntent {no its not correct|Literalslot}
ConverseGenieIntent {no my payroll id is |Literalslot}
ConverseGenieIntent {its not correct|Literalslot}
ConverseGenieIntent {its wrong|Literalslot}
ConverseGenieIntent {no|Literalslot}
ConverseGenieIntent {that's not correct|Literalslot}
ConverseGenieIntent {that is not correct|Literalslot}
ConverseGenieIntent {hi yeah|Literalslot}
ConverseGenieIntent {what is your name|Literalslot}
ConverseGenieIntent {may i know your name please|Literalslot}
ConverseGenieIntent {hey what is your name|Literalslot}
</code>```

My skill is actually a bot which gives multiple conversations.

Expected converstion:

User: Alexa ask genie to say hello.

Alexa: Welcome to genie.

User: Start session..

Alexa: Please tell me the store number?

User: one two three four

Alexa: Are you calling from BRAYBOOK 1234?

User: Yes

Alexa: Please tell me payroll ID?

User: 5678
(....and continues for at least three more conversations)

But while testing in Echo:

User: Alexa ask genie to say hello.

Alexa: Welcome to genie. Please tell me the store number?

User: one two three four

Alexa: Sorry i couldn't find that

.....ALWAYS THE CONVERSATION STOPS HERE.......     I really don't know why...   I don't wanna use dialog directives as the response from the lambda function comes from a DialogFlow bot.

I tested the skill in service simulator the skill is working fine!!!   This problem happens only why i test my skill in Echo.

答: Hey it not actually like that. Your answer is wrong. I don't have to give input as "One" then "two" and after it asks "three" ....No not like that.  Inputs like "1234" can be given as it worked well in Echo device. Never test your skill in Echosim.io. Always test in an Amazon device.</p>

Body:
Hi My intent schema is like this:

{
  "intents": [
    {
      "slots": [
        {
          "name": "Literalslot",
          "type": "AMAZON.LITERAL"
        }
      ],
      "intent": "ConverseGenieIntent"
    },
    {
      "intent": "AMAZON.HelpIntent"
    },
    {
      "intent": "AMAZON.StopIntent"
    },
    {
      "intent": "AMAZON.CancelIntent"
    }
  ]
}

And my utterances are:

ConverseGenieIntent {hello|Literalslot}
ConverseGenieIntent {validate payroll|Literalslot}
ConverseGenieIntent {no no|Literalslot}
ConverseGenieIntent {no|Literalslot}
ConverseGenieIntent {no its not correct|Literalslot}
ConverseGenieIntent {no my payroll id is |Literalslot}
ConverseGenieIntent {its not correct|Literalslot}
ConverseGenieIntent {its wrong|Literalslot}
ConverseGenieIntent {no|Literalslot}
ConverseGenieIntent {that's not correct|Literalslot}
ConverseGenieIntent {that is not correct|Literalslot}
ConverseGenieIntent {hi yeah|Literalslot}
ConverseGenieIntent {what is your name|Literalslot}
ConverseGenieIntent {may i know your name please|Literalslot}
ConverseGenieIntent {hey what is your name|Literalslot}

My skill is actually a bot which gives multiple conversations.

Expected converstion:

User: Alexa ask genie to say hello.

Alexa: Welcome to genie.

User: Start session..

Alexa: Please tell me the store number?

User: one two three four

Alexa: Are you calling from BRAYBOOK 1234?

User: Yes

Alexa: Please tell me payroll ID?

User: 5678
(....and continues for at least three more conversations)

But while testing in Echo:

User: Alexa ask genie to say hello.

Alexa: Welcome to genie. Please tell me the store number?

User: one two three four

Alexa: Sorry i couldn't find that

.....ALWAYS THE CONVERSATION STOPS HERE.......     I really don't know why...   I don't wanna use dialog directives as the response from the lambda function comes from a DialogFlow bot.

I tested the skill in service simulator the skill is working fine!!!   This problem happens only why i test my skill in Echo.


问:
How do you load an existing data project in EF 6.2 with database first methodology into a Web API Core2 Controller?
So I have an EF application that is working great but it is thick client and I wanted to go service based and use Azure and MS's Core 2 framework.  I go to build the Web API out of the box.  Test it works, it does great.  Now let's add a reference to my DataAccess Library that uses EF, bombs out.  Oops forgot to add EF to new project through NuGet, do that.  It proceeds to tell me it cannot find my reference to the connection string.  Okay so I wire up it in the appsettings.json to a local instance database like so (copying from what works in a WPF client project already):

```<code>{
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  },
  "ConnectionStrings": {
    "ExpensesEntities": "metadata=res://*/Expenses.csdl|res://*/Expenses.ssdl|res://*/Expenses.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=Expenses;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
  }
}
</code>```

And I change my startup like so:

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddScoped(_ => new MoneyEntry.DataAccess.ExpensesEntities());
}
</code>```

I can see it attempt to get to my context and break saying

```<code> 'FileNotFoundException: Could not load file or assembly
 'System.Configuration.ConfigurationManager,
  Version=0.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'.
  The system cannot find the file specified.'
</code>```

Yet it's breaking on this section of the EF Context

```<code>public ExpensesEntities()
        : base("name=ExpensesEntities")
    {
    }
</code>```

So I am pretty sure I just need to have the reference for the connection string in the right order and I goofed in where I put the connection string or some type of loading of the config.  I was following this thread: https://learn.microsoft.com/en-us/ef/core/miscellaneous/connection-strings

My other concern is can I mix EF Frameworks?  I wrote my Data Access Layer in EF 6.1.3 I just upgraded to 6.2 and yet I know .NET Core has it's own libraries.  Can I mix EF.NET Core with EF.NET Framework?  Or should I try to rewrite my DAL in Core too?  Whatever it is, it appears to not like it and I may just try to see if I can add a model self contained from scratch to see how it works.  But thought I would ask to see if people had experience blending frameworks on the new .NET Core 2.

EDIT 11-15-17
Okay so following this link https://learn.microsoft.com/en-us/aspnet/core/data/entity-framework-6#handle-connection-strings is a little helpful.  Yet they are doing an MVC site and not an API alone, assuming code first methodology, and also that you want dependency injection.  To simplify can you do this with Database first and just get the appsettings to recognize the EF connection string?  In the past you just make another project, copy and paste your EF section into the new app config, poof it works.  Since ASP.NET Core 2 uses an appsettings I have tried to do a simpler connection string like:

```<code>"Expenses": "Server=.;Database=Expenses;Trusted_Connection=True;MultipleActiveResultSets=true"
</code>```

I use one of my simplest tables that only has an Id int property, and a string Description property.  It then bombs on loading the controller when I hit a breakpoint just trying to get the data like so:

```<code> var data = await _context.tdType.ToListAsync();
 return View(data);
</code>```

and assumes I need to define a key and am using code first.  Am I assuming that EF Core cannot handle Model first behavior then and I need to adorn POCOs generated with Code first methodology?  If so at this point I may need to recreate my entire EF with code first and consider how to handle procedures and views with it too.

I think the key to understanding this is this model I am using has views, functions, and procedures.  From the little I know of code first you can update the mapping options of a DbSet object to override the Insert, Update, and Delete options.  But the views, functions and procedures that are not directly related to tables but multiple operations are really kind of a mystery.  It may be that EF Core simply is not full featured enough.  But for that reason I thought piggy backing an existing EF 6.2 would fix this.

答:
In short, EF Core 2.1 is not ready for production yet since it doesn't have a lot of major features like:

many-to-many relationship: https://github.com/aspnet/EntityFrameworkCore/issues/1368

Lazy loading: https://github.com/aspnet/EntityFrameworkCore/issues/3797

...

We have tried to use EF Core 2.1 on a new project but it doesn't work well for us.

I think you should check the roadmap and issue list carefully:

Road map

Issue list

Another alternatives is to use OrmLite or Dapper:
https://github.com/ServiceStack/ServiceStack.OrmLite

https://github.com/StackExchange/Dapper

I know that OrmLite and Dapper aren't what you're looking for, but those are the most stable librarys available for net core right now. We have been done two project, one with dapper and one with OrmLite.

Hope this help.

Body:
So I have an EF application that is working great but it is thick client and I wanted to go service based and use Azure and MS's Core 2 framework.  I go to build the Web API out of the box.  Test it works, it does great.  Now let's add a reference to my DataAccess Library that uses EF, bombs out.  Oops forgot to add EF to new project through NuGet, do that.  It proceeds to tell me it cannot find my reference to the connection string.  Okay so I wire up it in the appsettings.json to a local instance database like so (copying from what works in a WPF client project already):

{
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  },
  "ConnectionStrings": {
    "ExpensesEntities": "metadata=res://*/Expenses.csdl|res://*/Expenses.ssdl|res://*/Expenses.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=Expenses;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
  }
}

And I change my startup like so:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddScoped(_ => new MoneyEntry.DataAccess.ExpensesEntities());
}

I can see it attempt to get to my context and break saying

 'FileNotFoundException: Could not load file or assembly
 'System.Configuration.ConfigurationManager,
  Version=0.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'.
  The system cannot find the file specified.'

Yet it's breaking on this section of the EF Context

public ExpensesEntities()
        : base("name=ExpensesEntities")
    {
    }

So I am pretty sure I just need to have the reference for the connection string in the right order and I goofed in where I put the connection string or some type of loading of the config.  I was following this thread: https://learn.microsoft.com/en-us/ef/core/miscellaneous/connection-strings

My other concern is can I mix EF Frameworks?  I wrote my Data Access Layer in EF 6.1.3 I just upgraded to 6.2 and yet I know .NET Core has it's own libraries.  Can I mix EF.NET Core with EF.NET Framework?  Or should I try to rewrite my DAL in Core too?  Whatever it is, it appears to not like it and I may just try to see if I can add a model self contained from scratch to see how it works.  But thought I would ask to see if people had experience blending frameworks on the new .NET Core 2.

EDIT 11-15-17
Okay so following this link https://learn.microsoft.com/en-us/aspnet/core/data/entity-framework-6#handle-connection-strings is a little helpful.  Yet they are doing an MVC site and not an API alone, assuming code first methodology, and also that you want dependency injection.  To simplify can you do this with Database first and just get the appsettings to recognize the EF connection string?  In the past you just make another project, copy and paste your EF section into the new app config, poof it works.  Since ASP.NET Core 2 uses an appsettings I have tried to do a simpler connection string like:

"Expenses": "Server=.;Database=Expenses;Trusted_Connection=True;MultipleActiveResultSets=true"

I use one of my simplest tables that only has an Id int property, and a string Description property.  It then bombs on loading the controller when I hit a breakpoint just trying to get the data like so:

 var data = await _context.tdType.ToListAsync();
 return View(data);

and assumes I need to define a key and am using code first.  Am I assuming that EF Core cannot handle Model first behavior then and I need to adorn POCOs generated with Code first methodology?  If so at this point I may need to recreate my entire EF with code first and consider how to handle procedures and views with it too.

I think the key to understanding this is this model I am using has views, functions, and procedures.  From the little I know of code first you can update the mapping options of a DbSet object to override the Insert, Update, and Delete options.  But the views, functions and procedures that are not directly related to tables but multiple operations are really kind of a mystery.  It may be that EF Core simply is not full featured enough.  But for that reason I thought piggy backing an existing EF 6.2 would fix this.


问:
What to do, Learn while Developing the app or Learn first and then develop the app
I am planning to develop a web and mobile application. Have a look on this Question on OnStartups

I have some PHP & MySql knowledge, however I didn't do any major projects so far.

My skills on a scale of 5

PHP&MySql 3/5,

Javascript 3/5

CSS 3/5

Android 1.5/5

IPhone    0/5

web development (2/5)

web    design(2/5)

Software Development &    management
(1.5/5)

My app, as said in one of the answers
in the question, is not much complex
as Mint. If the complexity of Mint is
rated 8. My app would be 5/8

I have lot of interest in programming. Only thing bothering and bogging me is the time to make the app live. I don't understand how to estimate the time as I am not so experienced.

Should I start developing the app and learn all the concepts on the way?

or

should I wait learn programming completely first and then develop the app.?

Edit: A small Edit based on below answers. How should I test myself to know whether I have the minimum web development knowledge to start developing the application.

答:
Learn while developing the first version of the app, then throw it all away (unless of course, you actually made it rather maintainable) and then remake/update it with what you've learned.

And keep asking here, not just if you run into errors, but also if you're not sure what you're doing is the right way.


问:
Async working, but getting unresolved reference for await
I have the following code.

I am unable to understand why this is happening. I found no existing answer on SO covering this. I tried putting await directly where tenny and twy are assigned, but that too doesn't work.

I don't think there is a problem with the dependencies because aysnc works. I have also posted my build.gradle file.

```<code>import kotlinx.coroutines.experimental.async

fun main(args: Array<String>) {
    async{
        val tenny = star_ten(1)
        val twy =star_two(10)

        println()
        println(twy.await()+tenny.await())
        println()
    }
}

fun star_two(num:Int):Int{
    return num * 2
}
fun star_ten(num:Int):Int{
    return num * 10
}
</code>```

My build.gradle is

```<code>group 'org.nul.cool'
version '1.0-SNAPSHOT'

buildscript {
    ext.kotlin_version = '1.1.60'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

apply plugin: 'java'
apply plugin: 'kotlin'

kotlin {
    experimental {
        coroutines 'enable'
    }
}

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.19.2"
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
</code>```

答:
You are getting an unresolved reference for await() because your star_two and star_ten functions return Int, so tenny and twy variables are just Int. The await() function is declared on a Deferred. In short, you aren't doing anything asynchronous in those functions so there's nothing to await.

One way to get those functions to behave asynchronously is to declare them as suspending functions and call them each in an async block. Something like this (untested)...

```<code>async{
    val tenny = async { star_ten(1) } //Should be Deferred<Int>
    val twy = async { star_two(10)}   //Should be Deferred<Int>
    println(twy.await() + tenny.await())
}

suspend fun star_two(num:Int): Int = num * 2
suspend fun star_ten(num:Int): Int = num * 10
</code>```

The Guide to kotlinx.coroutines by example page has many good examples, especially this section.

Body:
I have the following code.

I am unable to understand why this is happening. I found no existing answer on SO covering this. I tried putting await directly where tenny and twy are assigned, but that too doesn't work.

I don't think there is a problem with the dependencies because aysnc works. I have also posted my build.gradle file.

import kotlinx.coroutines.experimental.async

fun main(args: Array<String>) {
    async{
        val tenny = star_ten(1)
        val twy =star_two(10)

        println()
        println(twy.await()+tenny.await())
        println()
    }
}

fun star_two(num:Int):Int{
    return num * 2
}
fun star_ten(num:Int):Int{
    return num * 10
}

My build.gradle is

group 'org.nul.cool'
version '1.0-SNAPSHOT'

buildscript {
    ext.kotlin_version = '1.1.60'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

apply plugin: 'java'
apply plugin: 'kotlin'

kotlin {
    experimental {
        coroutines 'enable'
    }
}

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.19.2"
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

Body:
You are getting an unresolved reference for await() because your star_two and star_ten functions return Int, so tenny and twy variables are just Int. The await() function is declared on a Deferred. In short, you aren't doing anything asynchronous in those functions so there's nothing to await.

One way to get those functions to behave asynchronously is to declare them as suspending functions and call them each in an async block. Something like this (untested)...

async{
    val tenny = async { star_ten(1) } //Should be Deferred<Int>
    val twy = async { star_two(10)}   //Should be Deferred<Int>
    println(twy.await() + tenny.await())
}

suspend fun star_two(num:Int): Int = num * 2
suspend fun star_ten(num:Int): Int = num * 10

The Guide to kotlinx.coroutines by example page has many good examples, especially this section.


答:
You're calling save on the manager (ie, objects)

```<code>return Order.objects.save(**validated_data)
</code>```

You call save on models.

I assume you're trying to create the model, in which case you want create.

```<code>return Order.objects.create(**validated_data)
</code>```

Title: Manager object has no attribute 'save'

Body:
You're calling save on the manager (ie, objects)

return Order.objects.save(**validated_data)

You call save on models.

I assume you're trying to create the model, in which case you want create.

return Order.objects.create(**validated_data)


问:
Write a list that contains headings and data to a CSV
I am currently writing a small Python 3.6 script that takes a CSV file and extracts a CVE and the hosts affected storing it in a list, as shown below.

```<code>CVE-2009-1234
10.11.1.1:80
10.11.1.3:80
10.11.1.4:80
10.11.1.2:80
10.11.1.22:80
10.11.1.2:80
10.11.1.27:80
10.11.1.23:80
10.11.1.29:80
10.11.1.228:80
CVE-2015-1234
10.11.1.224:443
10.11.1.224:80
10.11.1.74:8080
CVE-2015-1235
10.11.1.22
CVE-2017-1234
10.11.1.22:443
10.11.1.22:80
10.11.1.73:8080
CVE-2009-1235
10.11.1.22:443
10.11.1.22:80
</code>```

However I am having trouble writing this data to a CSV file so each CVE and it's affected hosts are in seperate columns for example:

```<code>CVE-2009-1234    | CVE-2015-1234      | ... |
-----------------+--------------------+-----+
10.11.1.1:80     | 10.11.1.224:443    |     |
10.11.1.3:80     | 10.11.1.224:80     |     |
10.11.1.4:80     | 10.11.1.74:8080    |     |
10.11.1.2:80     |                    |     |
10.11.1.22:80    |                    |     |
10.11.1.2:80     |                    |     |
10.11.1.22:80    |                    |     |
10.11.1.23:80    |                    |     |
10.11.1.29:80    |                    |     |
10.11.1.228:80   |                    |     |
</code>```

I originally thought that if I initialised a list the same size as the number of CVE's - then did an index lookup on the CVE number I could place each host into its corresponding index in the new list - however this became difficult when I had to try to initialise a new row because the previous spot had been filled.

I also looked into wether or not the CSV library has insert column functionality (which is obviously doesn't for good reason.

My working code is as follows:

```<code>import csv

filename = 'report.csv'
cve = set()

data = []

with open(filename) as csvfile:
    reader = csv.reader(csvfile, delimiter=',')

    for row in reader:
        if ',' in row[11]:
            multi_cve = row[11].split(', ')
            for entry in multi_cve:
                cve.add(entry)
        else:
            cve.add(row[11])

    csvfile.seek(0)

    for uniq_cve in cve:
        data.append(uniq_cve)
        for row in reader:
            if row[2] == '':
                full_address = row[0]
            else:
                full_address = row[0] + ':' + row[2]

            if ',' in row[11]:
                multi_cve = row[11].split(', ')
                for entry in multi_cve:
                    if uniq_cve == entry:
                        data.append(full_address)
            else:
                if uniq_cve == row[11]:
                    data.append(full_address)
        csvfile.seek(0)

for entry in data:
    print(entry)
</code>```

Forgot to add an example of the CSV:

```<code>IP,Hostname,Port,Port Protocol,CVSS,Severity,Solution Type,NVT Name,Summary,Specific Result,NVT OID,CVEs,Task ID,Task Name,Timestamp,Result ID,Impact,Solution,Affected Software/OS,Vulnerability Insight,Vulnerability Detection Method,Product Detection Result,BIDs,CERTs,Other References
10.11.1.1,,80,tcp,5,Medium,VendorFix,IIS Service Pack - 404,Ensure that the server is running the latest stable Service Pack,The remote IIS server *seems* to be Microsoft IIS 6.0 - w2k3 build 3790,1.3.6.1.4.1.25623.1.0.11874,NOCVE,80e72026-6304-4d23-8cdf-e4789507d231,Scan of all pinged hosts,2017-11-14T05:19:39Z,8a3d71d2-6fa4-4f06-ab7f-b8965667c56b,,"The Patch level (Service Pack) of the remote IIS server appears to be lower
  than the current IIS service pack level. As each service pack typically
  contains many security patches, the server may be at risk.

  Caveat: This test makes assumptions of the remote patch level based on static
  return values (Content-Length) within the IIS Servers 404 error message.
  As such, the test can not be totally reliable and should be manually confirmed.",,,"
Details:
IIS Service Pack - 404
(OID: 1.3.6.1.4.1.25623.1.0.11874)
Version used: $Revision: 4703 $
",,,,
10.11.1.1,,80,tcp,5,Medium,VendorFix,IIS Service Pack - 404,Ensure that the server is running the latest stable Service Pack,The remote IIS server *seems* to be Microsoft IIS 6.0 - w2k3 build 3790,1.3.6.1.4.1.25623.1.0.11874,NOCVE,80e72026-6304-4d23-8cdf-e4789507d231,Scan of all pinged hosts,2017-11-14T05:19:39Z,2ba7442c-5a46-4628-95d3-a2decae3a57a,,"The Patch level (Service Pack) of the remote IIS server appears to be lower
  than the current IIS service pack level. As each service pack typically
  contains many security patches, the server may be at risk.

  Caveat: This test makes assumptions of the remote patch level based on static
  return values (Content-Length) within the IIS Servers 404 error message.
  As such, the test can not be totally reliable and should be manually confirmed.",,,"
Details:
IIS Service Pack - 404
(OID: 1.3.6.1.4.1.25623.1.0.11874)
Version used: $Revision: 4703 $
",,,,
10.11.1.1,,80,tcp,4.3,Medium,VendorFix,Adobe BlazeDS XML and XML External Entity Injection Vulnerabilities,Adobe BlazeDS is prone to an XML-injection vulnerability and an XML External Entity injection vulnerability.,Vulnerable url: http://10.11.1.10/flex2gateway/http,1.3.6.1.4.1.25623.1.0.105211,CVE-2009-3960,80e72026-6304-4d23-8cdf-e4789507d231,Scan of all pinged hosts,2017-11-14T05:19:39Z,0a09cb06-7ae6-4234-90f3-bb61f10da46a,Attackers can exploit these issues to obtain sensitive information and carry out other attacks.,"Updates are available, please refer to the linked advisory.","The following applications are affected:

 BlazeDS 3.2 and earlier versions
 LiveCycle 9.0, 8.2.1, and 8.0.1
 LiveCycle Data Services 3.0, 2.6.1, and 2.5.1
 Flex Data Services 2.0.1
 ColdFusion 9.0, 8.0.1, 8.0, and 7.0.2",,"Send an modificated GET request and check the response
Details:
Adobe BlazeDS XML and XML External Entity Injection Vulnerabilities
(OID: 1.3.6.1.4.1.25623.1.0.105211)
Version used: $Revision: 7293 $
",,38197,,"http://www.securityfocus.com/bid/38197, http://www.adobe.com/support/security/bulletins/apsb10-05.html"
</code>```

答:
I ended up with a solution in the end. It may not be the best solution, but it works for my purposes. What I did:

Instead of inserting everything into the one list I created a list of
lists cve_lists

I then find the longest list in cve_lists - which tells us how many rows we need at a minimum

The code is as follows:

```<code>longest_list = len(max(cve_lists,key=len))

rows = []
row = []

# works out the maximum number of iterations we need to get all entries
for count in range(0, (len(cve) * longest_list)):
    for entry in cve_lists:
        try:
            row.append(entry[0])
            entry.pop(0)
        except IndexError:
            # if there is no index, we know there is no data and
            # append a blank entry
            row.append('')

    rows.append(row)
    row = []

with open(args.file , 'w') as resultFile:
    wr = csv.writer(resultFile, dialect='excel')
    wr.writerows(rows)
</code>```

Body:
I am currently writing a small Python 3.6 script that takes a CSV file and extracts a CVE and the hosts affected storing it in a list, as shown below.

CVE-2009-1234
10.11.1.1:80
10.11.1.3:80
10.11.1.4:80
10.11.1.2:80
10.11.1.22:80
10.11.1.2:80
10.11.1.27:80
10.11.1.23:80
10.11.1.29:80
10.11.1.228:80
CVE-2015-1234
10.11.1.224:443
10.11.1.224:80
10.11.1.74:8080
CVE-2015-1235
10.11.1.22
CVE-2017-1234
10.11.1.22:443
10.11.1.22:80
10.11.1.73:8080
CVE-2009-1235
10.11.1.22:443
10.11.1.22:80

However I am having trouble writing this data to a CSV file so each CVE and it's affected hosts are in seperate columns for example:

CVE-2009-1234    | CVE-2015-1234      | ... |
-----------------+--------------------+-----+
10.11.1.1:80     | 10.11.1.224:443    |     |
10.11.1.3:80     | 10.11.1.224:80     |     |
10.11.1.4:80     | 10.11.1.74:8080    |     |
10.11.1.2:80     |                    |     |
10.11.1.22:80    |                    |     |
10.11.1.2:80     |                    |     |
10.11.1.22:80    |                    |     |
10.11.1.23:80    |                    |     |
10.11.1.29:80    |                    |     |
10.11.1.228:80   |                    |     |

I originally thought that if I initialised a list the same size as the number of CVE's - then did an index lookup on the CVE number I could place each host into its corresponding index in the new list - however this became difficult when I had to try to initialise a new row because the previous spot had been filled.

I also looked into wether or not the CSV library has insert column functionality (which is obviously doesn't for good reason.

My working code is as follows:

import csv

filename = 'report.csv'
cve = set()

data = []

with open(filename) as csvfile:
    reader = csv.reader(csvfile, delimiter=',')

    for row in reader:
        if ',' in row[11]:
            multi_cve = row[11].split(', ')
            for entry in multi_cve:
                cve.add(entry)
        else:
            cve.add(row[11])

    csvfile.seek(0)

    for uniq_cve in cve:
        data.append(uniq_cve)
        for row in reader:
            if row[2] == '':
                full_address = row[0]
            else:
                full_address = row[0] + ':' + row[2]

            if ',' in row[11]:
                multi_cve = row[11].split(', ')
                for entry in multi_cve:
                    if uniq_cve == entry:
                        data.append(full_address)
            else:
                if uniq_cve == row[11]:
                    data.append(full_address)
        csvfile.seek(0)

for entry in data:
    print(entry)

Forgot to add an example of the CSV:

IP,Hostname,Port,Port Protocol,CVSS,Severity,Solution Type,NVT Name,Summary,Specific Result,NVT OID,CVEs,Task ID,Task Name,Timestamp,Result ID,Impact,Solution,Affected Software/OS,Vulnerability Insight,Vulnerability Detection Method,Product Detection Result,BIDs,CERTs,Other References
10.11.1.1,,80,tcp,5,Medium,VendorFix,IIS Service Pack - 404,Ensure that the server is running the latest stable Service Pack,The remote IIS server *seems* to be Microsoft IIS 6.0 - w2k3 build 3790,1.3.6.1.4.1.25623.1.0.11874,NOCVE,80e72026-6304-4d23-8cdf-e4789507d231,Scan of all pinged hosts,2017-11-14T05:19:39Z,8a3d71d2-6fa4-4f06-ab7f-b8965667c56b,,"The Patch level (Service Pack) of the remote IIS server appears to be lower
  than the current IIS service pack level. As each service pack typically
  contains many security patches, the server may be at risk.

  Caveat: This test makes assumptions of the remote patch level based on static
  return values (Content-Length) within the IIS Servers 404 error message.
  As such, the test can not be totally reliable and should be manually confirmed.",,,"
Details:
IIS Service Pack - 404
(OID: 1.3.6.1.4.1.25623.1.0.11874)
Version used: $Revision: 4703 $
",,,,
10.11.1.1,,80,tcp,5,Medium,VendorFix,IIS Service Pack - 404,Ensure that the server is running the latest stable Service Pack,The remote IIS server *seems* to be Microsoft IIS 6.0 - w2k3 build 3790,1.3.6.1.4.1.25623.1.0.11874,NOCVE,80e72026-6304-4d23-8cdf-e4789507d231,Scan of all pinged hosts,2017-11-14T05:19:39Z,2ba7442c-5a46-4628-95d3-a2decae3a57a,,"The Patch level (Service Pack) of the remote IIS server appears to be lower
  than the current IIS service pack level. As each service pack typically
  contains many security patches, the server may be at risk.

  Caveat: This test makes assumptions of the remote patch level based on static
  return values (Content-Length) within the IIS Servers 404 error message.
  As such, the test can not be totally reliable and should be manually confirmed.",,,"
Details:
IIS Service Pack - 404
(OID: 1.3.6.1.4.1.25623.1.0.11874)
Version used: $Revision: 4703 $
",,,,
10.11.1.1,,80,tcp,4.3,Medium,VendorFix,Adobe BlazeDS XML and XML External Entity Injection Vulnerabilities,Adobe BlazeDS is prone to an XML-injection vulnerability and an XML External Entity injection vulnerability.,Vulnerable url: http://10.11.1.10/flex2gateway/http,1.3.6.1.4.1.25623.1.0.105211,CVE-2009-3960,80e72026-6304-4d23-8cdf-e4789507d231,Scan of all pinged hosts,2017-11-14T05:19:39Z,0a09cb06-7ae6-4234-90f3-bb61f10da46a,Attackers can exploit these issues to obtain sensitive information and carry out other attacks.,"Updates are available, please refer to the linked advisory.","The following applications are affected:

 BlazeDS 3.2 and earlier versions
 LiveCycle 9.0, 8.2.1, and 8.0.1
 LiveCycle Data Services 3.0, 2.6.1, and 2.5.1
 Flex Data Services 2.0.1
 ColdFusion 9.0, 8.0.1, 8.0, and 7.0.2",,"Send an modificated GET request and check the response
Details:
Adobe BlazeDS XML and XML External Entity Injection Vulnerabilities
(OID: 1.3.6.1.4.1.25623.1.0.105211)
Version used: $Revision: 7293 $
",,38197,,"http://www.securityfocus.com/bid/38197, http://www.adobe.com/support/security/bulletins/apsb10-05.html"

Body:
I ended up with a solution in the end. It may not be the best solution, but it works for my purposes. What I did:

Instead of inserting everything into the one list I created a list of
lists cve_lists

I then find the longest list in cve_lists - which tells us how many rows we need at a minimum

The code is as follows:

longest_list = len(max(cve_lists,key=len))

rows = []
row = []

# works out the maximum number of iterations we need to get all entries
for count in range(0, (len(cve) * longest_list)):
    for entry in cve_lists:
        try:
            row.append(entry[0])
            entry.pop(0)
        except IndexError:
            # if there is no index, we know there is no data and
            # append a blank entry
            row.append('')

    rows.append(row)
    row = []

with open(args.file , 'w') as resultFile:
    wr = csv.writer(resultFile, dialect='excel')
    wr.writerows(rows)


问:
SqlPackage.exe takes a long time
So we are working on adding SQL DACPACs as part of our continues integration. We do this with powershell script running "sqlpackage.exe" with each DacPac file. we have about 12 DBs so it's about 12 DacPacs.

Everytime we run "sqlpackage.exe" to publish or script the DacPac we notice that it will take between 0.5-1+ min to complete initialization. Most of this time is being taken during initialization flow when "sqlpackage.exe" begins.

i'm trying to find a way to reduce this if possible since we have 12 DBs we are talking about at least 12 min for DB Deployment which is too much for us.

Do you know of any way to be able to reduce this?

答: This might be too late but potentially useful for others - we found that opening up all ports in the firewall on the SQL server solved our problem of deployment taking a long time. Went from about 4-5 minutes to about 1 minute.</p>

Title: SqlPackage.exe takes a long time


问:
2 tables in Local DB in MVC using a foreign key to interact - Error, returns "The property cannot be configured as a navigation property
So my teammates and I are building a website that aggregates textbook prices from different textbook websites (we aren't dynamically getting the prices from the websites themselves, but for the purposes of the school project we are in, we are just randomly entering them in).

So I've got two tables in my database Book1 - a "Books" table and a "Prices" table. I have a foreign key in my Prices table (screenshot of design view) that relates back to my Books table (screenshot of design view).

The ISBN field of our Prices table is a foreign key to the ISBN field of our Books table.

We believe we've set everything else up correctly but when we run it, it returns an exception saying:

The property 'ISBN' cannot be configured as a navigation property. The
  property must be a valid entity type and the property should have a
  non-abstract getter and setter. For collection properties the type
  must implement ICollection where T is a valid entity type.

Here are all the relevant classes.

Book.cs

```<code>public partial class Book
{
    [Key, Required]
    [StringLength(14)]
    public string ISBN { get; set; }

    public string Title { get; set; }

    public string Author { get; set; }

    public string Publisher { get; set; }

    public string YearPublished { get; set; }

    public virtual Price Price { get; set; }
}
</code>```

Price.cs

```<code> public partial class Price
    {
        [Key, Required]
        public int PriceID { get; set; }

        [ForeignKey("ISBN")]
        public string ISBN { get; set; }

        public decimal? AmazonPrice { get; set; }

        public decimal? BarnesAndNoblePrice { get; set; }

        public decimal? CheggPrice { get; set; }

        public decimal? SecondAndCharlesPrice { get; set; }

        public decimal? AlibrisPrice { get; set; }

        public decimal? ThriftBooksPrice { get; set; }

        public decimal? ValoreBooksPrice { get; set; }

        public virtual Book Book { get; set; }

        public virtual IEnumerable<Book> Books { get; set; }
    }
</code>```

MyModel.cs

```<code>public class MyModel : DbContext
{
    public MyModel()
        : base("name=DefaultConnection") { }

    public virtual DbSet<Book> Books { get; set; }
    public virtual DbSet<Price> Prices { get; set; }
}
</code>```

HomeController.cs

```<code>public ActionResult Index()
    {
        var model = new IndexVM();
        var ctx = new MyModel();
        foreach (var bk in ctx.Books)
        {
            model.Books.Add(bk);
        }
        return View(model);
    }
</code>```

We've been told by our professor that it has something to do with the IEnumerable class, but we've tried every combination in the book and we still can't get it to work.

Any and all help will be appreciated.

答:
In Price.cs

```<code>[ForeignKey("ISBN")]
public string ISBN { get; set; }
</code>```

should read

```<code>[ForeignKey("Book")]
public string ISBN { get; set; }
</code>```

Additionally in Book.cs I think you need somewhere to store the cross reference to Price

```<code>[ForeignKey("Price")]
public int PriceId { get; set; }
</code>```

this question describes the same issue Foreign Key Annotation in MVC

Body:
So my teammates and I are building a website that aggregates textbook prices from different textbook websites (we aren't dynamically getting the prices from the websites themselves, but for the purposes of the school project we are in, we are just randomly entering them in).

So I've got two tables in my database Book1 - a "Books" table and a "Prices" table. I have a foreign key in my Prices table (screenshot of design view) that relates back to my Books table (screenshot of design view).

The ISBN field of our Prices table is a foreign key to the ISBN field of our Books table.

We believe we've set everything else up correctly but when we run it, it returns an exception saying:

The property 'ISBN' cannot be configured as a navigation property. The
  property must be a valid entity type and the property should have a
  non-abstract getter and setter. For collection properties the type
  must implement ICollection where T is a valid entity type.

Here are all the relevant classes.

Book.cs

public partial class Book
{
    [Key, Required]
    [StringLength(14)]
    public string ISBN { get; set; }

    public string Title { get; set; }

    public string Author { get; set; }

    public string Publisher { get; set; }

    public string YearPublished { get; set; }

    public virtual Price Price { get; set; }
}

Price.cs

 public partial class Price
    {
        [Key, Required]
        public int PriceID { get; set; }

        [ForeignKey("ISBN")]
        public string ISBN { get; set; }

        public decimal? AmazonPrice { get; set; }

        public decimal? BarnesAndNoblePrice { get; set; }

        public decimal? CheggPrice { get; set; }

        public decimal? SecondAndCharlesPrice { get; set; }

        public decimal? AlibrisPrice { get; set; }

        public decimal? ThriftBooksPrice { get; set; }

        public decimal? ValoreBooksPrice { get; set; }

        public virtual Book Book { get; set; }

        public virtual IEnumerable<Book> Books { get; set; }
    }

MyModel.cs

public class MyModel : DbContext
{
    public MyModel()
        : base("name=DefaultConnection") { }

    public virtual DbSet<Book> Books { get; set; }
    public virtual DbSet<Price> Prices { get; set; }
}

HomeController.cs

public ActionResult Index()
    {
        var model = new IndexVM();
        var ctx = new MyModel();
        foreach (var bk in ctx.Books)
        {
            model.Books.Add(bk);
        }
        return View(model);
    }

We've been told by our professor that it has something to do with the IEnumerable class, but we've tried every combination in the book and we still can't get it to work.

Any and all help will be appreciated.

Body:
In Price.cs

[ForeignKey("ISBN")]
public string ISBN { get; set; }

should read

[ForeignKey("Book")]
public string ISBN { get; set; }

Additionally in Book.cs I think you need somewhere to store the cross reference to Price

[ForeignKey("Price")]
public int PriceId { get; set; }

this question describes the same issue Foreign Key Annotation in MVC


问:
What are extensions need to run cakePHP
Im new to cakePHP. With it upload function not working now. I got already developed project to work. What are PHP extensions I need to enable for cakePHP ? </p>

答:
Go to your php.ini file and enable this two extension.

extension=php_mbstring.dll

extension=php_intl.dll

and make sure
file_uploads = On.

Then restart the apache.

Title: What are extensions need to run cakePHP


问:
How precise are Google Chrome extension statistics?
I published a Chrome Extension, but statistics are weird. At first, I realized that it doesn't count inline installation on my custom webpage.

Do you think that Total Current Users is precise?

For some days I have bigger drop of Total Current Users than number of uninstallations, which is nonsense.

Is there any way how to get precise statistics of total users, installations and uninstallations?

答:
I am not sure is how precise stats in the current version of Developer Dashboard. But I know that Google working on a new version and it is already in closed-beta testing.

The new one has more detailed stats about installation sources.

Here also some steps that can help to improve your stats counting:

Add Google Analytics tracking ID to your Chrome Web Store item;

Track 'successCallback' event on the extensions promo website;

Open a "welcome" page, hosted on your website – so you can count those who just installed the extension. Docs: chrome.runtime.onInstalled;

Open a "good bye" page, after users remove your extension from a browser. So you can calc uninstall events. One more benefit - you can ask "what was wrong?". Docs: chrome.runtime.setUninstallURL.

Updated.


问:
Android Facebook Login get Email
I have a simple app with facebook login button and displaying the user info. I am trying to get the user email, used many ways but it gives back a null value. How to get the user email ?</p>

```<code>loginButton=(LoginButton)findViewById(R.id.loginButton);
loginButton.setReadPermissions(Arrays.asList("public_profile", "email"));
callbackManager= CallbackManager.Factory.create();
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(LoginResult loginResult) {
        loginButton.setVisibility(View.GONE);
        //how to get user email here
        finish();
    }

    @Override
    public void onCancel() {
        Toast.makeText(PopUpFaceBook.this,"تم الغاء تسجيل الدخول",Toast.LENGTH_SHORT).show();
        finish();
    }

    @Override
    public void onError(FacebookException error) {
        Toast.makeText(PopUpFaceBook.this,"هناك مشكلة فى تسجيل الدخول حاول مجددا",Toast.LENGTH_SHORT).show();
        finish();
    }
});
</code>```

答:
You may use Firebase for this, it will really help you to get all information of facebook profile, such as:
1. Email
2. Name
3. Profile Photo, etc.

Follow steps in below link:

https://firebase.google.com/docs/auth/android/facebook-login

Thanks

Title: Android Facebook Login get Email

Body:
I have a simple app with facebook login button and displaying the user info. I am trying to get the user email, used many ways but it gives back a null value. How to get the user email ?

loginButton=(LoginButton)findViewById(R.id.loginButton);
loginButton.setReadPermissions(Arrays.asList("public_profile", "email"));
callbackManager= CallbackManager.Factory.create();
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(LoginResult loginResult) {
        loginButton.setVisibility(View.GONE);
        //how to get user email here
        finish();
    }

    @Override
    public void onCancel() {
        Toast.makeText(PopUpFaceBook.this,"تم الغاء تسجيل الدخول",Toast.LENGTH_SHORT).show();
        finish();
    }

    @Override
    public void onError(FacebookException error) {
        Toast.makeText(PopUpFaceBook.this,"هناك مشكلة فى تسجيل الدخول حاول مجددا",Toast.LENGTH_SHORT).show();
        finish();
    }
});


问:
No Image on IE browser when using Image Button or Button Field in Grid View
Does anyone know why I'm encountering this issue using IE (all version) as browser? The image works perfectly on Chrome but not on IE.

Here is an example screenshot of what I'm talking about:

IE:

And when I try this using Chrome it works as expected.

Chrome:

and here is the code I use which I also found on the Internet.

```<code><asp:GridView ID="gvJobs" runat="server" OnRowCommand="gvJobs_RowCommand">
    <Columns>
        <%--<asp:ButtonField ButtonType="Image" CommandName="btnExtract_Click" ImageUrl="~/images/icons/ExcelLogo.png" CausesValidation="false" />--%>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:ImageButton ID="btnExtractId" AutoPostback="true" runat="server"
                    ToolTip="Calibration Form" CommandName="btnExtract_Click" CausesValidation="false" ImageUrl="~/images/icons/ExcelLogo.png" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:HyperLinkField HeaderText="Job Reference" DataTextField="JobReference" DataNavigateUrlFields="JobId" DataNavigateUrlFormatString="job.aspx?jobid={0}" />
        <asp:BoundField HeaderText="Job Type" DataField="JobTypeName" />
        <asp:BoundField HeaderText="Business Unit" DataField="BusinessUnitName" />
        <asp:BoundField HeaderText="Client" DataField="ClientFullname" />
        <asp:BoundField HeaderText="Planned Completion Date" DataField="PlannedCompletionDate" DataFormatString="{0:dd/MM/yyyy}" />
        <asp:HyperLinkField HeaderText="Parent Job" DataTextField="ParentJobReference" DataNavigateUrlFields="ParentJobId" DataNavigateUrlFormatString="job.aspx?jobid={0}" Visible="false" />
    </Columns>
</asp:GridView>
</code>```

I already tried the two controls but still no luck on the issue. I also look for a solution on the Internet but it does not help me solve my problem.

Thanks in advance to someone who can help me.

答:
i have tried your code with static values and its working fine.
you need to clear cache of internet Explorer i guess. or press ctrl + F5

Either its cached on chrome or IE also you need to check file exist or not after clearing cache.

here we go with the screenshot using your code.

do let me know if you need any help

Body:
Does anyone know why I'm encountering this issue using IE (all version) as browser? The image works perfectly on Chrome but not on IE.

Here is an example screenshot of what I'm talking about:

IE:

And when I try this using Chrome it works as expected.

Chrome:

and here is the code I use which I also found on the Internet.

<asp:GridView ID="gvJobs" runat="server" OnRowCommand="gvJobs_RowCommand">
    <Columns>
        <%--<asp:ButtonField ButtonType="Image" CommandName="btnExtract_Click" ImageUrl="~/images/icons/ExcelLogo.png" CausesValidation="false" />--%>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:ImageButton ID="btnExtractId" AutoPostback="true" runat="server"
                    ToolTip="Calibration Form" CommandName="btnExtract_Click" CausesValidation="false" ImageUrl="~/images/icons/ExcelLogo.png" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:HyperLinkField HeaderText="Job Reference" DataTextField="JobReference" DataNavigateUrlFields="JobId" DataNavigateUrlFormatString="job.aspx?jobid={0}" />
        <asp:BoundField HeaderText="Job Type" DataField="JobTypeName" />
        <asp:BoundField HeaderText="Business Unit" DataField="BusinessUnitName" />
        <asp:BoundField HeaderText="Client" DataField="ClientFullname" />
        <asp:BoundField HeaderText="Planned Completion Date" DataField="PlannedCompletionDate" DataFormatString="{0:dd/MM/yyyy}" />
        <asp:HyperLinkField HeaderText="Parent Job" DataTextField="ParentJobReference" DataNavigateUrlFields="ParentJobId" DataNavigateUrlFormatString="job.aspx?jobid={0}" Visible="false" />
    </Columns>
</asp:GridView>

I already tried the two controls but still no luck on the issue. I also look for a solution on the Internet but it does not help me solve my problem.

Thanks in advance to someone who can help me.


问:
API security: how to secure refresh token api's
I have two api's used in auth

1)api/auth/newtoken

Successfully validates user (ie username and password check in DB) and return token(expir:3 days) and refreshToken.

1)api/auth/updatetoken

when the token is expired call this api with refreshToken and get the new token.

My question is how can i protect api/auth/updatetoken api ? currenlty this api's are for an android application and it will easy to get this api's once we decomplile the application .

What are some better approach to secure this api??

答: Save the device id then for refresh you can check if the device id submitted is correct or not, if necessary use IP too</p>


问:
Giant set of strings leads to memory error - alternative?
I'm trying to create a really huge list of incrementing 9 digits numbers (worst case). My plan is to have something like this:

```<code>['000000001', '000000002' , ..............,'999999999']
</code>```

I already wrote the code. However, as soon as I run the code, my console prints "Memory Error" message.

Here is my current code:

```<code>HUGE_LIST = [''.join(i) for i in product('012345678', repeat = 9)
</code>```

I know this might not be the best code to produce the list. Thus, can someone help me find a better way to solve this memory issue?

I'm planning to use HUGE_LIST for comparison with user input.

Example: a user enters '12345678' as input, then I want my code to assert that input with the HUGE_LIST.

答:
The best way to solve an issue like this is to avoid a memory-intensive algorithm entirely. In this case, since your goal is to test whether a particular string is in the list, just write a function that checks whether the string satisfies the criteria to be in the list. For example, if your list contains all sequences of 9 digits, then your function just has to check whether a given input is a sequence of 9 digits.

```<code>def check(string):
    return len(string) == 9 and all(c.isdigit() for c in string)
</code>```

(in practice, give it a better name than check). Or if you want all sequences of 9 digits in which none of them is a 9, as your current code defining HUGE_LIST suggests, you could write

```<code>def check(string):
    return len(string) == 9 and all(c.isdigit() and c != '9' for c in string)
</code>```

Or so on.

If you can't write an algorithm to decide whether a string (or whatever) is in the list or not, the next best thing is to make a generator that will produce the values one at a time. If you already have a list comprehension, like

```<code>HUGE_LIST = [<something> for <variable> in <expression>]
</code>```

then you can turn that into a generator by replacing the square brackets with parentheses:

```<code>HUGE_GENERATOR = (<something> for <variable> in <expression>)
</code>```

Then you can test for membership using string in HUGE_GENERATOR. Note that after doing so, HUGE_GENERATOR will be (at least partially) consumed, so you can't use it for another membership test; you will have to recreate it if you want to test again.

Body:
I'm trying to create a really huge list of incrementing 9 digits numbers (worst case). My plan is to have something like this:

['000000001', '000000002' , ..............,'999999999']

I already wrote the code. However, as soon as I run the code, my console prints "Memory Error" message.

Here is my current code:

HUGE_LIST = [''.join(i) for i in product('012345678', repeat = 9)

I know this might not be the best code to produce the list. Thus, can someone help me find a better way to solve this memory issue?

I'm planning to use HUGE_LIST for comparison with user input.

Example: a user enters '12345678' as input, then I want my code to assert that input with the HUGE_LIST.

Body:
The best way to solve an issue like this is to avoid a memory-intensive algorithm entirely. In this case, since your goal is to test whether a particular string is in the list, just write a function that checks whether the string satisfies the criteria to be in the list. For example, if your list contains all sequences of 9 digits, then your function just has to check whether a given input is a sequence of 9 digits.

def check(string):
    return len(string) == 9 and all(c.isdigit() for c in string)

(in practice, give it a better name than check). Or if you want all sequences of 9 digits in which none of them is a 9, as your current code defining HUGE_LIST suggests, you could write

def check(string):
    return len(string) == 9 and all(c.isdigit() and c != '9' for c in string)

Or so on.

If you can't write an algorithm to decide whether a string (or whatever) is in the list or not, the next best thing is to make a generator that will produce the values one at a time. If you already have a list comprehension, like

HUGE_LIST = [<something> for <variable> in <expression>]

then you can turn that into a generator by replacing the square brackets with parentheses:

HUGE_GENERATOR = (<something> for <variable> in <expression>)

Then you can test for membership using string in HUGE_GENERATOR. Note that after doing so, HUGE_GENERATOR will be (at least partially) consumed, so you can't use it for another membership test; you will have to recreate it if you want to test again.


问:
Access API returns JSON array
I am using Javascript to decode a vehicles VIN number via an API. The returned message looks like this:

```<code>{Count: 116, Message: "Results returned successfully", SearchCriteria: "VIN(s): 60540kjhkjhkj5885", Results: Array(1)}
</code>```

I need to know how to access the returned array in results.

This is my current Javascript:

```<code>   // Decode VIN Number
function post_VIN_decode() {
    var vinNumber = $('#id_vin_number').val();
    console.log("VIN Decode Sent") // sanity check
    $.ajax({
        url : "https://vpic.nhtsa.dot.gov/api/vehicles/decodevinvalues/" + vinNumber + "?format=json", // the endpoint
        type : "GET", // http method

        // handle a successful response
        success : function(json) {
            console.log(json); // log the returned json to the console
        },

        // handle a non-successful response
        error : function(xhr,errmsg,err) {
            $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
                " <a href='#' class='close'>×</a></div>"); // add the error to the dom
            console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
        }
    });
};

$('#id_vin_number').keyup(function(e){
    if($("#id_vin_number").val().length >= 17){
        event.preventDefault();
        console.log("VIN Decode started")  // sanity check
        post_VIN_decode();
    }
});
</code>```

Any help is appreciated.

答:
If you would like to iterate through the array and do some processing on the elements, Array#forEach is what you need here.

```<code>...

success: function(json) {
  json.Results.forEach(function(item, index) {
    console.log(item, index);
  });
},

...
</code>```

Refer to the link in my answer to read more about this function and examples.

Title: Access API returns JSON array

Body:
I am using Javascript to decode a vehicles VIN number via an API. The returned message looks like this:

{Count: 116, Message: "Results returned successfully", SearchCriteria: "VIN(s): 60540kjhkjhkj5885", Results: Array(1)}

I need to know how to access the returned array in results.

This is my current Javascript:

   // Decode VIN Number
function post_VIN_decode() {
    var vinNumber = $('#id_vin_number').val();
    console.log("VIN Decode Sent") // sanity check
    $.ajax({
        url : "https://vpic.nhtsa.dot.gov/api/vehicles/decodevinvalues/" + vinNumber + "?format=json", // the endpoint
        type : "GET", // http method

        // handle a successful response
        success : function(json) {
            console.log(json); // log the returned json to the console
        },

        // handle a non-successful response
        error : function(xhr,errmsg,err) {
            $('#results').html("
Oops! We have encountered an error: "+errmsg+
                " ×
"); // add the error to the dom
            console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
        }
    });
};

$('#id_vin_number').keyup(function(e){
    if($("#id_vin_number").val().length >= 17){
        event.preventDefault();
        console.log("VIN Decode started")  // sanity check
        post_VIN_decode();
    }
});

Any help is appreciated.

Body:
If you would like to iterate through the array and do some processing on the elements, Array#forEach is what you need here.

...

success: function(json) {
  json.Results.forEach(function(item, index) {
    console.log(item, index);
  });
},

...

Refer to the link in my answer to read more about this function and examples.


问:
how to put carousel scroll arrow key to middle of the page
I have bootstrap carousel scroll arrows key in left and right side. but currently it is on the top side of the banner page. but I need put it middle of the page. My css class is this for arrow keys.

```<code>.carousel-control.left {margin-left: -85px; color: black;}
.carousel-control.right {margin-right: -85px; color: black;}
</code>```

how can put my arrow keys to middle of the page?

答:
Add this.

```<code>.carousel-control {
position: absolute;
top: 50%;
z-index: 5;
display: inline-block;
}
</code>```

Sample

http://jsfiddle.net/WmMXa/671/

Body:
I have bootstrap carousel scroll arrows key in left and right side. but currently it is on the top side of the banner page. but I need put it middle of the page. My css class is this for arrow keys.

.carousel-control.left {margin-left: -85px; color: black;}
.carousel-control.right {margin-right: -85px; color: black;}

how can put my arrow keys to middle of the page?

Body:
Add this.

.carousel-control {
position: absolute;
top: 50%;
z-index: 5;
display: inline-block;
}

Sample

http://jsfiddle.net/WmMXa/671/


问:
Extract relationships from a sentence in NLTK
I am using NLTK to extract the relationship between a PERSON and an ORGANIZATION.

Also, I want to extract the relationship between ORGANIZATION and LOCATION.
The NLTK version is 3.2.1.

I've made use of Part-Of-Speech tagging and Named Entity Recognition (NER). Also the Parse Tree is drawn for the NER results.

But I am not able to extract the mentioned relationships from that sentence.

Here is the code:

```<code>import nltk, re
from nltk import word_tokenize

sentence = "Mark works at JPMC in London every day"
pos_tags = nltk.pos_tag(word_tokenize(sentence))            # POS tagging of the sentence
ne = nltk.ne_chunk(pos_tags)                                # Named Entity Recognition
ne.draw()                                                   # Draw the Parse Tree

IN = re.compile(r'.*\bin\b(?!\b.+ing)')
for rel1 in nltk.sem.extract_rels('PER', 'ORG', pos_tags, pattern = IN):
    print(nltk.sem.rtuple(rel1))
for rel2 in nltk.sem.extract_rels('ORG', 'LOC', pos_tags, pattern = IN):
    print(nltk.sem.rtuple(rel2))
</code>```

How to extract 'Person - Organization' relationship and 'Organization - Location' relationship?

答:
I think docs is not tagged pos, it should be NE.

Working code

```<code>senten = "Mark works in JPMC in London every day"
pos_tags = nltk.pos_tag(word_tokenize(senten))  # POS tagging of the sentence
ne = nltk.ne_chunk(pos_tags)  # Named Entity Recognition

chunked = nltk.ne_chunk_sents(pos_tags, binary=True)
# ne.draw()  # Draw the Parse Tree

print(pos_tags)

IN = re.compile(r'.*\bin\b(?!\b.+ing)')

for rel in nltk.sem.extract_rels('PERSON', 'ORGANIZATION', ne, corpus='ace', pattern=IN):
    print(nltk.sem.rtuple(rel))
</code>```

Output

[PER: 'Mark/NNP'] 'works/VBZ in/IN' [ORG: 'JPMC/NNP']

Body:
I am using NLTK to extract the relationship between a PERSON and an ORGANIZATION.

Also, I want to extract the relationship between ORGANIZATION and LOCATION.
The NLTK version is 3.2.1.

I've made use of Part-Of-Speech tagging and Named Entity Recognition (NER). Also the Parse Tree is drawn for the NER results.

But I am not able to extract the mentioned relationships from that sentence.

Here is the code:

import nltk, re
from nltk import word_tokenize

sentence = "Mark works at JPMC in London every day"
pos_tags = nltk.pos_tag(word_tokenize(sentence))            # POS tagging of the sentence
ne = nltk.ne_chunk(pos_tags)                                # Named Entity Recognition
ne.draw()                                                   # Draw the Parse Tree

IN = re.compile(r'.*\bin\b(?!\b.+ing)')
for rel1 in nltk.sem.extract_rels('PER', 'ORG', pos_tags, pattern = IN):
    print(nltk.sem.rtuple(rel1))
for rel2 in nltk.sem.extract_rels('ORG', 'LOC', pos_tags, pattern = IN):
    print(nltk.sem.rtuple(rel2))

How to extract 'Person - Organization' relationship and 'Organization - Location' relationship?

Body:
I think docs is not tagged pos, it should be NE.

Working code

senten = "Mark works in JPMC in London every day"
pos_tags = nltk.pos_tag(word_tokenize(senten))  # POS tagging of the sentence
ne = nltk.ne_chunk(pos_tags)  # Named Entity Recognition

chunked = nltk.ne_chunk_sents(pos_tags, binary=True)
# ne.draw()  # Draw the Parse Tree

print(pos_tags)

IN = re.compile(r'.*\bin\b(?!\b.+ing)')

for rel in nltk.sem.extract_rels('PERSON', 'ORGANIZATION', ne, corpus='ace', pattern=IN):
    print(nltk.sem.rtuple(rel))

Output

[PER: 'Mark/NNP'] 'works/VBZ in/IN' [ORG: 'JPMC/NNP']


问:
reprocess ssl certbot , when a alias domain fails but certificate is generated, no mode certonly
I've start certbot process with:

```<code>sudo certbot --nginx -d example.com -d www.example.com
</code>```

but I forgot to add 'www.example.com' in 'servernam' nginx virtualsite for example.com

```<code>server {
        (...)
        server_name example.com www.example.com;
        (...)
}
</code>```

then i've got the certificate but not the auto complet process to config my nginx with ssl

```<code>Obtaining a new certificate
Performing the following challenges:
tls-sni-01 challenge for examle.com
tls-sni-01 challenge for www.example.com
Cleaning up challenges
Cannot find a VirtualHost matching domain www.example.com. In order for Certbot to correctly perform the challenge please add a corresponding server_name directive to your nginx configuration: https://nginx.org/en/docs/http/server_names.html

IMPORTANT NOTES:
 - Your account credentials have been saved in your Certbot
   configuration directory at /etc/letsencrypt. You should make a
   secure backup of this folder now. This configuration directory will
   also contain certificates and private keys obtained by Certbot so
   making regular backups of this folder is ideal.
</code>```

It's like I wrote just:

```<code>cerbot --certonly --standalone -d example.com
</code>```

because I have just the certificate, now the config on nginx it's ok, i can lauch again the process and overwrite all the old values ? is there a problem with Let's Encrypt Certificate Authority , call again a new certificate for the same domain? what is the solution? delete all again, or complete the rest of process ( nginx config) by hand ?

答:
It's possible with cerbot to launch again the ssl for domains already created. In my case when domains fails, and it's the first time you use  certbot. Nginx config is changed but not totally , so when you try second time that will be complet and update nginx config. Certbot just update the config for the domain, and comment the old lines that it think are duplicated and inserting the new ones , addigng #manage by Certbod, so when you need to renovate your certificate Cerbot can change smartly the lines.

Example my nginx config ,with the first try, and second:

```<code>if ($scheme != "https") {
    return 301 https://$host$request_uri;
} # managed by Certbot

# Redirect non-https traffic to https
# if ($scheme != "https") {
#     return 301 https://$host$request_uri;
# } # managed by Certbot
</code>```

Body:
I've start certbot process with:

sudo certbot --nginx -d example.com -d www.example.com

but I forgot to add 'www.example.com' in 'servernam' nginx virtualsite for example.com

server {
        (...)
        server_name example.com www.example.com;
        (...)
}

then i've got the certificate but not the auto complet process to config my nginx with ssl

Obtaining a new certificate
Performing the following challenges:
tls-sni-01 challenge for examle.com
tls-sni-01 challenge for www.example.com
Cleaning up challenges
Cannot find a VirtualHost matching domain www.example.com. In order for Certbot to correctly perform the challenge please add a corresponding server_name directive to your nginx configuration: https://nginx.org/en/docs/http/server_names.html

IMPORTANT NOTES:
 - Your account credentials have been saved in your Certbot
   configuration directory at /etc/letsencrypt. You should make a
   secure backup of this folder now. This configuration directory will
   also contain certificates and private keys obtained by Certbot so
   making regular backups of this folder is ideal.

It's like I wrote just:

cerbot --certonly --standalone -d example.com

because I have just the certificate, now the config on nginx it's ok, i can lauch again the process and overwrite all the old values ? is there a problem with Let's Encrypt Certificate Authority , call again a new certificate for the same domain? what is the solution? delete all again, or complete the rest of process ( nginx config) by hand ?

Body:
It's possible with cerbot to launch again the ssl for domains already created. In my case when domains fails, and it's the first time you use  certbot. Nginx config is changed but not totally , so when you try second time that will be complet and update nginx config. Certbot just update the config for the domain, and comment the old lines that it think are duplicated and inserting the new ones , addigng #manage by Certbod, so when you need to renovate your certificate Cerbot can change smartly the lines.

Example my nginx config ,with the first try, and second:

if ($scheme != "https") {
    return 301 https://$host$request_uri;
} # managed by Certbot

# Redirect non-https traffic to https
# if ($scheme != "https") {
#     return 301 https://$host$request_uri;
# } # managed by Certbot


问:
can i get realtime user login list in firebase?
I want to create an app that displays the list of users who are logged in realtime, and if the user closes the app it will automatically be deleted from the list of users who are logging .. can i make it in firebase, or what technology is suitable to make it.</p>

答:
You have to create your custom web API to handle with active users.
Although Firebase show active users in Firebase Console, it does not return what u want.</p>


问:
Error on jest when I try to run the test
This is the error in the console: Cannot find module 'expo' from 'setup.js'.

Below is my code:

component.test.js:

```<code>import React from 'react';
import MyComponent from '../components/Component';
import renderer from 'react-test-renderer';

test('create component correctly', () =>{
   const tree = renderer.create(
       <MyComponent/>
   ).toJSON();
   expect(tree).toMatchSnapshot();
});
</code>```

Component.js:

```<code>import React, { Component } from 'react';
import {Text, View } from 'react-native';

export default class MyComponent extends React.Component{
   render(){
       return(
          <View style={{flex: 1}}>
              <View style={styles.cameraContainer}>
                  <Text> Test Component </Text>
              </View>
          </View>
      );
   }
}
</code>```

When I try to use npm test the error that I mentioned before appears and I already try to uninstall and re-install jest and the error keeps showing.

答:
Assuming you are using create-react-native-app, looks like this is coming from the "jest-expo" preset in the jest configuration.

Replace it with the react-native Jest preset, which is now built in to Jest:

jest.config.js:

module.exports = {
  preset: 'react-native'
};

Or in package.json:

```<code>"jest": {
    "preset": "react-native"
  }
</code>```

Body:
This is the error in the console: Cannot find module 'expo' from 'setup.js'.

Below is my code:

component.test.js:

import React from 'react';
import MyComponent from '../components/Component';
import renderer from 'react-test-renderer';

test('create component correctly', () =>{
   const tree = renderer.create(
       <MyComponent/>
   ).toJSON();
   expect(tree).toMatchSnapshot();
});

Component.js:

import React, { Component } from 'react';
import {Text, View } from 'react-native';

export default class MyComponent extends React.Component{
   render(){
       return(
          <View style={{flex: 1}}>
              <View style={styles.cameraContainer}>
                  <Text> Test Component </Text>
              </View>
          </View>
      );
   }
}

When I try to use npm test the error that I mentioned before appears and I already try to uninstall and re-install jest and the error keeps showing.

Body:
Assuming you are using create-react-native-app, looks like this is coming from the "jest-expo" preset in the jest configuration.

Replace it with the react-native Jest preset, which is now built in to Jest:

jest.config.js:

module.exports = {
  preset: 'react-native'
};

Or in package.json:

"jest": {
    "preset": "react-native"
  }