问:
How to iterate keys of an object nested in an object in Angular 4?
Variables:

```<code> objectKeys = Object.keys;
  objectValues = Object.values;
</code>```

JSON:

```<code>@Injectable()
export class DbService {
    db:Database[] = [
        {
        "id":0,
        "img":"../../../assets/img/logo/gro.png",
        "name":"CompName",
        "type":"CompType",
        "hours": "9:00AM-9:00PM",
        "number": 999999,
        "email": 'info@company.com',
        "items": [
                    {"Beverage":[
                        {"Bigga":'lg'},
                        {"Soda":'sm'},
                        {"Wata":'fresh'},
                        {"Sprite":'codein'}
                    ]},
                    {'Canned':[
                        {"Tuna":'lg'},
                        {"Salmon":'sm'},
                        {"Mackerel":'fresh'},
                        {"Spam":'codein'}
                    ]}
                ]
        },
</code>```

These lines displays all the keys from the item objects

```<code><div *ngFor="let item of store[0].items" class="ai">
        <div *ngFor="let key of objectKeys(item)">{{key}}</div>
    </div>
</code>```

However trying to get the values from the child object of above object is displaying .."0 1 2 3 0 1 2 3 "

```<code><div *ngFor="let rn of store[0].items" class="items">
            <div *ngFor="let value of objectValues(rn)">
                <div *ngFor="let btn of objectKeys(value)">
                    {{btn}}
                </div>
            </div>
        </div>
</code>```

答:
in

```<code> <div *ngFor="let btn of objectKeys(value)">
       {{btn}}
 </div>
</code>```

value is for exemple for store[0].items, its an array of objects, a collection.

```<code>[
   {"Bigga":'lg'},
   {"Soda":'sm'},
   {"Wata":'fresh'},
   {"Sprite":'codein'}
]
</code>```

so if you use objectKeys(values) you will have keys of the array, the indexes.

you need iterate in the array to get the object, then use Object.keys and Object.value

```<code><div *ngFor="let rn of store[0].items" class="items">
    <div *ngFor="let value of objectValues(rn)">
        <div *ngFor="let item of value">
            {{ objectKeys(item)[0]  }} {{ objectValues(item)[0]  }}
        </div>
    </div>
</div>
</code>```

in order to get

Bigga lg
Soda sm ...

Body:
Variables:

 objectKeys = Object.keys;
  objectValues = Object.values;

JSON:

@Injectable()
export class DbService {
    db:Database[] = [
        {
        "id":0,
        "img":"../../../assets/img/logo/gro.png",
        "name":"CompName",
        "type":"CompType",
        "hours": "9:00AM-9:00PM",
        "number": 999999,
        "email": 'info@company.com',
        "items": [
                    {"Beverage":[
                        {"Bigga":'lg'},
                        {"Soda":'sm'},
                        {"Wata":'fresh'},
                        {"Sprite":'codein'}
                    ]},
                    {'Canned':[
                        {"Tuna":'lg'},
                        {"Salmon":'sm'},
                        {"Mackerel":'fresh'},
                        {"Spam":'codein'}
                    ]}
                ]
        },

These lines displays all the keys from the item objects

{{key}}

However trying to get the values from the child object of above object is displaying .."0 1 2 3 0 1 2 3 "

                    {{btn}}

Body:
in

 <div *ngFor="let btn of objectKeys(value)">
       {{btn}}
 </div>

value is for exemple for store[0].items, its an array of objects, a collection.

[
   {"Bigga":'lg'},
   {"Soda":'sm'},
   {"Wata":'fresh'},
   {"Sprite":'codein'}
]

so if you use objectKeys(values) you will have keys of the array, the indexes.

you need iterate in the array to get the object, then use Object.keys and Object.value

<div *ngFor="let rn of store[0].items" class="items">
    <div *ngFor="let value of objectValues(rn)">
        <div *ngFor="let item of value">
            {{ objectKeys(item)[0]  }} {{ objectValues(item)[0]  }}
        </div>
    </div>
</div>

in order to get

Bigga lg
Soda sm ...


来源: stackexchange

问:
How to refresh component when navigate to same route?
I have this:

```<code>  this.activatedRoute.queryParams.subscribe((params: Params) => {
            if (localStorage.getItem('queryParams')) {
                this.queryParams = JSON.parse(localStorage.getItem('queryParams'));
                if (this.queryParams[Object.keys(this.queryParams)[0]]) {
                    this.procesId = this.queryParams[Object.keys(this.queryParams)[0]];
                }
            }
})
</code>```

I want to triger queryParams when i click on same route. Any suggestion how can i do that? I have menu so when i click on same link i want to reload that other component where i do something in queryParams. But right now its triggering only when route is change.

答:
If you want to reload a component when you navigate to another component, you can do it like this:

first Component:

```<code>import {Component, OnInit} from '@angular/core';

export class ComponentOne implements OnInit {
     constructor() {//some stuff here}

     ngOnInit() {
          //here the code you want to trigger by nagivating to the second component
     }
}
</code>```

second Component:

```<code>import {Component, OnInit} from '@angular/core';
import {ComponentOne} from 'path_to_first_component';

    export class ComponentTwo implements OnInit {
         constructor(private firstComponent: ComponentOne) {} //dependency injection

         ngOnInit() {
              this.firstComponent.ngOnInit(); //this will call the ngOnInit from the first component
         }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this:

  this.activatedRoute.queryParams.subscribe((params: Params) => {
            if (localStorage.getItem('queryParams')) {
                this.queryParams = JSON.parse(localStorage.getItem('queryParams'));
                if (this.queryParams[Object.keys(this.queryParams)[0]]) {
                    this.procesId = this.queryParams[Object.keys(this.queryParams)[0]];
                }
            }
})

I want to triger queryParams when i click on same route. Any suggestion how can i do that? I have menu so when i click on same link i want to reload that other component where i do something in queryParams. But right now its triggering only when route is change.

Body:
If you want to reload a component when you navigate to another component, you can do it like this:

first Component:

import {Component, OnInit} from '@angular/core';

export class ComponentOne implements OnInit {
     constructor() {//some stuff here}

     ngOnInit() {
          //here the code you want to trigger by nagivating to the second component
     }
}

second Component:

import {Component, OnInit} from '@angular/core';
import {ComponentOne} from 'path_to_first_component';

    export class ComponentTwo implements OnInit {
         constructor(private firstComponent: ComponentOne) {} //dependency injection

         ngOnInit() {
              this.firstComponent.ngOnInit(); //this will call the ngOnInit from the first component
         }
    }


问:
predicting proper regular expression from seeing target string
I want to know it is possible to predict proper regular expression by seeing several strings. For example, regex ^[a-z0-9_-]{3,16}$ will match my-us3r_n4m3 and ^[a-z0-9_-]{6,18}$ match myp4ssw0rd. But after seeing my-us3r_n4m3, is it possible output ^[a-z0-9_-]{3,16}$ or ^[a-z0-9_-]{6,18}$from seeing myp4ssw0rd.

I guess this would be stupid question, and I don't want to predict exact regular expression.

Anyone who has idea for this, pls let me know.
Thanks.

答: Regexp::Assemble will create regular expressions from strings. The more strings you give it, the more precise the regex it generates.


问:
How does back_inserter work?
I'm trying to understand how back_inserter work, and this is its implementation that I have from SGI-STL:

```<code>template<class C>
class back_insert_iterator {
protected:
    C* container;
public:
    typedef C                   container_type;
    typedef output_iterator_tag iterator_category;
    typedef void                value_type;
    typedef void                difference_type;
    typedef void                pointer;
    typedef void                reference;

    explicit back_insert_iterator( C& __x ) :container( &__x ) {
    }

    back_insert_iterator<C>& operator=( const typename C::value_type& val ) {
        container->push_back( val );
        return *this;
    }

    back_insert_iterator<C>& operator*() {
        return *this;
    }

    back_insert_iterator<C>& operator++() {
        return *this;
    }

    back_insert_iterator<C>& operator++( int ) {
        return *this;
    }
};
</code>```

I understood most parts, except the last three operator *, ++, ++( int ). My guess for their existence is because they need to support operations when placed inside the STL algorithm. Other than that, I don't know what are they used for? Could anyone help me clarify this?

Thanks,

Chan

答:
They exist because STL algorithms work on iterators which must be post and pre incrementable and have a dereference operator.

try to think what this does:

```<code>(*back_inserter) = value;
++back_inserter;
</code>```

ContentLicense: CC BY-SA 2.5

Title: How does back_inserter work?

Body:
I'm trying to understand how back_inserter work, and this is its implementation that I have from SGI-STL:

template<class C>
class back_insert_iterator {
protected:
    C* container;
public:
    typedef C                   container_type;
    typedef output_iterator_tag iterator_category;
    typedef void                value_type;
    typedef void                difference_type;
    typedef void                pointer;
    typedef void                reference;

    explicit back_insert_iterator( C& __x ) :container( &__x ) {
    }

    back_insert_iterator<C>& operator=( const typename C::value_type& val ) {
        container->push_back( val );
        return *this;
    }

    back_insert_iterator<C>& operator*() {
        return *this;
    }

    back_insert_iterator<C>& operator++() {
        return *this;
    }

    back_insert_iterator<C>& operator++( int ) {
        return *this;
    }
};

I understood most parts, except the last three operator *, ++, ++( int ). My guess for their existence is because they need to support operations when placed inside the STL algorithm. Other than that, I don't know what are they used for? Could anyone help me clarify this?

Thanks,

Chan

Body:
They exist because STL algorithms work on iterators which must be post and pre incrementable and have a dereference operator.

try to think what this does:

(*back_inserter) = value;
++back_inserter;


问:
Background subtraction when background brightness is unknown
I'm currently working on a computer vision project, and got most of my algorithm working. However I'm currently doing background subtraction manually on every image. This is because the most common background subtraction algorithms that I can find make use of thresholding, and my project should deal with backgrounds both brighter and darker than the object I want to extract.

This is the way I am subtracting the background currently (using python and the scikit stack):

```<code>val = filters.threshold_otsu(image)
return image > val
</code>```

Of course, this only works with backgrounds darker than the subject.
I had the idea of finding whether or not the background is bright, and then depending on that change the sign of the inequality, but could not find a way to do that.

Is there a background subtraction algorithm which is able to handle both bright and dark backgrounds, or is there another way to solve this problem?

答:
There are no fixed method of solving your problem generally. Foreground and background can be defined differently according to situations.

That being said, it is not impossible to use some heuristic method to make the algorithm work on your dataset. It will be helpful if you can share some of the images to give us a better understanding of your definition of foreground and background.

Here are some of heuristic method that might help:

Run Ostu thresholding with both THRESH_BINARY and THRESH_BINARY_INV. Then assuming your foreground is always centered, choose the result where the a large portion of the center region is white.

If the foreground is always larger than backgorund or vice versa, calculate the area of white region instead.

Body:
I'm currently working on a computer vision project, and got most of my algorithm working. However I'm currently doing background subtraction manually on every image. This is because the most common background subtraction algorithms that I can find make use of thresholding, and my project should deal with backgrounds both brighter and darker than the object I want to extract.

This is the way I am subtracting the background currently (using python and the scikit stack):

val = filters.threshold_otsu(image)
return image > val

Of course, this only works with backgrounds darker than the subject.
I had the idea of finding whether or not the background is bright, and then depending on that change the sign of the inequality, but could not find a way to do that.

Is there a background subtraction algorithm which is able to handle both bright and dark backgrounds, or is there another way to solve this problem?


问:
Not able to drag a formula calculating days
I have a formula which gives me the day ie Monday , Tuesday etc. But the problem i am having is that i am not able drag the formula to give me the next day.

I am trying to drag this along the row.

```<code>=TEXT(WEEKDAY(DATE(CurrentYear,1,1),1),"aaa")
</code>```

So if i drag i should get the below formulea which i am not getting.

```<code>=TEXT(WEEKDAY(DATE(CurrentYear,1,2),1),"aaa")
</code>```

Therefore the next formula will have a 2 in the formula , and then the next will have 3 in the formula and so.

答:
If you use this formula

=TEXT(WEEKDAY(DATE(2017,1,1)),"ddd")

then you are not actually finding the day of 1/1/2017 because =WEEKDAY(DATE(2017,1,1) resolves to the number 1 and then TEXT function finds the weekday of the date represented by 1 in Excel - this can be two different dates, normally 1/1/1900, but if you use 1904 date system (which used to be common on Macs) then that date is 2nd Jan 1904. While 1/1/1900 was a Sunday (according to Excel) the 2nd Jan 1904 was a Saturday so your result might be incorrect.

WEEKDAY function here is at best redundant, or worst it results in an incorrect result, so should be removed

To answer your query it's best to use COLUMNS function, rather than COLUMN (as per Rory's suggestion in comments), because then adding or deleting columns or rows won't affect the result, so final formula, to be dragged across, should be similar to this:

=TEXT(DATE(CurrentYear,1,COLUMNS($B3:B3)),"ddd")

Where B3 is the first cell with the formula - change as required

1904 Date System setting is workbook level setting than can be altered through Options > Advanced

Body:
I have a formula which gives me the day ie Monday , Tuesday etc. But the problem i am having is that i am not able drag the formula to give me the next day.

I am trying to drag this along the row.

=TEXT(WEEKDAY(DATE(CurrentYear,1,1),1),"aaa")

So if i drag i should get the below formulea which i am not getting.

=TEXT(WEEKDAY(DATE(CurrentYear,1,2),1),"aaa")

Therefore the next formula will have a 2 in the formula , and then the next will have 3 in the formula and so.


问:
angular universal with asp.net mvc
Anyone working with angular 5.0-universal with Asp.net MVC 5.0 combination ?
note: we are not using asp.net core 2.0.

We are loading templateurl as {controller/action} so that we are using the razor view (cshtml) benefits. Problem here is we are unable to bundle it using webpack. Any example or reference will be helpful for us.
Thanks in advance!

答:
You cannot use Angular Universal(SSR) with Asp.net MVC 5.0.

Because Angular universal rendering engine was written with ASP.Net Core in mind. https://github.com/angular/universal/tree/master/modules/aspnetcore-engine

And the actual magic for invoking, communicating and executing NodeJs scripts by spinning NodeJs thread from .Net webpage was implemented by aspnet .net core team through following Github project - JavascriptService. There is no backward port of this project.
https://github.com/aspnet/JavaScriptServices.

So for the second half of the question:
If you are concerned about the webpack bundle generate hashed filenames, then you should be able to handle it by specifying wildcard patterns for including files in your Bundle config. https://stackoverflow.com/a/46593613/2952405

Note: You need to configure your deployment task to delete the old script files "myscript.[hash].js", before deploying the new one, to avoid ASP .net from bundling duplicate copies of previous version of same js.

Following article shows how to do it with core (just for an idea)
https://davidsekar.com/aspnetcore/dealing-with-hashed-filenames

Title: angular universal with asp.net mvc


问:
I set the toValue of rotation to 2*PI, but why after the animation these views are not horizontal?
Codes are as follows:

```<code>CABasicAnimation *rotateWhenBoom = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
rotateWhenBoom.fromValue = @0;
rotateWhenBoom.toValue = @(M_PI*2.0);
rotateWhenBoom.duration = 0.3f;
rotateWhenBoom.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];

CAAnimationGroup *boom = [CAAnimationGroup animation];
boom.animations = @[[self moveOutWithBtn:btn], rotateWhenBoom];
boom.fillMode = kCAFillModeForwards;
boom.removedOnCompletion = NO;
</code>```

And the effect:
effect

Before the animation the views are all horizontal. I add a rotation animation to these views, and the toValue of rotation is 2*PI. Why after the animation they are not horizontal?
Thanks in advance!!

答:
Your last two lines of code:

boom.fillMode = kCAFillModeForwards;
boom.removedOnCompletion = NO;

mean that the layer stays at the final state of animation and that the animation is not automatically removed from the layer when it completes. You probably want to remove the last line boom.removeOnCompletion = NO

A good guide for CALayer and CAAnimation that explains this: https://www.objc.io/issues/12-animations/animations-explained/

Body:
Codes are as follows:

CABasicAnimation *rotateWhenBoom = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
rotateWhenBoom.fromValue = @0;
rotateWhenBoom.toValue = @(M_PI*2.0);
rotateWhenBoom.duration = 0.3f;
rotateWhenBoom.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];

CAAnimationGroup *boom = [CAAnimationGroup animation];
boom.animations = @[[self moveOutWithBtn:btn], rotateWhenBoom];
boom.fillMode = kCAFillModeForwards;
boom.removedOnCompletion = NO;

And the effect:
effect

Before the animation the views are all horizontal. I add a rotation animation to these views, and the toValue of rotation is 2*PI. Why after the animation they are not horizontal?
Thanks in advance!!


问:
Getting header strings in DataGridColumnHeader click events
I'm trying to add a DataGrid, where clicking the column header causes an action to be done on all cells below it.  I can set an event handler on header click events. But since the headers are bound to string constants in the VM, their value doesn't seem to be passed along to the event handler.  I can't find the value of the clicked header anywhere in the "sender" object in the event handler.  Any ideas?

Here's a screenshot of the DataGrid:

XAML:

```<code><DataGrid Grid.Column="1" Grid.Row="1" ItemsSource="{Binding Path=InfoFieldCollection, Mode=TwoWay}"
            AutoGenerateColumns="False" CanUserAddRows="False">
    <DataGrid.Resources>
        <Style TargetType="DataGrid">
            <EventSetter Event="SelectionChanged" Handler="RovIllustrationInfoFieldDataGrid_SelectionChanged" />
        </Style>
        <Style TargetType="DataGridCell">
            <Setter Property="FocusVisualStyle" Value="{x:Null}" />
            <Setter Property="BorderThickness" Value="0" />
        </Style>
        <Style TargetType="DataGridColumnHeader">
            <EventSetter Event="Click" Handler="RovIllustrationInfoFieldDataGridColumnHeader_Click" />
        </Style>
    </DataGrid.Resources>
    <DataGrid.RowHeaderTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType=DataGridRow},
                            Converter={StaticResource DataGridRowToHeaderStringConverter}}" />
        </DataTemplate>
    </DataGrid.RowHeaderTemplate>
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.HeaderTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Path=DataContext.InfoFieldIsVisibleLabel, RelativeSource={RelativeSource AncestorType=DataGrid}}" />
                </DataTemplate>
            </DataGridTemplateColumn.HeaderTemplate>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <CheckBox IsChecked="{Binding Path=IsVisible, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>
