问:
Django custom manager to filter nearby through related model
I have two models Shop and Address.

Shop Model:

```<code>class Shop(BaseModel):
    name = models.CharField(
        max_length=100,
        blank=True,
        null=True
    )
    address = models.ForeignKey(
        Address,
        blank=True,
        null=True,
        on_delete=models.SET_NULL
    )
    objects = LocationManager()
</code>```

Address Model:

```<code>class Address(BaseModel):
    latitude = models.DecimalField(
        max_digits=16,
        decimal_places=14,
        blank=True,
        null=True
    )
    longitude = models.DecimalField(
        max_digits=16,
        decimal_places=14,
        blank=True,
        null=True
     )
     status = models.NullBooleanField(null=True)
</code>```

I have created a custom Manager for Shop model

```<code>class LocationManager(models.Manager):
    def nearby(self, latitude, longitude, proximity):
        """
        Return all object which distance to specified coordinates
        is less than proximity given in kilometers
        """
        # Great circle distance formula
        # acos will not work in sqlite
        gcd = """
            6371 * acos(
                cos(radians(%s)) * cos(radians(latitude))
                * cos(radians(longitude) - radians(%s)) +
                sin(radians(%s)) * sin(radians(latitude))
            )
        """
        queryset =  self.get_queryset().select_related(
            'address'
        ).exclude(
            latitude=None
        )
        .exclude(
            longitude=None
        )
        .annotate(
            distance=RawSQL(
                gcd,
                (
                    latitude,
                    longitude,
                    latitude
                )
            )
        ).filter(
            distance__lt=proximity
        ).order_by('distance')

        return queryset
</code>```

Now I want to find nearby shops using custom manager:

```<code>Shop.objects.nearby(13.244334,72.329832,20)
</code>```

But i am getting this error:

```<code>Cannot resolve keyword 'latitude' into field. Choices are: address, address_id, name
</code>```

How can I use filter my queryset by latitude to find nearby shop?

答:
Your are querying your Shop model, not your Address model.
Your Shop model don't have any field named latitude, as stated by your error.

You should use the field lookup to filter your Shops by the attribute of the linked object Address (documentation)

Since your Shop model is linked to your Address model by the field address, to filter the Shop by the Address attributes, you can do (ie for the latitude field):

```<code>Shop.objects.filter(address__latitude=<your_lookup_here>)
</code>```

Also, your two exclude methods could be rewritted like this (using the Q object):

```<code>Shop.objects.exclude(
    Q(address__latitude__isnull=True)
    | Q(address__longitude__isnull=True)
)
</code>```

I advice you to read the documentation linked above about the queryset API.

Body:
I have two models Shop and Address.

Shop Model:

class Shop(BaseModel):
    name = models.CharField(
        max_length=100,
        blank=True,
        null=True
    )
    address = models.ForeignKey(
        Address,
        blank=True,
        null=True,
        on_delete=models.SET_NULL
    )
    objects = LocationManager()

Address Model:

class Address(BaseModel):
    latitude = models.DecimalField(
        max_digits=16,
        decimal_places=14,
        blank=True,
        null=True
    )
    longitude = models.DecimalField(
        max_digits=16,
        decimal_places=14,
        blank=True,
        null=True
     )
     status = models.NullBooleanField(null=True)

I have created a custom Manager for Shop model

class LocationManager(models.Manager):
    def nearby(self, latitude, longitude, proximity):
        """
        Return all object which distance to specified coordinates
        is less than proximity given in kilometers
        """
        # Great circle distance formula
        # acos will not work in sqlite
        gcd = """
            6371 * acos(
                cos(radians(%s)) * cos(radians(latitude))
                * cos(radians(longitude) - radians(%s)) +
                sin(radians(%s)) * sin(radians(latitude))
            )
        """
        queryset =  self.get_queryset().select_related(
            'address'
        ).exclude(
            latitude=None
        )
        .exclude(
            longitude=None
        )
        .annotate(
            distance=RawSQL(
                gcd,
                (
                    latitude,
                    longitude,
                    latitude
                )
            )
        ).filter(
            distance__lt=proximity
        ).order_by('distance')

        return queryset

Now I want to find nearby shops using custom manager:

Shop.objects.nearby(13.244334,72.329832,20)

But i am getting this error:

Cannot resolve keyword 'latitude' into field. Choices are: address, address_id, name

How can I use filter my queryset by latitude to find nearby shop?

Body:
Your are querying your Shop model, not your Address model.
Your Shop model don't have any field named latitude, as stated by your error.

You should use the field lookup to filter your Shops by the attribute of the linked object Address (documentation)

Since your Shop model is linked to your Address model by the field address, to filter the Shop by the Address attributes, you can do (ie for the latitude field):

Shop.objects.filter(address__latitude=<your_lookup_here>)

Also, your two exclude methods could be rewritted like this (using the Q object):

Shop.objects.exclude(
    Q(address__latitude__isnull=True)
    | Q(address__longitude__isnull=True)
)

I advice you to read the documentation linked above about the queryset API.


来源: stackexchange

问:
How to manage empty span in GridLayoutManager?
I am setting up contact directory in section recyclerview with grid layout manager, what my problem is that header is also set as an item in the span if the span is empty.

I tried using the SpanSizeLookup method. It's not working as I expected.

```<code>layoutManager = new GridLayoutManager(getActivity(), 3);
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                switch(adapterDocument.getItemViewType(position)){
                    case SectionedRecyclerViewAdapter.VIEW_TYPE_HEADER:
                        return 3;

                    case SectionedRecyclerViewAdapter.VIEW_TYPE_ITEM_LOADED:
                        return 1;
                    default:
                        return 1;
                }
            }
        });
</code>```

This is what I get

And this is what I really wants:

How to make header should be in next line with full width? Thank you.

答:
there is something with your code, I changed the code in onCreateView from Example1 to:

```<code>    sectionAdapter = new SectionedRecyclerViewAdapter();

    for(char alphabet = 'A'; alphabet <= 'Z';alphabet++) {
        List<String> contacts = getContactsWithLetter(alphabet);

        if (alphabet == 'B' || alphabet == 'D') {
            contacts = Collections.emptyList();
        }

        if (contacts.size() > 0) {
            sectionAdapter.addSection(new ContactsSection(String.valueOf(alphabet), contacts));
        }
    }

    RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
    GridLayoutManager glm = new GridLayoutManager(getContext(), 3);
    glm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            switch(sectionAdapter.getSectionItemViewType(position)) {
                case SectionedRecyclerViewAdapter.VIEW_TYPE_HEADER:
                    return 3;
                default:
                    return 1;
            }
        }
    });
    recyclerView.setLayoutManager(glm);
    recyclerView.setAdapter(sectionAdapter);
</code>```

and it's working fine, this is the result:

ContentLicense: CC BY-SA 3.0

Body:
I am setting up contact directory in section recyclerview with grid layout manager, what my problem is that header is also set as an item in the span if the span is empty.

I tried using the SpanSizeLookup method. It's not working as I expected.

layoutManager = new GridLayoutManager(getActivity(), 3);
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                switch(adapterDocument.getItemViewType(position)){
                    case SectionedRecyclerViewAdapter.VIEW_TYPE_HEADER:
                        return 3;

                    case SectionedRecyclerViewAdapter.VIEW_TYPE_ITEM_LOADED:
                        return 1;
                    default:
                        return 1;
                }
            }
        });

This is what I get

And this is what I really wants:

How to make header should be in next line with full width? Thank you.

Body:
there is something with your code, I changed the code in onCreateView from Example1 to:

    sectionAdapter = new SectionedRecyclerViewAdapter();

    for(char alphabet = 'A'; alphabet <= 'Z';alphabet++) {
        List<String> contacts = getContactsWithLetter(alphabet);

        if (alphabet == 'B' || alphabet == 'D') {
            contacts = Collections.emptyList();
        }

        if (contacts.size() > 0) {
            sectionAdapter.addSection(new ContactsSection(String.valueOf(alphabet), contacts));
        }
    }

    RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
    GridLayoutManager glm = new GridLayoutManager(getContext(), 3);
    glm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            switch(sectionAdapter.getSectionItemViewType(position)) {
                case SectionedRecyclerViewAdapter.VIEW_TYPE_HEADER:
                    return 3;
                default:
                    return 1;
            }
        }
    });
    recyclerView.setLayoutManager(glm);
    recyclerView.setAdapter(sectionAdapter);

and it's working fine, this is the result:


问:
Disabling/enabling requiredFieldValidators with javascript and server side
I have a drop down (dropdown2) that is required IF there is something in it but it's options data is driven by ajax from another dropdown (dropdown1) selection.  Sometimes dropdown2 will be empty and in that case I can't require it.  So I can disable the requiredFieldValidators in javascript by calling this...

```<code>ValidatorEnable(document.getElementById(validatorId), false);
</code>```

This works fine but the server still fires the requiredFieldValidator logic.  Is anyone aware of how I can force the server to not validate if the validator is set to false client side?

答:
```<code>  ValidatorEnable($("[id$='RegularExpressionValidator4']")[0], true);
</code>```

Body:
I have a drop down (dropdown2) that is required IF there is something in it but it's options data is driven by ajax from another dropdown (dropdown1) selection.  Sometimes dropdown2 will be empty and in that case I can't require it.  So I can disable the requiredFieldValidators in javascript by calling this...

ValidatorEnable(document.getElementById(validatorId), false);

This works fine but the server still fires the requiredFieldValidator logic.  Is anyone aware of how I can force the server to not validate if the validator is set to false client side?


问:
How to `HAVING` on `SUM` without "Non-grouping field x is used in HAVING clause"
So, I have this query, which runs fine in HeidiSQL, but not in Laravel because of strict mode (and more specifically probably because of the SQL mode ONLY_FULL_GROUP_BY being set):

```<code>SELECT
    project.id
        'Project code',
    SUM(report.hours)
        'Total hours',
    SUM(CASE WHEN report.date BETWEEN :report_start AND :report_end THEN report.hours END)
        'Total report hours'

FROM report
    INNER JOIN project ON project.id = report.id
WHERE report.date <= :report_end

GROUP BY
    project.id

HAVING
    `Total report hours` != 0
</code>```

It gives me the following error:

Syntax error or access violation: 1463 Non-grouping field 'Total report hours' is used in HAVING clause

I've tried searching around here, but all questions I find are solved by moving the filter from HAVING to WHERE, which can be done because those cases don't actually include an aggregate function. However, in my case, it does, and I thought this was exactly what HAVING was for? I.e. I want to filter out all rows that do not have any hours in the reported period.

I can "solve" it by instead of referring to Total report hours, instead repeating the whole SUM, like this:

```<code>HAVING
    SUM(CASE WHEN report.date BETWEEN :report_start AND :report_end THEN report.hours END) != 0
</code>```

But that feels very unnecessary and messy when it's already calculated and (from my point of view) available right there in the query itself.

So, is there a way I can express this, that works in strict mode, without having to repeat myself?

答:
In some databases, you need to copy the aggregation expression:

```<code>SELECT p.id as 'Project code',
       SUM(r.hours) as 'Total hours',
       SUM(CASE WHEN r.date BETWEEN :report_start AND :report_end THEN r.hours END) as 'Total report hours'
FROM report r INNER JOIN
     project p
     ON p.id = r.id
WHERE r.date <= :report_end
GROUP BY p.id
HAVING SUM(CASE WHEN r.date BETWEEN :report_start AND :report_end THEN r.hours END) <> 0;
</code>```

I would advise you to not use single quotes for column aliases.  You are using multiple databases, so it is unclear which escape character is best -- backticks, double quotes, or square braces.

Of course, you can also use a subquery.

