问:
Count number of rows between start and end date
I have a table with few hundred thousand rows, with columns containing a start and finish datetime, something like this:

```<code>ID    StartDateTime              FinishDateTime
--------------------------------------------------------
1     2001-01-01 04:05:06.789    2001-02-03 04:05:06.789
2     2001-01-01 05:05:06.789    2001-01-01 07:05:06.789
3     2001-01-01 06:05:06.789    2001-02-04 07:05:06.789
4     2001-03-01 06:05:06.789    2001-02-03 04:05:06.789
</code>```

For each row, I need to count the number of 'active' rows at the start time; as in count rows that start before and finish after the startdatetime for each row. For instance: for ID=3, the startdatetime falls between the startdatetime and finishdatetime of ID=1 and ID=2, but not ID=3 or ID=4, so it should return 2.

The desired output is:

```<code>ID    ActiveRows
-----------------
1     0
2     1
3     2
4     0
</code>```

I can get it to work using the query below, but it takes hours to run.

```<code>select
    ID,
    (select count(1)
     from table tbl2
     where tbl2.StartDateTime < tbl.StartDateTime
       and tbl2.FinishDateTime > tbl.StartDateTime) as 'ActiveRows'
from
    table tbl
</code>```

I've also tried joining the table on itself, but it also seems extremely slow.

```<code>select
    tbl.ID, count(1)
from
    table tbl
left join table
    tbl2 on tbl2.StartDateTime < tbl.StartDateTime
         and tbl2.FinishDateTime > tbl.StartDateTime
group by
    tbl.ID
</code>```

What is the fastest way to perform this calculation?

答:
You can do this using Apply operator

```<code>SELECT tbl.id,
       oa.activerows
FROM   yourtable tbl
       OUTER apply(SELECT Count(tbl2.id)
                   FROM   yourtable tbl2
                   WHERE  tbl2.startdatetime < tbl.startdatetime
                          AND tbl2.finishdatetime > tbl.startdatetime) oa (activerows)
</code>```

and your original query should be using LEFT JOIN to get the ID's with 0 count

To further improve the performance you can create a non clustered index on yourtable

```<code>Create Nonclustered Index Nix_table on
      yourtable (startdatetime,finishdatetime) Include (Id)
</code>```

Live Demo

Body:
I have a table with few hundred thousand rows, with columns containing a start and finish datetime, something like this:

ID    StartDateTime              FinishDateTime
--------------------------------------------------------
1     2001-01-01 04:05:06.789    2001-02-03 04:05:06.789
2     2001-01-01 05:05:06.789    2001-01-01 07:05:06.789
3     2001-01-01 06:05:06.789    2001-02-04 07:05:06.789
4     2001-03-01 06:05:06.789    2001-02-03 04:05:06.789

For each row, I need to count the number of 'active' rows at the start time; as in count rows that start before and finish after the startdatetime for each row. For instance: for ID=3, the startdatetime falls between the startdatetime and finishdatetime of ID=1 and ID=2, but not ID=3 or ID=4, so it should return 2.

The desired output is:

ID    ActiveRows
-----------------
1     0
2     1
3     2
4     0

I can get it to work using the query below, but it takes hours to run.

select
    ID,
    (select count(1)
     from table tbl2
     where tbl2.StartDateTime < tbl.StartDateTime
       and tbl2.FinishDateTime > tbl.StartDateTime) as 'ActiveRows'
from
    table tbl

I've also tried joining the table on itself, but it also seems extremely slow.

select
    tbl.ID, count(1)
from
    table tbl
left join table
    tbl2 on tbl2.StartDateTime < tbl.StartDateTime
         and tbl2.FinishDateTime > tbl.StartDateTime
group by
    tbl.ID

What is the fastest way to perform this calculation?

Body:
You can do this using Apply operator

SELECT tbl.id,
       oa.activerows
FROM   yourtable tbl
       OUTER apply(SELECT Count(tbl2.id)
                   FROM   yourtable tbl2
                   WHERE  tbl2.startdatetime < tbl.startdatetime
                          AND tbl2.finishdatetime > tbl.startdatetime) oa (activerows)

and your original query should be using LEFT JOIN to get the ID's with 0 count

To further improve the performance you can create a non clustered index on yourtable

Create Nonclustered Index Nix_table on
      yourtable (startdatetime,finishdatetime) Include (Id)

Live Demo


来源: stackexchange

问:
Uploading file using $_FILES and PHP
Today I tried for the first time to upload files to my website, but it seems that it doesn't work. I hope someone can help me, and I hope my code is readable :)

The problem is when I choose file and SUBMIT form it is not accepted because $_FILES is NULL

```<code>if (move_uploaded_file($_FILES['obrazok']['tmp_name'], $uploadfile))
</code>```

UPDATED Error

```<code>Warning: move_uploaded_file(www_nekonomagic/res/img/anime/uploads/793392545Untitled.jpg): failed to open stream: No such file or directory in /home/gj020900/www_nekonomagic/admin/admin-nove-anime.php on line 107

Warning: move_uploaded_file(): Unable to move '/home/gj020900/tmp/php9izgwb' to 'www_nekonomagic/res/img/anime/uploads/793392545Untitled.jpg' in /home/gj020900/www_nekonomagic/admin/admin-nove-anime.php on line 107
</code>```

Shorted form:

```<code><form enctype="multipart/form-data" action="../admin/admin-nove-anime.php" method="post" role="form">
    <div class="form-group col-md-6">
        <!-- MAX_FILE_SIZE must precede the file input field -->
        <input type="hidden" name="MAX_FILE_SIZE" value="3145728" />
        <label for="obrazok" class=""> Obrázok anime (Max. 3MB):</label>
        <input type="file" name="obrazok" id="obrazok" class="form-control" required>
    </div>
    <div class="form-group col-md-12">
        <input type="submit" class="btn btn-success" name="pridaj_anime_submit" value="Pridať anime" style="width: 100%;">
    </div>
</form>
</code>```

PHP part:

```<code>if (isset($_POST['pridaj_anime_submit'])) {
    // skontroluje sa ci sa subor ulozil ak ano pokracuje ak nie napise chybu
    $uploaddir = '/www_nekonomagic/res/img/anime/uploads/';
    $uploadfile = $uploaddir . basename($_FILES['obrazok']['name']);
    if (move_uploaded_file($_FILES['obrazok']['tmp_name'], $uploadfile)) {
        // prva cast formy
        $nazov = mysqli_real_escape_string($connect_to_db, $_POST['nazov']);
        $rok = mysqli_real_escape_string($connect_to_db, $_POST['rok']);
        $pocet = mysqli_real_escape_string($connect_to_db, $_POST['pocet']);
        $preklad = mysqli_real_escape_string($connect_to_db, $_POST['preklad']);
        $stav = mysqli_real_escape_string($connect_to_db, $_POST['stav']);

        $sql_vloz_anime = "INSERT INTO anime (a_name, a_year, a_translated_min, a_translated_max, a_rate_min, a_rate_max, a_edit, a_condition)
                                  VALUES ('$nazov', '$rok', '0', '$pocet', '8', '10', '$preklad', '$stav')";
        mysqli_query($connect_to_db, $sql_vloz_anime);
        $sql_ziskaj_a_id_pridaneho_anime = "SELECT * FROM anime WHERE a_name = '$nazov'";
        $run_sql_ziskaj_a_id_pridaneho_anime = mysqli_query($connect_to_db, $sql_ziskaj_a_id_pridaneho_anime);
        $a_id_ziskane = "";

        while ($db_data = mysqli_fetch_assoc($run_sql_ziskaj_a_id_pridaneho_anime)) {
            $a_id_ziskane = $db_data['a_id'];
        }

        // druha cast formy
        $obrazok = mysqli_real_escape_string($connect_to_db, $uploaddir.$_FILES['obrazok']['name']);
        $zaciatok = mysqli_real_escape_string($connect_to_db, $_POST['zaciatok']);
        $koniec = mysqli_real_escape_string($connect_to_db, $_POST['koniec']);
        $cas = mysqli_real_escape_string($connect_to_db, $_POST['cas']);
        $akihabara = mysqli_real_escape_string($connect_to_db, $_POST['akihabara']);

        $sql_vloz_anime_info = "INSERT INTO anime_info (a_id, a_img, a_start, a_stop, a_time_ep, a_akihabara)
                                            VALUES ('$a_id_ziskane', '$obrazok', '$zaciatok', '$koniec', '$cas', '$akihabara')";
        mysqli_query($connect_to_db, $sql_vloz_anime_info);
    }
    else {
        echo "
            <div class=\"alert alert-success alert-info\" style=\"margin: 10px 0\">
                <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>
                <strong>POZOR!</strong> Súbor sa nepodarilo nahrať.
            </div>
        ";
    }
}
</code>```

答:
Everything is fine. You just need to change this:

```<code>$uploaddir = '/www_nekonomagic/res/img/anime/uploads/';
</code>```

to

```<code>$uploaddir = 'www_nekonomagic/res/img/anime/uploads/';
</code>```

ContentLicense: CC BY-SA 3.0

Title: Uploading file using $_FILES and PHP

Body:
Today I tried for the first time to upload files to my website, but it seems that it doesn't work. I hope someone can help me, and I hope my code is readable :)

The problem is when I choose file and SUBMIT form it is not accepted because $_FILES is NULL

if (move_uploaded_file($_FILES['obrazok']['tmp_name'], $uploadfile))

UPDATED Error

Warning: move_uploaded_file(www_nekonomagic/res/img/anime/uploads/793392545Untitled.jpg): failed to open stream: No such file or directory in /home/gj020900/www_nekonomagic/admin/admin-nove-anime.php on line 107

Warning: move_uploaded_file(): Unable to move '/home/gj020900/tmp/php9izgwb' to 'www_nekonomagic/res/img/anime/uploads/793392545Untitled.jpg' in /home/gj020900/www_nekonomagic/admin/admin-nove-anime.php on line 107

Shorted form:

<form enctype="multipart/form-data" action="../admin/admin-nove-anime.php" method="post" role="form">

        <input type="hidden" name="MAX_FILE_SIZE" value="3145728" />
         Obrázok anime (Max. 3MB):
        <input type="file" name="obrazok" id="obrazok" class="form-control" required>

        <input type="submit" class="btn btn-success" name="pridaj_anime_submit" value="Pridať anime" style="width: 100%;">

</form>

PHP part:

if (isset($_POST['pridaj_anime_submit'])) {
    // skontroluje sa ci sa subor ulozil ak ano pokracuje ak nie napise chybu
    $uploaddir = '/www_nekonomagic/res/img/anime/uploads/';
    $uploadfile = $uploaddir . basename($_FILES['obrazok']['name']);
    if (move_uploaded_file($_FILES['obrazok']['tmp_name'], $uploadfile)) {
        // prva cast formy
        $nazov = mysqli_real_escape_string($connect_to_db, $_POST['nazov']);
        $rok = mysqli_real_escape_string($connect_to_db, $_POST['rok']);
        $pocet = mysqli_real_escape_string($connect_to_db, $_POST['pocet']);
        $preklad = mysqli_real_escape_string($connect_to_db, $_POST['preklad']);
        $stav = mysqli_real_escape_string($connect_to_db, $_POST['stav']);

        $sql_vloz_anime = "INSERT INTO anime (a_name, a_year, a_translated_min, a_translated_max, a_rate_min, a_rate_max, a_edit, a_condition)
                                  VALUES ('$nazov', '$rok', '0', '$pocet', '8', '10', '$preklad', '$stav')";
        mysqli_query($connect_to_db, $sql_vloz_anime);
        $sql_ziskaj_a_id_pridaneho_anime = "SELECT * FROM anime WHERE a_name = '$nazov'";
        $run_sql_ziskaj_a_id_pridaneho_anime = mysqli_query($connect_to_db, $sql_ziskaj_a_id_pridaneho_anime);
        $a_id_ziskane = "";

        while ($db_data = mysqli_fetch_assoc($run_sql_ziskaj_a_id_pridaneho_anime)) {
            $a_id_ziskane = $db_data['a_id'];
        }

        // druha cast formy
        $obrazok = mysqli_real_escape_string($connect_to_db, $uploaddir.$_FILES['obrazok']['name']);
        $zaciatok = mysqli_real_escape_string($connect_to_db, $_POST['zaciatok']);
        $koniec = mysqli_real_escape_string($connect_to_db, $_POST['koniec']);
        $cas = mysqli_real_escape_string($connect_to_db, $_POST['cas']);
        $akihabara = mysqli_real_escape_string($connect_to_db, $_POST['akihabara']);

        $sql_vloz_anime_info = "INSERT INTO anime_info (a_id, a_img, a_start, a_stop, a_time_ep, a_akihabara)
                                            VALUES ('$a_id_ziskane', '$obrazok', '$zaciatok', '$koniec', '$cas', '$akihabara')";
        mysqli_query($connect_to_db, $sql_vloz_anime_info);
    }
    else {
        echo "

                ×
                POZOR! Súbor sa nepodarilo nahrať.

        ";
    }
}

Body:
Everything is fine. You just need to change this:

$uploaddir = '/www_nekonomagic/res/img/anime/uploads/';

to

$uploaddir = 'www_nekonomagic/res/img/anime/uploads/';


问:
App does not start in Genymotion
i have installed Genymotion recently, and everything is fine, but when I click on run icon in Android Studio, it asks to create AVD.

I want to test my app using Genymotion virtual device.

答:
You need to install the Genymotion plugin for the IDE.

To install the Genymotion plugin for Android Studio.

In Android Studio, go to File/Settings (for Windows and Linux) or to Android Studio/Preferences (for Mac OS X)

Select Plugins and click Browse Repositories.

Right-click on Genymotion and click Download and install. To see Genymotion plugin icon, display the toolbar by clicking View > Toolbar.

Source: https://www.genymotion.com/plugins/

Title: App does not start in Genymotion


问:
Paytm Checksum in Asp.net core
In Paytm for generating checksums for .NET, DLL must be imported but I cannot use the dll in ASP.NET Core. Please let me know how to generate and validate a checksum.</p>

答:
Depending on the version of .NET Core you are running, you might need to import System.Security.Cryptography.Algorithms

That said, you can generate an MD5 Checksum with the following

```<code>using (var md5 = MD5.Create())
{
    using (var stream = File.OpenRead(filename))
    {
         return Encoding.Default.GetString(md5.ComputeHash(stream));
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Paytm Checksum in Asp.net core

Body:
Depending on the version of .NET Core you are running, you might need to import System.Security.Cryptography.Algorithms

That said, you can generate an MD5 Checksum with the following

using (var md5 = MD5.Create())
{
    using (var stream = File.OpenRead(filename))
    {
         return Encoding.Default.GetString(md5.ComputeHash(stream));
    }
}


问:
Issue concerning the upgrade of an Ember app to the version 2.14
I have an issue with the new version of ember (2.14).
I upgraded my project using this help.
I fixed some issues that I had, for example:

Transform -> DS.Transform.

But there is one error that I cannot solve, it's a warning that show up in the debbuging console:

DEPRECATION: Using "_lookupFactory" is deprecated. Please use
             container.factoryFor instead. [deprecation id: container-lookupFactory]
             See http://emberjs.com/deprecations/v2.x/#toc_migrating-from-_lookupfactory-to-factoryfor for more details.
        at logDeprecationStackTrace (http://localhost:4200/assets/vendor.js:32785:21)
        at HANDLERS.(anonymous function) (http://localhost:4200/assets/vendor.js:33003:9)
        at raiseOnDeprecation (http://localhost:4200/assets/vendor.js:32815:14)
        at HANDLERS.(anonymous function) (http://localhost:4200/assets/vendor.js:33003:9)
        at invoke (http://localhost:4200/assets/vendor.js:33015:9)
        at deprecate (http://localhost:4200/assets/vendor.js:32869:24)
        at Container.lookupFactory (http://localhost:4200/assets/vendor.js:29145:54)
        at Class._lookupFactory (http://localhost:4200/assets/vendor.js:57166:33)
        at Locale._compileTemplate (http://localhost:4200/assets/vendor.js:92841:32)
logDeprecationStackTrace @ deprecate.js:116
HANDLERS.(anonymous function) @ handlers.js:14
raiseOnDeprecation @ deprecate.js:128
HANDLERS.(anonymous function) @ handlers.js:14
invoke @ handlers.js:26
deprecate @ deprecate.js:182
lookupFactory @ container.js:43
_lookupFactory @ container_proxy.js:26
_compileTemplate @ locale.js:116
getCompiledTemplate @ locale.js:60
t @ i18n.js:47
compute @ boolean-to-colored-yes-no.js:9
compute @ references.js:459
value @ references.js:70
compute @ reference.js:287
value @ reference.js:256
initialize @ reference.js:337
peek @ reference.js:311
evaluate @ runtime.js:6615
(anonymous) @ runtime.js:6562
evaluate @ runtime.js:202
next @ runtime.js:6115
execute @ runtime.js:6090
resume @ runtime.js:6081
handleException @ runtime.js:6360
handleException @ runtime.js:6551
_throw @ runtime.js:6245
evaluate @ runtime.js:411
execute @ runtime.js:6232
rerender @ runtime.js:5642
_this.render @ renderer.js:68
exports.runInTransaction @ ember-metal.js:693
_renderRoots @ renderer.js:335
_renderRootsTransaction @ renderer.js:373
_revalidate @ renderer.js:412
invokeWithOnError @ backburner.js:271
flush @ backburner.js:157
flush @ backburner.js:320
end @ backburner.js:399
run @ backburner.js:478
join @ backburner.js:491
run$1.join @ ember-metal.js:4456
(anonymous) @ has_element.js:18
exports.flaggedInstrument @ ember-metal.js:3883
handleEvent @ has_element.js:17
exports.default._emberMetal.Mixin.create._Mixin$create.handleEvent @ view_support.js:260
_bubbleEvent @ event_dispatcher.js:267
(anonymous) @ event_dispatcher.js:201
dispatch @ jquery.js:5206
elemData.handle @ jquery.js:5014```

I already checked, I don't have any call to _lookupFactory.

I'm quite new to ember and Javascript in general.

答:
It is probably coming from i18n addon. You can see in stack trace:

t @ i18n.js:47

It looks like addon owners already fixed this issue in January. You can see related pull request: https://github.com/jamesarosen/ember-i18n/pull/431/files

The file which probably resulted in causing deprecation was: addon/utils/locale.js - Line of Code: 33:

```<code>const defaultConfig = this.owner._lookupFactory('ember-i18n@config:zh');
</code>```

Please upgrade version of i18n you depend on in your project.

Body:
I have an issue with the new version of ember (2.14).
I upgraded my project using this help.
I fixed some issues that I had, for example:

Transform -> DS.Transform.

But there is one error that I cannot solve, it's a warning that show up in the debbuging console:

DEPRECATION: Using "_lookupFactory" is deprecated. Please use
             container.factoryFor instead. [deprecation id: container-lookupFactory]
             See http://emberjs.com/deprecations/v2.x/#toc_migrating-from-_lookupfactory-to-factoryfor for more details.
        at logDeprecationStackTrace (http://localhost:4200/assets/vendor.js:32785:21)
        at HANDLERS.(anonymous function) (http://localhost:4200/assets/vendor.js:33003:9)
        at raiseOnDeprecation (http://localhost:4200/assets/vendor.js:32815:14)
        at HANDLERS.(anonymous function) (http://localhost:4200/assets/vendor.js:33003:9)
        at invoke (http://localhost:4200/assets/vendor.js:33015:9)
        at deprecate (http://localhost:4200/assets/vendor.js:32869:24)
        at Container.lookupFactory (http://localhost:4200/assets/vendor.js:29145:54)
        at Class._lookupFactory (http://localhost:4200/assets/vendor.js:57166:33)
        at Locale._compileTemplate (http://localhost:4200/assets/vendor.js:92841:32)
logDeprecationStackTrace @ deprecate.js:116
HANDLERS.(anonymous function) @ handlers.js:14
raiseOnDeprecation @ deprecate.js:128
HANDLERS.(anonymous function) @ handlers.js:14
invoke @ handlers.js:26
deprecate @ deprecate.js:182
lookupFactory @ container.js:43
_lookupFactory @ container_proxy.js:26
_compileTemplate @ locale.js:116
getCompiledTemplate @ locale.js:60
t @ i18n.js:47
compute @ boolean-to-colored-yes-no.js:9
compute @ references.js:459
value @ references.js:70
compute @ reference.js:287
value @ reference.js:256
initialize @ reference.js:337
peek @ reference.js:311
evaluate @ runtime.js:6615
(anonymous) @ runtime.js:6562
evaluate @ runtime.js:202
next @ runtime.js:6115
execute @ runtime.js:6090
resume @ runtime.js:6081
handleException @ runtime.js:6360
handleException @ runtime.js:6551
_throw @ runtime.js:6245
evaluate @ runtime.js:411
execute @ runtime.js:6232
rerender @ runtime.js:5642
_this.render @ renderer.js:68
exports.runInTransaction @ ember-metal.js:693
_renderRoots @ renderer.js:335
_renderRootsTransaction @ renderer.js:373
_revalidate @ renderer.js:412
invokeWithOnError @ backburner.js:271
flush @ backburner.js:157
flush @ backburner.js:320
end @ backburner.js:399
run @ backburner.js:478
join @ backburner.js:491
run$1.join @ ember-metal.js:4456
(anonymous) @ has_element.js:18
exports.flaggedInstrument @ ember-metal.js:3883
handleEvent @ has_element.js:17
exports.default._emberMetal.Mixin.create._Mixin$create.handleEvent @ view_support.js:260
_bubbleEvent @ event_dispatcher.js:267
(anonymous) @ event_dispatcher.js:201
dispatch @ jquery.js:5206
elemData.handle @ jquery.js:5014

I already checked, I don't have any call to _lookupFactory.

I'm quite new to ember and Javascript in general.

Body:
It is probably coming from i18n addon. You can see in stack trace:

t @ i18n.js:47

It looks like addon owners already fixed this issue in January. You can see related pull request: https://github.com/jamesarosen/ember-i18n/pull/431/files

The file which probably resulted in causing deprecation was: addon/utils/locale.js - Line of Code: 33:

const defaultConfig = this.owner._lookupFactory('ember-i18n@config:zh');

Please upgrade version of i18n you depend on in your project.


问:
to find unequal partitions of an integer in php
I have total partitions of an integer and I want only those partitions which have all the values unequal.

For ex.

-Partitions of 3 are {1,1,1,1},{2,2},{3,1},{1,1,2} and {4}.

So, the required unequal partitions are {3,1} and {4} because they contain no equal elements.I can filter the partitions to get the desired result, but I want some efficient way to find all the partitions, which have no equal terms in them, without finding all the partitions. I have searched the net and StackOverflow but nothing states exactly the problem that I am facing. Every idea is appreciated. Thanks.

答:
Ok, so you want to have speed, right?

I guess the speed comes from the best possible partitioning algorithm with memorization instead of just any partitioning with pre-abortion in case of equal numbers.

If you search on stackoverflow, you'll find plenty of good ones, e.g.:
https://stackoverflow.com/a/44209393/701049 (including a benchmark)
or
https://stackoverflow.com/a/18503368/701049 (from his EDIT).

I'd combine such a good one with the filter provided by Turn.
If you want even more speed, you could also try to return None from the function in case of same numbers, and/or to write the partitioning in C-Code and compile it.

Combined it could look like this (accel_asc() copied from the link):

```<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-

def accel_asc(n):
    a = [0 for i in range(n + 1)]
    k = 1
    y = n - 1
    while k != 0:
        x = a[k - 1] + 1
        k -= 1
        while 2 * x <= y:
            a[k] = x
            y -= x
            k += 1
        l = k + 1
        while x <= y:
            a[k] = x
            a[l] = y
            yield a[:k + 2]
            x += 1
            y -= 1
        a[k] = x + y
        y = x + y - 1
        yield a[:k + 1]

N = 20
unequal_partitions = [p for p in accel_asc(N) if len(p) == len(set(p))]
print unequal_partitions
</code>```

You could also try to compile using Cython to make it even faster.

Body:
Ok, so you want to have speed, right?

I guess the speed comes from the best possible partitioning algorithm with memorization instead of just any partitioning with pre-abortion in case of equal numbers.

If you search on stackoverflow, you'll find plenty of good ones, e.g.:
https://stackoverflow.com/a/44209393/701049 (including a benchmark)
or
https://stackoverflow.com/a/18503368/701049 (from his EDIT).

I'd combine such a good one with the filter provided by Turn.
If you want even more speed, you could also try to return None from the function in case of same numbers, and/or to write the partitioning in C-Code and compile it.

Combined it could look like this (accel_asc() copied from the link):

#!/usr/bin/env python
# -*- coding: utf-8 -*-

def accel_asc(n):
    a = [0 for i in range(n + 1)]
    k = 1
    y = n - 1
    while k != 0:
        x = a[k - 1] + 1
        k -= 1
        while 2 * x <= y:
            a[k] = x
            y -= x
            k += 1
        l = k + 1
        while x <= y:
            a[k] = x
            a[l] = y
            yield a[:k + 2]
            x += 1
            y -= 1
        a[k] = x + y
        y = x + y - 1
        yield a[:k + 1]

N = 20
unequal_partitions = [p for p in accel_asc(N) if len(p) == len(set(p))]
print unequal_partitions

You could also try to compile using Cython to make it even faster.


问:
Resubmitting dead letter queue message inside a transaction scope
How can I read a message from a dead letter queue and put it back on the parent queue inside a transaction scope given the restriction of only one top level entity being able to participate in a transaction? Ordinarily I'd use a transfer queue to move a message from one queue to another as an atomic operation, but I don't believe DLQ's have transfer queues and even if they did, wouldn't I then have the problem of handling the transfer queues DLQ!

I need to perform this re-submission in a secure way and without the risk of losing the message during the re-submission process.

答:
Azure Service Bus does not allow re-submitting messages. You need to send a new message with corrected data. For the messages found in DLQ, you could defer the original message, submit a copy, and if that was successful, receive and delete the original DLQed message by the sequence number you've received when originally deferred it.

Similar thing is implemented by ServiceBus360 with the Deferred DLQ feature.


问:
Check if a file is available (not used by another process) in Python
I'm looking for some code to check if a file in the file system is available (not used by another process). How could I do it in Python? Thanks!

How I'll use it: cylically check if file is available and when it is (processes don't need it anymore) delete it.

答:
```<code>while True:
    try:
        os.remove(yourfilename) # try to remove it directly
    except OSError as e:
        if e.errno == errno.ENOENT: # file doesn't exist
            break
        time.sleep(5)
    else:
        break
</code>```

ContentLicense: CC BY-SA 2.5


问:
How to add a seperate layout with date picker dialog?
I have a history button,when I click that my date picker dialog appears but I want it to be like in the picture. How can I add that box on the top of dialog?Please help.enter image description here</p>

答:
I think what you're looking for is a DiaogFragment. This class allows you to open a dialog with main content being that of the one you set in the xml layout class. In the .xml layout class add the header view that you had along with datepicker widget.

Implementation of a DialogFragment is the same as that of a fragment you just need to extend it. Here is a basic example from the net.


问:
Typescript - Parameter 'u' implicitly has an 'any' type
I converted this code to the latest Angular 2.  authentication.service.ts

What should the code look like?

```<code>app/auth/auth.service.ts(30,40): error TS7006: Parameter 'u' implicitly has an 'any' type.

// services/auth.service.ts
import {Injectable} from '@angular/core';
import {Router} from '@angular/router';

//http://4dev.tech/2016/03/login-screen-and-authentication-with-angular2/
//https://github.com/leonardohjines/angular2-login
export class User {
  constructor(
    public email: string,
    public password: string) { }
}

var users:any = [
  new User('admin@admin.com','adm9'),
  new User('user1@gmail.com','a23')
];

@Injectable()
export class AuthenticationService {

  constructor(
    private _router: Router){}

  logout() {
    localStorage.removeItem("user");
    this._router.navigate(['Login']);
  }

  login(user:any){
    var authenticatedUser = users.find(u => u.email === user.email);
    if (authenticatedUser){
      localStorage.setItem("user", authenticatedUser);
      this._router.navigate(['Home']);
      return true;
    }
    return false;

  }

   checkCredentials( ){
    if (localStorage.getItem("user") === null){
        this._router.navigate(['Login']);
    }
  }
}
</code>```

答:
2 changes to make:

in tsconfig.json file: "noImplicitAny": false,

in systemjs.config.js, add:

'ng2-formly': 'npm:ng2-formly/bundles/ng2-formly.umd.js',

Body:
I converted this code to the latest Angular 2.  authentication.service.ts

What should the code look like?

app/auth/auth.service.ts(30,40): error TS7006: Parameter 'u' implicitly has an 'any' type.

// services/auth.service.ts
import {Injectable} from '@angular/core';
import {Router} from '@angular/router';

//http://4dev.tech/2016/03/login-screen-and-authentication-with-angular2/
//https://github.com/leonardohjines/angular2-login
export class User {
  constructor(
    public email: string,
    public password: string) { }
}

var users:any = [
  new User('admin@admin.com','adm9'),
  new User('user1@gmail.com','a23')
];

@Injectable()
export class AuthenticationService {

  constructor(
    private _router: Router){}

  logout() {
    localStorage.removeItem("user");
    this._router.navigate(['Login']);
  }

  login(user:any){
    var authenticatedUser = users.find(u => u.email === user.email);
    if (authenticatedUser){
      localStorage.setItem("user", authenticatedUser);
      this._router.navigate(['Home']);
      return true;
    }
    return false;

  }

   checkCredentials( ){
    if (localStorage.getItem("user") === null){
        this._router.navigate(['Login']);
    }
  }
}


问:
Cannot install Genymotion 2.0.1 under Ubuntu: [[: not found
```<code>sudo sh genymotion-2.0.1_x86.bin
genymotion-2.0.1_x86.bin: 100: genymotion-2.0.1_x86.bin: [[: not found
genymotion-2.0.1_x86.bin: 106: genymotion-2.0.1_x86.bin: [[: not found
-e
-e Aborting.
</code>```

I have this problem on version 1.*, yesterday on 2.0 and today on 2.0.1 on Lubuntu 13.10 x32. I already writed to developers, but if in Google I can't find anything about this problem - it's affect only me? Maybe something not good at my side?

If I open this .bin file in Sublime Text 2 I have this code (from line 97 to 111):

```<code>#------------------------------------------------------------------------------
_ask_user() {
    local ans=a
    while [[ ! "$ans" =~ ^[YyNn]$ ]]
    do
        echo -ne "$1"
        read ans
    done

    [[ "$ans" =~ ^[Yy]$ ]] && return 0

    # if $ans == No
    return 1
}
#------------------------------------------------------------------------------
</code>```

答:
I know that the problem is solved by Andrei B's answer, but I would like share a script that automatize all steps needed for install genymotion on linux.

You can find the script here.

Maybe this can help some other users in the future.

Body:
sudo sh genymotion-2.0.1_x86.bin
genymotion-2.0.1_x86.bin: 100: genymotion-2.0.1_x86.bin: [[: not found
genymotion-2.0.1_x86.bin: 106: genymotion-2.0.1_x86.bin: [[: not found
-e
-e Aborting.

I have this problem on version 1.*, yesterday on 2.0 and today on 2.0.1 on Lubuntu 13.10 x32. I already writed to developers, but if in Google I can't find anything about this problem - it's affect only me? Maybe something not good at my side?

If I open this .bin file in Sublime Text 2 I have this code (from line 97 to 111):

#------------------------------------------------------------------------------
_ask_user() {
    local ans=a
    while [[ ! "$ans" =~ ^[YyNn]$ ]]
    do
        echo -ne "$1"
        read ans
    done

    [[ "$ans" =~ ^[Yy]$ ]] && return 0

    # if $ans == No
    return 1
}
#------------------------------------------------------------------------------


问:
How to insert data into database using prepared statement query in Django and Python
I need to insert form data into SQLite3 database using prepared statement query in Django and Python. My code is below:

models.py:

```<code>class Meeting(models.Model):
    """In this class the columns for Meeting table has declared"""
    room_name = models.CharField(max_length=200)
    from_date = models.DateTimeField(default=datetime.now, blank=True)
    to_date = models.DateTimeField(default=datetime.now, blank=True)
    no_seat = models.CharField(max_length=200)
    projector = models.CharField(max_length=200)
    video = models.CharField(max_length=200)
    created_date = models.DateTimeField(default=datetime.now, blank=True)
</code>```

Here I have already created the table by migrating. My views.py is below:

```<code>import sqlite3
def insert(request):

    """ This function helps to insert all booking data into database """
    conn = sqlite3.connect("db.sqlite3")
    cursor = conn.cursor()
    if request.method == 'POST':
        location_name = request.POST.get('lname')
        rname = request.POST.get('rname')
        seat = request.POST.get('seat')
        projector = request.POST.get('projector')
        video = request.POST.get('video')
        location_name = location_name[0:255]
        rname = rname[0:255]
        seat = seat[0:10]
        from_date = request.POST.get('from_date')
        to_date = request.POST.get('from_date')
</code>```

Here I need all data should save into the database by running prepared statement query.

答:
Python's SQLite libraries don't have prepared statement objects, but they do allow you to use parameterized queries, and to provide more than one set of parameters.</p>

```<code>values_to_insert = [(location_name,rname,........other_fields)]

cursor.execute("""
    INSERT INTO some_table ('location_name', 'rname','..... other_fields')
    VALUES (?, ?, ?, ?, total fields = total ? marks)""", values_to_insert)
</code>```

Body:
I need to insert form data into SQLite3 database using prepared statement query in Django and Python. My code is below:

models.py:

class Meeting(models.Model):
    """In this class the columns for Meeting table has declared"""
    room_name = models.CharField(max_length=200)
    from_date = models.DateTimeField(default=datetime.now, blank=True)
    to_date = models.DateTimeField(default=datetime.now, blank=True)
    no_seat = models.CharField(max_length=200)
    projector = models.CharField(max_length=200)
    video = models.CharField(max_length=200)
    created_date = models.DateTimeField(default=datetime.now, blank=True)

Here I have already created the table by migrating. My views.py is below:

import sqlite3
def insert(request):

    """ This function helps to insert all booking data into database """
    conn = sqlite3.connect("db.sqlite3")
    cursor = conn.cursor()
    if request.method == 'POST':
        location_name = request.POST.get('lname')
        rname = request.POST.get('rname')
        seat = request.POST.get('seat')
        projector = request.POST.get('projector')
        video = request.POST.get('video')
        location_name = location_name[0:255]
        rname = rname[0:255]
        seat = seat[0:10]
        from_date = request.POST.get('from_date')
        to_date = request.POST.get('from_date')

Here I need all data should save into the database by running prepared statement query.

Body:
Python's SQLite libraries don't have prepared statement objects, but they do allow you to use parameterized queries, and to provide more than one set of parameters.

values_to_insert = [(location_name,rname,........other_fields)]

cursor.execute("""
    INSERT INTO some_table ('location_name', 'rname','..... other_fields')
    VALUES (?, ?, ?, ?, total fields = total ? marks)""", values_to_insert)


问:
Angular 2 with CodeIgniter
I searched a lot but unable to find the solution for this.

In angular 1.x, I used to include js in php pages and load the pages from server side code like CodeIgniter controller.

In angular 2.x, I unable to figure out that how I use server side features like $_SESSION?

e.g. I want to insert the data to mysql table and I will send data using POST service of Angular 2. How can I achieve that which user is logged in and created that record??

```<code>$city = $this->input->post("city");
$specialty= $this->input->post("specialty");

$data = array("city"=>, "specialty"=>$specialty, "createdBy"=>$this->session->userdata("userid"));

$this->db->insert("citywise", $data);
</code>```

How to get this $this->session->userdata("userid"); because application is loading at client and everything is handling like REST services.

Using localStorage I can get login data on client browser but what about server?

答:
Use JWT(Json Web Token) for the same purpose
refer this link</p>

Title: Angular 2 with CodeIgniter

Body:
I searched a lot but unable to find the solution for this.

In angular 1.x, I used to include js in php pages and load the pages from server side code like CodeIgniter controller.

In angular 2.x, I unable to figure out that how I use server side features like $_SESSION?

e.g. I want to insert the data to mysql table and I will send data using POST service of Angular 2. How can I achieve that which user is logged in and created that record??

$city = $this->input->post("city");
$specialty= $this->input->post("specialty");

$data = array("city"=>, "specialty"=>$specialty, "createdBy"=>$this->session->userdata("userid"));

$this->db->insert("citywise", $data);

How to get this $this->session->userdata("userid"); because application is loading at client and everything is handling like REST services.

Using localStorage I can get login data on client browser but what about server?


问:
ASP.NET: Can GridView be used to create a hierarchy?
We are using the GridView controls in some pages of our project which we dont want to change drastically, would it be possible to create a hierarchy in a gridview? Can this be achieved by using a GridView inside a Gridview to get the parent - child relation? </p>

答:
Yes, you can nest GridViews inside one another. See the following article.

Nesting GridViews

OwnerDisplayName: Anthraxer

OwnerDisplayName: Bbetances


问:
Python beautiful soup4- find_all returns "[]"
I am using python BS4 to scrape the https://skinup.gg website. I am trying to get the multiplier class, in order, from a website.

I tried to scrape the information by taking all the data from the div history class. However it just returns [] and I am stumped on how to get the multipliers.

I wonder if it is because the div tag class values are constantly changing. Which leads me to my second question: how do they have dynamic values in html tags? Is it done via Javascript?

Excuse my grammar.

Here is my code:

```<code>import urllib.request
import requests
from bs4 import BeautifulSoup
import urllib

page = requests.g et("https://skinup.gg/"
soup = BeautifulSoup(page.content, "html.parser")

print(soup.find_all('div', attrs={'class': 'win'}))
</code>```

Relevant website code:

```<code><div class="history"><div class="win" style="">
  <time class="date">23:05</time>
  <span class="multiplier">2.19</span>
</div><div class="win" style="">
  <time class="date">23:04</time>
  <span class="multiplier">2.62</span>
</div><div class="lose" style="">
  <time class="date">23:04</time>
  <span class="multiplier">1.75</span>
</div><div class="lose" style="">
  <time class="date">23:04</time>
  <span class="multiplier">1.00</span>
</div><div class="lose" style="">
  <time class="date">23:04</time>
  <span class="multiplier">1.21</span>
</div><div style="">
  <time class="date">23:03</time>
  <span class="multiplier">1.82</span>
</div><div class="lose" style="">
  <time class="date">23:03</time>
  <span class="multiplier">1.00</span>
</div><div class="win" style="">
  <time class="date">23:03</time>
  <span class="multiplier">2.91</span>
</div><div class="lose" style="">
  <time class="date">23:02</time>
  <span class="multiplier">1.01</span>
</div><div class="win" style="">
  <time class="date">23:02</time>
  <span class="multiplier">1184.44</span>
</div><div class="win" style="">
  <time class="date">23:01</time>
  <span class="multiplier">36.81</span>
</div><div class="lose" style="">
  <time class="date">22:59</time>
  <span class="multiplier">1.38</span>
</div><div class="win" style="">
  <time class="date">22:59</time>
  <span class="multiplier">2.42</span>
</div><div class="win" style="">
  <time class="date">22:59</time>
  <span class="multiplier">8.00</span>
</div><div class="win" style="">
  <time class="date">22:58</time>
  <span class="multiplier">3.42</span>
</div><div class="win" style="">
  <time class="date">22:57</time>
  <span class="multiplier">2.04</span>
</div><div class="lose" style="">
  <time class="date">22:57</time>
  <span class="multiplier">1.17</span>
</div><div class="lose" style="">
  <time class="date">22:57</time>
  <span class="multiplier">1.24</span>
</div><div class="lose" style="">
  <time class="date">22:57</time>
  <span class="multiplier">1.11</span>
</div><div class="lose" style="">
  <time class="date">22:56</time>
  <span class="multiplier">1.53</span>
</div>

                </div>
</code>```

答: For the website in question you will need to use selenium to get the data you want.</p>

Body:
I am using python BS4 to scrape the https://skinup.gg website. I am trying to get the multiplier class, in order, from a website.

I tried to scrape the information by taking all the data from the div history class. However it just returns [] and I am stumped on how to get the multipliers.

I wonder if it is because the div tag class values are constantly changing. Which leads me to my second question: how do they have dynamic values in html tags? Is it done via Javascript?

Excuse my grammar.

Here is my code:

import urllib.request
import requests
from bs4 import BeautifulSoup
import urllib

page = requests.g et("https://skinup.gg/"
soup = BeautifulSoup(page.content, "html.parser")

print(soup.find_all('div', attrs={'class': 'win'}))

Relevant website code:

  <time class="date">23:05</time>
  2.19

  <time class="date">23:04</time>
  2.62

  <time class="date">23:04</time>
  1.75

  <time class="date">23:04</time>
  1.00

  <time class="date">23:04</time>
  1.21

  <time class="date">23:03</time>
  1.82

  <time class="date">23:03</time>
  1.00

  <time class="date">23:03</time>
  2.91

  <time class="date">23:02</time>
  1.01

  <time class="date">23:02</time>
  1184.44

  <time class="date">23:01</time>
  36.81

  <time class="date">22:59</time>
  1.38

  <time class="date">22:59</time>
  2.42

  <time class="date">22:59</time>
  8.00

  <time class="date">22:58</time>
  3.42

  <time class="date">22:57</time>
  2.04

  <time class="date">22:57</time>
  1.17

  <time class="date">22:57</time>
  1.24

  <time class="date">22:57</time>
  1.11

  <time class="date">22:56</time>
  1.53


问:
getting android.content.res.Resources$NotFoundException when using Picasso Library
I am updating profile picture using Picasso library. I am getting below issue

```<code>android.content.res.Resources$NotFoundException: Resource "com.adamas.selfiereporter:id/profile_picture" (7f100176) is not a Drawable (color or path): TypedValue{t=0x12/d=0x0 a=2 r=0x7f100176}
</code>```

this is picasso object

```<code> Picasso.with(getContext())
                                .load(profileImageUrl)
                                .placeholder(R.id.profile_picture)
                                .transform(new PicassoRoundedTransformation())
                                .fit()
                                .noFade()
                                .into(personImagee);
</code>```

getting issue at

```<code> .into(personImagee);
</code>```

please someone help me

答:
You are passing id in a placeholder, You have to pass a drawable there.</p>

```<code>Picasso.with(getContext())
       .load(profileImageUrl)
       .placeholder(R.drawable.profile_picture)
       .transform(new PicassoRoundedTransformation())
       .fit()
       .noFade()
       .into(personImagee);
</code>```

Body:
I am updating profile picture using Picasso library. I am getting below issue

android.content.res.Resources$NotFoundException: Resource "com.adamas.selfiereporter:id/profile_picture" (7f100176) is not a Drawable (color or path): TypedValue{t=0x12/d=0x0 a=2 r=0x7f100176}

this is picasso object

 Picasso.with(getContext())
                                .load(profileImageUrl)
                                .placeholder(R.id.profile_picture)
                                .transform(new PicassoRoundedTransformation())
                                .fit()
                                .noFade()
                                .into(personImagee);

getting issue at

 .into(personImagee);

please someone help me

Body:
You are passing id in a placeholder, You have to pass a drawable there.

Picasso.with(getContext())
       .load(profileImageUrl)
       .placeholder(R.drawable.profile_picture)
       .transform(new PicassoRoundedTransformation())
       .fit()
       .noFade()
       .into(personImagee);


问:
How to tag an older commit in Git?
We are new to git, and I want to set a tag at the beginning of our repository.
Our production code is the same as the beginning repository, but we've made commits since then.
A tag at the beginning would allow us to "roll back" production to a known, stable state.

So how to add a tag to an arbitrary, older commit?

答:
OK, You can simply do:

```<code>git tag -a <tag> <commit-hash>
</code>```

So if you want to add tag: 1.0.2 to commit e50f795, just simply do:

```<code>git tag -a 1.0.2 e50f795
</code>```

Also you add a message at the end, using -m, something like this:

```<code>git tag -a 1.0.2 e50f795 -m "my message"
</code>```

After all, you need to push it to the remote, to do that, simply do:

```<code>git push origin 1.0.2
</code>```

If you have many tags which you don't want to mention them one by one, just simply do:

```<code>git push origin --tags
</code>```

to push all tags together...

Also, I created the steps in the image below, for more clarification of the steps:

You can also dd the tag in Hub or using tools like SourceTree, to avoid the previous steps, I logged-in to my Bitbucket in this case and doing it from there:

Go to your branch and find the commit you want to add the tag to and click on it:

In the commit page, on the right, find where it says No tags and click on the + icon:

In the tag name box, add your tag:

Now you see that the tag has successfully created:

Title: How to tag an older commit in Git?

Body:
OK, You can simply do:

git tag -a <tag> <commit-hash>

So if you want to add tag: 1.0.2 to commit e50f795, just simply do:

git tag -a 1.0.2 e50f795

Also you add a message at the end, using -m, something like this:

git tag -a 1.0.2 e50f795 -m "my message"

After all, you need to push it to the remote, to do that, simply do:

git push origin 1.0.2

If you have many tags which you don't want to mention them one by one, just simply do:

git push origin --tags

to push all tags together...

Also, I created the steps in the image below, for more clarification of the steps:

You can also dd the tag in Hub or using tools like SourceTree, to avoid the previous steps, I logged-in to my Bitbucket in this case and doing it from there:

Go to your branch and find the commit you want to add the tag to and click on it:

In the commit page, on the right, find where it says No tags and click on the + icon:

In the tag name box, add your tag:

Now you see that the tag has successfully created:


问:
Decompress a zip file with Swift
I made a game in Swift but I need to download .zip files on my website, and use the content (images) in game.
Actually, I download the .zip file and store it in documents, and I need to unzip the file into the same documents folder.

I tried marmelroy's Zip, iOS 9 Compression module and tidwall's DeflateSwift but none of these worked. It could be good if it was compatible with iOS 8.

答:
I recently released a Swift native framework that allows you to create, read and update ZIP archive files: ZIP Foundation.

It internally uses libcompression for great compression performance.

Unzipping a file is basically just one line:

```<code>try fileManager.unzipItem(at: sourceURL, to: destinationURL)
</code>```

A full example with some context would look like this:

```<code>let fileManager = FileManager()
let currentWorkingPath = fileManager.currentDirectoryPath
var sourceURL = URL(fileURLWithPath: currentWorkingPath)
sourceURL.appendPathComponent("archive.zip")
var destinationURL = URL(fileURLWithPath: currentWorkingPath)
destinationURL.appendPathComponent("directory")
do {
    try fileManager.createDirectory(at: destinationURL, withIntermediateDirectories: true, attributes: nil)
    try fileManager.unzipItem(at: sourceURL, to: destinationURL)
} catch {
    print("Extraction of ZIP archive failed with error:\(error)")
}
</code>```

The README on GitHub contains more information. All public methods also have full documentation available via Xcode Quick Help.

I also wrote a blog post about the performance characteristics here.

Title: Decompress a zip file with Swift

Body:
I recently released a Swift native framework that allows you to create, read and update ZIP archive files: ZIP Foundation.

It internally uses libcompression for great compression performance.

Unzipping a file is basically just one line:

try fileManager.unzipItem(at: sourceURL, to: destinationURL)

A full example with some context would look like this:

let fileManager = FileManager()
let currentWorkingPath = fileManager.currentDirectoryPath
var sourceURL = URL(fileURLWithPath: currentWorkingPath)
sourceURL.appendPathComponent("archive.zip")
var destinationURL = URL(fileURLWithPath: currentWorkingPath)
destinationURL.appendPathComponent("directory")
do {
    try fileManager.createDirectory(at: destinationURL, withIntermediateDirectories: true, attributes: nil)
    try fileManager.unzipItem(at: sourceURL, to: destinationURL)
} catch {
    print("Extraction of ZIP archive failed with error:\(error)")
}

The README on GitHub contains more information. All public methods also have full documentation available via Xcode Quick Help.

I also wrote a blog post about the performance characteristics here.


问:
Android SwitchPreference not working
I'm trying to retrieve the SwitchPreference's value using SharedPreferences but it isn't working. I'm using SwitchPreference so that user can turn on/off notifications, but it shows notifications no matter whatever the value is.
Here's the code.

NotificationUtils.java

```<code>SharedPreferences preferences = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
    if (preferences.getBoolean("notification_key", true)) {
        notificationManager.notify(NOTIFICATION_ID + rowId, notBuilder.build());
    }
</code>```

preferences.xml

```<code><SwitchPreference
    android:contentDescription="Turn notifications on/off"
    android:defaultValue="true"
    android:key="notification_key"
    android:summaryOff="Off"
    android:summaryOn="On"
    android:title="Notifications" />
</code>```

I also have overridden and registered the OnSharedPreferenceChange listener in SettingsFragment.java.

答:
Try replacing

```<code>SharedPreferences preferences = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
</code>```

with

```<code>PreferenceManager.getDefaultSharedPreferences(context);
</code>```

I believe you're attempting to retrieve "notification_key" from the wrong SharedPreferences, which is why it's always using the default value of true and showing your notification.

Edit: You can check to see whether the SharedPreferences you're using contains the "notification_key" key with the contains() method.

Title: Android SwitchPreference not working

Body:
I'm trying to retrieve the SwitchPreference's value using SharedPreferences but it isn't working. I'm using SwitchPreference so that user can turn on/off notifications, but it shows notifications no matter whatever the value is.
Here's the code.

NotificationUtils.java

SharedPreferences preferences = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
    if (preferences.getBoolean("notification_key", true)) {
        notificationManager.notify(NOTIFICATION_ID + rowId, notBuilder.build());
    }

preferences.xml

<SwitchPreference
    android:contentDescription="Turn notifications on/off"
    android:defaultValue="true"
    android:key="notification_key"
    android:summaryOff="Off"
    android:summaryOn="On"
    android:title="Notifications" />

I also have overridden and registered the OnSharedPreferenceChange listener in SettingsFragment.java.

Body:
Try replacing

SharedPreferences preferences = context.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);

with

PreferenceManager.getDefaultSharedPreferences(context);

I believe you're attempting to retrieve "notification_key" from the wrong SharedPreferences, which is why it's always using the default value of true and showing your notification.

Edit: You can check to see whether the SharedPreferences you're using contains the "notification_key" key with the contains() method.


问:
Saving User foreign key upon creation of related model
My Category model is related to User, but I can't find a way to store the logged in user's id into user_id field in Category.

Category models.py:

```<code>class Category(models.Model):
    user = models.ForeignKey(User, default=None)
    name = models.CharField(max_length=32, unique=True)
</code>```

views.py:

```<code>class CategoryList(APIView):
    ...
    def post(self, request):
        """
        Create a new Category
        :param request:
        :return: Category
        """
        user_id = request.user.pk
        serializer = CategorySerializer(data=request.data)

        if serializer.is_valid():
            serializer.save()

            return Response(serializer.data, status=HTTP_201_CREATED)

        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
</code>```

I can access request.user.pk and see it's correctly shown, but I can't figure out how I can store this value when creating a new category.

答:
To add current user id to new record you can pass current user as save argument:

```<code>if serializer.is_valid():
    serializer.save(user=request.user)
</code>```

Or you can change serializer and use CurrentUserDefault:

```<code>user = serializers.HiddenField(default=serializers.CurrentUserDefault())
</code>```

from docs:

A default class that can be used to represent the current user. In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer.

So to use CurrentUserDefault you need to pass request to serializer in view:

```<code>serializer = CategorySerializer(data=request.data, context={'request': request})
</code>```

Body:
My Category model is related to User, but I can't find a way to store the logged in user's id into user_id field in Category.

Category models.py:

class Category(models.Model):
    user = models.ForeignKey(User, default=None)
    name = models.CharField(max_length=32, unique=True)

views.py:

class CategoryList(APIView):
    ...
    def post(self, request):
        """
        Create a new Category
        :param request:
        :return: Category
        """
        user_id = request.user.pk
        serializer = CategorySerializer(data=request.data)

        if serializer.is_valid():
            serializer.save()

            return Response(serializer.data, status=HTTP_201_CREATED)

        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

I can access request.user.pk and see it's correctly shown, but I can't figure out how I can store this value when creating a new category.

Body:
To add current user id to new record you can pass current user as save argument:

if serializer.is_valid():
    serializer.save(user=request.user)

Or you can change serializer and use CurrentUserDefault:

user = serializers.HiddenField(default=serializers.CurrentUserDefault())

from docs:

A default class that can be used to represent the current user. In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer.

So to use CurrentUserDefault you need to pass request to serializer in view:

serializer = CategorySerializer(data=request.data, context={'request': request})


问:
tensorflow two matrix elementwise multiply in axis = 0, (M,k) * (M,l) --> (M,k*l)
I have a two matrix, F(shape = (4000, 64)) and M(shape=(4000,9))
and want to have result that have shape = (4000,64*9)

i can think with for loop with below code(ideal)

```<code>result = np.zeros(4000,64*9)
ind = 0
for i in range(64):
    for j in range(9):
        result[:,ind]= tf.muliply(F[:,i]),M[:,j])
        ind += 1
</code>```

but i know For Loop is not support in tensorflow

Is there a function that performs the same function as above code?

edit)

I came up with an idea. F,M repeat to shape (4000,64*9) [liek repmat in MATLAB] and elementwise multiply.
Could you ever have any other ideas?

答:
You can use tf.matmul if you reshape your inputs to F(shape = (4000, 64, 1)) and  M(shape=(4000,1, 9)). An example,

```<code>F = tf.Variable(tf.random_uniform(shape=(4000, 64, 1)))
M = tf.Variable(tf.random_uniform(shape=(4000, 1, 9)))
C = tf.matmul(F, M)
C = tf.reshape(C, (4000, -1))
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
print(C.eval().shape)

#Output: (4000, 576)
</code>```

Body:
I have a two matrix, F(shape = (4000, 64)) and M(shape=(4000,9))
and want to have result that have shape = (4000,64*9)

i can think with for loop with below code(ideal)

result = np.zeros(4000,64*9)
ind = 0
for i in range(64):
    for j in range(9):
        result[:,ind]= tf.muliply(F[:,i]),M[:,j])
        ind += 1

but i know For Loop is not support in tensorflow

Is there a function that performs the same function as above code?

edit)

I came up with an idea. F,M repeat to shape (4000,64*9) [liek repmat in MATLAB] and elementwise multiply.
Could you ever have any other ideas?

Body:
You can use tf.matmul if you reshape your inputs to F(shape = (4000, 64, 1)) and  M(shape=(4000,1, 9)). An example,

F = tf.Variable(tf.random_uniform(shape=(4000, 64, 1)))
M = tf.Variable(tf.random_uniform(shape=(4000, 1, 9)))
C = tf.matmul(F, M)
C = tf.reshape(C, (4000, -1))
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
print(C.eval().shape)

#Output: (4000, 576)


问:
String interpretation in Swift
I have a struct that looks like this:

```<code>struct colorShapeSize{
    let color: String!
    let shape: String!
    let size: UIImage!
}
</code>```

and I have a string that looks something like this:

"color:{Blue}shape:{round}size:{medium}"

All of the strings will be in the same format (i.e. color will always come first, shape second, and size third).

How would I extract the data from the string and put it into a colorShapeSize struct?

答:
try this, it will extract the string in array, then you can do what you want with the value</p>

```<code>func test() {
    let givenString = "color:{Blue}shape:{round}size:{medium}"
    var results = [String]()
    do {
        let regex = try NSRegularExpression(pattern: "\\{(.*?)\\}", options: [])
        let tempString = givenString as NSString
        regex.enumerateMatches(in: givenString, options: [], range: NSMakeRange(0, givenString.characters.count), using: { (result, flag, stop) in
            if let range = result?.rangeAt(1) {
                let number = tempString.substring(with: range)
                results.append(number)
            }
        })
        print(results) //["Blue", "round", "medium"] (Here you can initialize your struct with the values)
    }
    catch(let error) {
        print("Unable to extract string : \(error.localizedDescription)")
    }
}
</code>```

Title: String interpretation in Swift

Body:
I have a struct that looks like this:

struct colorShapeSize{
    let color: String!
    let shape: String!
    let size: UIImage!
}

and I have a string that looks something like this:

"color:{Blue}shape:{round}size:{medium}"

All of the strings will be in the same format (i.e. color will always come first, shape second, and size third).

How would I extract the data from the string and put it into a colorShapeSize struct?

Body:
try this, it will extract the string in array, then you can do what you want with the value

func test() {
    let givenString = "color:{Blue}shape:{round}size:{medium}"
    var results = [String]()
    do {
        let regex = try NSRegularExpression(pattern: "\\{(.*?)\\}", options: [])
        let tempString = givenString as NSString
        regex.enumerateMatches(in: givenString, options: [], range: NSMakeRange(0, givenString.characters.count), using: { (result, flag, stop) in
            if let range = result?.rangeAt(1) {
                let number = tempString.substring(with: range)
                results.append(number)
            }
        })
        print(results) //["Blue", "round", "medium"] (Here you can initialize your struct with the values)
    }
    catch(let error) {
        print("Unable to extract string : \(error.localizedDescription)")
    }
}


答:
put your profile_picture.png to drawble folders  then
Change this line   .placeholder(R.id.profile_picture) to  .placeholder(R.drawable.profile_picture)

Title: getting android.content.res.Resources$NotFoundException when using Picasso Library


问:
Building survey from railscast in rails 5
I have been following both the old and revised railscasts & this for something that i have to make along the same lines

I followed it upto some point but neither are the questions being displayed on the form nor are the answers getting added . Following is my model code

answers.rb

```<code>class Answer < ActiveRecord::Base
  attr_accessor :content, :question_id
  belongs_to :question
end
</code>```

surveys.rb

```<code>class Survey < ApplicationRecord
   attr_accessor :name, :questions_attributes
   has_many :questions
   accepts_nested_attributes_for :questions, allow_destroy: true
end
</code>```

questions.rb

```<code>class Question < ApplicationRecord
  attr_accessor :content, :survey_id, :answers_attributes
  belongs_to :survey
  has_many :answers
  accepts_nested_attributes_for :answers, allow_destroy: true
end
</code>```

Surveys Controller

```<code>class SurveysController < ApplicationController
  before_action :set_survey, only: [:show, :edit, :update, :destroy]

  # GET /surveys
  # GET /surveys.json
  def index
    @surveys = Survey.all
  end

  # GET /surveys/1
  # GET /surveys/1.json
  def show
  end

  # GET /surveys/new
  def new
    @survey = Survey.new
    3.times do
      question = @survey.questions.build
      4.times { question.answers.build }
    end
  end

private
    # Use callbacks to share common setup or constraints between actions.
    def set_survey
      @survey = Survey.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def survey_params
      params.require(:survey).permit(:name, :question_id)
    end
end
</code>```

Views

_form.html.erb

```<code><%= f.fields_for :questions do |builder| %>
  <%= render 'question_fields', f: builder %>
<% end %>
<%= link_to_add_fields "Add Question", f, :questions %>
</code>```

_question_fields.html.erb

```<code><fieldset>
  <%= f.label :content, "Question" %><br />
  <%= f.text_area :content %><br />
  <%= f.check_box :_destroy %>
  <%= f.label :_destroy, "Remove Question" %>
  <%= f.fields_for :answers do |builder| %>
    <%= render 'answer_fields', f: builder %>
  <% end %>
  <%= link_to_add_fields "Add Answer", f, :answers %>
</fieldset>
</code>```

_answers_fields.html.erb

```<code><p>
  <%= f.label :content, "Answer" %>
  <%= f.text_field :content %>
  <%= f.check_box :_destroy %>
  <%= f.label :_destroy, "Remove" %>
</p>
</code>```

show.html.erb

```<code><p id="notice"><%= notice %></p>

<p>
  <strong>Name:</strong>
  <%= @survey.name %>
</p>

<ol>
  <% for question in @survey.questions %>
  <li><%= h question.content %></li>
  <% end %>
</ol>

<p>
  <%= link_to "Edit", edit_survey_path(@survey) %> |
  <%= link_to "Destroy", @survey, :confirm => 'Are you sure?', :method => :delete %> |
  <%= link_to "View All", surveys_path %>
</p>
</code>```

Migrations

```<code>class CreateSurveys < ActiveRecord::Migration[5.0]
  def change
    create_table :surveys do |t|
      t.string :name

      t.timestamps
    end
  end
end

class CreateQuestions < ActiveRecord::Migration[5.0]
  def change
    create_table :questions do |t|
      t.string :survey_id
      t.string :integer
      t.text :content

      t.timestamps
    end
  end
end
</code>```

Is there anything else i am missing out that needs to be done in rails 5 , i have been hours at this and it still confuses me why does it show me this error - Table 'app.answers' doesn't exist when i am calling answers from nested form . Any help in this regard would be very much appreciated .

答:
The main issue here is it looks like you forgot an 'answer' migration to create the tables, create that and run it and should fix things up.

Additionally, those attr_accessor calls are going to be messing things up. They were required in older versions of Rails, but aren't anymore and now just serve throw things off. Example

With attr_accessor code

```<code>post = Post.new(title: "Something")
#=> #<Post id: nil, title: nil, created_at: nil, updated_at: nil>
post.title = "Something"
#=> "Something"
puts post
#=> #<Post id: nil, title: nil, created_at: nil, updated_at: nil>
</code>```

Without

```<code>post = Post.new(title: "Something")
#=> #<Post id: nil, title: "Something", created_at: nil, updated_at: nil>
post.title = "Something Else"
#=> "Something Else"
puts post
#=> #<Post id: nil, title: "Something Else", created_at: nil, updated_at: nil>
</code>```

As you can see, the first block, where my Post model had the attr_accessor for the title attribute, nothing was working as expected; I couldn't update the title. Once I removed it, things started to work as they should.

Based on the chat discussion, your _form.html.erb is missing form_for tag, and should looks something like

```<code><%= form_for @survey do |f| %>
  <%= f.label :name %><br />
  <%= f.text_field :name %>
  <!-- your current code here -->
<% end %>
</code>```

you've got _answers_field.html.erb and in _question_fields.html.erb are calling

```<code><%= render 'answer_fields', f: builder %>
</code>```

Notice, the plural/singular mismatch.

and lastly, in your controller, you aren't permitting the nested attribute params which should end up looking like (unless I'm mistaken)

```<code>def survey_params
  params.require(:survey).permit(:name, :question_attributes: [:id, :content, :_destroy, answer_attributes: [:id, :content, :_destroy])
end
</code>```

Last couple of issues from chat were that the associations needed inverse_of because belongs_to is required by default in rails 5. And the last minor thing is that Answer is currently inheriting ActiveRecord::Base and the other models ApplicationRecord

Body:
I have been following both the old and revised railscasts & this for something that i have to make along the same lines

I followed it upto some point but neither are the questions being displayed on the form nor are the answers getting added . Following is my model code

answers.rb

class Answer < ActiveRecord::Base
  attr_accessor :content, :question_id
  belongs_to :question
end

surveys.rb

class Survey < ApplicationRecord
   attr_accessor :name, :questions_attributes
   has_many :questions
   accepts_nested_attributes_for :questions, allow_destroy: true
end

questions.rb

class Question < ApplicationRecord
  attr_accessor :content, :survey_id, :answers_attributes
  belongs_to :survey
  has_many :answers
  accepts_nested_attributes_for :answers, allow_destroy: true
end

Surveys Controller

class SurveysController < ApplicationController
  before_action :set_survey, only: [:show, :edit, :update, :destroy]

  # GET /surveys
  # GET /surveys.json
  def index
    @surveys = Survey.all
  end

  # GET /surveys/1
  # GET /surveys/1.json
  def show
  end

  # GET /surveys/new
  def new
    @survey = Survey.new
    3.times do
      question = @survey.questions.build
      4.times { question.answers.build }
    end
  end

private
    # Use callbacks to share common setup or constraints between actions.
    def set_survey
      @survey = Survey.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def survey_params
      params.require(:survey).permit(:name, :question_id)
    end
end

Views

_form.html.erb

<%= f.fields_for :questions do |builder| %>
  <%= render 'question_fields', f: builder %>
<% end %>
<%= link_to_add_fields "Add Question", f, :questions %>

_question_fields.html.erb

<fieldset>
  <%= f.label :content, "Question" %>

  <%= f.text_area :content %>

  <%= f.check_box :_destroy %>
  <%= f.label :_destroy, "Remove Question" %>
  <%= f.fields_for :answers do |builder| %>
    <%= render 'answer_fields', f: builder %>
  <% end %>
  <%= link_to_add_fields "Add Answer", f, :answers %>
</fieldset>

_answers_fields.html.erb

  <%= f.label :content, "Answer" %>
  <%= f.text_field :content %>
  <%= f.check_box :_destroy %>
  <%= f.label :_destroy, "Remove" %>

show.html.erb

<%= notice %>

  Name:
  <%= @survey.name %>

  <% for question in @survey.questions %>

<%= h question.content %>

  <% end %>

  <%= link_to "Edit", edit_survey_path(@survey) %> |
  <%= link_to "Destroy", @survey, :confirm => 'Are you sure?', :method => :delete %> |
  <%= link_to "View All", surveys_path %>

Migrations

class CreateSurveys < ActiveRecord::Migration[5.0]
  def change
    create_table :surveys do |t|
      t.string :name

      t.timestamps
    end
  end
end

class CreateQuestions < ActiveRecord::Migration[5.0]
  def change
    create_table :questions do |t|
      t.string :survey_id
      t.string :integer
      t.text :content

      t.timestamps
    end
  end
end

Is there anything else i am missing out that needs to be done in rails 5 , i have been hours at this and it still confuses me why does it show me this error - Table 'app.answers' doesn't exist when i am calling answers from nested form . Any help in this regard would be very much appreciated .

Body:
The main issue here is it looks like you forgot an 'answer' migration to create the tables, create that and run it and should fix things up.

Additionally, those attr_accessor calls are going to be messing things up. They were required in older versions of Rails, but aren't anymore and now just serve throw things off. Example

With attr_accessor code

post = Post.new(title: "Something")
#=> #<Post id: nil, title: nil, created_at: nil, updated_at: nil>
post.title = "Something"
#=> "Something"
puts post
#=> #<Post id: nil, title: nil, created_at: nil, updated_at: nil>

Without

post = Post.new(title: "Something")
#=> #<Post id: nil, title: "Something", created_at: nil, updated_at: nil>
post.title = "Something Else"
#=> "Something Else"
puts post
#=> #<Post id: nil, title: "Something Else", created_at: nil, updated_at: nil>

As you can see, the first block, where my Post model had the attr_accessor for the title attribute, nothing was working as expected; I couldn't update the title. Once I removed it, things started to work as they should.

Based on the chat discussion, your _form.html.erb is missing form_for tag, and should looks something like

<%= form_for @survey do |f| %>
  <%= f.label :name %><br />
  <%= f.text_field :name %>
  <!-- your current code here -->
<% end %>

you've got _answers_field.html.erb and in _question_fields.html.erb are calling

<%= render 'answer_fields', f: builder %>

Notice, the plural/singular mismatch.

and lastly, in your controller, you aren't permitting the nested attribute params which should end up looking like (unless I'm mistaken)

def survey_params
  params.require(:survey).permit(:name, :question_attributes: [:id, :content, :_destroy, answer_attributes: [:id, :content, :_destroy])
end

Last couple of issues from chat were that the associations needed inverse_of because belongs_to is required by default in rails 5. And the last minor thing is that Answer is currently inheriting ActiveRecord::Base and the other models ApplicationRecord


问:
'MySQL' object has no attribute connection while using mysql.connection.cursor()
Actual code is

```<code>from flask_mysqldb import MySQL

mysql=MySQL(app)
mysql.connection.cursor()
</code>```

I just changed the library flask_mysqldb to flaskext.mysql because I am getting some error while installing flask_mysqldb library.

```<code>from flaskext.mysql import MySQL

mysql=MySQL(app)
mysql.connection.cursor()
</code>```

What is wrong with this code? and also suggest best way of connecting to MySQL database using Flask?

Thanks

答:
I have looked everywhere and well researched into different solutions. I have come closer to the solution by reducing the number of errors. Here is my piece of code that's giving me a headache

```<code>from flask import Flask, render_template, json, request
from flaskext.mysql import MySQL
from werkzeug import generate_password_hash,check_password_hash

mysql = MySQL()
app = Flask(__name__)

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'root'
app.config['MYSQL_DB'] = 'BucketList'

mysql.init_app(app)
cur = mysql.connection.cursor()
</code>```

I have been running the app.py file and keep getting the following error:

AttributeError: 'MySQL' object has no attribute 'connection'.

I am using MySQL 5.7 and attempting to create my first web app using a tutorial that's dated back in time. The above piece of code is after editing it closer to relevant standards.

Body:
Actual code is

from flask_mysqldb import MySQL

mysql=MySQL(app)
mysql.connection.cursor()

I just changed the library flask_mysqldb to flaskext.mysql because I am getting some error while installing flask_mysqldb library.

from flaskext.mysql import MySQL

mysql=MySQL(app)
mysql.connection.cursor()

What is wrong with this code? and also suggest best way of connecting to MySQL database using Flask?

Thanks

Body:
I have looked everywhere and well researched into different solutions. I have come closer to the solution by reducing the number of errors. Here is my piece of code that's giving me a headache

from flask import Flask, render_template, json, request
from flaskext.mysql import MySQL
from werkzeug import generate_password_hash,check_password_hash

mysql = MySQL()
app = Flask(__name__)

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'root'
app.config['MYSQL_DB'] = 'BucketList'

mysql.init_app(app)
cur = mysql.connection.cursor()

I have been running the app.py file and keep getting the following error:

AttributeError: 'MySQL' object has no attribute 'connection'.

I am using MySQL 5.7 and attempting to create my first web app using a tutorial that's dated back in time. The above piece of code is after editing it closer to relevant standards.


问:
Very strange problem about NSString
A very strange behavior about this function,

```<code>void* getNSString(const NSString* str){

str = @"This is new test";
//NSString* str1 = @"so strange test";

return;
}
</code>```

Then

```<code>NSLog(@"%@",getNSString(@"test"));
</code>```

The result will be

```<code>This is new test
</code>```

if uncomment

```<code>NSString* str1 = @"so strange test";
</code>```

My understanding is that nothing is returned, so that should be NULL , why print out those string ?

Then result will be

```<code>so strange test
</code>```

答:
cocoa/objective c does this way.... I also face this type problem before,

for example :

```<code>-(NSObject*) someMethod ()
{  ...

   NSString* result =@"some value";
   // because too busy ,I just forgot write the return statement during dev :)
}
</code>```

although nothing was return like above code, but the app also can return the result value ....

that is very funny....

Title: Very strange problem about NSString

Body:
A very strange behavior about this function,

void* getNSString(const NSString* str){

str = @"This is new test";
//NSString* str1 = @"so strange test";

return;
}

Then

NSLog(@"%@",getNSString(@"test"));

The result will be

This is new test

if uncomment

NSString* str1 = @"so strange test";

My understanding is that nothing is returned, so that should be NULL , why print out those string ?

Then result will be

so strange test

Body:
cocoa/objective c does this way.... I also face this type problem before,

for example :

-(NSObject*) someMethod ()
{  ...

   NSString* result =@"some value";
   // because too busy ,I just forgot write the return statement during dev :)
}

although nothing was return like above code, but the app also can return the result value ....

that is very funny....


问:
Odoo v10 display amount in company currency in purchase tree and form view
I am using Odoo v10 .

As we know in purchase.order, there is a base (Monetary) field amount_total which contains value of total amount of a Purchase Order based on (self) currency_id .

Now, I create a new float field home_currency_amount_total in purchase.order .

```<code>home_currency_amount_total = fields.Float(string='Total Amount in company currency', store=True)
</code>```

How can i have a value in this field based on company currency? i.e. I want to have a corresponding value in company base currency and can be used in my tree & form views.

I am new to Odoo and I wonder if there is a "shortcut"  (e.g. a built-in compute method) instead of I have to write up related codes.

答:
There is a built-in method for conversion of currency.

Eg.

```<code>  @api.model
  def _compute(self, from_currency, to_currency, from_amount, round=True):
     if (to_currency == from_currency):
        amount = to_currency.round(from_amount) if round else from_amount
     else:
        rate = self._get_conversion_rate(from_currency, to_currency)
        amount = to_currency.round(from_amount * rate) if round else from_amount * rate
     return amount
</code>```

So, if you want to calculate the conversion you can use this method.

This method takes 3 arguments, first from currency, second to currency and amount which you want to convert as a third argument.

Eg.

```<code>self.env['res.currency']._compute(order.currency_id,order.company_id.currency_id,order.amount_total)
</code>```

Update :

Create you field like this.

```<code>home_currency_amount_total = fields.Float(string='Total Amount in company currency', compute="_compute", store=True)

@api.depends('order_lines.price_subtotal','company_id','currency_id')
def _compute(self);
    for order in self:
        home_currency_amount_total =  self.env['res.currency']._compute(order.currency_id,order.company_id.currency_id,order.amount_total)
</code>```

Body:
I am using Odoo v10 .

As we know in purchase.order, there is a base (Monetary) field amount_total which contains value of total amount of a Purchase Order based on (self) currency_id .

Now, I create a new float field home_currency_amount_total in purchase.order .

home_currency_amount_total = fields.Float(string='Total Amount in company currency', store=True)

How can i have a value in this field based on company currency? i.e. I want to have a corresponding value in company base currency and can be used in my tree & form views.

I am new to Odoo and I wonder if there is a "shortcut"  (e.g. a built-in compute method) instead of I have to write up related codes.

Body:
There is a built-in method for conversion of currency.

Eg.

  @api.model
  def _compute(self, from_currency, to_currency, from_amount, round=True):
     if (to_currency == from_currency):
        amount = to_currency.round(from_amount) if round else from_amount
     else:
        rate = self._get_conversion_rate(from_currency, to_currency)
        amount = to_currency.round(from_amount * rate) if round else from_amount * rate
     return amount

So, if you want to calculate the conversion you can use this method.

This method takes 3 arguments, first from currency, second to currency and amount which you want to convert as a third argument.

Eg.

self.env['res.currency']._compute(order.currency_id,order.company_id.currency_id,order.amount_total)

Update :

Create you field like this.

home_currency_amount_total = fields.Float(string='Total Amount in company currency', compute="_compute", store=True)

@api.depends('order_lines.price_subtotal','company_id','currency_id')
def _compute(self);
    for order in self:
        home_currency_amount_total =  self.env['res.currency']._compute(order.currency_id,order.company_id.currency_id,order.amount_total)


问:
How to modify boolean property value in html in polymer 1.0?
If I assign a boolean property to a component, how can I modify the value of the boolean in html, without creating any function in javascript?

For example, lets say I have the following component:

Polymer({
  is: 'find-retailer-map',
  properties: {
    fixedPosition: {
      type: Boolean,
      notify: true,
    },
  },
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><dom-module id="osb-retailer-page">
  <template>
    <find-retailer-map fixed-position></find-retailer-map>
  </template>
</dom-module></code>```

How can I make fixed-position true or false within the html?

Thanks

答:
Booleans in HTML and Polymer works the same. Either they are there (true), or they are not (false). These three are doing the same thing ...

```<code><find-retailer-map fixed-position></find-retailer-map>
<find-retailer-map fixed-position="true"></find-retailer-map>
<find-retailer-map fixed-position="false"></find-retailer-map>
</code>```

... as you can pass in anything in the fixed-position attribute to set it true. To set it false, however, you need to remove the attribute.

```<code><find-retailer-map></find-retailer-map>
</code>```

If you want to set the property dynamically, pass in a variable, as an attribute, from osb-retailer-page into find-retailer map.

```<code><dom-module id="osb-retailer-page">
  <template>
    <find-retailer-map fixed-position="[[aVariableInRetailerPage]]"></find-retailer-map>
  </template>
</dom-module>
</code>```

However, the default value for the fixedPosition property in find-retailer-map must be false (or not set, just like your example). You cannot change that property if it defaults to true.

Boolean properties are set based on the presence of the attribute: if the attribute exists at all, the property is set to true, regardless of the attribute value. If the attribute is absent, the property gets its default value.
  /.../
  For a Boolean property to be configurable from markup, it must default to false. If it defaults to true, you cannot set it to false from markup, since the presence of the attribute, with or without a value, equates to true. This is the standard behavior for attributes in the web platform.

https://www.polymer-project.org/1.0/docs/devguide/properties

Body:
If I assign a boolean property to a component, how can I modify the value of the boolean in html, without creating any function in javascript?

For example, lets say I have the following component:

Polymer({
  is: 'find-retailer-map',
  properties: {
    fixedPosition: {
      type: Boolean,
      notify: true,
    },
  },
});

<dom-module id="osb-retailer-page">
  <template>
    <find-retailer-map fixed-position></find-retailer-map>
  </template>
</dom-module>

How can I make fixed-position true or false within the html?

Thanks

Body:
Booleans in HTML and Polymer works the same. Either they are there (true), or they are not (false). These three are doing the same thing ...

<find-retailer-map fixed-position></find-retailer-map>
<find-retailer-map fixed-position="true"></find-retailer-map>
<find-retailer-map fixed-position="false"></find-retailer-map>

... as you can pass in anything in the fixed-position attribute to set it true. To set it false, however, you need to remove the attribute.

<find-retailer-map></find-retailer-map>

If you want to set the property dynamically, pass in a variable, as an attribute, from osb-retailer-page into find-retailer map.

<dom-module id="osb-retailer-page">
  <template>
    <find-retailer-map fixed-position="[[aVariableInRetailerPage]]"></find-retailer-map>
  </template>
</dom-module>

However, the default value for the fixedPosition property in find-retailer-map must be false (or not set, just like your example). You cannot change that property if it defaults to true.

Boolean properties are set based on the presence of the attribute: if the attribute exists at all, the property is set to true, regardless of the attribute value. If the attribute is absent, the property gets its default value.
  /.../
  For a Boolean property to be configurable from markup, it must default to false. If it defaults to true, you cannot set it to false from markup, since the presence of the attribute, with or without a value, equates to true. This is the standard behavior for attributes in the web platform.

https://www.polymer-project.org/1.0/docs/devguide/properties


问:
using an http proxy to heroku login
I am trying to run heroku login from my work using the

```<code>> set HTTP_PROXY=http://proxy.server.com:portnumber
or
> set HTTPS_PROXY=https://proxy.server.com:portnumber
> heroku login
</code>```

but for some reason I keep getting the same errors. Can someone please help me?!

enotfound: getaddrinfoo enotfound api.heroku.com api.heroku.com:443

I had a problem installing django but I fixed it using -- proxy http://proxy.server.com:portnumber

Can someone please help me?

答:
You may want to try updating the Heroku CLI and, be sure you update to v3 as soon as possible to ensure consistent operation!

Also install apt-transport-https package

Title: using an http proxy to heroku login

Body:
I am trying to run heroku login from my work using the

> set HTTP_PROXY=http://proxy.server.com:portnumber
or
> set HTTPS_PROXY=https://proxy.server.com:portnumber
> heroku login

but for some reason I keep getting the same errors. Can someone please help me?!

enotfound: getaddrinfoo enotfound api.heroku.com api.heroku.com:443

I had a problem installing django but I fixed it using -- proxy http://proxy.server.com:portnumber

Can someone please help me?


问:
Why is the strip() function depleting my mustard?
I'm creating a Hot Dog simulator in python, with a class "HotDog".

When I'm formatting the string, if there are 2 condiments, I wrote this code to add it to the string:

```<code>if len(self.condiments) == 2:
    for i in self.condiments:
        msg = msg + i + " and "
    msg = msg.strip(" and ")
</code>```

If the second condiment is "mustard", the strip() function is taking away the "d" of mustard, so the string prints like this:

```<code>Raw hot dog with ketchup and mustar.
</code>```

I've used trial and error to find more info, and it seems "d" is the only letter that will disappear, i.e.: mustarg and mustarb will be fine.

Also, it seems to be the "a" of msg = msg.strip(" and ") that is causing the problem.

If I only strip "d " or "nd ", mustard will be fine.

答:
That's the documented feature.

the characters in the string will be stripped from the both ends of the string this method is called on

So, if you initially did a raw hotdog, then you'd end up with raw hotdog

How about instead you used

```<code> " and ".join(condiments)
</code>```

If I only strip "d " or "nd ", mustard will be fine.

But you'd have an a at the end of the message, no?

Body:
I'm creating a Hot Dog simulator in python, with a class "HotDog".

When I'm formatting the string, if there are 2 condiments, I wrote this code to add it to the string:

if len(self.condiments) == 2:
    for i in self.condiments:
        msg = msg + i + " and "
    msg = msg.strip(" and ")

If the second condiment is "mustard", the strip() function is taking away the "d" of mustard, so the string prints like this:

Raw hot dog with ketchup and mustar.

I've used trial and error to find more info, and it seems "d" is the only letter that will disappear, i.e.: mustarg and mustarb will be fine.

Also, it seems to be the "a" of msg = msg.strip(" and ") that is causing the problem.

If I only strip "d " or "nd ", mustard will be fine.

Body:
That's the documented feature.

the characters in the string will be stripped from the both ends of the string this method is called on

So, if you initially did a raw hotdog, then you'd end up with raw hotdog

How about instead you used

 " and ".join(condiments)

If I only strip "d " or "nd ", mustard will be fine.

But you'd have an a at the end of the message, no?


问:
IIS 6 not serving up asp.net 1.1 pages?
Ok, this is strange.  Some background

Windows 2003 R2 SP2 32-bit

IIS 6.0

I've got a very simple dot.net 1.1 example app that just echoes something to the screen via a response.write.  Works fine on my workstation. Once I deploy it to this server, when i go to the page, it wouldn't render but instead serves up the source code of my aspx file - i.e. it shows all my asp.net markup but does not execute/render the page.

I've run asp.net_regiis -i

I've enabled asp.net 1.1 in the web services extensions.

the virtual directory is setup to run under asp.net 1.1

I've gone into the configuration option and made sure .aspx files are mapped to the aspnet_isapi.dll in the 1.1 framework folder.

it is set up as an application and has an application name that matches the virtual directory

I know I must be missing SOMETHING but can't see what..

edit

another clue.. if I go into properties for the virtual directory, there is NO tab to select asp.net version.  I have to use the aspnetswitcher utility to select which framework to process a given vdir.

答:
If you use IIS 6.0 on your local workstation to connect to the servers IIS instance then the ASP.net tab doesn't display (go figure!).  If you remote onto the server then view it then it'll be there.

It would be unlikely that this would lead to the solution as if the incorrect .net version was selected you would still get either the page rendered or the yellow screen of death.

ASP.net 1.1 needed certain files in the root of the site to understand that it was a .net app.  Off the top of my head it was web.config, maybe global.  But 1.1 needed to be compiled (atleast in our instance) so you needed to copy up the bin folder with the related dll in also.

Good luck.

Title: IIS 6 not serving up asp.net 1.1 pages?


问:
Entity Framework record is adding a new record instead of using existing record
I have an issue where I'm inserting a new record of order and inside of order i have order details.  There can be multiple details each with a product which already exists in the database. My problem is when i try to update the order detail product with the product from the database it wants to put a new record into the database with an empty guid instead of using the one that is already there.

```<code>var order = context.Orders.FirstOrDefault(o => o.OrderId == request.Order.OrderId);
if (order == null)
{
    ...

    // This is where a new order is mapped in from a class model
    // The class model contains order information and order details.

    ...

    // Order Detail
    foreach (var detail in order.OrderDetails)
    {
        var product = context.Products.FirstOrDefault(p => p.ProductId == detail.Product.ProductId);
        detail.Product = product;
        detail.ProductId = product.Id;
    }

    context.SaveChanges();
}
</code>```

I have tried to set the detail.Product state to unchanged but that does not work either.

Here is what the records look like after one order has been inserted.  You can see the same ProductId but different Guid's.  The one that has a Guid is the original that it found but after doing SaveChanges then the empty Guid record was inserted.

```<code>Id                                      ProductId   CostPrice   DateCreated
00000000-0000-0000-0000-000000000000    11671170639 14.75       2017-07-08 04:16:21.927
931F65C2-919B-4876-8D6A-77387FF22001    11671170639 14.75       2017-07-07 11:11:29.327
</code>```

答:
First up, consider changing your field naming convention to avoid confusion. Where you have Product.ProductId, consider naming this Product.ProductNumber. I'd also consider using the same field name for the PK and FK (ProductId vs. Id). When your OrderDetail has a ProductId this is easily confused with your "ProductId" column on your Product entity.

As for the issue you are seeing: What is the source of the OrderDetail instance being operated against? Is it a New OrderDetail or one that was retrieved from EF? What is the source of the existing "Product" item referenced by this OrderDetail? (before your code here to find the Product in EF) Was it New'ed or pulled from EF?

My guess is that you've pulled the OrderDetail from EF where it did not include a Product, and had a virtual Product Product{get;set;} declared. The Product that was added was New'd up based on details of a product. It had a ProductId but no "Id" specified. Before saving your OrderDetail you want to use that ProductId to find the "real" Product from EF and bind it.

After you save the OrderDetail, what was the ProductId on the order detail record? the 000... or "real" id? If it was pointing a the real ID but left that 000.. record orphaned then I suspect that by adding a Product to your OrderDetail EF entity via the proxy, EF has already recorded that a new Product is being added. Your mappings don't have the ID set to identify it as a Generated column, so EF records the Guid.Default for the new entity. EF has no notion of deleting orphaned entities.

If it's pointing at the 0000 then my guess would be that you have a disconnect between the Product and ProductId reference on OrderDetail and/or you are dealing with multiple dbContext instances. Both are generally bad. When using reference properties (OrderDetail.Product) then you should avoid adding properties for the FKs. (OrderDetail.ProductId) This leads to disconnects where the Product's ID does not necessarily match the ProductId and EF has to "pick one". In your case we would need to see your mapping declarations and whether this is Code first or Schema first. Also check whether OrderDetail.Product is declared as virtual or not.

If this was the result of a round trip from the domain through to the view and back, my advice would be to avoid passing Entities around, and instead use ViewModels to talk to your views. These are plain POCO elements where when they get back to the domain, EF can load or create the appropriate entities and match the references up. Passing entities around outside the scope of their DB Context generally leads to pain like this and worse. Multiple instances of a DBContext is another source of issues like this. (I.e. the "context" used by this code is not the same reference as "contexts" used to pull other entities)

Body:
I have an issue where I'm inserting a new record of order and inside of order i have order details.  There can be multiple details each with a product which already exists in the database. My problem is when i try to update the order detail product with the product from the database it wants to put a new record into the database with an empty guid instead of using the one that is already there.

var order = context.Orders.FirstOrDefault(o => o.OrderId == request.Order.OrderId);
if (order == null)
{
    ...

    // This is where a new order is mapped in from a class model
    // The class model contains order information and order details.

    ...

    // Order Detail
    foreach (var detail in order.OrderDetails)
    {
        var product = context.Products.FirstOrDefault(p => p.ProductId == detail.Product.ProductId);
        detail.Product = product;
        detail.ProductId = product.Id;
    }

    context.SaveChanges();
}

I have tried to set the detail.Product state to unchanged but that does not work either.

Here is what the records look like after one order has been inserted.  You can see the same ProductId but different Guid's.  The one that has a Guid is the original that it found but after doing SaveChanges then the empty Guid record was inserted.

Id                                      ProductId   CostPrice   DateCreated
00000000-0000-0000-0000-000000000000    11671170639 14.75       2017-07-08 04:16:21.927
931F65C2-919B-4876-8D6A-77387FF22001    11671170639 14.75       2017-07-07 11:11:29.327