</code>```

C#:

```<code>private void RovIllustrationInfoFieldDataGridColumnHeader_Click(object sender, RoutedEventArgs e) {
    var header = sender as DataGridColumnHeader;
    var vm = DataContext as ElementDetailsUserControlVM;
    if (header != null && vm != null) {
        Console.WriteLine(header.Content.ToString());
    }
}
</code>```

答:
You must set DataGridTemplateColumn.Header at first. You can set your header text binding (from DataContext) to your DataGridTemplateColumn.Header and bind your TextBlock.Text to the related DataGridTemplateColumn.Header.

It seems currently you are setting DataGridTemplateColumn.HeaderTemplate and viewing header by using a TextBlock, But you are setting TextBlock.Text Property directionally through a binding, Rather than DataGridTemplateColumn.Header property. Therefore when user clicks your column's header, and you get the 'sender' as Column Header in code, its header.Content has its default value, null.

Body:
I'm trying to add a DataGrid, where clicking the column header causes an action to be done on all cells below it.  I can set an event handler on header click events. But since the headers are bound to string constants in the VM, their value doesn't seem to be passed along to the event handler.  I can't find the value of the clicked header anywhere in the "sender" object in the event handler.  Any ideas?

Here's a screenshot of the DataGrid:

XAML:

<DataGrid Grid.Column="1" Grid.Row="1" ItemsSource="{Binding Path=InfoFieldCollection, Mode=TwoWay}"
            AutoGenerateColumns="False" CanUserAddRows="False">
    <DataGrid.Resources>

    </DataGrid.Resources>
    <DataGrid.RowHeaderTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType=DataGridRow},
                            Converter={StaticResource DataGridRowToHeaderStringConverter}}" />
        </DataTemplate>
    </DataGrid.RowHeaderTemplate>
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.HeaderTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Path=DataContext.InfoFieldIsVisibleLabel, RelativeSource={RelativeSource AncestorType=DataGrid}}" />
                </DataTemplate>
            </DataGridTemplateColumn.HeaderTemplate>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <CheckBox IsChecked="{Binding Path=IsVisible, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

C#:

private void RovIllustrationInfoFieldDataGridColumnHeader_Click(object sender, RoutedEventArgs e) {
    var header = sender as DataGridColumnHeader;
    var vm = DataContext as ElementDetailsUserControlVM;
    if (header != null && vm != null) {
        Console.WriteLine(header.Content.ToString());
    }
}


问:
Eclipse XML formatter
What is a free alternative to the built-in Eclipse XML editor?

The one packaged with the IDE has two major problems with formatting:

The formatter tries to parse escaped char's as though they were unescaped. E.g. '<' is treated like '<' which causes the formatter to "stop".

White space between elements is not honored:

```<code><foo>   text </foo>
</code>```

will be formatted to:

```<code><foo>text</foo>
</code>```

We are using Eclipse 3.4.

Updates

Issue #1 is a known bug: Formatting issues with entities in XML files.

Apparently the white space formatting is intended functionality.  I have requested this be provided as an option or advise on fixing this in a plugin of my own, but as of yet, no answer.

答:
I like Notepad++ with the XML Tools plugin.  It does XSLT, has an XPATH expression evaluator, and does DTD and schema validation.  Toolchain download links:

Notepad++: http://sourceforge.net/project/downloading.php?group_id=95717&use_mirror=internap&filename=npp.5.0.Installer.exe&24657954

XML Plugins: http://sourceforge.net/project/downloading.php?group_id=189927&use_mirror=voxel&filename=xmltools_2.3.1_r639.zip&44936797

External Libraries: http://sourceforge.net/project/downloading.php?group_id=189927&use_mirror=internap&filename=ext_libs.zip&52274848

Title: Eclipse XML formatter

Body:
What is a free alternative to the built-in Eclipse XML editor?

The one packaged with the IDE has two major problems with formatting:

The formatter tries to parse escaped char's as though they were unescaped. E.g. '<' is treated like '<' which causes the formatter to "stop".

White space between elements is not honored:

<foo>   text </foo>

will be formatted to:

<foo>text</foo>

We are using Eclipse 3.4.

Updates

Issue #1 is a known bug: Formatting issues with entities in XML files.

Apparently the white space formatting is intended functionality.  I have requested this be provided as an option or advise on fixing this in a plugin of my own, but as of yet, no answer.

LastEditorDisplayName: Roger Pate

OwnerDisplayName: Stephen Friederichs


问:
What is the default value of Validity in Angular?
In angular project, once I set the $setValidity as false

```<code>$scope.form[key].$setValidity("has_already_taken", false);
</code>```

How can I set Validity True?

I tried  $scope.form[key].$setValidity(null , true);
But it's never working.
I am new to angular and any kind of help!

答:
Simple, you set has_already_taken's validity as false so you have to has_already_taken's validity as true.

Please see reference doc

Body:
In angular project, once I set the $setValidity as false

$scope.form[key].$setValidity("has_already_taken", false);

How can I set Validity True?

I tried  $scope.form[key].$setValidity(null , true);
But it's never working.
I am new to angular and any kind of help!


问:
Kubernetes on GCP
Im trying to run my app on GCE cluster but I think Im missing something connected to the kubernetes resources for deployment. I have 4 deployments with respectively 3 deployments with 2 replicaset (with autoscale set) and 1 deployment with 1 replicaset (daemons). From my initial understanding and calculations I've tried to set requests of: 400m vCPU and 1500M RAM and limits to: 500m and 1800M RAM for all of my deployments. After setting those resources my pod weren't runing because of insufficient cpu and memory. After reading more docs of kubernetes it look like kubernetes kube-system is taking some of the cluster resources so in the end Im able to manage only X% (not 100%) of my 4 node cluster (4vCpu & 15GB ram). So im trying to understand how much exactly does kubernetes take so i know what values are under my full control of this cluster resources but I cant figure it out what resources and limits will be best suited.
Can anyone help me with this??

Appreciate.

答:
how much exactly does kubernetes take

You can examine the node's 'allocatable' capacity by running kubectl describe node. In general it's like

[Allocatable] = [Node Capacity] - [Kube-Reserved] - [System-Reserved] - [Hard-Eviction-Threshold]

Actual values will differ based on environment and configuration.

More on this subject here: https://github.com/kubernetes/community/blob/master/contributors/design-proposals/node/node-allocatable.md

Title: Kubernetes on GCP


问:
How to get value after 2nd hash in input parameter
My below t-sql only works when there is one hash symbol in the input parameter.

How can I change it to so I can get the value after the 2nd hash symbol?

I think I need to use a combination of REVERSE and RIGHT but I can't figure it out.

```<code>DECLARE @SEAL_SECURITY3 As Varchar(50); SET @SEAL_SECURITY3 = NULL;
DECLARE @SEAL_SECURITY As Varchar(50); SET @SEAL_SECURITY = 'MS-7#MS-8#MS-9'