Body:
So, I have this query, which runs fine in HeidiSQL, but not in Laravel because of strict mode (and more specifically probably because of the SQL mode ONLY_FULL_GROUP_BY being set):

SELECT
    project.id
        'Project code',
    SUM(report.hours)
        'Total hours',
    SUM(CASE WHEN report.date BETWEEN :report_start AND :report_end THEN report.hours END)
        'Total report hours'

FROM report
    INNER JOIN project ON project.id = report.id
WHERE report.date <= :report_end

GROUP BY
    project.id

HAVING
    `Total report hours` != 0

It gives me the following error:

Syntax error or access violation: 1463 Non-grouping field 'Total report hours' is used in HAVING clause

I've tried searching around here, but all questions I find are solved by moving the filter from HAVING to WHERE, which can be done because those cases don't actually include an aggregate function. However, in my case, it does, and I thought this was exactly what HAVING was for? I.e. I want to filter out all rows that do not have any hours in the reported period.

I can "solve" it by instead of referring to Total report hours, instead repeating the whole SUM, like this:

HAVING
    SUM(CASE WHEN report.date BETWEEN :report_start AND :report_end THEN report.hours END) != 0

But that feels very unnecessary and messy when it's already calculated and (from my point of view) available right there in the query itself.

So, is there a way I can express this, that works in strict mode, without having to repeat myself?

Body:
In some databases, you need to copy the aggregation expression:

SELECT p.id as 'Project code',
       SUM(r.hours) as 'Total hours',
       SUM(CASE WHEN r.date BETWEEN :report_start AND :report_end THEN r.hours END) as 'Total report hours'
FROM report r INNER JOIN
     project p
     ON p.id = r.id
WHERE r.date <= :report_end
GROUP BY p.id
HAVING SUM(CASE WHEN r.date BETWEEN :report_start AND :report_end THEN r.hours END) <> 0;

I would advise you to not use single quotes for column aliases.  You are using multiple databases, so it is unclear which escape character is best -- backticks, double quotes, or square braces.

Of course, you can also use a subquery.


问:
Array to DB::insert()->values(), which is in different order with the columns
Hi folks! I'm trying to transfer data as array from the controller to the model, and then paste the data into the query builder, but the data must be in the same order as specified in the columns.

What options do I have?

And do you think this is a bad practice?

Controller:

```<code>            $responseNotes = Model::factory('Notes')-> createTicket([
                'description'   => htmlspecialchars($_POST['description']),
                'contact_id'    => $_POST['contact_id'],
                'pref_contact'  => $_POST['pref_contact'],
                'dog_id'        => $_POST['document_id'],
                'type'          => $_POST['type'],
                'owner_id'      => Auth::instance()->get_user()->id,
                'cc'            => $_POST['cc-emails'],
                'title'         => $_POST['title']
            ]);
</code>```

Model:

```<code>public function createNote(array $data)
{
    $columns = [
        'type',
        'owner_id',
        'cc',
        'title',
        'description',
        'contact_id',
        'pref_contact',
        'dog_id'
    ];
    if (!array_diff($columns, array_keys($data))) {
        // All needed values exists
        $result = DB::insert($this->NOTES, $columns)-> values($data)-> execute($this->SCHEMA);
    }
    return  ($result) ? $result : false ;
}
</code>```

答:
Thanks to this answer. Solved this by:</p>

```<code>// Order $data array according to $column.values
$orderedData = [];
foreach ($columns as $key) {
    $orderedData[$key] = $data[$key];
}
$result = DB::insert($this->TICKETS, $columns)
    -> values($orderedData)
    -> execute($this->SCHEMA);
</code>```

Body:
Hi folks! I'm trying to transfer data as array from the controller to the model, and then paste the data into the query builder, but the data must be in the same order as specified in the columns.

What options do I have?

And do you think this is a bad practice?

Controller:

            $responseNotes = Model::factory('Notes')-> createTicket([
                'description'   => htmlspecialchars($_POST['description']),
                'contact_id'    => $_POST['contact_id'],
                'pref_contact'  => $_POST['pref_contact'],
                'dog_id'        => $_POST['document_id'],
                'type'          => $_POST['type'],
                'owner_id'      => Auth::instance()->get_user()->id,
                'cc'            => $_POST['cc-emails'],
                'title'         => $_POST['title']
            ]);

Model:

public function createNote(array $data)
{
    $columns = [
        'type',
        'owner_id',
        'cc',
        'title',
        'description',
        'contact_id',
        'pref_contact',
        'dog_id'
    ];
    if (!array_diff($columns, array_keys($data))) {
        // All needed values exists
        $result = DB::insert($this->NOTES, $columns)-> values($data)-> execute($this->SCHEMA);
    }
    return  ($result) ? $result : false ;
}

Body:
Thanks to this answer. Solved this by:

// Order $data array according to $column.values
$orderedData = [];
foreach ($columns as $key) {
    $orderedData[$key] = $data[$key];
}
$result = DB::insert($this->TICKETS, $columns)
    -> values($orderedData)
    -> execute($this->SCHEMA);

ContentLicense: CC BY-SA 4.0


问:
How to find and replace string in a file with a variable in Shell script?
I want Shell script to find my Orignal_literal and change it with dynamic literal, this literal would be runtime input to script.

答:
sed -i "s/Orignal_literal/c \\$variable/g" file.txt

Explanation:

sed = Stream Editor

-i = In-place (i.e. save back to the original file)

The command string:

s: The substitute command

Orignal_literal: A regular expression
describing the word to replace (or just the word itself)

g: Global (i.e. replace all and not just the first occurrence)

variable: Runtime variable

file.txt: The file name


问:
Copy timestamp value fails from one column to another
I have a table with two timestamp fields formed with -

```<code>CREATE TABLE `test`
(`id` INT NOT NULL AUTO_INCREMENT ,
`first_date` TIMESTAMP NULL ,
`second_date` TIMESTAMP on update CURRENT_TIMESTAMP() NULL ,
PRIMARY KEY (`id`)) ENGINE = InnoDB;
</code>```

I inserted two rows using

```<code>INSERT INTO `test` (`id`, `first_date`, `second_date`)
VALUES (NULL, NULL, '2017-10-18 17:02:14'), (NULL, NULL, '2017-10-18 17:02:14');
</code>```

Now, I need to copy the second date value to the first date column, but when I try the update query both the date value get updated to today's date.

```<code>update test set first_date = second_date where id=<row_id>

id | first_date          | second_date
----------------------------------------------
3  | 2017-11-17 16:09:03 | 2017-11-17 16:09:29 --> This value was
4  | NULL                | 2017-10-18 17:02:14     "2017-10-18 17:02:14"
5  | NULL                | 2017-10-18 17:02:14      before the update query.
</code>```

Somehow, the on update CURRENT_TIMESTAMP() attribute of the second_date  is creating a problem here. How would I copy the value from second column without affecting the existing value of second_date?

答:
The following query should help you to copy the value from second column without affecting the existing value of second_date:</p>

```<code>UPDATE test SET first_date = second_date , second_date = second_date WHERE  id=<row_id>
</code>```

Body:
I have a table with two timestamp fields formed with -

CREATE TABLE `test`
(`id` INT NOT NULL AUTO_INCREMENT ,
`first_date` TIMESTAMP NULL ,
`second_date` TIMESTAMP on update CURRENT_TIMESTAMP() NULL ,
PRIMARY KEY (`id`)) ENGINE = InnoDB;

I inserted two rows using

INSERT INTO `test` (`id`, `first_date`, `second_date`)
VALUES (NULL, NULL, '2017-10-18 17:02:14'), (NULL, NULL, '2017-10-18 17:02:14');

Now, I need to copy the second date value to the first date column, but when I try the update query both the date value get updated to today's date.

update test set first_date = second_date where id=<row_id>

id | first_date          | second_date
----------------------------------------------
3  | 2017-11-17 16:09:03 | 2017-11-17 16:09:29 --> This value was
4  | NULL                | 2017-10-18 17:02:14     "2017-10-18 17:02:14"
5  | NULL                | 2017-10-18 17:02:14      before the update query.

Somehow, the on update CURRENT_TIMESTAMP() attribute of the second_date  is creating a problem here. How would I copy the value from second column without affecting the existing value of second_date?

Body:
The following query should help you to copy the value from second column without affecting the existing value of second_date:

UPDATE test SET first_date = second_date , second_date = second_date WHERE  id=<row_id>


问:
How can I create a xy line chart with c3?
On the example page http://c3js.org/samples/simple_multiple.html I see I can easily create a multiline chart, as columns or rows based.

Though, I cannot find out a simple case covered where I want to build  a line chart from a sequence of xy coordinates, like this:

```<code>[
    {x:1, y:2},
    {x:2, y:3}
    ...
]
</code>```

I can perform this with NVD3.

Is it possible to build a line chart with xy coordinates for each point of it?