SET @SEAL_SECURITY3 = CASE WHEN CHARINDEX('#', @SEAL_SECURITY) = 0 THEN NULL
ELSE SUBSTRING(@SEAL_SECURITY, CHARINDEX('#', @SEAL_SECURITY) + 1, LEN(@SEAL_SECURITY) - CHARINDEX('#', @SEAL_SECURITY) + 1)
END

SELECT @SEAL_SECURITY3
</code>```

The result of this is MS-8#MS-9

Desired result is  MS-9

UPDATE

is it possible to get the Desired result by changing the SET ELSE block as opposed to the SELECT statement?

答:
In case you're using a SQL Server Version before 2012:</p>

```<code>SELECT RIGHT(@SEAL_SECURITY, CHARINDEX('#', REVERSE(@SEAL_SECURITY))-1)
</code>```

Body:
My below t-sql only works when there is one hash symbol in the input parameter.

How can I change it to so I can get the value after the 2nd hash symbol?

I think I need to use a combination of REVERSE and RIGHT but I can't figure it out.

DECLARE @SEAL_SECURITY3 As Varchar(50); SET @SEAL_SECURITY3 = NULL;
DECLARE @SEAL_SECURITY As Varchar(50); SET @SEAL_SECURITY = 'MS-7#MS-8#MS-9'

SET @SEAL_SECURITY3 = CASE WHEN CHARINDEX('#', @SEAL_SECURITY) = 0 THEN NULL
ELSE SUBSTRING(@SEAL_SECURITY, CHARINDEX('#', @SEAL_SECURITY) + 1, LEN(@SEAL_SECURITY) - CHARINDEX('#', @SEAL_SECURITY) + 1)
END

SELECT @SEAL_SECURITY3

The result of this is MS-8#MS-9

Desired result is  MS-9

UPDATE

is it possible to get the Desired result by changing the SET ELSE block as opposed to the SELECT statement?

Body:
In case you're using a SQL Server Version before 2012:

SELECT RIGHT(@SEAL_SECURITY, CHARINDEX('#', REVERSE(@SEAL_SECURITY))-1)


问:
How get a collection of objects <edge, vertex> Neo4jClient .NET Cypher vs. C#
```<code>    public IEnumerable<EdVeObj> Parse(string word)
    {
        var res = graphClient.Cypher.OptionalMatch($"(a{{name:'{word}'}})-[r]->(b)")
        .Return((a, r, b) => new EdVeObj{RelUp = r.As<Edge>(), Target = b.<Vertex>()}).Results;
        return res;
    }
    public class EdVeObj
    {
        public Edge RelUp { get; set; }
        public Vertex Target { get; set; }
    }
</code>```

I need to go through all the outgoing edges and get a collection of objects: the edge plus the vertex to which it comes.
Tell me please: how to perform this iteration?

答:
The question isn't super clear, but as Gabor has mentioned, if you're looking to iterate through your results, you use foreach, i.e.:

```<code>var results = Parse("word");
foreach(var ev in results){
    //Do something with ev
}
</code>```

You could equally use a for loop - but you'd need to .ToList() the results:

```<code>var results = Parse("word").ToList();
for(int i = 0; i < results.Count; i++){
    //Do something with results[i]
}
</code>```

Your cypher would benefit from a bit of tuning, first off - there's no need to use OptionalMatch - you need the results to exist, if there's nothing there then it would return nothing anyway. Also - you really should be using a label of some variety, at the very least on the a node. You should also use parameters to get some more performance from the server.

I would change your code to:

```<code>public IEnumerable<EdVeObj> Parse(string word)
{
    var res = graphClient.Cypher
        .Match("(:YOUR_LABEL_HERE {name:$word})-[r]->(b)")
        .WithParam("word", word)
        .Return((r, b) => new EdVeObj
            {
                RelUp = r.As<Edge>(),
                Target = b.<Vertex>()
            })
        .Results;

    return res;
}
</code>```

On any big graph this is going to be pretty long running :/

Body:
    public IEnumerable<EdVeObj> Parse(string word)
    {
        var res = graphClient.Cypher.OptionalMatch($"(a{{name:'{word}'}})-[r]->(b)")
        .Return((a, r, b) => new EdVeObj{RelUp = r.As<Edge>(), Target = b.<Vertex>()}).Results;
        return res;
    }
    public class EdVeObj
    {
        public Edge RelUp { get; set; }
        public Vertex Target { get; set; }
    }

I need to go through all the outgoing edges and get a collection of objects: the edge plus the vertex to which it comes.
Tell me please: how to perform this iteration?

Body:
The question isn't super clear, but as Gabor has mentioned, if you're looking to iterate through your results, you use foreach, i.e.:

var results = Parse("word");
foreach(var ev in results){
    //Do something with ev
}

You could equally use a for loop - but you'd need to .ToList() the results:

var results = Parse("word").ToList();
for(int i = 0; i < results.Count; i++){
    //Do something with results[i]
}

Your cypher would benefit from a bit of tuning, first off - there's no need to use OptionalMatch - you need the results to exist, if there's nothing there then it would return nothing anyway. Also - you really should be using a label of some variety, at the very least on the a node. You should also use parameters to get some more performance from the server.

I would change your code to:

public IEnumerable<EdVeObj> Parse(string word)
{
    var res = graphClient.Cypher
        .Match("(:YOUR_LABEL_HERE {name:$word})-[r]->(b)")
        .WithParam("word", word)
        .Return((r, b) => new EdVeObj
            {
                RelUp = r.As<Edge>(),
                Target = b.<Vertex>()
            })
        .Results;

    return res;
}

On any big graph this is going to be pretty long running :/


问:
Python Input function not working in IDE 2.7
I have a basic query... The below mentioned program is not running in IDE Python 2.7 Version.
Also please help me to understand what is myName here. Is it a kind of variable? Once i enter the input value its not moving to next statement How are you. Can anyone help me to come out of this basic stuff?</p>

```<code>print('Hello world!')
print('What is your name?')
myName = input()
print('How are you, ' + myName)
</code>```

答:
There are two basic methods to read input from the console in python2.x.

The first one is input and the second one is raw_input (by the way there are other ways to read from console, not to mention those.)

For input you have to enter pure python code that can be evaluated by the interpreter, and for raw_input your input will be stored as string that you can later parse for your need.

So to demonstrate:

```<code>myName = input('Enter code here: ')
Enter code here: abc
</code>```

This one will raise a NameError: name 'abc' is not defined.

While:

```<code>myName = raw_input('Enter text here: ')
Enter text here: abc
</code>```

Will pass, and store the string abc in the variable called myName.

Although you can get the same result with input if you type your input between quotes:

```<code>myName = input('Enter code here: ')
Enter code here: 'abc'
</code>```

As a conclusion you should never use input to get text from the console, as it will be interpreted as pure python code and can lead to dangerous and undesired results, instead always use raw_input.

Hope it helps!

Note: in python3 raw_input's equivalent is input and the old input is gone.

Body:
I have a basic query... The below mentioned program is not running in IDE Python 2.7 Version.
Also please help me to understand what is myName here. Is it a kind of variable? Once i enter the input value its not moving to next statement How are you. Can anyone help me to come out of this basic stuff?

print('Hello world!')
print('What is your name?')
myName = input()
print('How are you, ' + myName)

Body:
There are two basic methods to read input from the console in python2.x.

The first one is input and the second one is raw_input (by the way there are other ways to read from console, not to mention those.)

For input you have to enter pure python code that can be evaluated by the interpreter, and for raw_input your input will be stored as string that you can later parse for your need.

So to demonstrate:

myName = input('Enter code here: ')
Enter code here: abc

This one will raise a NameError: name 'abc' is not defined.

While:

myName = raw_input('Enter text here: ')
Enter text here: abc

Will pass, and store the string abc in the variable called myName.

Although you can get the same result with input if you type your input between quotes:

myName = input('Enter code here: ')
Enter code here: 'abc'

As a conclusion you should never use input to get text from the console, as it will be interpreted as pure python code and can lead to dangerous and undesired results, instead always use raw_input.

Hope it helps!

Note: in python3 raw_input's equivalent is input and the old input is gone.


问:
how to make element check code simpler or one-liner in python?
I wanna make simple condition to check whether element 'a' in A and element 'b' in B has a some characteristic.

the below code operates well, it looks dirty, so, I wanna make it simpler, or one-liner. are there any way to do that?

```<code>    def check_direction(A, B):
        for a in A:
            for b in B:
                if c_matrix.loc()[a][b]!="->":
                    return False
        return True