答:
Yes, just need to tell c3 which of those variables is the 'x' value (we know it's x, but just need to tell c3)

A slight tweak to the example at http://c3js.org/samples/data_json.html shows this in practice:

```<code>var chart = c3.generate({
    data: {
        json: [
            {name: 'www.site1.com', upload: 200, download: 200, total: 400, x: 2},
            {name: 'www.site2.com', upload: 100, download: 300, total: 400, x: 3},
            {name: 'www.site3.com', upload: 300, download: 200, total: 500, x: 4},
            {name: 'www.site4.com', upload: 400, download: 100, total: 500, x: 5},
        ],
        keys: {
            x: 'x',
            value: ['upload', 'download'],
        }
    },
});
</code>```

JSFiddle version of above: http://jsfiddle.net/dj27wwef/

Body:
On the example page http://c3js.org/samples/simple_multiple.html I see I can easily create a multiline chart, as columns or rows based.

Though, I cannot find out a simple case covered where I want to build  a line chart from a sequence of xy coordinates, like this:

[
    {x:1, y:2},
    {x:2, y:3}
    ...
]

I can perform this with NVD3.

Is it possible to build a line chart with xy coordinates for each point of it?

Body:
Yes, just need to tell c3 which of those variables is the 'x' value (we know it's x, but just need to tell c3)

A slight tweak to the example at http://c3js.org/samples/data_json.html shows this in practice:

var chart = c3.generate({
    data: {
        json: [
            {name: 'www.site1.com', upload: 200, download: 200, total: 400, x: 2},
            {name: 'www.site2.com', upload: 100, download: 300, total: 400, x: 3},
            {name: 'www.site3.com', upload: 300, download: 200, total: 500, x: 4},
            {name: 'www.site4.com', upload: 400, download: 100, total: 500, x: 5},
        ],
        keys: {
            x: 'x',
            value: ['upload', 'download'],
        }
    },
});

JSFiddle version of above: http://jsfiddle.net/dj27wwef/


问:
how i can show object in gridview or in any usful control
i have an class and into this class i have tow another class how to bind this class to grid view to show properties of inner class

here is my code

```<code>public class EventDetail
 {
    private static Data.Data.BatisEntities Batis_CmsDb = new Data.Data.BatisEntities();
    private Int64 logID;

    public Int64 LogID
    {
        get { return logID; }
        set { logID = value; }
    }
    private object logedObject;

    public object LogedObject
    {
        get { return logedObject; }
        set { logedObject = value; }
    }

    /// <summary>
    /// show detailed information for an selected log
    /// </summary>
    /// <param name="_LogId"></param>
    /// <returns></returns>
    public static List<Modules.EventLog.Wraper.EventDetail.EventDetail> Show_DetailLog(Int64 _LogId)
    {
        string _XmlObjBefor, _XmlObjAfter, _strObjectType;
        var _SelectedLLogDetail = (from e in Batis_CmsDb.Eventlog_Detial
                                   where e.LogID == _LogId
                                   select e).First();
        //get the string object to desrialize;
        _XmlObjBefor = _SelectedLLogDetail.BEFOR_OBJECT;
        _XmlObjAfter = _SelectedLLogDetail.AFTER_OBJECT;
        _strObjectType = _SelectedLLogDetail.OBJECT_TYPE;

        //now create an instanse of type;
        Type ObjectType = Type.GetType(_strObjectType);
        object _objbefor = Activator.CreateInstance(ObjectType);

        object _objAfter = Activator.CreateInstance(ObjectType);
        //get the type of new object to send xml serilizer
        Type _ObjectType = _objbefor.GetType();

        //Deserilize object
        _objbefor = Convertor.XmlDesrialize.XmlDesrializer.DesrializeAnyObject(_XmlObjBefor, _ObjectType);
        _objAfter = Convertor.XmlDesrialize.XmlDesrializer.DesrializeAnyObject(_XmlObjAfter, _ObjectType);

        List<Modules.EventLog.Wraper.EventDetail.EventDetail> lstLog = new List<Modules.EventLog.Wraper.EventDetail.EventDetail>();

        Modules.EventLog.Wraper.EventDetail.EventDetail _EventDetailBefor = new Modules.EventLog.Wraper.EventDetail.EventDetail();
        Modules.EventLog.Wraper.EventDetail.EventDetail _EventDetailAfter = new Modules.EventLog.Wraper.EventDetail.EventDetail();
        _EventDetailAfter.LogedObject = _objAfter;
        _EventDetailBefor.LogedObject = _objbefor;
        _EventDetailBefor.LogID = _LogId;
        _EventDetailAfter.LogID = _LogId;

        lstLog.Add(_EventDetailBefor);
        lstLog.Add(_EventDetailAfter);

        return lstLog;
    }

}
</code>```

答:
In aspx.cs

```<code>protected void Page_Load(object sender, EventArgs e)
{
    List<TestOne> testOneItems = new List<TestOne>();
    TestOne testOne = new TestOne { TestProperty = new TestOne.TestInner { TestInnerProperty = "test Inner Property" }};
    testOneItems.Add(testOne);

    GridView1.DataSource = testOneItems;
    GridView1.DataBind();
}
</code>```

In aspx

```<code>   <asp:GridView ID='GridView1' runat='server' AutoGenerateColumns="false"        >
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Label ID='Label1' runat='server' Text ='<%# Bind("TestProperty.TestInnerProperty")  %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</code>```

The sample types used:

```<code>public class TestOne
{
    public TestOne()
    {
    }

    public TestInner TestProperty
    {
        get;
        set;
    }

    public class TestInner
    {

        public String TestInnerProperty
        {
            get;
            set;
        }
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
i have an class and into this class i have tow another class how to bind this class to grid view to show properties of inner class

here is my code

public class EventDetail
 {
    private static Data.Data.BatisEntities Batis_CmsDb = new Data.Data.BatisEntities();
    private Int64 logID;

    public Int64 LogID
    {
        get { return logID; }
        set { logID = value; }
    }
    private object logedObject;

    public object LogedObject
    {
        get { return logedObject; }
        set { logedObject = value; }
    }

    ///
    /// show detailed information for an selected log
    ///
    /// <param name="_LogId"></param>
    /// <returns></returns>
    public static List<Modules.EventLog.Wraper.EventDetail.EventDetail> Show_DetailLog(Int64 _LogId)
    {
        string _XmlObjBefor, _XmlObjAfter, _strObjectType;
        var _SelectedLLogDetail = (from e in Batis_CmsDb.Eventlog_Detial
                                   where e.LogID == _LogId
                                   select e).First();
        //get the string object to desrialize;
        _XmlObjBefor = _SelectedLLogDetail.BEFOR_OBJECT;
        _XmlObjAfter = _SelectedLLogDetail.AFTER_OBJECT;
        _strObjectType = _SelectedLLogDetail.OBJECT_TYPE;

        //now create an instanse of type;
        Type ObjectType = Type.GetType(_strObjectType);
        object _objbefor = Activator.CreateInstance(ObjectType);

        object _objAfter = Activator.CreateInstance(ObjectType);
        //get the type of new object to send xml serilizer
        Type _ObjectType = _objbefor.GetType();

        //Deserilize object
        _objbefor = Convertor.XmlDesrialize.XmlDesrializer.DesrializeAnyObject(_XmlObjBefor, _ObjectType);
        _objAfter = Convertor.XmlDesrialize.XmlDesrializer.DesrializeAnyObject(_XmlObjAfter, _ObjectType);

        List<Modules.EventLog.Wraper.EventDetail.EventDetail> lstLog = new List<Modules.EventLog.Wraper.EventDetail.EventDetail>();

        Modules.EventLog.Wraper.EventDetail.EventDetail _EventDetailBefor = new Modules.EventLog.Wraper.EventDetail.EventDetail();
        Modules.EventLog.Wraper.EventDetail.EventDetail _EventDetailAfter = new Modules.EventLog.Wraper.EventDetail.EventDetail();
        _EventDetailAfter.LogedObject = _objAfter;
        _EventDetailBefor.LogedObject = _objbefor;
        _EventDetailBefor.LogID = _LogId;
        _EventDetailAfter.LogID = _LogId;

        lstLog.Add(_EventDetailBefor);
        lstLog.Add(_EventDetailAfter);

        return lstLog;
    }

}

Body:
In aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    List<TestOne> testOneItems = new List<TestOne>();
    TestOne testOne = new TestOne { TestProperty = new TestOne.TestInner { TestInnerProperty = "test Inner Property" }};
    testOneItems.Add(testOne);

    GridView1.DataSource = testOneItems;
    GridView1.DataBind();
}

In aspx

   <asp:GridView ID='GridView1' runat='server' AutoGenerateColumns="false"        >
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Label ID='Label1' runat='server' Text ='<%# Bind("TestProperty.TestInnerProperty")  %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

The sample types used:

public class TestOne
{
    public TestOne()
    {
    }

    public TestInner TestProperty
    {
        get;
        set;
    }

    public class TestInner
    {

        public String TestInnerProperty
        {
            get;
            set;
        }
    }
}


问:
Creating & Using 9-patch images in Android
I recently heard about 9-patch images. I know its 9 tiled and is stretchable. I'd like to know more about it.

How can I create a 9-patch image?

Is there any tool? Can I create it from AndroidSDK or code?

Main Advantages of 9-patch over regular png?

(is it stretchable dynamically/ automatically according to screen?)

答:
This is good tool:
Click here.

9 Patch images are stretchable, repeatable images reduced to their smallest size. The simplest example would be if you were to take a rounded div and slice it up into 9 squares like you would a tic-tac-toe board. The four corners wouldn't change sizes at all but would be static while the other 5 pieces would be stretched or repeated to allow the whole image to scale appropriately.

With that explanation and the advent of CSS3 you might think that there is no reason to use 9 patch images but the name '9 patch' is a misnomer. The images can be sliced up into even smaller pieces.

9 Patch images contain an index of which piece is what by adding a 1px border to the image. The colors in the border determine if a piece is static (doesn't scale), it stretches, or it repeats.

Google Slideshow: https://docs.google.com/present/view?id=dc7ghz8w_34f8338rcg

See also the Android developer info about 9-patch images: http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch


问:
Code Review Best way use SharedPreferences solving MemoryLeak
i try to resolve memory leak in Shared Preferences use, i try all day to do this, but still confuse, my goal is possible call pref in anywhere i want. here my code.

```<code>class Preferences (private val context: Context) {

private val sharedPreferences: SharedPreferences =
        context.getSharedPreferences(context.packageName+"_pref", Context.MODE_PRIVATE)
private val editor: SharedPreferences.Editor

companion object {
    private val KEY_USER = "user"
    private val KEY_EMAIL = "email"
}

init {
    editor = sharedPreferences.edit()
}

private fun isKeyExist(Key: String): Boolean = sharedPreferences.contains(Key)

private fun putString(Key: String, value: String) {
    editor.putString(Key, value)
    editor.apply()
}
private fun putInt(Key: String, value: Int) {
    editor.putInt(Key, value)
    editor.apply()
}
private fun putBoolean(Key: String, value: Boolean) {
    editor.putBoolean(Key, value)
    editor.apply()
}
private fun putDouble(key: String, value: Double) {
    editor.putLong(key, java.lang.Double.doubleToRawLongBits(value))
}

private fun getInt(Key: String): Int = sharedPreferences.getInt(Key, 0)
private fun getString(Key: String): String = sharedPreferences.getString(Key, "")
private fun getBoolean(key: String): Boolean = sharedPreferences.getBoolean(key, false)
private fun getLong(key: String): Long = sharedPreferences.getLong(key, 0)

fun init (){
    if(!isKeyExist(KEY_USER)){
        putString(KEY_USER,"")
    }
    if(!isKeyExist(KEY_EMAIL)){
        putString(KEY_EMAIL,"")
    }
}

private fun resetPref(){
    if(isKeyExist(KEY_USER)){
        putString(KEY_USER,"")
    }
    if(isKeyExist(KEY_EMAIL)){
        putString(KEY_EMAIL,"")
    }
}

var user : String
    get() = getString(KEY_USER)
    set(value) = putString(KEY_USER,value)
var email : String
    get() = getString(KEY_EMAIL)
    set(value) = putString(KEY_EMAIL,value)
</code>```

Because pref need context, i init pref in some class with extend Application like code below,

```<code>class BaseApplication : android.app.Application() {

override fun onCreate() {
    super.onCreate()
    preferences = Preferences(applicationContext)
}

companion object {
    @SuppressLint("StaticFieldLeak")
    var preferences : Preferences? = null
}
</code>```

with this method, it's possible to call pref anywhere like activity, fragment, or some class with no context, with this simple way,

```<code>BaseApplication.preferences!!.user
</code>```

but it will make memory leak in my apps.
will appreciate if any someone can give me some advice how to resolve memory leak.

答:
We call this use as a singleton pattern. Use this class :

```<code>public class Prefs {

private static final String TAG = "Prefs";

static Prefs singleton = null;

static SharedPreferences preferences;

static SharedPreferences.Editor editor;

private static Gson GSON = new Gson();
Type typeOfObject = new TypeToken<Object>() {
}.getType();

Prefs(Context context) {
    preferences = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
    editor = preferences.edit();
}

public static Prefs with(Context context) {
    if (singleton == null) {
        singleton = new Builder(context).build();
    }
    return singleton;
}

public void save(String key, boolean value) {
    editor.putBoolean(key, value).apply();
}

public void save(String key, String value) {
    editor.putString(key, value).apply();
}

public void save(String key, int value) {
    editor.putInt(key, value).apply();
}

public void save(String key, float value) {
    editor.putFloat(key, value).apply();
}

public void save(String key, long value) {
    editor.putLong(key, value).apply();
}

public void save(String key, Set<String> value) {
    editor.putStringSet(key, value).apply();
}

// to save object in prefrence
public void save(String key, Object object) {
    if (object == null) {
        throw new IllegalArgumentException("object is null");
    }

    if (key.equals("") || key == null) {
        throw new IllegalArgumentException("key is empty or null");
    }

    editor.putString(key, GSON.toJson(object)).apply();
}

// To get object from prefrences

public <T> T getObject(String key, Class<T> a) {

    String gson = preferences.getString(key, null);
    if (gson == null) {
        return null;
    } else {
        try {
            return GSON.fromJson(gson, a);
        } catch (Exception e) {
            throw new IllegalArgumentException("Object storaged with key "
                    + key + " is instanceof other class");
        }
    }
}

public boolean getBoolean(String key, boolean defValue) {
    return preferences.getBoolean(key, defValue);
}

public String getString(String key, String defValue) {
    return preferences.getString(key, defValue);
}

public int getInt(String key, int defValue) {
    return preferences.getInt(key, defValue);
}

public float getFloat(String key, float defValue) {
    return preferences.getFloat(key, defValue);
}

public long getLong(String key, long defValue) {
    return preferences.getLong(key, defValue);
}

public Set<String> getStringSet(String key, Set<String> defValue) {
    return preferences.getStringSet(key, defValue);
}

public Map<String, ?> getAll() {
    return preferences.getAll();
}

public void remove(String key) {
    editor.remove(key).apply();
}

public void removeAll() {
    editor.clear();
    editor.apply();
}

private static class Builder {

    private final Context context;

    public Builder(Context context) {
        if (context == null) {
            throw new IllegalArgumentException("Context must not be null.");
        }
        this.context = context.getApplicationContext();
    }

    /**
     * Method that creates an instance of Prefs
     *
     * @return an instance of Prefs
     */
    public Prefs build() {
        return new Prefs(context);
    }
}
}
</code>```

The kotlin version:

```<code>class Prefs internal constructor(context: Context) {
internal var typeOfObject = object : TypeToken<Any>() {

}.type

val all: Map<String, *>
    get() = preferences.all

init {
    preferences = context.getSharedPreferences(TAG, Context.MODE_PRIVATE)
    editor = preferences.edit()
}

fun save(key: String, value: Boolean) {
    editor.putBoolean(key, value).apply()
}

fun save(key: String, value: String) {
    editor.putString(key, value).apply()
}

fun save(key: String, value: Int) {
    editor.putInt(key, value).apply()
}

fun save(key: String, value: Float) {
    editor.putFloat(key, value).apply()
}

fun save(key: String, value: Long) {
    editor.putLong(key, value).apply()
}

fun save(key: String, value: Set<String>) {
    editor.putStringSet(key, value).apply()
}

// to save object in prefrence
fun save(key: String?, `object`: Any?) {
    if (`object` == null) {
        throw IllegalArgumentException("object is null")
    }

    if (key == "" || key == null) {
        throw IllegalArgumentException("key is empty or null")
    }

    editor.putString(key, GSON.toJson(`object`)).apply()
}

// To get object from prefrences

fun <T> getObject(key: String, a: Class<T>): T? {

    val gson = preferences.getString(key, null)
    return if (gson == null) {
        null
    } else {
        try {
            GSON.fromJson(gson, a)
        } catch (e: Exception) {
            throw IllegalArgumentException("Object storaged with key "
                    + key + " is instanceof other class")
        }

    }
}

fun getBoolean(key: String, defValue: Boolean): Boolean {
    return preferences.getBoolean(key, defValue)
}

fun getString(key: String, defValue: String): String? {
    return preferences.getString(key, defValue)
}

fun getInt(key: String, defValue: Int): Int {
    return preferences.getInt(key, defValue)
}

fun getFloat(key: String, defValue: Float): Float {
    return preferences.getFloat(key, defValue)
}

fun getLong(key: String, defValue: Long): Long {
    return preferences.getLong(key, defValue)
}

fun getStringSet(key: String, defValue: Set<String>): Set<String>? {
    return preferences.getStringSet(key, defValue)
}

fun remove(key: String) {
    editor.remove(key).apply()
}

fun removeAll() {
    editor.clear()
    editor.apply()
}

private class Builder(context: Context?) {

    private val context: Context

    init {
        if (context == null) {
            throw IllegalArgumentException("Context must not be null.")
        }
        this.context = context.applicationContext
    }

    /**
     * Method that creates an instance of Prefs
     *
     * @return an instance of Prefs
     */
    fun build(): Prefs {
        return Prefs(context)
    }
}

companion object {

    private val TAG = "Prefs"

    lateinit var singleton: Prefs

    lateinit var preferences: SharedPreferences

    lateinit var editor: SharedPreferences.Editor

    private val GSON = Gson()

    fun with(context: Context): Prefs {
        if (singleton == null) {
            singleton = Builder(context).build()
        }
        return singleton
    }
}
}
</code>```

You will need google GSON to save objects.
Calling it is like this :

```<code>Prefs.with(context).save("key","value or object or int or boolean");
</code>```

Hope this helps.

Body:
i try to resolve memory leak in Shared Preferences use, i try all day to do this, but still confuse, my goal is possible call pref in anywhere i want. here my code.

class Preferences (private val context: Context) {

private val sharedPreferences: SharedPreferences =
        context.getSharedPreferences(context.packageName+"_pref", Context.MODE_PRIVATE)
private val editor: SharedPreferences.Editor

companion object {
    private val KEY_USER = "user"
    private val KEY_EMAIL = "email"
}

init {
    editor = sharedPreferences.edit()
}

private fun isKeyExist(Key: String): Boolean = sharedPreferences.contains(Key)

private fun putString(Key: String, value: String) {
    editor.putString(Key, value)
    editor.apply()
}
private fun putInt(Key: String, value: Int) {
    editor.putInt(Key, value)
    editor.apply()
}
private fun putBoolean(Key: String, value: Boolean) {
    editor.putBoolean(Key, value)
    editor.apply()
}
private fun putDouble(key: String, value: Double) {
    editor.putLong(key, java.lang.Double.doubleToRawLongBits(value))
}

private fun getInt(Key: String): Int = sharedPreferences.getInt(Key, 0)
private fun getString(Key: String): String = sharedPreferences.getString(Key, "")
private fun getBoolean(key: String): Boolean = sharedPreferences.getBoolean(key, false)
private fun getLong(key: String): Long = sharedPreferences.getLong(key, 0)

fun init (){
    if(!isKeyExist(KEY_USER)){
        putString(KEY_USER,"")
    }
    if(!isKeyExist(KEY_EMAIL)){
        putString(KEY_EMAIL,"")
    }
}

private fun resetPref(){
    if(isKeyExist(KEY_USER)){
        putString(KEY_USER,"")
    }
    if(isKeyExist(KEY_EMAIL)){
        putString(KEY_EMAIL,"")
    }
}

var user : String
    get() = getString(KEY_USER)
    set(value) = putString(KEY_USER,value)
var email : String
    get() = getString(KEY_EMAIL)
    set(value) = putString(KEY_EMAIL,value)

Because pref need context, i init pref in some class with extend Application like code below,

class BaseApplication : android.app.Application() {

override fun onCreate() {
    super.onCreate()
    preferences = Preferences(applicationContext)
}

companion object {
    @SuppressLint("StaticFieldLeak")
    var preferences : Preferences? = null
}

with this method, it's possible to call pref anywhere like activity, fragment, or some class with no context, with this simple way,

BaseApplication.preferences!!.user

but it will make memory leak in my apps.
will appreciate if any someone can give me some advice how to resolve memory leak.

Body:
We call this use as a singleton pattern. Use this class :

public class Prefs {

private static final String TAG = "Prefs";

static Prefs singleton = null;

static SharedPreferences preferences;

static SharedPreferences.Editor editor;

private static Gson GSON = new Gson();
Type typeOfObject = new TypeToken<Object>() {
}.getType();

Prefs(Context context) {
    preferences = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
    editor = preferences.edit();
}

public static Prefs with(Context context) {
    if (singleton == null) {
        singleton = new Builder(context).build();
    }
    return singleton;
}

public void save(String key, boolean value) {
    editor.putBoolean(key, value).apply();
}

public void save(String key, String value) {
    editor.putString(key, value).apply();
}

public void save(String key, int value) {
    editor.putInt(key, value).apply();
}

public void save(String key, float value) {
    editor.putFloat(key, value).apply();
}

public void save(String key, long value) {
    editor.putLong(key, value).apply();
}

public void save(String key, Set<String> value) {
    editor.putStringSet(key, value).apply();
}

// to save object in prefrence
public void save(String key, Object object) {
    if (object == null) {
        throw new IllegalArgumentException("object is null");
    }

    if (key.equals("") || key == null) {
        throw new IllegalArgumentException("key is empty or null");
    }

    editor.putString(key, GSON.toJson(object)).apply();
}

// To get object from prefrences

public <T> T getObject(String key, Class<T> a) {

    String gson = preferences.getString(key, null);
    if (gson == null) {
        return null;
    } else {
        try {
            return GSON.fromJson(gson, a);
        } catch (Exception e) {
            throw new IllegalArgumentException("Object storaged with key "
                    + key + " is instanceof other class");
        }
    }
}

public boolean getBoolean(String key, boolean defValue) {
    return preferences.getBoolean(key, defValue);
}

public String getString(String key, String defValue) {
    return preferences.getString(key, defValue);
}

public int getInt(String key, int defValue) {
    return preferences.getInt(key, defValue);
}

public float getFloat(String key, float defValue) {
    return preferences.getFloat(key, defValue);
}

public long getLong(String key, long defValue) {
    return preferences.getLong(key, defValue);
}

public Set<String> getStringSet(String key, Set<String> defValue) {
    return preferences.getStringSet(key, defValue);
}

public Map<String, ?> getAll() {
    return preferences.getAll();
}

public void remove(String key) {
    editor.remove(key).apply();
}

public void removeAll() {
    editor.clear();
    editor.apply();
}

private static class Builder {

    private final Context context;

    public Builder(Context context) {
        if (context == null) {
            throw new IllegalArgumentException("Context must not be null.");
        }
        this.context = context.getApplicationContext();
    }

    /**
     * Method that creates an instance of Prefs
     *
     * @return an instance of Prefs
     */
    public Prefs build() {
        return new Prefs(context);
    }
}
}

The kotlin version:

class Prefs internal constructor(context: Context) {
internal var typeOfObject = object : TypeToken<Any>() {

}.type

val all: Map<String, *>
    get() = preferences.all

init {
    preferences = context.getSharedPreferences(TAG, Context.MODE_PRIVATE)
    editor = preferences.edit()
}

fun save(key: String, value: Boolean) {
    editor.putBoolean(key, value).apply()
}

fun save(key: String, value: String) {
    editor.putString(key, value).apply()
}

fun save(key: String, value: Int) {
    editor.putInt(key, value).apply()
}

fun save(key: String, value: Float) {
    editor.putFloat(key, value).apply()
}

fun save(key: String, value: Long) {
    editor.putLong(key, value).apply()
}

fun save(key: String, value: Set<String>) {
    editor.putStringSet(key, value).apply()
}

// to save object in prefrence
fun save(key: String?, `object`: Any?) {
    if (`object` == null) {
        throw IllegalArgumentException("object is null")
    }

    if (key == "" || key == null) {
        throw IllegalArgumentException("key is empty or null")
    }

    editor.putString(key, GSON.toJson(`object`)).apply()
}

// To get object from prefrences

fun <T> getObject(key: String, a: Class<T>): T? {

    val gson = preferences.getString(key, null)
    return if (gson == null) {
        null
    } else {
        try {
            GSON.fromJson(gson, a)
        } catch (e: Exception) {
            throw IllegalArgumentException("Object storaged with key "
                    + key + " is instanceof other class")
        }

    }
}

fun getBoolean(key: String, defValue: Boolean): Boolean {
    return preferences.getBoolean(key, defValue)
}

fun getString(key: String, defValue: String): String? {
    return preferences.getString(key, defValue)
}

fun getInt(key: String, defValue: Int): Int {
    return preferences.getInt(key, defValue)
}

fun getFloat(key: String, defValue: Float): Float {
    return preferences.getFloat(key, defValue)
}

fun getLong(key: String, defValue: Long): Long {
    return preferences.getLong(key, defValue)
}

fun getStringSet(key: String, defValue: Set<String>): Set<String>? {
    return preferences.getStringSet(key, defValue)
}

fun remove(key: String) {
    editor.remove(key).apply()
}

fun removeAll() {
    editor.clear()
    editor.apply()
}

private class Builder(context: Context?) {

    private val context: Context

    init {
        if (context == null) {
            throw IllegalArgumentException("Context must not be null.")
        }
        this.context = context.applicationContext
    }

    /**
     * Method that creates an instance of Prefs
     *
     * @return an instance of Prefs
     */
    fun build(): Prefs {
        return Prefs(context)
    }
}

companion object {

    private val TAG = "Prefs"

    lateinit var singleton: Prefs

    lateinit var preferences: SharedPreferences

    lateinit var editor: SharedPreferences.Editor

    private val GSON = Gson()

    fun with(context: Context): Prefs {
        if (singleton == null) {
            singleton = Builder(context).build()
        }
        return singleton
    }
}
}

You will need google GSON to save objects.
Calling it is like this :

Prefs.with(context).save("key","value or object or int or boolean");

Hope this helps.


问:
Angular 5, Passing table of tags to pipe filter
I'm new in angular so please be lenient :-)
I'm working with angular 5 and I can't find a way to filter array of objects using array of tags.
I'm trying to pass array of tags ty my custom pipe, unfortunately it doesn't work.
My code looks like this:

Component

```<code>*export class StarsComponent implements OnInit {
....
tagFilter: string[];
....
}*
</code>```

Pipe

```<code>*@Pipe({
name: 'filterByTag'
})
export class FilterByPipe implements PipeTransform {

    transform(items: any[], prop: string, tags: string[]): any {
    console.log('filterByTag items - ', items);
    console.log('filterByTag prop - ', prop);
    console.log('filterByTag tags - ', tags);
    return items;
}*
</code>```

View

```<code>**<div>
<button type="button" class="btn btn-default" *ngFor="let tag of uniqTags"
    (click)="addTagToFilter(tag)" [ngClass]="{'btn-primary': (tagFilter.indexOf(tag) != -1)}">
    {{tag}}
</button>
</div>
<ul class="stars">
<li *ngFor="let starE of allstars | filterByTag: 'tagFilter': tagFilter">
....
</li>
</code>```

**

My console looks like this:

```<code>filterByTag items -  {array of my items} - it's OK
filterByTag prop -  tagFilter - it's OK
filterByTag tags -**it's empty, why?**
</code>```

Is there any way to pass array of string tags to FilterByPipe ?
Thanks

答:
Pipes take an array that contains all arguments, so you need to call them like this:</p>

```<code><li *ngFor="let starE of allstars | filterByTag: args">

 transform(items: any[], args: any[]): any {
    console.log('filterByTag items - ', items);
    console.log('filterByTag prop - ', args[0]);
    console.log('filterByTag tags - ', args[1]);
    return items;

args = any[];
args[0] = 'tagFilter';
args[1] = tags;
</code>```

Body:
I'm new in angular so please be lenient :-)
I'm working with angular 5 and I can't find a way to filter array of objects using array of tags.
I'm trying to pass array of tags ty my custom pipe, unfortunately it doesn't work.
My code looks like this:

Component

*export class StarsComponent implements OnInit {
....
tagFilter: string[];
....
}*

Pipe

*@Pipe({
name: 'filterByTag'
})
export class FilterByPipe implements PipeTransform {

    transform(items: any[], prop: string, tags: string[]): any {
    console.log('filterByTag items - ', items);
    console.log('filterByTag prop - ', prop);
    console.log('filterByTag tags - ', tags);
    return items;
}*

View

**

<button type="button" class="btn btn-default" *ngFor="let tag of uniqTags"
    (click)="addTagToFilter(tag)" [ngClass]="{'btn-primary': (tagFilter.indexOf(tag) != -1)}">
    {{tag}}
</button>

....

**

My console looks like this:

filterByTag items -  {array of my items} - it's OK
filterByTag prop -  tagFilter - it's OK
filterByTag tags -**it's empty, why?**

Is there any way to pass array of string tags to FilterByPipe ?
Thanks

Body:
Pipes take an array that contains all arguments, so you need to call them like this:

<li *ngFor="let starE of allstars | filterByTag: args">

 transform(items: any[], args: any[]): any {
    console.log('filterByTag items - ', items);
    console.log('filterByTag prop - ', args[0]);
    console.log('filterByTag tags - ', args[1]);
    return items;

args = any[];
args[0] = 'tagFilter';
args[1] = tags;


问:
Can i use Watson TTS in my C++ project?
I'm working on a chat bot in C++ on a Linux system and I just need to give it a voice.

I know Watson TTS is awesome, I can even work on the tone of the voice and customize it.

How can I use Watson TTS for my C++ project? I saw on the official website that the SDKs are available for Node, java, python, .Net, Unity and Salesforce.

Is there any way I can use it to read the answers of my chat bot?

答: I don't think/I haven't heard yet of using Watson's TTS for a C++ program. There are , though here you can see a top 5 of TTS working with C++ (https://www.quora.com/What-are-the-best-text-to-speech-library-for-C) .</p>

Title: Can i use Watson TTS in my C++ project?


问:
return Json as string from spring controller and get in Ajax to populate in datatable
am trying to convert my list of data as string using Json and return it to Ajax to populate in datatable. The spring controller able to convert it to Json data but am confusing how to return it from spring and get it in Ajax success, can anyone help me on this. Below is my code details,

Controller Class

```<code>    @Controller
    @RequestMapping(value = "/json")
    public class JsonController {
        @RequestMapping(value = "/postEmployee", method = RequestMethod.POST, produces = "application/json")
        public @ResponseBody
        String postEmployeeData() throws JsonGenerationException,
                JsonMappingException, IOException {
            List<Users> users = new ArrayList<Users>();
            for (int i = 0; i < 5; i++) {
                Users user = new Users();
                user.setName("Akram");
                user.setPrincipal("DEC");
                users.add(user);
            }
            ObjectMapper mapper = new ObjectMapper();
            String data = mapper.writeValueAsString(users);
            return data;
        }
</code>```

Jquery

```<code>    <script type="text/javascript">
            $("#submit").click(function() {
                $.ajax({
                    type : "post",
                    url : "/myApp/json/postEmployee.do",
                    cache : false,
                    success : function(response) {
                        display(response);
                        alert('Inside success');
                        var obj = JSON.parse(response);
                        alert(obj);
                    },
                    error : function() {
                        alert('Error while request..');
                    }
                });
            });
        </script>
</code>```

In POM.xml

```<code><dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.6.3</version>
</dependency>
</code>```

Here am getting no response. So please help me to achieve this.

答:
Why don't you use ResponseEntity to send the response back?

```<code>@RequestMapping(value = "/postEmployee", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity List<Users> postEmployeeData() throws JsonGenerationException, JsonMappingException, IOException {
  List<Users> users = new ArrayList<Users> ();
  for (int i = 0; i < 5; i++) {
    Users user = new Users();
    user.setName("Akram");
    user.setPrincipal("DEC");
    users.add(user);
  }

  return ResponseEntity<>(users, HttpStatus.OK);
}
</code>```

Changes

Added

```<code>method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE

public ResponseEntity List<Users> postEmployeeData() ...

return ResponseEntity<>(users, HttpStatus.OK);
</code>```

Removed

```<code>ObjectMapper mapper = new ObjectMapper();

String data = mapper.writeValueAsString(users);

return data;
</code>```

Body:
am trying to convert my list of data as string using Json and return it to Ajax to populate in datatable. The spring controller able to convert it to Json data but am confusing how to return it from spring and get it in Ajax success, can anyone help me on this. Below is my code details,

Controller Class

    @Controller
    @RequestMapping(value = "/json")
    public class JsonController {
        @RequestMapping(value = "/postEmployee", method = RequestMethod.POST, produces = "application/json")
        public @ResponseBody
        String postEmployeeData() throws JsonGenerationException,
                JsonMappingException, IOException {
            List<Users> users = new ArrayList<Users>();
            for (int i = 0; i < 5; i++) {
                Users user = new Users();
                user.setName("Akram");
                user.setPrincipal("DEC");
                users.add(user);
            }
            ObjectMapper mapper = new ObjectMapper();
            String data = mapper.writeValueAsString(users);
            return data;
        }

Jquery

In POM.xml

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.6.3</version>
</dependency>

Here am getting no response. So please help me to achieve this.

Body:
Why don't you use ResponseEntity to send the response back?

@RequestMapping(value = "/postEmployee", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity List<Users> postEmployeeData() throws JsonGenerationException, JsonMappingException, IOException {
  List<Users> users = new ArrayList<Users> ();
  for (int i = 0; i < 5; i++) {
    Users user = new Users();
    user.setName("Akram");
    user.setPrincipal("DEC");
    users.add(user);
  }

  return ResponseEntity<>(users, HttpStatus.OK);
}

Changes

Added

method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE

public ResponseEntity List<Users> postEmployeeData() ...

return ResponseEntity<>(users, HttpStatus.OK);

Removed

ObjectMapper mapper = new ObjectMapper();

String data = mapper.writeValueAsString(users);

return data;


答:
For a relatively simple implementation, you can try as follows:

Consider a running slice of the data, with a constant width. The width must be larger than the largest gap.

Construct the upper and lower hull of the points, using the Monotone Chain algorithm (there is no need to sort, your points are already by increasing abscissa). https://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain

For the middle abscissa in the slice, estimate the two ordinates on the convex hull (by identifying the hull edges at that particular absicssa). By sweeping, this will create the desired curves. At both ends of the range, use all abscissas in the first and last half-slices.

There will be a small downward bias where the curvature is high and/or the window is large, but nobody's perfect.

The total running time will be proportional to the product of the number of points and the window width. But I guess that an incremental version can do better.

Title: Lower Bound of a Curve

Body:
I have a curve likes the following:

As can be seen, there are two upper bound and lower bound curves on the above (see the following image for the approx visualization!):

I have tried to find the lower bound by the following code:

lower_bound = rbind()
for(i in 2:(length(data[,1])-1))
{
    if(data[i,2] < data[i+1,2] && data[i,2] < data[i-1,2])
    {
        lower_bound = rbind2(lower_bound, c(data[i,1], data[i,2]))
    }
}

But, the problem is there are some local minima in the middle, so the result is not what I've expected (as follow).

Hence the question is how can I find the lower bound of such a curve in R? Is there any known algorithm to find the lower bound?

About the minimal reproducible example, I've included 500 of data (to make sense) in the following:

structure(c(3.54246575342466, 5.75616438356164, 6.54246575342466,
9.73424657534247, 7.75616438356164, 9.75616438356164, 1.41917808219178,
2.75342465753425, 3.16986301369863, 2.27123287671233, 3.74520547945205,
5.74520547945205, 4.29315068493151, 3.37260273972603, 8.37534246575343,
3.33698630136986, 5.04657534246575, 6.92328767123288, 1.33972602739726,
6.34246575342466, 26.358904109589, 2.34794520547945, 4.35068493150685,
7.35342465753425, 27.3671232876712, 1.15068493150685, 2.14794520547945,
4.15342465753425, 6.15342465753425, 9.15616438356164, 19.1616438356164,
29.1698630136986, 2.58904109589041, 4.5972602739726, 9.6, 29.613698630137,
3.10684931506849, 8.11780821917808, 3.35068493150685, 8.37260273972603,
5.11506849315068, 28.1315068493151, 5.36986301369863, 28.386301369863,
4.87945205479452, 4.46027397260274, 5.35616438356164, 25.3698630136986,
25.8684931506849, 5.85479452054795, 1.85205479452055, 4.37260273972603,
6.37260273972603, 9.37534246575343, 19.3835616438356, 29.3890410958904,
18.3808219178082, 1.36986301369863, 8.37534246575343, 3.37260273972603,
5.85479452054795, 28.3890410958904, 2.87671232876712, 4.87945205479452,
7.37808219178082, 8.17260273972603, 28.186301369863, 4.29315068493151,
6.96164383561644, 26.3479452054795, 7.96438356164384, 1.53972602739726,
1.58630136986301, 5.04657534246575, 16.6356164383562, 18.4684931506849,
25.0602739726027, 15.6493150684932, 24.8547945205479, 25.3506849315068,
26.1068493150685, 16.0547945205479, 2.16712328767123, 19.2657534246575,
20.6849315068493, 1.04383561643836, 3.04383561643836, 23.0575342465753,
3.29315068493151, 4.13150684931507, 2.04383561643836, 22.0575342465753,
22.8904109589041, 2.87671232876712, 5.54246575342466, 25.5561643835616,
1.04931506849315, 6.05205479452055, 26.0657534246575, 2.09041095890411,
7.09315068493151, 27.1068493150685, 2.09041095890411, 4.09315068493151,
6.09315068493151, 9.0958904109589, 19.1013698630137, 29.1095890410959,
1.83287671232877, 1.42739726027397, 3.43013698630137, 9.3041095890411,
2.72328767123288, 8.58082191780822, 2.8958904109589, 4.92054794520548,
9.92328767123288, 6.92054794520548, 19.9315068493151, 29.9369863013699,
20.9315068493151, 2.25205479452055, 22.2657534246575, 3.40821917808219,
23.4219178082192, 8.21095890410959, 3.20821917808219, 5.20821917808219,
18.8027397260274, 19.8054794520548, 21.7232876712329, 2.25205479452055,
22.8054794520548, 24.4301369863014, 4.41643835616438, 25.2684931506849,
5.25479452054795, 6.33698630136986, 26.3506849315068, 2.87671232876712,
4.29315068493151, 2.78630136986301, 1.2958904109589, 1.75890410958904,
2.29041095890411, 7.2958904109589, 3.44657534246575, 4.5041095890411,
9.73424657534247, 8.21643835616438, 6.29315068493151, 7.50684931506849,
3.75616438356164, 7.96438356164384, 9.96438356164384, 29.9780821917808,
17.3452054794521, 26.8547945205479, 5.5041095890411, 7.17260273972603,
6.13150684931507, 3.62739726027397, 5.79452054794521, 7.7972602739726,
5.75616438356164, 3.09041095890411, 8.0958904109589, 9.63013698630137,
4.93424657534247, 6.93424657534247, 9.93698630136986, 19.9452054794521,
6.42191780821918, 8.96438356164384, 28.9780821917808, 15.7643835616438,
18.7205479452055, 1.20547945205479, 4.16986301369863, 24.1835616438356,
25.2520547945205, 26.3095890410959, 9.61917808219178, 12.3424657534247,
14.2986301369863, 23.7698630136986, 3.71232876712329, 8.71506849315069,
3.58082191780822, 1.25205479452055, 5.96164383561644, 3.46027397260274,
8.46301369863014, 7.88219178082192, 5.54246575342466, 6.46027397260274,
4.79452054794521, 3.20821917808219, 15.5506849315068, 9.5972602739726,
20.6, 2.09041095890411, 1.87671232876712, 22.2191780821918, 5.67397260273973,
25.7260273972603, 26.9753424657534, 7.2958904109589, 27.5205479452055,
8.17260273972603, 28.3095890410959, 29.2246575342466, 3.87945205479452,
9.13424657534247, 5.84109589041096, 3.96164383561644, 4.54246575342466,
9.92602739726027, 29.9397260273973, 16.1397260273973, 16.1780821917808,
16.1397260273973, 18.7643835616438, 18.7643835616438, 20.2191780821918,
20.6383561643836, 20.8904109589041, 1.16712328767123, 21.2657534246575,
1.33424657534247, 2.04383561643836, 2.20547945205479, 4.75616438356164,
2.92054794520548, 23.2219178082192, 4.09315068493151, 4.24931506849315,
5.13150684931507, 5.96164383561644, 6.20821917808219, 27.3917808219178,
29.2246575342466, 9.75890410958904, 8.75890410958904, 28.2712328767123,
8.42465753424658, 28.4383561643836, 2.37260273972603, 4.37534246575343,
4.75616438356164, 1.67123287671233, 3.96164383561644, 2.37260273972603,
5.04657534246575, 2.25205479452055, 5.62739726027397, 4.29315068493151,
1.29041095890411, 3.5041095890411, 5.5041095890411, 5.09315068493151,
3.83561643835616, 8.46301369863014, 3.42191780821918, 1.33424657534247,
4.5041095890411, 4.79452054794521, 6.37534246575343, 7.21095890410959,
9.37808219178082, 29.3534246575342, 3.54246575342466, 28.6904109589041,
8.2958904109589, 8.54246575342466, 4.62739726027397, 12.4082191780822,
19.4712328767123, 20.972602739726, 3.67397260273973, 4.42191780821918,
4.46027397260274, 25.3890410958904, 5.87945205479452, 25.8931506849315,
2.20547945205479, 27.2246575342466, 7.88219178082192, 1.43561643835616,
2.43561643835616, 4.46027397260274, 6.46027397260274, 9.46301369863014,
19.4712328767123, 29.4767123287671, 2.45753424657534, 9.63013698630137,
7.88219178082192, 23.641095890411, 5.13150684931507, 6.46027397260274,
9.7972602739726, 29.8109589041096, 3.21095890410959, 8.21643835616438,
4.92328767123288, 3.25479452054795, 2.62465753424658, 3.71232876712329,
5.75616438356164, 25.7698630136986, 6.20821917808219, 1.20547945205479,
4.96164383561644, 2.09041095890411, 4.13150684931507, 2.45753424657534,
27.4767123287671, 7.46301369863014, 3.2, 18.2164383561644, 1.1972602739726,
5.20821917808219, 8.21095890410959, 28.2246575342466, 19.972602739726,
7.50684931506849, 9.92602739726027, 3.75616438356164, 1.38904109589041,
3.39178082191781, 19.4082191780822, 2.04383561643836, 24.0602739726027,
5.75616438356164, 26.4356164383562, 6.42191780821918, 28.0630136986301,
8.21095890410959, 18.2164383561644, 6.37534246575343, 3.96164383561644,
6.87945205479452, 7.75890410958904, 5.54246575342466, 7.75890410958904,
2.19452054794521, 27.213698630137, 29.227397260274, 8.2, 5.87945205479452,
1.12876712328767, 3.12876712328767, 7.54520547945206, 2.74246575342466,
4.74520547945205, 6.74520547945205, 9.74794520547945, 29.7616438356164,
3.58904109589041, 8.53150684931507, 18.5369863013699, 28.5452054794521,
4.96164383561644, 19.3479452054795, 1.04657534246575, 21.386301369863,
3.96164383561644, 5.42191780821918, 3.62739726027397, 7.13150684931507,
2.54246575342466, 27.5616438356164, 18.0547945205479, 4.16986301369863,
9.25753424657534, 4.76986301369863, 15.2164383561644, 6.37534246575343,
8.17808219178082, 3.73424657534247, 1.26849315068493, 6.27123287671233,
6.2986301369863, 19.3945205479452, 17.1397260273973, 1.20547945205479,
6.20821917808219, 3.37534246575342, 5.25479452054795, 4.75616438356164,
6.54246575342466, 3.16986301369863, 2.04383561643836, 4.25479452054795,
1.04383561643836, 7.71506849315069, 5.09315068493151, 4.42191780821918,
6.71232876712329, 3.04383561643836, 1.67945205479452, 3.30958904109589,
3.96164383561644, 2.92054794520548, 7.92602739726027, 27.9397260273973,
2.83835616438356, 7.46301369863014, 8.21095890410959, 7.23835616438356,
27.2520547945205, 2.53972602739726, 6.58904109589041, 9.96438356164384,
29.9780821917808, 16.4301369863014, 18.3671232876712, 19.2657534246575,
20.386301369863, 2.37534246575342, 6.46027397260274, 26.4739726027397,
6.62739726027397, 4.75616438356164, 6.71232876712329, 28.8958904109589,
15.5123287671233, 14.8465753424658, 14.8465753424658, 2.0027397260274,
3.20821917808219, 3.71232876712329, 1.6958904109589, 2.07671232876712,
7.75616438356164, 2.88493150684931, 4.29315068493151, 1.84931506849315,
8.8958904109589, 1.12328767123288, 5.38630136986301, 5.12602739726027,
8.25205479452055, 3.24931506849315, 1.38904109589041, 5.89315068493151,
6.60821917808219, 1.5013698630137, 3.46027397260274, 6.5041095890411,
7.75890410958904, 6.54246575342466, 9.37808219178082, 3.96164383561644,
5.04657534246575, 7.04657534246575, 8.13424657534247, 6.13150684931507,
9.37808219178082, 7.96438356164384, 11.0493150684932, 12.213698630137,
2.12876712328767, 6.67397260273973, 4.46027397260274, 24.4739726027397,
3.75616438356164, 8.75890410958904, 18.7643835616438, 8.46301369863014,
5.13150684931507, 9.88219178082192, 9.33150684931507, 5.96164383561644,
7.25753424657534, 5.62739726027397, 7.50684931506849, 4.84109589041096,
3.46027397260274, 3.92054794520548, 18.5095890410959, 7.13150684931507,
8.59178082191781, 3.42191780821918, 6.75616438356164, 4.75616438356164,
2.95890410958904, 3.96164383561644, 20.4328767123288, 1.41917808219178,
21.4328767123288, 22.1041095890411, 2.09041095890411, 23.2219178082192,
3.20821917808219, 3.75616438356164, 24.7698630136986, 25.4739726027397,
4.46027397260274, 2.75970346198464, 3.45063169924232, 3.64711503029937,
4.21614538082358, 4.46897200885451, 4.78330432863798, 2.44945159376164,
3.0246987676982, 3.18637219409113, 2.82704067767991, 3.39633877759394,
4.01211492772477, 3.58227507536714, 3.26211339894416, 4.58021400951056,
3.24894671597498, 3.81640051029768, 4.29811641034397, 2.41235239871336,
4.16381972504066, 4.82320604897032, 2.85924829032196, 3.60102245001335,
4.38947242891732, 4.83225858506487, 2.32276057802484, 2.77466777269801,
3.53613679638981, 4.11732178923756, 4.70239811454869, 5.02684596680901,
4.89394362719873, 2.95858956427959, 3.67972641713649, 4.76329504168897,
4.91952178329268, 3.16243766754998, 4.53553009720828, 3.25401782240246,
4.57975033696973, 3.83648225102819, 4.85066377882221, 3.90946630290976,
4.85924427553214, 3.7665702648057, 3.63632959242775, 3.90561093988307,
4.82873462476434, 4.25993172383506, 3.47661513525158, 2.08147939877802,
3.04373161945452, 3.60670989847648, 4.16882946922235, 4.45461902145002,
4.34162315280691, 4.48802758727908, 1.86206866940942, 4.01581962612883,
2.69771901556242, 3.47661513525158, 4.29494911958988, 2.50903075277185,
3.20217588142397, 3.83011128813872, 3.980829920259, 4.28800748360142,
3.58227507536714, 4.30653857989399, 4.82319396445967, 4.50784277427558,
1.94072216406505, 1.96202863703256, 3.25200612691594, 4.52865722521467,
4.48533445537866, 4.26859229653523, 4.53731981080683, 4.27200767176305,
4.26457120140531, 4.2589693893104, 4.53525135174211, 2.21846989417729,
4.45880330075475, 4.40569121171677, 1.7068990376281, 2.57392106736465,
4.31836655689863, 2.66826592342152, 2.96442641830962, 2.16545787147435,
4.35324929683238, 4.32386522416303, 2.50903075277185, 3.39298854017977,
4.26232802572813, 1.70955300282675, 3.52741837222827, 4.25907996756536,
2.18557386001823, 3.77060768900683, 4.26395740412398, 2.18557386001823,
2.95157192131744, 3.53780855712753, 4.12926524629975, 4.46454130003024,
4.32641578537161, 2.63737387449928, 2.45327077112083, 3.28325793775465,
4.41181850146463, 3.01267661647382, 4.30273228804522, 3.0809392572752,
3.77893332429253, 4.80391883502991, 4.29751273896985, 4.9988952974639,
4.94101980513708, 4.96053762255352, 2.81894331471379, 4.91003396772332,
3.27522101695249, 4.87134979305318, 4.55194984744145, 3.20084942592193,
3.86347792664764, 5.03902446306499, 5.00360541053749, 4.93013307063464,
2.81894331471379, 4.89111202391337, 4.84484889948005, 3.62226986596664,
4.83000471370643, 3.87684000847915, 4.16249148956975, 4.82319682171546,
3.07342513615359, 3.58227507536714, 3.03776390795916, 2.39174353424389,
2.60441382154721, 2.83511983796416, 4.3776430683761, 3.28927099619789,
3.65030540624117, 4.78053976420514, 3.98851220598087, 3.84027419541323,
4.10888701756863, 3.08864056496118, 4.50784277427558, 4.80886282388512,
4.94393108371142, 5.0798798303101, 4.82563811883379, 3.9468402869224,
4.35189109140176, 4.11184051977588, 3.35459034230467, 4.02517710657812,
4.47676297113471, 4.01502608262676, 2.59176865382458, 3.96722952163555,
4.76721313996148, 3.21864402185455, 3.73613392685585, 4.2411779069777,
4.43398643591996, 3.61855452792053, 4.10980345553821, 4.31985435471796,
5.10135192405871, 5.04171773535286, 2.34892141444876, 3.5416097666887,
4.85054794533227, 4.83022204838818, 4.82316539945316, 4.76579152488111,
4.70585851301182, 4.77956222001954, 4.54973985879503, 3.38475186086735,
4.63579216766113, 3.33790973940492, 2.37103458556849, 3.75717008349914,
2.98272273951349, 4.28337045807013, 4.49267828838454, 3.9573829235615,
4.19209673281346, 3.74079199043232, 3.20084942592193, 5.10187826143602,
4.76293750094991, 4.97336905684238, 2.74996824339996, 2.65677488819793,
4.91172311677223, 3.99307443262087, 4.82526350378577, 4.8268073878022,
4.3776430683761, 4.83510606972691, 4.54522430364073, 4.85652654574101,
4.89686171640296, 2.87874743905149, 4.13483923719495, 4.03742401175551,
3.47139417367879, 3.66246558484484, 4.80424996332984, 4.94121262270349,
4.53454492449136, 4.53419598722523, 4.53454492449136, 4.47589167424468,
4.47589167424468, 4.42360799906947, 4.4074923871952, 4.39773506579433,
2.01907578318878, 4.38322128535129, 1.84538737297096, 2.41830268718988,
2.23480800909955, 3.16465475329972, 2.52618004042805, 4.56596058005526,
2.95157192131744, 3.00349899341948, 3.52972300068793, 3.75717008349914,
3.56654832534446, 4.26829419274457, 4.33246733302122, 4.47209933166968,
4.07829496689505, 4.54366179335202, 4.02412309850527, 4.29676089988903,
2.8695390825768, 3.60901246346208, 3.72904913668145, 2.56498963399193,
3.47139417367879, 2.8695390825768, 3.81640051029768, 2.81894331471379,
3.98051398879079, 3.58227507536714, 2.38916039360867, 3.31021811457649,
3.9468402869224, 3.83007753533476, 3.42794910435245, 4.59492002573633,
3.28024670656985, 2.4097817563527, 3.65030540624117, 3.74079199043232,
4.17176477555296, 4.35996196359352, 4.73359981456944, 4.90398228783007,
3.32409784536479, 4.87118581003356, 4.56666593488235, 4.60802805678997,
3.68916442604293, 5.02118529619339, 4.4514690518147, 4.39455164410878,
2.80677702722226, 3.05963754502245, 3.07193520904601, 4.2641136733005,
3.48305015568073, 4.25979660315916, 2.23480800909955, 4.26558395648925,
3.9282839050028, 1.89269207014021, 2.33130752327983, 3.07193520904601,
3.62770234943172, 4.18074663670204, 4.4514690518147, 4.34675554764834,
2.34036194508005, 4.20281875657975, 4.49267828838454, 4.86491005913173,
3.84127256835413, 4.19209673281346, 4.78844960315538, 4.93234475967529,
3.20188086629451, 4.5529065893626, 3.7797549774533, 3.21833597902597,
2.97302436839012, 3.38475186086735, 4.01502608262676, 4.82494685548552,
4.1309427087262, 2.34892141444876, 3.79122469981557, 2.74996824339996,
3.52882080169136, 2.90475632846179, 4.83425050183613, 4.41167553240461,
3.19775298791517, 5.05733248819791, 2.34500731502677, 3.86347792664764,
4.55194984744145, 4.8536532162969, 4.68580090262939, 3.8560422018531,
4.80424996332984, 2.83579574924565, 2.43541801827223, 3.26917867887851,
4.70658092262176, 2.41830268718988, 4.54205071405147, 3.70347651496055,
4.51179026913548, 3.87139934363606, 4.53702297816656, 4.24040027977525,
4.74578292053171, 4.17176477555296, 3.15984460601259, 3.9768746297032,
4.46949323821673, 3.9573829235615, 4.46949323821673, 2.79454182212808,
4.82981722014996, 4.89700936635987, 4.55003332824908, 4.04744453906246,
2.31225215646125, 3.17078397447093, 4.42804643606615, 3.02033214617563,
3.72568245460231, 4.25829574912718, 4.78226928394965, 4.92905316482749,
3.34086061969711, 4.04183801378363, 4.48319605565641, 4.30085456068988,
3.79122469981557, 4.45589006029623, 1.70822621819291, 4.63142865759546,
2.90699979029706, 3.35965176254463, 2.79019595892293, 3.77878982474076,
2.37522576957373, 4.27154459842833, 4.49758018625893, 2.97721538330697,
4.15244511731778, 3.73325024745895, 5.10139379386631, 4.17176477555296,
4.54618813621284, 3.39248194962301, 2.37881218415977, 4.1464619591812,
4.15316130101696, 4.70707172705424, 4.77267338855031, 2.03737184678255,
3.81939314106, 3.26312377270195, 3.87684000847915, 3.72904913668145,
4.21150941368065, 2.87482262642492, 2.41830268718988, 3.25814616479328,
1.95974385334363, 4.14957253152334, 3.51852796766856, 3.31248236073798,
3.93926475863266, 2.82676588308018, 2.25715273670682, 3.23877823069724,
3.47139417367879, 3.09057442380978, 4.50079498118852, 4.84503359841119,
3.05834404390917, 4.41167553240461, 4.55194984744145, 4.36569411888241,
4.83039001292176, 2.93850101323729, 4.22239549435516, 4.80886282388512,
4.94393108371142, 5.09584661299229, 5.05283820324407, 5.02319768413649,
4.67005370266932, 2.87068065591085, 4.19209673281346, 4.82343926231588,
3.91974901504793, 3.72904913668145, 4.25081432629887, 4.88033737221285,
4.53751058675557, 5.09889228357165, 5.09889228357165, 2.7120126164778,
3.20084942592193, 3.38475186086735, 2.57611729759449, 2.74406304100437,
4.46897200885461, 3.07664762906049, 3.58227507536714, 2.64466064962826,
4.66384481684621, 2.30962110926233, 3.91408252149265, 3.83967705403174,
4.55910078340349, 3.21628402040912, 2.43541801827223, 4.05100906700729,
4.22685401869853, 2.48748627144419, 3.29427230717969, 4.20248230878606,
4.46949323821673, 4.21150941368065, 4.73359981456944, 3.47139417367879,
3.81640051029768, 4.32499408591158, 4.53844903952499, 4.11184051977588,
4.73359981456944, 4.50784277427558, 4.92221662489616, 5.00972596707877,
2.76645294455757, 4.24203451863899, 3.63632959242775, 4.8438946910502,
3.40019013262738, 4.64268935027678, 5.04028605762641, 4.59492002573633,
3.84127256835413, 4.79892563273548, 4.41562762186783, 4.06871965116534,
4.36969042097439, 3.98051398879079, 4.42043658523483, 3.75496657158094,
3.29427230717969, 3.45730608585978, 5.04844935470778, 3.77878982474076,
4.05166542652766, 3.28024670656985, 4.26078052262918, 3.72904913668145,
3.10550475341744, 3.47139417367879, 4.41541846233588, 1.88505721037991,
4.3767970882106, 4.35153448481756, 2.18557386001823, 4.31311576433973,
2.6364550425402, 2.83579574924565, 4.27355104887647, 4.26316357649486,
3.07193520904601), .Dim = c(500L, 2L), .Dimnames = list(c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24",
"25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35",
"36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46",
"47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57",
"58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68",
"69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79",
"80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90",
"91", "92", "93", "94", "95", "96", "97", "98", "99", "100",
"101", "102", "103", "104", "105", "106", "107", "108", "109",
"110", "111", "112", "113", "114", "115", "116", "117", "118",
"119", "120", "121", "122", "123", "124", "125", "126", "127",
"128", "129", "130", "131", "132", "133", "134", "135", "136",
"137", "138", "139", "140", "141", "142", "143", "144", "145",
"146", "147", "148", "149", "150", "151", "152", "153", "154",
"155", "156", "157", "158", "159", "160", "161", "162", "163",
"164", "165", "166", "167", "168", "169", "170", "171", "172",
"173", "174", "175", "176", "177", "178", "179", "180", "181",
"182", "183", "184", "185", "186", "187", "188", "189", "190",
"191", "192", "193", "194", "195", "196", "197", "198", "199",
"200", "201", "202", "203", "204", "205", "206", "207", "208",
"209", "210", "211", "212", "213", "214", "215", "216", "217",
"218", "219", "220", "221", "222", "223", "224", "225", "226",
"227", "228", "229", "230", "231", "232", "233", "234", "235",
"236", "237", "238", "239", "240", "241", "242", "243", "244",
"245", "246", "247", "248", "249", "250", "251", "252", "253",
"254", "255", "256", "257", "258", "259", "260", "261", "262",
"263", "264", "265", "266", "267", "268", "269", "270", "271",
"272", "273", "274", "275", "276", "277", "278", "279", "280",
"281", "282", "283", "284", "285", "286", "287", "288", "289",
"290", "291", "292", "293", "294", "295", "296", "297", "298",
"299", "300", "301", "302", "303", "304", "305", "306", "307",
"308", "309", "310", "311", "312", "313", "314", "315", "316",
"317", "318", "319", "320", "321", "322", "323", "324", "325",
"326", "327", "328", "329", "330", "331", "332", "333", "334",
"335", "336", "337", "338", "339", "340", "341", "342", "343",
"344", "345", "346", "347", "348", "349", "350", "351", "352",
"353", "354", "355", "356", "357", "358", "359", "360", "361",
"362", "363", "364", "365", "366", "367", "368", "369", "370",
"371", "372", "373", "374", "375", "376", "377", "378", "379",
"380", "381", "382", "383", "384", "385", "386", "387", "388",
"389", "390", "391", "392", "393", "394", "395", "396", "397",
"398", "399", "400", "401", "402", "403", "404", "405", "406",
"407", "408", "409", "410", "411", "412", "413", "414", "415",
"416", "417", "418", "419", "420", "421", "422", "423", "424",
"425", "426", "427", "428", "429", "430", "431", "432", "433",
"434", "435", "436", "437", "438", "439", "440", "441", "442",
"443", "444", "445", "446", "447", "448", "449", "450", "451",
"452", "453", "454", "455", "456", "457", "458", "459", "460",
"461", "462", "463", "464", "465", "466", "467", "468", "469",
"470", "471", "472", "473", "474", "475", "476", "477", "478",
"479", "480", "481", "482", "483", "484", "485", "486", "487",
"488", "489", "490", "491", "492", "493", "494", "495", "496",
"497", "498", "499", "500"), NULL))


问:
How to show annotations on the upper half og mapview?
I have a special case that I can't seem to wrap my head around.

I have a full screen mapview as a background. Of the lower half I have som other elements and I need to set the mapregion for my mapview, so that all annotations is visible and positioned in the upper half of the view.

I can find the maprect for all annotations.
I can also find the rect for the upper half - even translate that into a maprect.

But how do I correlate these two maprects in order to move (and squeeze) the maprect-that-fits the annotations, into the upper half?

Can anybody give me a hint on this?

答:
I had a similar design once, except it was for a single annotation and not multiple but in principle its the same thing.

In ViewDidLayoutSubviews:

Make a MKRegion that contains your annotation(s) Create a CGPoint
that is at the center of part of the map that is not covered.

Change
the center of your region to the center of the uncovered map portion
by using MKMapView.convert(point: toCoordinateFrom:)

Show the new
center by calling mapView.setRegion(region, animated: false)

You need to figure out what region contains your annotations (not hard just find max and min lat, lon and add padding).  Here is example code for the rest of it:

```<code>        let point = CGPoint(x: mapView.bounds.size.width/2, y: -100)
        region.center = mapView.convert(point, toCoordinateFrom: mapView)
        mapView.setRegion(region, animated: false)
</code>```

Body:
I had a similar design once, except it was for a single annotation and not multiple but in principle its the same thing.

In ViewDidLayoutSubviews:

Make a MKRegion that contains your annotation(s) Create a CGPoint
that is at the center of part of the map that is not covered.

Change
the center of your region to the center of the uncovered map portion
by using MKMapView.convert(point: toCoordinateFrom:)

Show the new
center by calling mapView.setRegion(region, animated: false)

You need to figure out what region contains your annotations (not hard just find max and min lat, lon and add padding).  Here is example code for the rest of it:

        let point = CGPoint(x: mapView.bounds.size.width/2, y: -100)
        region.center = mapView.convert(point, toCoordinateFrom: mapView)
        mapView.setRegion(region, animated: false)


问:
keep annotation and legend within same seaborn plot
I am using seaborn to generate some figures.

```<code>import seaborn as sns
g=sns.JointGrid(...)
</code>```

At the end, I need to add a legend and annotate the plot. I do:

```<code>...
g.ax_joint.legend(...)
...
g.annotate(scipy.stats.spearmanr,fontsize=14)
</code>```

but after the annotate() the legend is not there anymore. How to keep both on the same ax_joint in the same figure?

答:
g.annotate adds the annotation information as a legend. Adding a new legend in a plot which already has a legend will replace the old legend. The solution is to readd the old legend to the plot.

```<code>oldlegend = plt.legend(<something>)
newlegend = plt.legend(<something else>)
plt.gca().add_artist(legend)
</code>```

For this case it would look like

```<code>import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats

mydataset=pd.DataFrame(data=np.random.rand(50,2),columns=['a','b'])
g = sns.JointGrid(x=mydataset['a'], y=mydataset['b'])
g=g.plot_marginals(sns.distplot,color='black',
                   kde=True,hist=False,rug=True,bins=20)
g=g.plot_joint(plt.scatter,label='X')

legend_properties = {'weight':'bold','size':8}
legendMain=g.ax_joint.legend(prop=legend_properties,loc='upper right')

legendSide=g.ax_marg_x.legend(labels=["x"],
                              prop=legend_properties,loc='upper right')
g.annotate(scipy.stats.spearmanr,fontsize=14, loc=4)
g.ax_joint.add_artist(legendMain)
plt.show()
</code>```

Body:
I am using seaborn to generate some figures.

import seaborn as sns
g=sns.JointGrid(...)

At the end, I need to add a legend and annotate the plot. I do:

...
g.ax_joint.legend(...)
...
g.annotate(scipy.stats.spearmanr,fontsize=14)

but after the annotate() the legend is not there anymore. How to keep both on the same ax_joint in the same figure?

Body:
g.annotate adds the annotation information as a legend. Adding a new legend in a plot which already has a legend will replace the old legend. The solution is to readd the old legend to the plot.

oldlegend = plt.legend(<something>)
newlegend = plt.legend(<something else>)
plt.gca().add_artist(legend)

For this case it would look like

import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats

mydataset=pd.DataFrame(data=np.random.rand(50,2),columns=['a','b'])
g = sns.JointGrid(x=mydataset['a'], y=mydataset['b'])
g=g.plot_marginals(sns.distplot,color='black',
                   kde=True,hist=False,rug=True,bins=20)
g=g.plot_joint(plt.scatter,label='X')

legend_properties = {'weight':'bold','size':8}
legendMain=g.ax_joint.legend(prop=legend_properties,loc='upper right')

legendSide=g.ax_marg_x.legend(labels=["x"],
                              prop=legend_properties,loc='upper right')
g.annotate(scipy.stats.spearmanr,fontsize=14, loc=4)
g.ax_joint.add_artist(legendMain)
plt.show()


问:
How to prevent access to all but ONE file with htaccess
I'm trying to prevent access to all files but ONE using .htaccess, in this way but it does not work.

```<code><Files accessibleFile.php>
allow from all
</Files>

<Filesmatch "^((?!accessibleFile\.php).)*$">
AuthUserFile .htpasswd
AuthGroupFile /dev/null
AuthName "Restricted Access"
AuthType Basic
</Filesmatch>

<Limit GET POST>
require valid-user
</Limit>
</code>```

Any one can help?
Added: I still want to have logged access to the other files.

答:
This is enough:

```<code>Deny from all

<Files "allowed.php">
    Allow from all
</Files>
</code>```

Also note that your <Limit GET POST> directive makes your site vulnerable to HTTP Verb Tampering.

Body:
I'm trying to prevent access to all files but ONE using .htaccess, in this way but it does not work.

<Files accessibleFile.php>
allow from all
</Files>

<Filesmatch "^((?!accessibleFile\.php).)*$">
AuthUserFile .htpasswd
AuthGroupFile /dev/null
AuthName "Restricted Access"
AuthType Basic
</Filesmatch>

<Limit GET POST>
require valid-user
</Limit>

Any one can help?
Added: I still want to have logged access to the other files.

Body:
This is enough:

Deny from all

<Files "allowed.php">
    Allow from all
</Files>

Also note that your <Limit GET POST> directive makes your site vulnerable to HTTP Verb Tampering.


问:
Verilog:Procedural Continuous Assignment to register is not supported
```<code>    input [31:0] write_data;
    input [4:0]  write_reg;
    reg [31:0] registers [31:0];

always @(*)
     assign registers[write_reg] = write_data;
</code>```

I have a 32-bit input write_data , which i want to an assign corresponding index which i get from write reg.Error says you cant do continuous assignment which i think causes by always@(*) but if i remove that

It says
object "registers" on left-hand side of assignment must have a net type
and its another error.

答:
assign inside an always block is the procedural assignment. It is not synthesizable and should not be used. It is there for very special modeling cases.

continuous assignment, or assign outside the always block is there for connecting nets and used all over the places. lhs of such an assignment must be a net type, i.e. wire. it cannot be a reg.

On the other hand all lhs in always blocks must be of 'reg' type.

what you had to do in your case was to remove the keyword assign:

```<code>input [31:0] write_data;
input [4:0]  write_reg;
reg [31:0] registers [31:0];

always @(*)
     registers[write_reg] = write_data;
</code>```

Body:
    input [31:0] write_data;
    input [4:0]  write_reg;
    reg [31:0] registers [31:0];

always @(*)
     assign registers[write_reg] = write_data;

I have a 32-bit input write_data , which i want to an assign corresponding index which i get from write reg.Error says you cant do continuous assignment which i think causes by always@(*) but if i remove that

It says
object "registers" on left-hand side of assignment must have a net type
and its another error.

Body:
assign inside an always block is the procedural assignment. It is not synthesizable and should not be used. It is there for very special modeling cases.

continuous assignment, or assign outside the always block is there for connecting nets and used all over the places. lhs of such an assignment must be a net type, i.e. wire. it cannot be a reg.

On the other hand all lhs in always blocks must be of 'reg' type.

what you had to do in your case was to remove the keyword assign:

input [31:0] write_data;
input [4:0]  write_reg;
reg [31:0] registers [31:0];

always @(*)
     registers[write_reg] = write_data;


答:
Wrap your query up in a derived table. Add the condition at top level:</p>

```<code>select *
from
(
SELECT
    project.id
        'Project code',
    SUM(report.hours)
        'Total hours',
    SUM(CASE WHEN report.date BETWEEN :report_start AND :report_end THEN report.hours END)
        'Total report hours'

FROM report
    INNER JOIN project ON project.id = report.id
WHERE report.date <= :report_end

GROUP BY
    project.id
) dt
WHERE `Total report hours` != 0
</code>```

Title: How to `HAVING` on `SUM` without "Non-grouping field x is used in HAVING clause"

Body:
So, I have this query, which runs fine in HeidiSQL, but not in Laravel because of strict mode (and more specifically probably because of the SQL mode ONLY_FULL_GROUP_BY being set):

SELECT
    project.id
        'Project code',
    SUM(report.hours)
        'Total hours',
    SUM(CASE WHEN report.date BETWEEN :report_start AND :report_end THEN report.hours END)
        'Total report hours'

FROM report
    INNER JOIN project ON project.id = report.id
WHERE report.date <= :report_end

GROUP BY
    project.id

HAVING
    `Total report hours` != 0

It gives me the following error:

Syntax error or access violation: 1463 Non-grouping field 'Total report hours' is used in HAVING clause

I've tried searching around here, but all questions I find are solved by moving the filter from HAVING to WHERE, which can be done because those cases don't actually include an aggregate function. However, in my case, it does, and I thought this was exactly what HAVING was for? I.e. I want to filter out all rows that do not have any hours in the reported period.

I can "solve" it by instead of referring to Total report hours, instead repeating the whole SUM, like this:

HAVING
    SUM(CASE WHEN report.date BETWEEN :report_start AND :report_end THEN report.hours END) != 0

But that feels very unnecessary and messy when it's already calculated and (from my point of view) available right there in the query itself.

So, is there a way I can express this, that works in strict mode, without having to repeat myself?

Body:
Wrap your query up in a derived table. Add the condition at top level:

select *
from
(
SELECT
    project.id
        'Project code',
    SUM(report.hours)
        'Total hours',
    SUM(CASE WHEN report.date BETWEEN :report_start AND :report_end THEN report.hours END)
        'Total report hours'

FROM report
    INNER JOIN project ON project.id = report.id
WHERE report.date <= :report_end

GROUP BY
    project.id
) dt
WHERE `Total report hours` != 0