</code>```

答:
Here I follow a different approach from Martijn's one, he postulated that Numpy/Pandas are not relevant for the answer, I proceed with the understanding that everything is a Numpy array...

First, for demonstrational purposes, we create a matrix of strings, among them the one we don't want in your sample

```<code>In [37]: toks = ['--', '-+', '+-', '-|', '|-', '->', '<-']
In [38]: matrix = np.array([[toks[np.random.randint(7)] for j in range(5)] for i in range(4)])
In [39]: matrix
Out[39]:
array([['|-', '--', '<-', '-|', '-|'],
       ['|-', '<-', '--', '+-', '--'],
       ['|-', '-+', '-+', '<-', '-+'],
       ['<-', '->', '->', '-|', '--']],
      dtype='<U2')
</code>```

next, two vector of indices

```<code>In [40]: A, B = np.array([2,3]), np.array([0,1,4])
</code>```

and the correct broadcasting rule to apply them to indexing matrix

```<code>In [41]: matrix[A[:,None],B]
Out[41]:
array([['|-', '-+', '-+'],
       ['<-', '->', '--']],
      dtype='<U2')
</code>```

and eventually, similar to what was suggested in comments and proposed in other answers

```<code>In [42]: np.all(matrix[A[:,None],B] == '->')
Out[42]: False
</code>```

I would like to stress the matrix[A[:,None],B] line, that could be commented like this "Look ma', no loops" ;-)

In terms of a function definition (more general than yours)

```<code>def(m, a, b, tok):
    return np.all(m[np.array(a)[:,None], np.array(b)] == tok)
</code>```

note that the function is resilient w/r receiving in a and b sequences that are not Numpy arrays.

Body:
I wanna make simple condition to check whether element 'a' in A and element 'b' in B has a some characteristic.

the below code operates well, it looks dirty, so, I wanna make it simpler, or one-liner. are there any way to do that?

    def check_direction(A, B):
        for a in A:
            for b in B:
                if c_matrix.loc()[a][b]!="->":
                    return False
        return True

Body:
Here I follow a different approach from Martijn's one, he postulated that Numpy/Pandas are not relevant for the answer, I proceed with the understanding that everything is a Numpy array...

First, for demonstrational purposes, we create a matrix of strings, among them the one we don't want in your sample

In [37]: toks = ['--', '-+', '+-', '-|', '|-', '->', '<-']
In [38]: matrix = np.array([[toks[np.random.randint(7)] for j in range(5)] for i in range(4)])
In [39]: matrix
Out[39]:
array([['|-', '--', '<-', '-|', '-|'],
       ['|-', '<-', '--', '+-', '--'],
       ['|-', '-+', '-+', '<-', '-+'],
       ['<-', '->', '->', '-|', '--']],
      dtype='<U2')

next, two vector of indices

In [40]: A, B = np.array([2,3]), np.array([0,1,4])

and the correct broadcasting rule to apply them to indexing matrix

In [41]: matrix[A[:,None],B]
Out[41]:
array([['|-', '-+', '-+'],
       ['<-', '->', '--']],
      dtype='<U2')

and eventually, similar to what was suggested in comments and proposed in other answers

In [42]: np.all(matrix[A[:,None],B] == '->')
Out[42]: False

I would like to stress the matrix[A[:,None],B] line, that could be commented like this "Look ma', no loops" ;-)

In terms of a function definition (more general than yours)

def(m, a, b, tok):
    return np.all(m[np.array(a)[:,None], np.array(b)] == tok)

note that the function is resilient w/r receiving in a and b sequences that are not Numpy arrays.


问:
Issue trying to implement stacked LSTM layers with Keras
I'm trying to add more LSTM layers to my neural net, but I keep getting the following error:

```<code>ValueError: Error when checking target: expected dense_4 to have 2 dimensions, but got array with shape (385, 128, 1)
</code>```

The code for my model is as follows:

```<code>model = Sequential()

model.add(LSTM(60, return_sequences=True, input_shape=(128, 14)))

model.add(LSTM(60, return_sequences=False))

model.add(Dense(1))

model.compile(loss='mean_squared_error', optimizer='adam')

model.fit(data_train, RUL_train, epochs=number_epochs, batch_size=batch_size, verbose=1)
</code>```

It works fine when I remove the second LSTM layer. Or if I add more dense layers. Just not when I add the LSTM layer. RUL_train has shape (385, 128, 1).
The output of model.summary is as follows:

```<code>_________________________________________________________________
   Layer (type)                 Output Shape              Param #
=================================================================
lstm_15 (LSTM)               (None, 128, 60)           18000
_________________________________________________________________
lstm_16 (LSTM)               (None, 60)                29040
_________________________________________________________________
dense_7 (Dense)              (None, 1)                 61
=================================================================
Total params: 47,101
Trainable params: 47,101
Non-trainable params: 0
_________________________________________________________________
</code>```

Any help appreciated.

答:
Your labels array has three dimensions: (385,128,1).

So, what is your purpose?

Classify all steps in each sequence? - All LSTMs must use return_sequence=True

One class for the entire sequence? - Fix your labels array somehow to be (samples,1).

Body:
I'm trying to add more LSTM layers to my neural net, but I keep getting the following error:

ValueError: Error when checking target: expected dense_4 to have 2 dimensions, but got array with shape (385, 128, 1)

The code for my model is as follows:

model = Sequential()

model.add(LSTM(60, return_sequences=True, input_shape=(128, 14)))

model.add(LSTM(60, return_sequences=False))

model.add(Dense(1))

model.compile(loss='mean_squared_error', optimizer='adam')

model.fit(data_train, RUL_train, epochs=number_epochs, batch_size=batch_size, verbose=1)

It works fine when I remove the second LSTM layer. Or if I add more dense layers. Just not when I add the LSTM layer. RUL_train has shape (385, 128, 1).
The output of model.summary is as follows:

_________________________________________________________________
   Layer (type)                 Output Shape              Param #
=================================================================
lstm_15 (LSTM)               (None, 128, 60)           18000
_________________________________________________________________
lstm_16 (LSTM)               (None, 60)                29040
_________________________________________________________________
dense_7 (Dense)              (None, 1)                 61
=================================================================
Total params: 47,101
Trainable params: 47,101
Non-trainable params: 0
_________________________________________________________________

Any help appreciated.


问:
Express req.body is empty when using the http.post
I do not know why the req.body is EMPTY...
app.js use the body-parser middleware(http://www.expressjs.com.cn/4x/api.html#req.body)

```<code>var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// add baseurl
app.use('/api', index);
app.use('/api', users);
</code>```

user.js

```<code>router.route('/user')
.post(function (req, res, next) {
    console.log(req.body);
    console.log(req.headers);
    //console.log(JSON.parse(Object.keys(req.body)[0]));
    res.json({title: 'RESTful: POST...'});
});
</code>```

I have printed the headers: But the req.body is empty and I used the JSON.parse(Object.keys(req.body)[0]) to parse the result from the other similar question, but it did not work to me.
I use the postman to request the POST,

```<code>{ 'cache-control': 'no-cache',
'postman-token': 'db7766d7-767c-4d33-be3a-acfa18ac1d9c',
'content-type': 'application/x-www-form-urlencoded',
'user-agent': 'PostmanRuntime/6.4.1',
accept: '*/*',
host: 'localhost:3000',
'accept-encoding': 'gzip, deflate',
'content-length': '0',
connection: 'keep-alive' }
</code>```

postman screenshot

答:
Your routes seem to be configured correctly.  I'd rule out any funny business with postman by trying to make the same request using curl.

```<code>curl -d "@/path/to/payload.json" -H "Content-Type: application/json" -X POST http://localhost:3000/api/user
</code>```

What happens then?

EDIT: From what I gather in the comments, it looks like the request you were posting contained a Content-Type: application/x-www-form-urlencoded header, but with a JSON body {"name":"user"}.  In other words, the content-type header and the body are mismatched.

Because the server was expecting URL encoded content, it would have been unable to parse the request body.  For that reason, it's important to make the Content-Type header agree with body format.  So in this case, you have two options.

Keep Content-Type: application/x-www-form-urlencoded and change the body to name=user

Change your header accordingly to Content-Type: application/json and keep the body as {"name":"user"}

Body:
I do not know why the req.body is EMPTY...
app.js use the body-parser middleware(http://www.expressjs.com.cn/4x/api.html#req.body)

var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// add baseurl
app.use('/api', index);
app.use('/api', users);

user.js

router.route('/user')
.post(function (req, res, next) {
    console.log(req.body);
    console.log(req.headers);
    //console.log(JSON.parse(Object.keys(req.body)[0]));
    res.json({title: 'RESTful: POST...'});
});

I have printed the headers: But the req.body is empty and I used the JSON.parse(Object.keys(req.body)[0]) to parse the result from the other similar question, but it did not work to me.
I use the postman to request the POST,

{ 'cache-control': 'no-cache',
'postman-token': 'db7766d7-767c-4d33-be3a-acfa18ac1d9c',
'content-type': 'application/x-www-form-urlencoded',
'user-agent': 'PostmanRuntime/6.4.1',
accept: '*/*',
host: 'localhost:3000',
'accept-encoding': 'gzip, deflate',
'content-length': '0',
connection: 'keep-alive' }

postman screenshot

Body:
Your routes seem to be configured correctly.  I'd rule out any funny business with postman by trying to make the same request using curl.

curl -d "@/path/to/payload.json" -H "Content-Type: application/json" -X POST http://localhost:3000/api/user

What happens then?

EDIT: From what I gather in the comments, it looks like the request you were posting contained a Content-Type: application/x-www-form-urlencoded header, but with a JSON body {"name":"user"}.  In other words, the content-type header and the body are mismatched.

Because the server was expecting URL encoded content, it would have been unable to parse the request body.  For that reason, it's important to make the Content-Type header agree with body format.  So in this case, you have two options.

Keep Content-Type: application/x-www-form-urlencoded and change the body to name=user

Change your header accordingly to Content-Type: application/json and keep the body as {"name":"user"}


问:
How to get the position of a picture inside an ImageView?
I have a gallery of images with different sizes. Each image is displayed inside an ImageView sequentially (through OnTouchListener). I need to know the position of the frame of the picture I'm showing relatives to the ImageView but with the testing I've done I've only gotten the coordinates of ImageView. Any idea?

I need the values of (x1, y1) and (x2, y2).

Thanks in advance.

This is my class:

```<code>public class PuzzleView extends ImageView {

protected Paint currentPaint;

protected boolean drawRect = false;
protected float left;
protected float top;
protected float right;
protected float bottom;

protected float pixelX;
protected float pixelY;

protected int nChunksX = 5;
protected int nChunksY = 5;

protected int currentWidth = 0;
protected int currentHeight = 0;

public PuzzleView(Context context, AttributeSet attrs) {
    super(context, attrs);

    currentPaint = new Paint();
    currentPaint.setDither(true);
    currentPaint.setColor(0xFF00CC00);
    currentPaint.setStyle(Paint.Style.STROKE);
    currentPaint.setStrokeJoin(Paint.Join.ROUND);
    currentPaint.setStrokeCap(Paint.Cap.ROUND);
    currentPaint.setStrokeWidth(2);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    float chunkWidth = currentWidth / nChunksX;
    float chunkHeight = currentHeight / nChunksY;

    float posX = ((int)(pixelX / chunkWidth)) * chunkWidth;
    float posY = ((int)(pixelY / chunkHeight)) * chunkHeight;

    canvas.drawRect(posX, posY, posX + chunkWidth, posY + chunkHeight, currentPaint);

    Rect rect = this.getDrawable().getBounds();
    canvas.drawRect(rect, currentPaint);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    // Get image matrix values and place them in an array
    float[] f = new float[9];
    getImageMatrix().getValues(f);

    // Extract the scale values using the constants (if aspect ratio maintained, scaleX == scaleY)
    final float scaleX = f[Matrix.MSCALE_X];
    final float scaleY = f[Matrix.MSCALE_Y];

    // Get the drawable (could also get the bitmap behind the drawable and getWidth/getHeight)
    final Drawable d = getDrawable();
    final int origW = d.getIntrinsicWidth();
    final int origH = d.getIntrinsicHeight();

    // Calculate the actual dimensions
    final int actW = Math.round(origW * scaleX);
    final int actH = Math.round(origH * scaleY);

    currentWidth = actW;
    currentHeight = actH;
}

public boolean isDrawRect() {
    return drawRect;
}

public void setDrawRect(boolean drawRect) {
    this.drawRect = drawRect;
}

public float getLeftRect() {
    return left;
}

public void setLeftRect(float left) {
    this.left = left;
}

public float getTopRect() {
    return top;
}

public void setTopRect(float top) {
    this.top = top;
}

public float getRightRect() {
    return right;
}

public void setRightRect(float right) {
    this.right = right;
}

public float getBottomRect() {
    return bottom;
}

public void setBottomRect(float bottom) {
    this.bottom = bottom;
}

public float getPixelX() {
    return pixelX;
}

public void setPixelX(float pixelX) {
    this.pixelX = pixelX;
}

public float getPixelY() {
    return pixelY;
}

public void setPixelY(float pixelY) {
    this.pixelY = pixelY;
}

public int getChunksX() {
    return nChunksX;
}

public void setChunksX(int nChunksX) {
    this.nChunksX = nChunksX;
}

public int getChunksY() {
    return nChunksY;
}

public void setChunksY(int nChunksY) {
    this.nChunksY = nChunksY;
}
}
</code>```

For now, the source image is defined in XML file:

```<code><com.jocajica.shakepic.PuzzleView
    android:id="@+id/imageViewSelected"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:contentDescription="@string/image_selected"
    android:src="@android:drawable/progress_indeterminate_horizontal" />
</code>```

I need to draw a grid over the image.

答:
Override the onLayout method

```<code>    //inside puzzleView
    float[] matrix = new float[9];
    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {

        super.onLayout(changed, left, top, right, bottom);
        matrix = getMatrix();

    }
    public void getMatrix(){
         return matrix;
    }

    private float[] getMatrix() {

        final float[] matrix = new float[9];
        getImageMatrix().getValues(matrix);

        return matrix;
    }
</code>```

and use this to get values

```<code>       // Extract the scale and translation values from the matrix.
       float scaleX = matrix[Matrix.MSCALE_X];
       float scaleY = matrix[Matrix.MSCALE_Y];
       float transX = matrix[Matrix.MTRANS_X];
       float transY = matrix[Matrix.MTRANS_Y];
</code>```

I hope that this help u

Body:
I have a gallery of images with different sizes. Each image is displayed inside an ImageView sequentially (through OnTouchListener). I need to know the position of the frame of the picture I'm showing relatives to the ImageView but with the testing I've done I've only gotten the coordinates of ImageView. Any idea?

I need the values of (x1, y1) and (x2, y2).

Thanks in advance.

This is my class:

public class PuzzleView extends ImageView {

protected Paint currentPaint;

protected boolean drawRect = false;
protected float left;
protected float top;
protected float right;
protected float bottom;

protected float pixelX;
protected float pixelY;

protected int nChunksX = 5;
protected int nChunksY = 5;

protected int currentWidth = 0;
protected int currentHeight = 0;

public PuzzleView(Context context, AttributeSet attrs) {
    super(context, attrs);

    currentPaint = new Paint();
    currentPaint.setDither(true);
    currentPaint.setColor(0xFF00CC00);
    currentPaint.setStyle(Paint.Style.STROKE);
    currentPaint.setStrokeJoin(Paint.Join.ROUND);
    currentPaint.setStrokeCap(Paint.Cap.ROUND);
    currentPaint.setStrokeWidth(2);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    float chunkWidth = currentWidth / nChunksX;
    float chunkHeight = currentHeight / nChunksY;

    float posX = ((int)(pixelX / chunkWidth)) * chunkWidth;
    float posY = ((int)(pixelY / chunkHeight)) * chunkHeight;

    canvas.drawRect(posX, posY, posX + chunkWidth, posY + chunkHeight, currentPaint);

    Rect rect = this.getDrawable().getBounds();
    canvas.drawRect(rect, currentPaint);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    // Get image matrix values and place them in an array
    float[] f = new float[9];
    getImageMatrix().getValues(f);

    // Extract the scale values using the constants (if aspect ratio maintained, scaleX == scaleY)
    final float scaleX = f[Matrix.MSCALE_X];
    final float scaleY = f[Matrix.MSCALE_Y];

    // Get the drawable (could also get the bitmap behind the drawable and getWidth/getHeight)
    final Drawable d = getDrawable();
    final int origW = d.getIntrinsicWidth();
    final int origH = d.getIntrinsicHeight();

    // Calculate the actual dimensions
    final int actW = Math.round(origW * scaleX);
    final int actH = Math.round(origH * scaleY);

    currentWidth = actW;
    currentHeight = actH;
}

public boolean isDrawRect() {
    return drawRect;
}

public void setDrawRect(boolean drawRect) {
    this.drawRect = drawRect;
}

public float getLeftRect() {
    return left;
}

public void setLeftRect(float left) {
    this.left = left;
}

public float getTopRect() {
    return top;
}

public void setTopRect(float top) {
    this.top = top;
}

public float getRightRect() {
    return right;
}

public void setRightRect(float right) {
    this.right = right;
}

public float getBottomRect() {
    return bottom;
}

public void setBottomRect(float bottom) {
    this.bottom = bottom;
}

public float getPixelX() {
    return pixelX;
}

public void setPixelX(float pixelX) {
    this.pixelX = pixelX;
}

public float getPixelY() {
    return pixelY;
}

public void setPixelY(float pixelY) {
    this.pixelY = pixelY;
}

public int getChunksX() {
    return nChunksX;
}

public void setChunksX(int nChunksX) {
    this.nChunksX = nChunksX;
}

public int getChunksY() {
    return nChunksY;
}

public void setChunksY(int nChunksY) {
    this.nChunksY = nChunksY;
}
}

For now, the source image is defined in XML file:

<com.jocajica.shakepic.PuzzleView
    android:id="@+id/imageViewSelected"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:contentDescription="@string/image_selected"
    android:src="@android:drawable/progress_indeterminate_horizontal" />

I need to draw a grid over the image.

Body:
Override the onLayout method

    //inside puzzleView
    float[] matrix = new float[9];
    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {

        super.onLayout(changed, left, top, right, bottom);
        matrix = getMatrix();

    }
    public void getMatrix(){
         return matrix;
    }

    private float[] getMatrix() {

        final float[] matrix = new float[9];
        getImageMatrix().getValues(matrix);

        return matrix;
    }

and use this to get values

       // Extract the scale and translation values from the matrix.
       float scaleX = matrix[Matrix.MSCALE_X];
       float scaleY = matrix[Matrix.MSCALE_Y];
       float transX = matrix[Matrix.MTRANS_X];
       float transY = matrix[Matrix.MTRANS_Y];

I hope that this help u


问:
Active Model Serializers nested associations that calls methods with arguments
for example if I have these models with these associations

```<code>class User
  has_many :posts
  has_many :comments

  def posts_has_comments_in_certain_day(day)
    posts.joins(:comments).where(comments: { created_at: day })
  end
end

class Post
  has_many :comments
  belongs_to :user

  def comments_in_certain_day(day)
    Comment.where(created_at: day, post_id: id)
  end
end

class Comment
  belongs_to :user
  belongs_to :post
end
</code>```

now I want active model serializer to get me all the users with their posts that has comments in a certain day including these comments too.

I've tried but all I could get is user with his posts that have comments in that certain day .. but I couldn't include the comments too.

thats what I did

```<code>class UserSerializer < ActiveModel::Serializer
  attributes :id, :name, :day_posts

  def day_posts
    object.posts_has_comments_in_certain_day(day)
  end
end
</code>```

and this is working fine
but when I try to include the comments !!! ..

```<code>class UserSerializer < ActiveModel::Serializer
  attributes :id, :name, :day_posts

  def day_posts
    object.posts_has_comments_in_certain_day(day).map do |post|
    PostSerializer.new(
      post,
      day: instance_options[:day]
    )
  end
end

class PostSerializer < ActiveModel::Serializer
  attributes :id, :body, :day_comments

  def day_comments
    object.comments_in_certain_day(day)
  end
end
</code>```

this is not working .. can any one help me with this ?

答:
Call .attributes on serializer instance

```<code>class UserSerializer < ActiveModel::Serializer
  attributes :id, :name, :day_posts

  def day_posts
    object.posts_has_comments_in_certain_day(day).map do |post|
    PostSerializer.new(
      post,
      day: instance_options[:day]
    ).attributes
  end
end
</code>```

if you need to customise comments attributes do the same thing for comments too.

```<code>class PostSerializer < ActiveModel::Serializer
  attributes :id, :body, :day_comments

  def day_comments
    object.comments_in_certain_day(day).map do |comment|
        CommentSerializer.new(comment).attributes
    end
  end
end
</code>```

Body:
for example if I have these models with these associations

class User
  has_many :posts
  has_many :comments

  def posts_has_comments_in_certain_day(day)
    posts.joins(:comments).where(comments: { created_at: day })
  end
end

class Post
  has_many :comments
  belongs_to :user

  def comments_in_certain_day(day)
    Comment.where(created_at: day, post_id: id)
  end
end

class Comment
  belongs_to :user
  belongs_to :post
end

now I want active model serializer to get me all the users with their posts that has comments in a certain day including these comments too.

I've tried but all I could get is user with his posts that have comments in that certain day .. but I couldn't include the comments too.

thats what I did

class UserSerializer < ActiveModel::Serializer
  attributes :id, :name, :day_posts

  def day_posts
    object.posts_has_comments_in_certain_day(day)
  end
end

and this is working fine
but when I try to include the comments !!! ..

class UserSerializer < ActiveModel::Serializer
  attributes :id, :name, :day_posts

  def day_posts
    object.posts_has_comments_in_certain_day(day).map do |post|
    PostSerializer.new(
      post,
      day: instance_options[:day]
    )
  end
end

class PostSerializer < ActiveModel::Serializer
  attributes :id, :body, :day_comments

  def day_comments
    object.comments_in_certain_day(day)
  end
end

this is not working .. can any one help me with this ?

Body:
Call .attributes on serializer instance

class UserSerializer < ActiveModel::Serializer
  attributes :id, :name, :day_posts

  def day_posts
    object.posts_has_comments_in_certain_day(day).map do |post|
    PostSerializer.new(
      post,
      day: instance_options[:day]
    ).attributes
  end
end

if you need to customise comments attributes do the same thing for comments too.

class PostSerializer < ActiveModel::Serializer
  attributes :id, :body, :day_comments

  def day_comments
    object.comments_in_certain_day(day).map do |comment|
        CommentSerializer.new(comment).attributes
    end
  end
end


问:
Warning in install.packages: unable to move temporary installation
I've found a number of questions related to this warning when installing or updating packages in R/RStudio, but none seem to completely match my situation:

Corporate Windows 7 system, so no access to admin privileges

No way to make changes to McAfee Anti-Virus exceptions lists

R is fully installed in the user space C:\Users\[myname]\R

RStudio fully installed in userspace C\Users\[myname]\RStudio

no permission issues in either of the directories... I have full access control over them

Problem only started after installing R 3.4, but RStudio has randomly failing at start or hanging for a few months now

R_LIBS_USER added as user environment variable, pointing to right directory

.libPaths() show correct directories, both system and user

R version 3.4.2, RStudio version 1.0.153

Uninstalled both R and Rstudio and did a clean re-install of both

Tried trace(utils:::unpackPkgZip,edit = T) and edited Line 140 Sys.sleep(0.5) to Sys.sleep(2), which sometimes works temporarily but the edit won't stay put... resets to Sys.sleep(0.5) on every session restart

Happens in both RStudio and RGui

Any package larger than a few Kb gives the message:

```<code>package ‘packagename’ successfully unpacked and MD5 sums checked
Warning in install.packages :
  unable to move temporary installation ‘C:\Users\[myname]\R\win-library\3.4\file2b884fc37c13\packagename’ to ‘C:\Users\[myname]\R\win-library\3.4\packagename’
</code>```

The packages are failing to install or update. So, my questions are:

is there a way to avoid the problem altogether that doesn't require admin privileges or changes to the antivirus policies?

is there a way to get the edit to unpackPkgZip to save permanently?

At this point, I'm stumped. I suspect it has something to do with the antivirus temporarily locking the file/directory after download, but I can't do anything about it from that end. The Sys.sleep(2) seems to do the trick, but I can't keep doing that before every package install or update and can't seem to get the edit to stay put.

答:
If you cannot turn off your antivirus here is a workaround that I found that doesn't involve editing the unpackPkgZip file. Debugging the unzip package function and then stepping through it gives the antivirus enough time to do its job without interfering. Use this command:

debug(utils:::unpackPkgZip)
install.packages("packageName")

and then step through the code (by pressing enter many times) when R starts debugging during the installation.

I found this solution here.

If you want to make this change more permanent you can add the debug code into your Rprofile file, see here, but you'll still need to use step through the unzip function each time a package is installed.

Body:
I've found a number of questions related to this warning when installing or updating packages in R/RStudio, but none seem to completely match my situation:

Corporate Windows 7 system, so no access to admin privileges

No way to make changes to McAfee Anti-Virus exceptions lists

R is fully installed in the user space C:\Users\[myname]\R

RStudio fully installed in userspace C\Users\[myname]\RStudio

no permission issues in either of the directories... I have full access control over them

Problem only started after installing R 3.4, but RStudio has randomly failing at start or hanging for a few months now

R_LIBS_USER added as user environment variable, pointing to right directory

.libPaths() show correct directories, both system and user

R version 3.4.2, RStudio version 1.0.153

Uninstalled both R and Rstudio and did a clean re-install of both

Tried trace(utils:::unpackPkgZip,edit = T) and edited Line 140 Sys.sleep(0.5) to Sys.sleep(2), which sometimes works temporarily but the edit won't stay put... resets to Sys.sleep(0.5) on every session restart

Happens in both RStudio and RGui

Any package larger than a few Kb gives the message:

package ‘packagename’ successfully unpacked and MD5 sums checked
Warning in install.packages :
  unable to move temporary installation ‘C:\Users\[myname]\R\win-library\3.4\file2b884fc37c13\packagename’ to ‘C:\Users\[myname]\R\win-library\3.4\packagename’

The packages are failing to install or update. So, my questions are:

is there a way to avoid the problem altogether that doesn't require admin privileges or changes to the antivirus policies?

is there a way to get the edit to unpackPkgZip to save permanently?

At this point, I'm stumped. I suspect it has something to do with the antivirus temporarily locking the file/directory after download, but I can't do anything about it from that end. The Sys.sleep(2) seems to do the trick, but I can't keep doing that before every package install or update and can't seem to get the edit to stay put.


问:
Words in a list with consecutively repeated letters
Right now I have a list of for example

```<code>data = ['dog','cat','a','aa','aac','bbb','bcca','ffffff']
</code>```

I want to remove the words with the repeated letters, in which I want to remove the words

```<code>'aa','aac','bbb','bcca','ffffff'
</code>```

Maybe import re?

答:
One line is all it takes :)

```<code>data = ['dog','cat','a','aa','aac','bbb','bcca','ffffff']
data =  [value for value in data if(len(set(value))!=1 or len(value) ==1)]
print(data)
</code>```

Output

```<code>['dog', 'cat', 'a', 'aac', 'bcca']
</code>```

Body:
Right now I have a list of for example

data = ['dog','cat','a','aa','aac','bbb','bcca','ffffff']

I want to remove the words with the repeated letters, in which I want to remove the words

'aa','aac','bbb','bcca','ffffff'

Maybe import re?

Body:
One line is all it takes :)

data = ['dog','cat','a','aa','aac','bbb','bcca','ffffff']
data =  [value for value in data if(len(set(value))!=1 or len(value) ==1)]
print(data)

Output

['dog', 'cat', 'a', 'aac', 'bcca']


问:
cant change Font color inside titleForHeaderInSection on iphone
How to change the Font color inside titleForHeaderInSection??</p>

```<code>- (NSString *)tableView:(UITableView *)tblView titleForHeaderInSection:(NSInteger)section {

//- (UIView *)tableView:(UITableView *)tblView viewForHeaderInSection:(NSInteger)section {

    //tabelView.backgroundColor = [UIColor blueColor];

    NSString *sectionName = nil;

    switch(section)
    {
        case 0:
            NSLog(@"ok");

            UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,100,30)];

            myLabel.font = [UIFont fontWithName:@"Zapfino" size: 14.0];
            myLabel.shadowColor = [UIColor grayColor];
            myLabel.shadowOffset = CGSizeMake(1,1);
            myLabel.textColor = [UIColor redColor];

            myLabel.backgroundColor = [UIColor clearColor];

            myLabel.text = @"DESCRIPTION";// not working i can only see value no color no font
    }
    }
</code>```

答:
i did it like this

```<code>(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 44.0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
// create the parent view that will hold header Label
UIView* customView = [[[UIView alloc] initWithFrame:CGRectMake(10.0, 0.0, 150.0, 44.0)]autorelease];

NSString *sectionName = nil;

switch(section)
{
case 0:

if(counter<=3)
NSLog(@"ok");

// create the buNSLog(@"ok");tton object
UILabel * headerLabel = [[[UILabel alloc] initWithFrame:CGRectZero]autorelease] ;
headerLabel.backgroundColor = [UIColor clearColor];
headerLabel.opaque = NO;
headerLabel.textColor = [UIColor whiteColor];
headerLabel.highlightedTextColor = [UIColor whiteColor];
headerLabel.font = [UIFont boldSystemFontOfSize:20];
headerLabel.frame = CGRectMake(10.0, 0.0, 300.0, 44.0);

// If you want to align the header text as centered
// headerLabel.frame = CGRectMake(150.0, 0.0, 300.0, 44.0);

headerLabel.text = @"Description"; // i.e. array element
[customView addSubview:headerLabel];

if(counter==7)

headerLabel.text = @""; // i.e. array element
[customView addSubview:headerLabel];

//sectionName = @"DES-";

break;

case 1:
</code>```

Thanks

Body:
How to change the Font color inside titleForHeaderInSection??

- (NSString *)tableView:(UITableView *)tblView titleForHeaderInSection:(NSInteger)section {

//- (UIView *)tableView:(UITableView *)tblView viewForHeaderInSection:(NSInteger)section {

    //tabelView.backgroundColor = [UIColor blueColor];

    NSString *sectionName = nil;

    switch(section)
    {
        case 0:
            NSLog(@"ok");

            UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,100,30)];

            myLabel.font = [UIFont fontWithName:@"Zapfino" size: 14.0];
            myLabel.shadowColor = [UIColor grayColor];
            myLabel.shadowOffset = CGSizeMake(1,1);
            myLabel.textColor = [UIColor redColor];

            myLabel.backgroundColor = [UIColor clearColor];

            myLabel.text = @"DESCRIPTION";// not working i can only see value no color no font
    }
    }

Body:
i did it like this

(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 44.0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
// create the parent view that will hold header Label
UIView* customView = [[[UIView alloc] initWithFrame:CGRectMake(10.0, 0.0, 150.0, 44.0)]autorelease];

NSString *sectionName = nil;

switch(section)
{
case 0:

if(counter<=3)
NSLog(@"ok");

// create the buNSLog(@"ok");tton object
UILabel * headerLabel = [[[UILabel alloc] initWithFrame:CGRectZero]autorelease] ;
headerLabel.backgroundColor = [UIColor clearColor];
headerLabel.opaque = NO;
headerLabel.textColor = [UIColor whiteColor];
headerLabel.highlightedTextColor = [UIColor whiteColor];
headerLabel.font = [UIFont boldSystemFontOfSize:20];
headerLabel.frame = CGRectMake(10.0, 0.0, 300.0, 44.0);

// If you want to align the header text as centered
// headerLabel.frame = CGRectMake(150.0, 0.0, 300.0, 44.0);

headerLabel.text = @"Description"; // i.e. array element
[customView addSubview:headerLabel];

if(counter==7)

headerLabel.text = @""; // i.e. array element
[customView addSubview:headerLabel];

//sectionName = @"DES-";

break;

case 1:

Thanks


问:
A Perl system call must send exactly both characters single & double quote ' "
A Perl system call must send the following string to the UnixShell:

```<code>'"XYZ"'
</code>```

In my Perl script I have used the following command:

```<code>system("cleartool mkattr -replace ATTRIBUTE '"$attribute"' lbtype:$label");
</code>```

Everything is well passed to the Shell Unix, except both uses of the quote character:

```<code>'
</code>```

Indeed,

```<code>cleartool mkattr -replace ATTRIBUTE
</code>```

The above command is passed as it is exactly what I want.
The Perl variables $attribute and $label are well interpreted.
But I don't know what to do to obtain exactly:

```<code>'"XYZ"'
</code>```

Here XYZ is the value of the Perl variable $attribute
OS is AIX (Unix) and Shell is ksh. cleartool is the command line interface of Clearcase but no Clearcase skill is necessary to fix my problem.

答:
If you want to execute a system command and don't have to use any shell syntax like redirects, it's usually better and safer to use the list form of system:

system(
    'cleartool',  'mkattr', '-replace', 'ATTRIBUTE',
    qq{"$attribute"}, qq{lbtype:$label}
);
# or, if you really want to pass both types of quotes:
system(
    'cleartool',  'mkattr', '-replace', 'ATTRIBUTE',
    qq{'"$attribute"'}, qq{lbtype:$label}
);
```

See perldoc -f system

It's not clear from your question if you want to pass '"XYZ"' or "XYZ".

Body:
A Perl system call must send the following string to the UnixShell:

'"XYZ"'

In my Perl script I have used the following command:

system("cleartool mkattr -replace ATTRIBUTE '"$attribute"' lbtype:$label");

Everything is well passed to the Shell Unix, except both uses of the quote character:

'

Indeed,

cleartool mkattr -replace ATTRIBUTE

The above command is passed as it is exactly what I want.
The Perl variables $attribute and $label are well interpreted.
But I don't know what to do to obtain exactly:

'"XYZ"'

Here XYZ is the value of the Perl variable $attribute
OS is AIX (Unix) and Shell is ksh. cleartool is the command line interface of Clearcase but no Clearcase skill is necessary to fix my problem.

Body:
If you want to execute a system command and don't have to use any shell syntax like redirects, it's usually better and safer to use the list form of system:

system(
    'cleartool',  'mkattr', '-replace', 'ATTRIBUTE',
    qq{"$attribute"}, qq{lbtype:$label}
);
# or, if you really want to pass both types of quotes:
system(
    'cleartool',  'mkattr', '-replace', 'ATTRIBUTE',
    qq{'"$attribute"'}, qq{lbtype:$label}
);

See perldoc -f system

It's not clear from your question if you want to pass '"XYZ"' or "XYZ".


问:
Use a stepper to give a limit to the number of objects that can be inside an array (swift)
I have an array in my VC

```<code>var list : [QCategoryy] = [QCategoryy]()
list = NearbyPlaces.getCategories()
</code>```

where getCategories() is

```<code>static func getCategories() -> [QCategoryy] {
        let list:[QCategoryy] = [QCategoryy(name: "bar", image: UIImage(named: "bar_button.png")!), QCategoryy(name :"night_club", image: UIImage(named: "nightclub_button.png")!), QCategoryy(name: "movie_theater", image: UIImage(named: "cinema_button.png")!), QCategoryy(name: "restaurant", image: UIImage(named: "restaurant_button.png")!), QCategoryy(name: "gym", image: UIImage(named: "gym_button.png")!), QCategoryy(name: "spa", image: UIImage(named: "spa_button.png")!), QCategoryy(name: "museum", image: UIImage(named: "museum_button.png")!)]
        return list
    }
</code>```

but i would like that in my viewController the user can choose the maximum number of objects that must be in this array with a stepper Int(steppeR.value) (for example if the value of the stepper is 1, in my list can be only the first item of getCategories) I also already have an extension for shuffle the array

```<code>extension MutableCollection where Indices.Iterator.Element == Index {
    /// Shuffles the contents of this collection.
    mutating func shuffle() {
        let c = count
        guard c > 1 else { return }

        for (firstUnshuffled , unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
            let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
            guard d != 0 else { continue }
            let i = index(firstUnshuffled, offsetBy: d)
            self.swapAt(firstUnshuffled, i)
        }
    }
}

extension Sequence {
    /// Returns an array with the contents of this sequence, shuffled.
    func shuffled() -> [Iterator.Element] {
        var result = Array(self)
        result.shuffle()
        return result
    }
}
</code>```

because i do not want that with the limitation there are always the same items. How can i do something like this?

答:
With your static func getCategories() you initialize your main list right ?
Then, when the user changes the value of the stepper Int(steppeR.value), you create a filtered list with only the number of objects needed :

```<code>//stepper is equal to 1
var filteredList = [QCategoryy]()
filteredList.append(list[0])
//stepper is equal to 3
var filteredList = [QCategoryy]()
for i in 0..<3 {
  filteredList.append(list[i])
}
</code>```

Body:
I have an array in my VC

var list : [QCategoryy] = [QCategoryy]()
list = NearbyPlaces.getCategories()

where getCategories() is

static func getCategories() -> [QCategoryy] {
        let list:[QCategoryy] = [QCategoryy(name: "bar", image: UIImage(named: "bar_button.png")!), QCategoryy(name :"night_club", image: UIImage(named: "nightclub_button.png")!), QCategoryy(name: "movie_theater", image: UIImage(named: "cinema_button.png")!), QCategoryy(name: "restaurant", image: UIImage(named: "restaurant_button.png")!), QCategoryy(name: "gym", image: UIImage(named: "gym_button.png")!), QCategoryy(name: "spa", image: UIImage(named: "spa_button.png")!), QCategoryy(name: "museum", image: UIImage(named: "museum_button.png")!)]
        return list
    }

but i would like that in my viewController the user can choose the maximum number of objects that must be in this array with a stepper Int(steppeR.value) (for example if the value of the stepper is 1, in my list can be only the first item of getCategories) I also already have an extension for shuffle the array

extension MutableCollection where Indices.Iterator.Element == Index {
    /// Shuffles the contents of this collection.
    mutating func shuffle() {
        let c = count
        guard c > 1 else { return }

        for (firstUnshuffled , unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) {
            let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))
            guard d != 0 else { continue }
            let i = index(firstUnshuffled, offsetBy: d)
            self.swapAt(firstUnshuffled, i)
        }
    }
}

extension Sequence {
    /// Returns an array with the contents of this sequence, shuffled.
    func shuffled() -> [Iterator.Element] {
        var result = Array(self)
        result.shuffle()
        return result
    }
}

because i do not want that with the limitation there are always the same items. How can i do something like this?

Body:
With your static func getCategories() you initialize your main list right ?
Then, when the user changes the value of the stepper Int(steppeR.value), you create a filtered list with only the number of objects needed :

//stepper is equal to 1
var filteredList = [QCategoryy]()
filteredList.append(list[0])
//stepper is equal to 3
var filteredList = [QCategoryy]()
for i in 0..<3 {
  filteredList.append(list[i])
}


问:
How can I call Scalar user defined function from linked server?
I have to run a query from linked server (SQL Server 2008) that contains Scalar UDF (with one parameter) on that server, when I run the query I got following error

```<code>Cannot find either column "PSW_Local" or the user-defined function or aggregate "PSW_Local.dbo.udf_psw_local_format_name", or the name is ambiguous.
</code>```

I followed someones suggestion on the internet using OPEN Query but it's not working.

Can anybody suggest different method?
Thanks in advance

答:
If you need to pass in arguments and return a value then you can use something like this;</p>

```<code>DECLARE @Arg1 INT = 1234;
DECLARE @Arg2 VARCHAR(15) = 'ABCD';
DECLARE @ReturnValue INT;
DECLARE @Parameters NVARCHAR(255) = '@ReturnValue INT OUTPUT'

DECLARE @Command NVARCHAR(MAX) =
    N'SELECT @ReturnValue = [ReturnValue] FROM OPENQUERY(
        [LINKED_SERVER]
        , ''SELECT [Database].[schema].[ScalarValuedFunction](' + CAST(@Arg1 AS VARCHAR(255)) + ', ''''' + @Arg2 + ''''') ReturnValue''
        )'

PRINT @Command

EXEC sys.sp_executesql
    @Command, @Parameters, @ReturnValue=@ReturnValue OUTPUT

SELECT @ReturnValue [ReturnValue]
</code>```

Body:
I have to run a query from linked server (SQL Server 2008) that contains Scalar UDF (with one parameter) on that server, when I run the query I got following error

Cannot find either column "PSW_Local" or the user-defined function or aggregate "PSW_Local.dbo.udf_psw_local_format_name", or the name is ambiguous.

I followed someones suggestion on the internet using OPEN Query but it's not working.

Can anybody suggest different method?
Thanks in advance

Body:
If you need to pass in arguments and return a value then you can use something like this;

DECLARE @Arg1 INT = 1234;
DECLARE @Arg2 VARCHAR(15) = 'ABCD';
DECLARE @ReturnValue INT;
DECLARE @Parameters NVARCHAR(255) = '@ReturnValue INT OUTPUT'

DECLARE @Command NVARCHAR(MAX) =
    N'SELECT @ReturnValue = [ReturnValue] FROM OPENQUERY(
        [LINKED_SERVER]
        , ''SELECT [Database].[schema].[ScalarValuedFunction](' + CAST(@Arg1 AS VARCHAR(255)) + ', ''''' + @Arg2 + ''''') ReturnValue''
        )'

PRINT @Command

EXEC sys.sp_executesql
    @Command, @Parameters, @ReturnValue=@ReturnValue OUTPUT

SELECT @ReturnValue [ReturnValue]


问:
AttributeError: 'file' object has no attribute 'append'
I'm really new to this whole thing, so excuse the maybe stupid question, but I am too stupid to find the answer myself.

I've got a list with links URLs and timestamps and want to shorten the URLs and save the result to a new file.
But running

```<code>file = open('history.csv','r')
clean = open('historyclean.csv','a')

for x in file:
    b = x.rsplit('/',1)
    b.pop()
        clean.append(b)
</code>```

results in

```<code>    AttributeError: 'file' object has no attribute 'append'
</code>```

and I can't find out why.
I am using Python 2.7, if relevant

Thanks in advance.

答: You probably want clean.write, not clean.append. As the error states files have no append operation.

Body:
I'm really new to this whole thing, so excuse the maybe stupid question, but I am too stupid to find the answer myself.

I've got a list with links URLs and timestamps and want to shorten the URLs and save the result to a new file.
But running

file = open('history.csv','r')
clean = open('historyclean.csv','a')

for x in file:
    b = x.rsplit('/',1)
    b.pop()
        clean.append(b)

results in

    AttributeError: 'file' object has no attribute 'append'

and I can't find out why.
I am using Python 2.7, if relevant

Thanks in advance.


问:
Installation of tensorflow-gpu 1.4 on cuda 9 and cudnnv7
I am trying to install tensorflow-gpu on gtx 1050 with cuda 9 and cudnn v7 on windows 10. I have added all the environment variables. But I am getting the following error:
ImportError: Could not find 'cudart64_80.dll'. TensorFlow requires that this DLL be installed in a directory that is named in your %PATH% environment variable</p>

答: Current version of tensorflow i.e 1.4 supports cuda 8, thus 'cudart64_80.dll' of cuda 8 is missing. download cuda 8 and suitable cudnn, it will fix the problem</p>


问:
SQL Server get string
I have two rows like below, from that I need to fetch the previous string in the select. e.g in the first row I need to fetch 'Auto Components', in the second row I need to fetch 'Plastic and Synthetic Resins'. Please suggest.</p>

```<code>Automotive > Auto Components > Auto Parts and Equipment
Chemicals > Commodity Chemicals > Plastic and Synthetic Resins > Plastic Products
</code>```

答:
You could try PARSENAME() function if you are working with SQL Server 2012 or above

```<code>SELECT LTRIM(PARSENAME(REPLACE(data, '>', '.'), 2)) FROM <table_name>
</code>```

else you could use conditional substring() & charindex() function method

```<code>SELECT CASE (A.RN)
           WHEN 1
           THEN SUBSTRING(LTRIM(SUBSTRING(DATA, CHARINDEX('>', DATA)+1, LEN(DATA))), 1 , CHARINDEX('>', LTRIM(SUBSTRING(DATA, CHARINDEX('>', DATA)+1, LEN(DATA))))-2)
           WHEN 2
           THEN LTRIM(SUBSTRING(SUBSTRING(SUBSTRING(DATA, CHARINDEX('>', DATA)+2, LEN(DATA)), CHARINDEX('>', SUBSTRING(DATA, CHARINDEX('>', DATA)+1, LEN(DATA))), LEN(DATA)), 1, CHARINDEX('>', LTRIM(SUBSTRING(SUBSTRING(DATA, CHARINDEX('>', DATA)+2, LEN(DATA)), CHARINDEX('>', SUBSTRING(DATA, CHARINDEX('>', DATA)+1, LEN(DATA))), LEN(DATA))))))
       END [DATA]
FROM
(
    SELECT DATA, ROW_NUMBER() OVER(ORDER BY(SELECT 1)) RN FROM <table_name>
) A;
</code>```

Result :

```<code>Auto Components
Plastic and Synthetic Resins
</code>```

Title: SQL Server get string

Body:
I have two rows like below, from that I need to fetch the previous string in the select. e.g in the first row I need to fetch 'Auto Components', in the second row I need to fetch 'Plastic and Synthetic Resins'. Please suggest.

Automotive > Auto Components > Auto Parts and Equipment
Chemicals > Commodity Chemicals > Plastic and Synthetic Resins > Plastic Products

Body:
You could try PARSENAME() function if you are working with SQL Server 2012 or above

SELECT LTRIM(PARSENAME(REPLACE(data, '>', '.'), 2)) FROM <table_name>

else you could use conditional substring() & charindex() function method

SELECT CASE (A.RN)
           WHEN 1
           THEN SUBSTRING(LTRIM(SUBSTRING(DATA, CHARINDEX('>', DATA)+1, LEN(DATA))), 1 , CHARINDEX('>', LTRIM(SUBSTRING(DATA, CHARINDEX('>', DATA)+1, LEN(DATA))))-2)
           WHEN 2
           THEN LTRIM(SUBSTRING(SUBSTRING(SUBSTRING(DATA, CHARINDEX('>', DATA)+2, LEN(DATA)), CHARINDEX('>', SUBSTRING(DATA, CHARINDEX('>', DATA)+1, LEN(DATA))), LEN(DATA)), 1, CHARINDEX('>', LTRIM(SUBSTRING(SUBSTRING(DATA, CHARINDEX('>', DATA)+2, LEN(DATA)), CHARINDEX('>', SUBSTRING(DATA, CHARINDEX('>', DATA)+1, LEN(DATA))), LEN(DATA))))))
       END [DATA]
FROM
(
    SELECT DATA, ROW_NUMBER() OVER(ORDER BY(SELECT 1)) RN FROM <table_name>
) A;

Result :

Auto Components
Plastic and Synthetic Resins


问:
How to make JavaScript and Python work together?
I want to make a two way communication model for JavaScript and Python.
I want JavaScript to process a data and send it to Python and then Python processes it and sends it back to JavaScript. I don't have a clue how this can be achieved and how the communication between the two languages will be made.

Consider the example:

Read the comments for clarity of the model!

var files = [];
const div_files = document.getElementById("files");
const div_results = document.getElementById("results");

function fetchNames() {
  div_files.innerHTML = ""; // clears the file div
  div_results.innerHTML = ""; // clears the results div

  var checkbox_elements = document.getElementsByClassName('filename');

  Array.from(checkbox_elements).forEach(function(k) {
    if (k.checked) {

      files.push(k.value);
      div_files.innerHTML += k.value + '
';
    }

  });

  // the files array should now be shared with python

  //console.log(files);

  // JavaScript SHOULD WAIT while PYTHON processes the data and shares the cal_array with JS

  // when the cal_array is available with JS only then it shall start processing the code mentioned below

  var cal_array = [
    [2231, 11640, 104621],
    [2231, 11640, 104621],
    [9, 494, 3339]
  ];
  Array.from(cal_array).forEach(function(k) {
    div_results.innerHTML += k + '
';
  })

};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <input type="checkbox" class="filename" value="./first.html">First File<br>
  <input type="checkbox" class="filename" value="./second.html">Second File<br>
  <input type="checkbox" class="filename" value="./third.html">Third File<br>
  <br>
  <input type="button" value="Submit" onclick="fetchNames()">
</form>
<br>
The selected file(s) are:
<div id="files"></div>
<br> The result shows the number of lines, words, and characters of the respective files mentioned above:
<div id="results"></div></code>```

The Python Script is as follows:

import os

files = ['./first.html','./second.html','./firstfile.txt'] #this array should be passed into python by the JS script
cal_array = [] #this array should be shared with JS after data has been entered into it
def calculation(): # this function calculates the number of lines, words and characters of the selected file(s)
    for val in files:
        file_details = []
        fname=(val)
        infile=open(fname, 'r')
        lines=0
        words=0
        characters=0
        for line in infile:
            line = line.strip(os.linesep)
            wordslist=line.split()
            lines=lines+1
            words=words+len(wordslist)
            characters=characters+ len(line)
        file_details.append(lines)
        file_details.append(words)
        file_details.append(characters)
        cal_array.append(file_details)

calculation()

print(cal_array)

# some code here to share cal_array with javascript```

I'm a noob in Python, but I want to know how to make the two languages interact with each other? I'll really appreciate any help!

答:
If what you want is to create a web-app, and then send the data from there to your server via. AJAX, where you will work on the data in Python, what you need is something like Flask.

If what you want is to create a web-app that also runs the Python code, you need a python interpreter written in JavaScript, something like pyjs

ContentLicense: CC BY-SA 4.0

Body:
I want to make a two way communication model for JavaScript and Python.
I want JavaScript to process a data and send it to Python and then Python processes it and sends it back to JavaScript. I don't have a clue how this can be achieved and how the communication between the two languages will be made.

Consider the example:

Read the comments for clarity of the model!

var files = [];
const div_files = document.getElementById("files");
const div_results = document.getElementById("results");

function fetchNames() {
  div_files.innerHTML = ""; // clears the file div
  div_results.innerHTML = ""; // clears the results div

  var checkbox_elements = document.getElementsByClassName('filename');

  Array.from(checkbox_elements).forEach(function(k) {
    if (k.checked) {

      files.push(k.value);
      div_files.innerHTML += k.value + '
';
    }

  });

  // the files array should now be shared with python

  //console.log(files);

  // JavaScript SHOULD WAIT while PYTHON processes the data and shares the cal_array with JS

  // when the cal_array is available with JS only then it shall start processing the code mentioned below

  var cal_array = [
    [2231, 11640, 104621],
    [2231, 11640, 104621],
    [9, 494, 3339]
  ];
  Array.from(cal_array).forEach(function(k) {
    div_results.innerHTML += k + '
';
  })

};

<form>
  <input type="checkbox" class="filename" value="./first.html">First File

  <input type="checkbox" class="filename" value="./second.html">Second File

  <input type="checkbox" class="filename" value="./third.html">Third File

  <input type="button" value="Submit" onclick="fetchNames()">
</form>

The selected file(s) are:

 The result shows the number of lines, words, and characters of the respective files mentioned above:

The Python Script is as follows:

import os

files = ['./first.html','./second.html','./firstfile.txt'] #this array should be passed into python by the JS script
cal_array = [] #this array should be shared with JS after data has been entered into it
def calculation(): # this function calculates the number of lines, words and characters of the selected file(s)
    for val in files:
        file_details = []
        fname=(val)
        infile=open(fname, 'r')
        lines=0
        words=0
        characters=0
        for line in infile:
            line = line.strip(os.linesep)
            wordslist=line.split()
            lines=lines+1
            words=words+len(wordslist)
            characters=characters+ len(line)
        file_details.append(lines)
        file_details.append(words)
        file_details.append(characters)
        cal_array.append(file_details)

calculation()

print(cal_array)

# some code here to share cal_array with javascript

I'm a noob in Python, but I want to know how to make the two languages interact with each other? I'll really appreciate any help!


问:
Yii2- How to align text on left and right side php
I want to align text on both the right and the left side. For solution I have looked into the text on left and right side of element. But it didn't worked for me.

What I have done?

```<code><section class="content">

<div>
    <div class="div1" style="text-align:left; float: left;">
        Date:
        <span style="padding-bottom: 10px; border-bottom: 1px solid black">
            <?php $model=$dataProvider->getModels()[0]; print_r($model['Date'])?>
        </span>

    </div>
    <div class="div2" style="text-align:right; float: right;">
        Reciept#:
        <span style="padding-bottom: 10px; border-bottom: 1px solid black">
            OGP-<?php $model=$dataProvider->getModels()[0]; print_r($model['OGP_Serial_No'])?>
        </span>

    </div>

</div>

</section>
</code>```

Output

As mentioned I already have checked for the solution.

Any help would be highly appreciated.

答: Add style display:block; for 'div1' and 'div2'

Body:
I want to align text on both the right and the left side. For solution I have looked into the text on left and right side of element. But it didn't worked for me.

What I have done?

        Date:

            <?php $model=$dataProvider->getModels()[0]; print_r($model['Date'])?>

        Reciept#:

            OGP-<?php $model=$dataProvider->getModels()[0]; print_r($model['OGP_Serial_No'])?>

Output

As mentioned I already have checked for the solution.

Any help would be highly appreciated.