问:
Hide Item in WPF ListView
I have a WPF XAML ListView which contains a GridView with two GridViewColumns.
The ListView has its ItemsSource bound to my class like so:

```<code><ListView Name="MyListView" ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type mynameSpace:MyClass}}, Path=ItemsSource}" >

<ListView.ItemContainerStyle>
    <Style TargetType="{x:Type ListViewItem}" BasedOn="{StaticResource ListViewItemStyle}">
        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        <Setter Property="VerticalContentAlignment" Value="Stretch"/>
        <!--<Setter Property="Visibility" Value="{Binding RelativeSource={RelativeSource Self}, Path=IsEnabled, Converter={StaticResource BoolToVisibility}}"></Setter>-->
        <Setter Property="Visibility" Value="{Binding Path=IsEnabled, Converter={StaticResource BoolToVisibility}}"/>
    </Style>
</ListView.ItemContainerStyle>
<ListView.View>
   <GridView>
        // blah blah
   </GridView>
</ListView>
</code>```

I am attempting to hide a ListView item based on a property IsEnabled so I have tried the two methods above but neither work as the item still appears in the ListView:

```<code><Setter Property="Visibility" Value="{Binding RelativeSource={RelativeSource Self}, Path=IsEnabled, Converter={StaticResource BoolToVisibility}}"></Setter>
<Setter Property="Visibility" Value="{Binding Path=IsEnabled, Converter={StaticResource BoolToVisibility}}"/>
</code>```

How can I hide an item in a list view like this?

答:
There is actually an alternative approach to this matter which does not touch any XAML code or the collection itself.

By utilizing the CollectionView of the source collection you can filter the items (and do other stuff like sorting and grouping) without changing the view or the model. Since in wpf ui elements never access collections directly, but through a collection view. That collection view inherits from ICollectionView and is either set automagically or can be set by the programmer.

To get to the default collection view use the following code somewhere when initializing your data.

```<code>var collectionView = CollectionViewSource.GetDefaultView(<List>);
collectionView.Filter = o => o.IsEnabled;
</code>```

Edit:
Nervermind, I didn't see the requirement for a xaml based solution.

Title: Hide Item in WPF ListView

Body:
I have a WPF XAML ListView which contains a GridView with two GridViewColumns.
The ListView has its ItemsSource bound to my class like so:

<ListView Name="MyListView" ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type mynameSpace:MyClass}}, Path=ItemsSource}" >

<ListView.ItemContainerStyle>

</ListView.ItemContainerStyle>
<ListView.View>
   <GridView>
        // blah blah
   </GridView>
</ListView>

I am attempting to hide a ListView item based on a property IsEnabled so I have tried the two methods above but neither work as the item still appears in the ListView:

<Setter Property="Visibility" Value="{Binding RelativeSource={RelativeSource Self}, Path=IsEnabled, Converter={StaticResource BoolToVisibility}}"></Setter>
<Setter Property="Visibility" Value="{Binding Path=IsEnabled, Converter={StaticResource BoolToVisibility}}"/>

How can I hide an item in a list view like this?

Body:
There is actually an alternative approach to this matter which does not touch any XAML code or the collection itself.

By utilizing the CollectionView of the source collection you can filter the items (and do other stuff like sorting and grouping) without changing the view or the model. Since in wpf ui elements never access collections directly, but through a collection view. That collection view inherits from ICollectionView and is either set automagically or can be set by the programmer.

To get to the default collection view use the following code somewhere when initializing your data.

var collectionView = CollectionViewSource.GetDefaultView(<List>);
collectionView.Filter = o => o.IsEnabled;

Edit:
Nervermind, I didn't see the requirement for a xaml based solution.


来源: stackexchange

问:
replace Dynamic string template variable with json object
I am having sample template like below i want to replace school, babydet.name,dept,babydet.section.secname with json object values how to do this please help me to solve this.

```<code>var Template1 = 'Welcome to the {{school}} baby {{babydet.name}}'
var Template2 = 'Welcome to the school {{school}} department {{dept}} babydetails {{babydet.name}} {{babydet.section.secname}}'

const namelist1= [{school:'GOVSchool',babydet: { name: 'shanker' }}];
const namelist2= [{school:'GOVSchool',dept:'CS',babydet: { name: 'shanker',section:{sectname:'A Section'}}}];
</code>```

with help of string replace need to achieve this(single logic). Output want like this "Welcome to the world baby shanker"

答:
I was doing something similar, the only difference is that my JSON object would not have nested properties.

I am using a simple approach (hopefully not too simplistic). It can accept any number of properties to be substituted in the HTML template.

Given a template:

```<code>let template =
  '<div><span>{{ text }}</span><span>{{description}}</span></div>';
</code>```

And some data:

```<code>let data = { text: 'My Text', description: 'my description' };
</code>```

I would get:

```<code><div><span>My Text</span><span>my description</span></div>
</code>```

See the implementation in JSBin here: https://jsbin.com/zelogof/7/edit?js,console

Better suggestions also welcome!

ContentLicense: CC BY-SA 3.0

Body:
I am having sample template like below i want to replace school, babydet.name,dept,babydet.section.secname with json object values how to do this please help me to solve this.

var Template1 = 'Welcome to the {{school}} baby {{babydet.name}}'
var Template2 = 'Welcome to the school {{school}} department {{dept}} babydetails {{babydet.name}} {{babydet.section.secname}}'

const namelist1= [{school:'GOVSchool',babydet: { name: 'shanker' }}];
const namelist2= [{school:'GOVSchool',dept:'CS',babydet: { name: 'shanker',section:{sectname:'A Section'}}}];

with help of string replace need to achieve this(single logic). Output want like this "Welcome to the world baby shanker"

Body:
I was doing something similar, the only difference is that my JSON object would not have nested properties.

I am using a simple approach (hopefully not too simplistic). It can accept any number of properties to be substituted in the HTML template.

Given a template:

let template =
  '<div><span>{{ text }}</span><span>{{description}}</span></div>';

And some data:

let data = { text: 'My Text', description: 'my description' };

I would get:

<div><span>My Text</span><span>my description</span></div>

See the implementation in JSBin here: https://jsbin.com/zelogof/7/edit?js,console

Better suggestions also welcome!


问:
selecting a set of objects based on index linq
Is there any way to select, from an array of for example 2000 elements, all the elements between the 100th(included) and the 200th(excluded) element without creating your own row index?</p>

答:
```<code>var pageItems = array.Skip(99).Take(100);
</code>```


问:
Find all customers who have an account at all branches located in Brooklyn
I have some tables:

"branch" table(branch_name, branch_city, assets)

"customer" table(customer_name, customer_street, customer_city)

"account" table (account_number, branch_name, balance)

"loan"table (loan_number, branch_name, amount)

"depositor"table (customer_name, account_number)

"borrower" table (customer_name, loan_number)

Now I want to find all customers who have an account at all branches located in Brooklyn. Here is my SQL for this problem. BUT I want to know how to use TABLE JOIN, and WITHOUT USING EXCEPT to solve this problem. CAN SOMEONE HELP ME ?????THANKS.

```<code>SELECT distinct S.customer_name FROM depositor as S
WHERE not exists (
     (SELECT branch_name
      FROM branch
      WHERE branch_city = 'Brooklyn')
      EXCEPT
      (SELECT R.branch_name
       FROM depositor as T, account as R
       WHERE T.account_number = R.account_number and
             S.customer_name = T.customer_name ))
</code>```

答:
```<code>Select A.customer_name
From depositor as A
Left join account as B
on B. account_number = A.account_number
group by A.customer_name
Having count(distinct(B.branch_name))  =
(select count(branch_name) from branch where branch_city = 'Brooklyn')
</code>```

Body:
I have some tables:

"branch" table(branch_name, branch_city, assets)

"customer" table(customer_name, customer_street, customer_city)

"account" table (account_number, branch_name, balance)

"loan"table (loan_number, branch_name, amount)

"depositor"table (customer_name, account_number)

"borrower" table (customer_name, loan_number)

Now I want to find all customers who have an account at all branches located in Brooklyn. Here is my SQL for this problem. BUT I want to know how to use TABLE JOIN, and WITHOUT USING EXCEPT to solve this problem. CAN SOMEONE HELP ME ?????THANKS.

SELECT distinct S.customer_name FROM depositor as S
WHERE not exists (
     (SELECT branch_name
      FROM branch
      WHERE branch_city = 'Brooklyn')
      EXCEPT
      (SELECT R.branch_name
       FROM depositor as T, account as R
       WHERE T.account_number = R.account_number and
             S.customer_name = T.customer_name ))


问:
implicit DataTemplates vs. sample data vs. blendability
I have two simple ViewModels, NodeViewModel and LeafViewModel that can be items in a TreeView. Just like below. Templates are applied implictly because I don't want a custom template selector.

```<code><UserControl x:Class="MyProject.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:ViewModels="clr-namespace:MyProject.ViewModels" mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300" d:DataContext="{d:DesignData /SampleData/NodeViewModelSampleData.xaml}">
 <UserControl.Resources>
  <HierarchicalDataTemplate DataType="{x:Type ViewModels:NodeViewModel}" ItemsSource={Binding Children}>
   <StackPanel Orientation="Horizontal">
    <CheckBox Content="{Binding Name}" IsChecked="{Binding Result}"/>
   </StackPanel>
  </HierarchicalDataTemplate>
  <HierarchicalDataTemplate DataType="{x:Type ViewModels:LeafViewModel}">
   <StackPanel Orientation="Horizontal">
    <TextBlock Text="{Binding Name}" />
   </StackPanel>
  </HierarchicalDataTemplate>
 </UserControl.Resources>
 <TreeView ItemsSource="{Binding Children}" />
</UserControl>
</code>```

How can I generate sample data in blend that contains a tree with both NodeViewModels and LeafViewModels and then display it as the data in the treeview while still using implict template selection?

答:
I think the answer is simple: You can't.

Blend doesn't really work well with implicit datatemplates and template selectors. This is not only true for sample data but also inplace wysiwyg template editing. So for blendability you should try to avoid implict templates and template selectors whenever you can.

ContentLicense: CC BY-SA 2.5

Body:
I have two simple ViewModels, NodeViewModel and LeafViewModel that can be items in a TreeView. Just like below. Templates are applied implictly because I don't want a custom template selector.

<UserControl x:Class="MyProject.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:ViewModels="clr-namespace:MyProject.ViewModels" mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300" d:DataContext="{d:DesignData /SampleData/NodeViewModelSampleData.xaml}">
 <UserControl.Resources>
  <HierarchicalDataTemplate DataType="{x:Type ViewModels:NodeViewModel}" ItemsSource={Binding Children}>
   <StackPanel Orientation="Horizontal">
    <CheckBox Content="{Binding Name}" IsChecked="{Binding Result}"/>
   </StackPanel>
  </HierarchicalDataTemplate>
  <HierarchicalDataTemplate DataType="{x:Type ViewModels:LeafViewModel}">
   <StackPanel Orientation="Horizontal">
    <TextBlock Text="{Binding Name}" />
   </StackPanel>
  </HierarchicalDataTemplate>
 </UserControl.Resources>
 <TreeView ItemsSource="{Binding Children}" />
</UserControl>

How can I generate sample data in blend that contains a tree with both NodeViewModels and LeafViewModels and then display it as the data in the treeview while still using implict template selection?


问:
django check if the uploaded file is a zip file
I have a handler for a POST method in Django which receives an uploaded file. What I would like to do is verify that the file is a valid zip file before proceeding.

So, I have:

```<code>@login_required(login_url="login/")
def upload(request):
    if request.method == 'POST' and request.FILES['upload_file']:
        uploaded_file = request.FILES['upload_file']
        print type(uploaded_file)

    return render(request, 'upload.html', {'context': RequestContext(request)})
</code>```

Now at this point uploaded_file is of type <class 'django.core.files.uploadedfile.InMemoryUploadedFile'>. My question is what would be the best way to verify that this is a valid archive? Do I need to save it to the disk and then use the zipfile module or is there some way to do it without writing to the disk?

Note: I am not using the Django model with a FileField and the corresponding Form for various unrelated reasons.

答:
Yes, you should use zipfile module.

zipfile.is_zipfile(filename)

Returns True if filename is a valid ZIP file based on its magic number, otherwise returns False. filename may be a file or file-like object too.
(Changed in version 3.1: Support for file and file-like objects.)

Another option:(not likely but your choice)

How to detect type of compression used on the file? (if no file extension is specified)

You can find the header formats in the descriptions:

Zip (.zip) format description, starts with 0x50, 0x4b, 0x03, 0x04 (unless empty — then the last two are 0x05, 0x06 or 0x06, 0x06)

Body:
I have a handler for a POST method in Django which receives an uploaded file. What I would like to do is verify that the file is a valid zip file before proceeding.

So, I have:

@login_required(login_url="login/")
def upload(request):
    if request.method == 'POST' and request.FILES['upload_file']:
        uploaded_file = request.FILES['upload_file']
        print type(uploaded_file)

    return render(request, 'upload.html', {'context': RequestContext(request)})

Now at this point uploaded_file is of type <class 'django.core.files.uploadedfile.InMemoryUploadedFile'>. My question is what would be the best way to verify that this is a valid archive? Do I need to save it to the disk and then use the zipfile module or is there some way to do it without writing to the disk?

Note: I am not using the Django model with a FileField and the corresponding Form for various unrelated reasons.


问:
sub string replacment in PHP
I have a string like:
$string = "/physics/mechanics/vectors/P-M-C (1).doc";

I want to get like this:

"/physics/mechanics/vectors/1-P-M-C (1).doc";

Please note that "1-" is added just before P in the original string.

Is it possible in PHP?
How the function in PHP should be used?

答: Take a look at explode() and join() for this. :)

Title: sub string replacment in PHP


问:
PHP array_search for multi dimensional array and return key
I'm trying to search for a value in a multi dimensional array (below is only a part of the big array) and get the key for that value but I can't manage it by myself. Here is what I have tried :

```<code>Array
(
    [0] => Array
        (
            [0] => SMEG - 30
            [1] => ALES
            [2] => -
            [3] => -
            [4] => -
            [5] => ALES
            [6] => 44-
            [7] => -
            [8] => FR*S30*E36*1*1
            [9] => FR*S30*E36*1*1
            [10] => US*S30
            [11] => Oui
            [12] => 3376
            [13] => Normale
            [14] => -
        )

    [1] => Array  // <-- wanted key
        (
            [0] => SMEG - 30
            [1] => ALES
            [2] => -
            [3] => Chemin Des Sports
            [4] => -
            [5] => ALES
            [6] => -
            [7] => -
            [8] => FR*S30*E37*2*1  // <-- wanted value
            [9] => FR*S30*E37*2*1
            [10] => FR*S30
            [11] => Oui
            [12] => 33762
            [13] => Normale
            [14] => -
        )

    [2] => Array
        (
            [0] => SMEG - 30
            [1] => ALES
            [2] => 0
            [3] => Ecole Des Mines
            [4] => -
            [5] => ALES
            [6] => 4-
            [7] => -
            [8] => FR*S30*E38*2*1
            [9] => FR*S30*E38*2*1
            [10] => FR*S30
            [11] => Oui
            [12] => 3376
            [13] => Normale
            [14] => -
        )
)

$key = array_search("FR*S30*E37*2*1", array_column($data, '8'));
var_dump($data[$key]);
</code>```

With this code I can't get the key of desired array. What am I doing wrong ?

Body:
I'm trying to search for a value in a multi dimensional array (below is only a part of the big array) and get the key for that value but I can't manage it by myself. Here is what I have tried :

Array
(
    [0] => Array
        (
            [0] => SMEG - 30
            [1] => ALES
            [2] => -
            [3] => -
            [4] => -
            [5] => ALES
            [6] => 44-
            [7] => -
            [8] => FR*S30*E36*1*1
            [9] => FR*S30*E36*1*1
            [10] => US*S30
            [11] => Oui
            [12] => 3376
            [13] => Normale
            [14] => -
        )

    [1] => Array  // <-- wanted key
        (
            [0] => SMEG - 30
            [1] => ALES
            [2] => -
            [3] => Chemin Des Sports
            [4] => -
            [5] => ALES
            [6] => -
            [7] => -
            [8] => FR*S30*E37*2*1  // <-- wanted value
            [9] => FR*S30*E37*2*1
            [10] => FR*S30
            [11] => Oui
            [12] => 33762
            [13] => Normale
            [14] => -
        )

    [2] => Array
        (
            [0] => SMEG - 30
            [1] => ALES
            [2] => 0
            [3] => Ecole Des Mines
            [4] => -
            [5] => ALES
            [6] => 4-
            [7] => -
            [8] => FR*S30*E38*2*1
            [9] => FR*S30*E38*2*1
            [10] => FR*S30
            [11] => Oui
            [12] => 3376
            [13] => Normale
            [14] => -
        )
)

$key = array_search("FR*S30*E37*2*1", array_column($data, '8'));
var_dump($data[$key]);

With this code I can't get the key of desired array. What am I doing wrong ?

Body:
PHP code demo

<?php
$array=Array
(
    0=>   Array
        (
            0=>   "SMEG - 30",
            1=>   "ALES",
            2=>   "-",
            3=>   "-",
            4=>   "-",
            5=>   "ALES",
            6=>   "44-",
            7=>   "-",
            8=>   "FR*S30*E36*1*1",
            9=>   "FR*S30*E36*1*1",
            10=>   "US*S30",
            11=>   "Oui",
            12=>   "3376",
            13=>   "Normale",
            14=>   "-"
        ),

    1=>   Array
        (
            0=>   "SMEG - 30",
            1=>   "ALES",
            2=>   "-",
            3=>   "Chemin Des Sports",
            4=>   "-",
            5=>   "ALES",
            6=>   "-",
            7=>   "-",
            8=>   "FR*S30*E37*2*1",
            9=>   "FR*S30*E37*2*1",
            10=>   "FR*S30",
            11=>   "Oui",
            12=>   "33762",
            13=>   "Normale",
            14=>   "-",
        ),

    2=>   Array
        (
            0=>   "SMEG - 30",
            1=>   "ALES",
            2=>   "0",
            3=>   "Ecole Des Mines",
            4=>   "-",
            5=>   "ALES",
            6=>   "4-",
            7=>   "-",
            8=>   "FR*S30*E38*2*1",
            9=>   "FR*S30*E38*2*1",
            10=>   "FR*S30",
            11=>   "Oui",
            12=>   "3376",
            13=>   "Normale",
            14=>   "-",
        )
);
$requiredKey=null;
$requiredValue=null;
finder($array,"FR*S30*E37*2*1");
function finder($array,$search)
{
    global $requiredKey,$requiredValue;
    foreach($array as $key => $value)
    {
        if(in_array($search, $value))
        {
            $requiredKey=$key;
            $requiredValue=$search;
            break;
        }
    }
}
echo $requiredKey;
echo $requiredValue;


问:
calculate checksum hex in Python 3
I want to calculate checksum. The process I want to do like below;

Step-1

```<code>a="10F8000041303131303030353000000000000000"
</code>```

Step-2

```<code>10+F8+00+00+41+30+31+31+30+30+30+35+30+00+00+00+00+00+00+00 = D0
</code>```

Step-3

```<code>~D0 = 2F -> 2F + 1 = 30
</code>```

I tried that;

```<code>def calc_checksum_two(s):
return '%2X' % (-(sum(ord(c) for c in s) % 256) & 0xFF)
print(calc_checksum_two(a))
</code>```

Result;

```<code>3D
</code>```

答:
with s="10F8000041303131303030353000000000000000, sum(ord(c) for c in s) will sum each ord value of each character. This will sums [ord('1'), ord('0'), ord('F'), ...]. This is not what you wanted.

to build array of bytes from that string you should instead using:

```<code>[ a[i:i+2]] for i in range(0, len(a), 2) ]
</code>```

this will create an array like this: ['10', 'F8', '00', ...]

Then to convert string hex/base16 to integer use int(hex_string,16)

That should do it, but here is the function

```<code>def calc_checksum_two(a):
    return hex(((sum(int(a[i:i+2],16) for i in range(0, len(a), 2))%0x100)^0xFF)+1)[2:]
</code>```

Title: calculate checksum hex in Python 3

Body:
I want to calculate checksum. The process I want to do like below;

Step-1

a="10F8000041303131303030353000000000000000"

Step-2

10+F8+00+00+41+30+31+31+30+30+30+35+30+00+00+00+00+00+00+00 = D0

Step-3

~D0 = 2F -> 2F + 1 = 30

I tried that;

def calc_checksum_two(s):
return '%2X' % (-(sum(ord(c) for c in s) % 256) & 0xFF)
print(calc_checksum_two(a))

Result;

3D

Body:
with s="10F8000041303131303030353000000000000000, sum(ord(c) for c in s) will sum each ord value of each character. This will sums [ord('1'), ord('0'), ord('F'), ...]. This is not what you wanted.

to build array of bytes from that string you should instead using:

[ a[i:i+2]] for i in range(0, len(a), 2) ]

this will create an array like this: ['10', 'F8', '00', ...]

Then to convert string hex/base16 to integer use int(hex_string,16)

That should do it, but here is the function

def calc_checksum_two(a):
    return hex(((sum(int(a[i:i+2],16) for i in range(0, len(a), 2))%0x100)^0xFF)+1)[2:]


问:
Handle errors thrown by require() module in node.js
having a bit of a snag in my code when trying to require() modules that don't exists.
The code loops through a directory and does a var appname = require('path') on each folder. This works for appropriately configured modules but throws: Error: Cannot find module when the loop hits a non-module.

I want to be able to handle this error gracefully, instead of letting it stop my entire process. So in short, how does one catch an error thrown by require()?

thanks!

答:
If the issue is with files that don't exist, what you should do is:</p>

```<code>let fs = require('fs');
let path = require('path');
let requiredModule = null; // or a default object {}

let pathToModule = path.join(__dirname, /* path to module */, 'moduleName');
if (fs.existsSync(pathToModule)) {
  requiredModule = require(pathToModule);
}

// This is in case the module is in node_modules
pathToModule = path.join(__dirname, 'node_modules', 'moduleName');
if (fs.existsSync(pathToModule)) {
  requiredModule = require(pathToModule);
}
</code>```

Body:
If the issue is with files that don't exist, what you should do is:

let fs = require('fs');
let path = require('path');
let requiredModule = null; // or a default object {}

let pathToModule = path.join(__dirname, /* path to module */, 'moduleName');
if (fs.existsSync(pathToModule)) {
  requiredModule = require(pathToModule);
}

// This is in case the module is in node_modules
pathToModule = path.join(__dirname, 'node_modules', 'moduleName');
if (fs.existsSync(pathToModule)) {
  requiredModule = require(pathToModule);
}


问:
Taking a sample of a CSV?
I have a program converting a CSV to a valid JSON file.

I would like to change it to take a random subset of my CSV file (as its 50k lines) and make a JSON from this. Here is my code so far -

```<code>import csv
import json

csvfile = open('C:\\Users\\ADMIN\\Desktop\\CSV_1.csv', 'r')
jsonfile = open('C:\\Users\\ADMIN\\Desktop\\Testing\\file.json', 'w')

with open('C:\\Users\\ADMIN\\Desktop\\CSV_1.csv') as f:
    reader = csv.DictReader(f)
    rows = list(reader)

with open('C:\\Users\\ADMIN\\Desktop\\Testing\\file.json', 'w') as f:
    json.dump(rows, f)
</code>```

What's the most efficient way to do this?

Thanks.

答:
If you want a sample having a determinated number of lines, as proposed by Satish Garg, the build in tool for that is random.sample.
The problem is that a file object is indeed iterable, but is not a sequence: no len method, no direct indexing.

If you have enough memory and if the csv file can easily fit in, the simpler way is to load everything in a list with reader.readlines() and then take a subset with random.sample. Alternatively, you could read the file once to get its length, choose the line numbers to compose the sample with:

```<code>line_numbers_to_keep = sorted(random.sample(range(file_length), size_of_sample))
</code>```

You can then build the sample with:

```<code>sample = []
index = 0
for i, row in enumerate(csv_reader):
    if i >= line_numbers_to_keep[index]:
        sample.append(row)
        index += 1
</code>```

If you want a sample of a determinated fraction of the original file, say 1/n, a simple trick would be to skip a random number in the range [0;2*n-1)

```<code>next = random.randrange(2*n-1)
sample = []
for i, row in enumerate(csv_reader):
    if i >= next:
        sample.append(row)
        next = i + random.randrange(2*n-1)
</code>```

You will not get the exact fraction, but statistically it should not be far and with an acceptable randomisation.

Title: Taking a sample of a CSV?

Body:
I have a program converting a CSV to a valid JSON file.

I would like to change it to take a random subset of my CSV file (as its 50k lines) and make a JSON from this. Here is my code so far -

import csv
import json

csvfile = open('C:\\Users\\ADMIN\\Desktop\\CSV_1.csv', 'r')
jsonfile = open('C:\\Users\\ADMIN\\Desktop\\Testing\\file.json', 'w')

with open('C:\\Users\\ADMIN\\Desktop\\CSV_1.csv') as f:
    reader = csv.DictReader(f)
    rows = list(reader)

with open('C:\\Users\\ADMIN\\Desktop\\Testing\\file.json', 'w') as f:
    json.dump(rows, f)

What's the most efficient way to do this?

Thanks.

Body:
If you want a sample having a determinated number of lines, as proposed by Satish Garg, the build in tool for that is random.sample.
The problem is that a file object is indeed iterable, but is not a sequence: no len method, no direct indexing.

If you have enough memory and if the csv file can easily fit in, the simpler way is to load everything in a list with reader.readlines() and then take a subset with random.sample. Alternatively, you could read the file once to get its length, choose the line numbers to compose the sample with:

line_numbers_to_keep = sorted(random.sample(range(file_length), size_of_sample))

You can then build the sample with:

sample = []
index = 0
for i, row in enumerate(csv_reader):
    if i >= line_numbers_to_keep[index]:
        sample.append(row)
        index += 1

If you want a sample of a determinated fraction of the original file, say 1/n, a simple trick would be to skip a random number in the range [0;2*n-1)

next = random.randrange(2*n-1)
sample = []
for i, row in enumerate(csv_reader):
    if i >= next:
        sample.append(row)
        next = i + random.randrange(2*n-1)

You will not get the exact fraction, but statistically it should not be far and with an acceptable randomisation.


问:
Loop zip, append in Python
I am strugling with something in python...

I have a function that when I input a date, it gives me back a column with 30 prices (one in each line) and in index 30 names.

```<code>[in] getPrice('14/07/2015')

[out]
apple   10
pear    20
orange  12
banana  23
etc...
</code>```

The number of fruit are the same.
What I am trying to do is, to loop this function to obtain a big file with the price of these fruits for all the days I have in a list.
with the ZIP function I dont really understand how it could work and with the append function it is not 'zipping' the price, meaning it recreate everytime the index, etc..
Any idea?
I have a list with all my dates already and the index is the same all along, no other fruit apprear or disapear.

It could look like something

```<code>Def Alltogether():
    Alltogether = []
    x = HistoricalDates
    For _ in Historicaldates :
        k = getPrice....
</code>```

and then I block...

I ultimately want something like

```<code>print Alltogether

[out]
apple   10 40 60 20 ...
pear    20 20 20 20 ...
orange  12 13 14 29 ...
banana  23 14 41 54 ...
etc...
</code>```

I am using panda dataframe.

Thank you very much!

答:
This could probably be streamlined by changing the format you get your data in, but here's an example that should get you on your way. I'm totally skipping the zip approach and doing this in more of a Pandas way. For testing I created a dummy function to return random prices for a fixed set of produce:

```<code>import pandas as pd
def getPrice(date):
    return pd.Series(np.random.randn(5), index=['apple', 'pear', 'orange', 'nanner', 'etc...'])
</code>```

And then we can create a pandas dataframe with some dates in it:

```<code>df = pd.DataFrame( pd.date_range('1/1/2017', periods=3, freq='D') )
df.columns=['MyDate'] # name the date column
</code>```

That gives us a simple df with 3 dates:

```<code>      MyDate
0 2017-01-01
1 2017-01-02
2 2017-01-03
</code>```

While iterating over rows is a little less idiomatic than some sort of apply function, I think it's very readable and easy to comprehend to simply iterate over the dates, get the prices, then shove them into a new dataframe and name the column the same as the date. Given your question, I suspect this is your desired output.

```<code>outputDF = pd.DataFrame() ## dump results into this df

for index, row in df.iterrows(): #iterate through every row of the date df
    outputDF[row.MyDate] = getPrice(row.MyDate) #shove values into output
</code>```

which gives us a pretty df like this:

```<code>        2017-01-01  2017-01-02  2017-01-03
apple     0.150646    0.209668    0.398204
pear      0.131142    0.046473   -0.261545
orange    0.822508    0.456384   -0.774957
nanner   -0.996102   -0.260049   -0.558503
etc...    0.622459   -0.173556   -0.681957
</code>```

Per your comment about handling situations where the date is invalid, there are a few ways to handle this. If the getPrice() function throws an error when you pass it a bad date, you might use try/except:

```<code>try:
    getPrice(date)
except:
    # do something else... return nulls maybe?
</code>```

if bad dates don't throw an error but instead they return nulls or an empty list, then just check for that condition after calling getPrice() but before putting it in the dataframe.

Title: Loop zip, append in Python

Body:
I am strugling with something in python...

I have a function that when I input a date, it gives me back a column with 30 prices (one in each line) and in index 30 names.

[in] getPrice('14/07/2015')

[out]
apple   10
pear    20
orange  12
banana  23
etc...

The number of fruit are the same.
What I am trying to do is, to loop this function to obtain a big file with the price of these fruits for all the days I have in a list.
with the ZIP function I dont really understand how it could work and with the append function it is not 'zipping' the price, meaning it recreate everytime the index, etc..
Any idea?
I have a list with all my dates already and the index is the same all along, no other fruit apprear or disapear.

It could look like something

Def Alltogether():
    Alltogether = []
    x = HistoricalDates
    For _ in Historicaldates :
        k = getPrice....

and then I block...

I ultimately want something like

print Alltogether

[out]
apple   10 40 60 20 ...
pear    20 20 20 20 ...
orange  12 13 14 29 ...
banana  23 14 41 54 ...
etc...

I am using panda dataframe.

Thank you very much!

Body:
This could probably be streamlined by changing the format you get your data in, but here's an example that should get you on your way. I'm totally skipping the zip approach and doing this in more of a Pandas way. For testing I created a dummy function to return random prices for a fixed set of produce:

import pandas as pd
def getPrice(date):
    return pd.Series(np.random.randn(5), index=['apple', 'pear', 'orange', 'nanner', 'etc...'])

And then we can create a pandas dataframe with some dates in it:

df = pd.DataFrame( pd.date_range('1/1/2017', periods=3, freq='D') )
df.columns=['MyDate'] # name the date column

That gives us a simple df with 3 dates:

      MyDate
0 2017-01-01
1 2017-01-02
2 2017-01-03

While iterating over rows is a little less idiomatic than some sort of apply function, I think it's very readable and easy to comprehend to simply iterate over the dates, get the prices, then shove them into a new dataframe and name the column the same as the date. Given your question, I suspect this is your desired output.

outputDF = pd.DataFrame() ## dump results into this df

for index, row in df.iterrows(): #iterate through every row of the date df
    outputDF[row.MyDate] = getPrice(row.MyDate) #shove values into output

which gives us a pretty df like this:

        2017-01-01  2017-01-02  2017-01-03
apple     0.150646    0.209668    0.398204
pear      0.131142    0.046473   -0.261545
orange    0.822508    0.456384   -0.774957
nanner   -0.996102   -0.260049   -0.558503
etc...    0.622459   -0.173556   -0.681957

Per your comment about handling situations where the date is invalid, there are a few ways to handle this. If the getPrice() function throws an error when you pass it a bad date, you might use try/except:

try:
    getPrice(date)
except:
    # do something else... return nulls maybe?

if bad dates don't throw an error but instead they return nulls or an empty list, then just check for that condition after calling getPrice() but before putting it in the dataframe.


问:
How to replace an entire Pandas DataFrame row if all values equal np.NaN
Example Code & Output:

```<code>data_country1 = {'Country': [np.NaN, 'India', 'Brazil'],
                 'Capital': [np.NaN, 'New Delhi', 'Brasília'],
                 'Population': [np.NaN, 1303171035, 207847528]}

df_country1 = pd.DataFrame(data_country1, columns=['Country', 'Capital', 'Population'])

data_country2= {'Country': ['Belgium', 'India', 'Brazil'],
                'Capital': ['Brussels', 'New Delhi', 'Brasília'],
                'Population': [102283932, 1303171035, 207847528]}

df_country2 = pd.DataFrame(data_country2, columns=['Country', 'Capital', 'Population'])

print(df_country1)
print(df_country2)

  Country    Capital    Population
0     NaN        NaN           NaN
1   India  New Delhi  1.303171e+09
2  Brazil   Brasília  2.078475e+08

   Country    Capital  Population
0  Belgium   Brussels   102283932
1    India  New Delhi  1303171035
2   Brazil   Brasília   207847528
</code>```

In the first DataFrame, for every row that is comprised of ALL NaN, I want to replace the entire row with a row from another dataframe.  In this example, row 0 from the second dataframe, so that the first df ends up with the same information as the second dataframe.

答:
I will join the two dataframes:</p>

```<code>data_complete=pd.merge(df_country1.dropna(),df_country2,on=['Country','Capital','Population'],how='outer')
</code>```

Body:
Example Code & Output:

data_country1 = {'Country': [np.NaN, 'India', 'Brazil'],
                 'Capital': [np.NaN, 'New Delhi', 'Brasília'],
                 'Population': [np.NaN, 1303171035, 207847528]}

df_country1 = pd.DataFrame(data_country1, columns=['Country', 'Capital', 'Population'])

data_country2= {'Country': ['Belgium', 'India', 'Brazil'],
                'Capital': ['Brussels', 'New Delhi', 'Brasília'],
                'Population': [102283932, 1303171035, 207847528]}

df_country2 = pd.DataFrame(data_country2, columns=['Country', 'Capital', 'Population'])

print(df_country1)
print(df_country2)

  Country    Capital    Population
0     NaN        NaN           NaN
1   India  New Delhi  1.303171e+09
2  Brazil   Brasília  2.078475e+08

   Country    Capital  Population
0  Belgium   Brussels   102283932
1    India  New Delhi  1303171035
2   Brazil   Brasília   207847528

In the first DataFrame, for every row that is comprised of ALL NaN, I want to replace the entire row with a row from another dataframe.  In this example, row 0 from the second dataframe, so that the first df ends up with the same information as the second dataframe.

Body:
I will join the two dataframes:

data_complete=pd.merge(df_country1.dropna(),df_country2,on=['Country','Capital','Population'],how='outer')


问:
create a Property-Sheet that can Add-Reference in Visual Studio 2015
Is it possible to Add Reference to a project in Visual Studio 2015 using Property Sheet?

 How?

This below image (Add Reference) is what I want, but I want to do it using Property Sheet.

This feature probably doesn't exist anymore :-

https://msdn.microsoft.com/en-us/library/669zx6zc.aspx

The Common Properties configurations in earlier versions of Visual
  Studio have been removed. To add a reference to a project, you now use
  the Add Reference dialog in the same way as for managed languages. See
  Managing references in a project.

Is there still a workaround?

I want to create a magic property-sheet, then "just include a certain property-sheet, and everything will work!" (without need to Add References manually).

It can also reduce cost to maintain / refactor project.

答:
The only thing Add Reference in VS does is adding something like this

```<code><ItemGroup>
  <ProjectReference Include="path\to\project.vcxproj">
    <Project>{e4abca85-42b0-4168-a628-e2287b9a8763}</Project>
  </ProjectReference>
</ItemGroup>
</code>```

to the project file. That is just standard msbuild code so you can put it in a property sheet (which after all is just another name for an 'msbuild file') like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup>
    <ProjectReference Include="path\to\project.vcxproj">
      <Project>{e4abca85-42b0-4168-a628-e2287b9a8763}</Project>
    </ProjectReference>
  </ItemGroup>
</Project>
</code>```

and it would have the same effect; when building, that is. It doesn't play well with the gui in VS though: it will see the reference but I don't think it is able to modify it (like setting CopyLocal) in the property sheet so adjustments liek that have to be done manually. Then again, seems like a small price to pay if you want the reusability a property sheet offers.

Body:
The only thing Add Reference in VS does is adding something like this

<ItemGroup>
  <ProjectReference Include="path\to\project.vcxproj">
    <Project>{e4abca85-42b0-4168-a628-e2287b9a8763}</Project>
  </ProjectReference>
</ItemGroup>

to the project file. That is just standard msbuild code so you can put it in a property sheet (which after all is just another name for an 'msbuild file') like this:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup>
    <ProjectReference Include="path\to\project.vcxproj">
      <Project>{e4abca85-42b0-4168-a628-e2287b9a8763}</Project>
    </ProjectReference>
  </ItemGroup>
</Project>

and it would have the same effect; when building, that is. It doesn't play well with the gui in VS though: it will see the reference but I don't think it is able to modify it (like setting CopyLocal) in the property sheet so adjustments liek that have to be done manually. Then again, seems like a small price to pay if you want the reusability a property sheet offers.


问:
Dashed line border around UIView
How do I add dashed line border around UIView.

Something Like this

答:
For Xamarin.iOS dashed/dotted border.</p>

```<code>        dottedLayer = new CAShapeLayer();
        dottedLayer.StrokeColor = UIColor.FromRGB(202, 202, 208).CGColor;
        dottedLayer.FillColor = null;
        dottedLayer.LineDashPattern = new[] { new NSNumber(4), new NSNumber(2) };

        dottedLayer.Path = UIBezierPath.FromRect(YourView.Bounds).CGPath; //for square
        dottedLayer.Path = UIBezierPath.FromRoundedRect(YourView.Bounds, 5).CGPath; //for rounded corners

        dottedLayer.Frame = YourView.Bounds;
        YourView.Layer.AddSublayer(dottedLayer);
</code>```

Title: Dashed line border around UIView

Body:
For Xamarin.iOS dashed/dotted border.

        dottedLayer = new CAShapeLayer();
        dottedLayer.StrokeColor = UIColor.FromRGB(202, 202, 208).CGColor;
        dottedLayer.FillColor = null;
        dottedLayer.LineDashPattern = new[] { new NSNumber(4), new NSNumber(2) };

        dottedLayer.Path = UIBezierPath.FromRect(YourView.Bounds).CGPath; //for square
        dottedLayer.Path = UIBezierPath.FromRoundedRect(YourView.Bounds, 5).CGPath; //for rounded corners

        dottedLayer.Frame = YourView.Bounds;
        YourView.Layer.AddSublayer(dottedLayer);


问:
Convert HTML with scripts to RTF
I want to convert HTML file to RTF File. It seems easy while working with simple HTML file. But my file contains some scripts which run at page load. Hence, not able to get proper HTML.

I checked with plenty of online tool & converters but none of them support scripting.

Does anyone know a solution?

答: Run the website - then take the output which is HTML (using I.E. its View -> Source)

Title: Convert HTML with scripts to RTF


问:
How to use Sizmek
I have been creating some html5 ads which all work ok. The ad provider I am using is asking me to create the tracking with sizmek. I have incorporated EBloader file and my code looks like this...

```<code>    <script type="text/javascript" src="js/EBloader.js"></script>
    <script type="text/javascript">
    function initEB(){
     if (!EB.isInitialized()) {
       EB.addEventListener(EBG.EventName.EB_INITIALIZED, startAdDS);
     }
     else {
       startAdDS();
     }
    }

    function startAdDS() {
      document.getElementById("banner").style.visibility = "visible";
    }

    function handleClickthroughButtonClick() {
      EB.clickthrough();
    }
   </script>
</code>```

I have also done a console log to make sure everything work and it seems fine.

The problem is that the ad provider has told me there is code missing from the sizmek export but as I didn't use sizmek to create the ads I have just incorporated the code it appears things are missing.

My question is, how would you create sizmek ads and how can I make a standard html5 ad sizmek compliant?

This is vague I know but then it comes to dealing with sizmek I am basic at best.

答:
Are you actually calling your initEB function? I think sizmek recommends that you attach a listener to the window.onload event.

Try adding window.addEventListener('load', initEB);

Other than that, ask them to specify what is missing? Usually clicktracking is all people want, but sizmek has a bunch of tracking features that you can call from within a creative.

Title: How to use Sizmek

Body:
I have been creating some html5 ads which all work ok. The ad provider I am using is asking me to create the tracking with sizmek. I have incorporated EBloader file and my code looks like this...

I have also done a console log to make sure everything work and it seems fine.

The problem is that the ad provider has told me there is code missing from the sizmek export but as I didn't use sizmek to create the ads I have just incorporated the code it appears things are missing.

My question is, how would you create sizmek ads and how can I make a standard html5 ad sizmek compliant?

This is vague I know but then it comes to dealing with sizmek I am basic at best.


问:
How to reverse vaadin Grid?
I'm trying to build a simple java application using Spring Boot and Vaadin.
I need to add a table on UI like this: https://www.screencast.com/t/1c4xkr4IE

It could be extended by periods.

Looks like Vaadin Grid element perfectly fits my requirements, but it adds my rows as columns. Is it possible to reverse grid or maybe there is another way to build needed table?

UPDATE

Here are my code:

```<code>@SpringComponent
@UIScope
public class MyDataEditor extends VerticalLayout {
private final MyDataRepository repository;
private MyData myData;

TextField month = new TextField("Period");
TextField numberOfWorkers = new TextField(" Number of workers");
TextField numberOfNewcomers = new TextField("Number of newcomers");
TextField numberOfDismissals = new TextField("Number of dismissals");

Button save = new Button("Save");
Button cancel = new Button("Cancel");
Button delete = new Button("Delete");
CssLayout actions = new CssLayout(save, cancel, delete);

Binder<MyData> binder = new Binder<>(MyData.class);

@Autowired
public MyDataEditor(MyDataRepository repository) {
    this.repository = repository;
    addComponents(month, numberOfWorkers, numberOfNewcomers, numberOfDismissals, actions);
    binder.bindInstanceFields(this);
    setSpacing(true);
    actions.setStyleName(ValoTheme.LAYOUT_COMPONENT_GROUP);
    save.setStyleName(ValoTheme.BUTTON_PRIMARY);
    save.setClickShortcut(ShortcutAction.KeyCode.ENTER);

    save.addClickListener(e -> repository.save(myData));
    delete.addClickListener(e -> repository.delete(myData));
    cancel.addClickListener(e -> editInputData(myData));
    setVisible(false);
}

public interface ChangeHandler {
    void onChange();
}

public final void editMyData(MyData c) {
    if (c == null) {
        setVisible(false);
        return;
    }
    final boolean persisted = c.getMonth() != null;
    if (persisted) {
        myData = repository.findOne(c.getMonth());
    } else {
        myData = c;
    }
    cancel.setVisible(persisted);
    binder.setBean(myData);
    save.focus();
    periodId.selectAll();
}

public void setChangeHandler(ChangeHandler h) {
    save.addClickListener(e -> h.onChange());
    delete.addClickListener(e -> h.onChange());
}

}

@SpringUI
@Theme("valo")
public class VaadinUI extends UI {
private final MyDataRepository repo;
private final MyDataEditor editor;
final Grid<MyData> grid;
private final Button addNewBtn;

@Autowired
public VaadinUI(MyDataRepository repo, MyDataEditor editor) {
    this.repo = repo;
    this.editor = editor;
    this.grid = new Grid<>(MyData.class);
    this.addNewBtn = new Button("Add new month");
}

@Override
protected void init(VaadinRequest request) {

    grid.setHeight(300, Unit.PIXELS);
    grid.setColumns("month", "numberOfWorkers", "numberOfNewcomers", "numberOfDismissals");
    grid.asSingleSelect().addValueChangeListener(e -> {
        editor.editMyData(e.getValue());
    });
    addNewBtn.addClickListener(e -> editor.editMyData(new MyData()));
    editor.setChangeHandler(() -> {
        editor.setVisible(false);
        grid.setItems(repo.findAll());
    });
}
}
</code>```

So what I mean by this question is that I set

```<code>grid.setColumns("month", "numberOfWorkers", "numberOfNewcomers", "numberOfDismissals");
</code>```

and do not find out method like setRows, so my table looks like: https://www.screencast.com/t/ndDY6tXp, but should be like on first picture.

答:
I believe the Vaadin grid (or table) component was designed having the table concept as a starting point. Hence you'd have a unified structure defined by the columns and display any number of same-type data elements, 1 per row. And as far as I know, up to 8.0.4, you can't rotate the structure.

Furthermore, from the user experience perspective, if you have multiple time periods, it'll be easier to scroll them vertically (with the mouse wheel) than horizontally, so I'd suggest discussing the possibility of displaying them just as you started, with the "month", "numberOfWorkers", "numberOfNewcomers" and "numberOfDismissals" columns, and supplying rows of MyData. This also makes it easier to sort, filter, add or edit selected items, whereas for the workaround below, you'd have to do something extra.

If for some reason that's not acceptable at all, you should be able to fake the feature you want with a bit of work (see below sample), but performance and usability wise, there's no guarantees... after all, this is not what it's been designed for.

Code

```<code>package com.example.grid;

import com.vaadin.data.ValueProvider;
import com.vaadin.ui.Grid;
import com.vaadin.ui.Notification;
import com.vaadin.ui.VerticalLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.function.Function;

public class HorizontalGrid extends VerticalLayout {

    private static final String ROW_CAPTION = "row-caption";

    public HorizontalGrid() {
        // basic grid setup without column header
        Grid<HorizontalDisplayAdapter> grid = new Grid<>();
        grid.setSizeFull();
        grid.setSelectionMode(Grid.SelectionMode.NONE);
        grid.removeHeaderRow(0);

        // load some data from the DB or someplace else
        List<PeriodSummary> periods = loadPeriods();

        // add row headers
        grid.addColumn(HorizontalDisplayAdapter::getCaption).setId(ROW_CAPTION).setWidth(150);

        // add a column for each period
        for (int i = 0; i < periods.size(); i++) {
            // save the column index so we ca figure out what to edit later
            grid.addColumn(new AdapterValueProvider(i)).setId(String.valueOf(i)).setWidth(60);
        }

        // wrap the data in "horizontal display adapters"
        grid.setItems(
                new HorizontalDisplayAdapter("Period", periods, PeriodSummary::getPeriod),
                new HorizontalDisplayAdapter("Workers", periods, PeriodSummary::getWorkers),
                new HorizontalDisplayAdapter("Newcomers", periods, PeriodSummary::getNewcomers),
                new HorizontalDisplayAdapter("Dismissals", periods, PeriodSummary::getDismissals)
        );

        // retrieve the correct period summary to edit, based on the column that was clicked (unless it's the header)
        grid.addItemClickListener(event -> {
            if (!ROW_CAPTION.equals(event.getColumn().getId())) {
                Integer columnIndex = Integer.valueOf(event.getColumn().getId());
                Notification.show("Editing " + event.getItem().getSummary(columnIndex), Notification.Type.ERROR_MESSAGE);
            }
        });

        // freeze first column for scrolling purposes
        grid.setFrozenColumnCount(1);

        addComponent(grid);
        setSizeFull();
    }

    // generate some dummy data to simulate loading from the DB
    private List<PeriodSummary> loadPeriods() {
        Random random = new Random();
        ArrayList<PeriodSummary> periodSummaries = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            periodSummaries.add(new PeriodSummary(i, random.nextInt(100), random.nextInt(100), random.nextInt(100)));
        }
        return periodSummaries;
    }

    // adapter to display data in a "horizontal format"
    public class HorizontalDisplayAdapter {
        // row caption
        private final String caption;

        // periods for each column
        private final List<PeriodSummary> periods;

        // used for brevity, a class hierarchy is probably more elegant
        private Function<PeriodSummary, Integer> valueExtractor;

        public HorizontalDisplayAdapter(String caption, List<PeriodSummary> periods, Function<PeriodSummary, Integer> valueExtractor) {
            this.caption = caption;
            this.periods = periods;
            this.valueExtractor = valueExtractor;
        }

        public String getCaption() {
            return caption;
        }

        public PeriodSummary getSummary(int columnIndex) {
            return periods.get(columnIndex);
        }

        // extract the data for a certain column
        public Integer getValue(int columnIndex) {
            return valueExtractor.apply(periods.get(columnIndex));
        }
    }

    // basic bean
    public class PeriodSummary {
        int period;
        int workers;
        int newcomers;
        int dismissals;

        public PeriodSummary(int period, int workers, int newcomers, int dismissals) {
            this.period = period;
            this.workers = workers;
            this.newcomers = newcomers;
            this.dismissals = dismissals;
        }

        public int getPeriod() {
            return period;
        }

        public void setPeriod(int period) {
            this.period = period;
        }

        public int getWorkers() {
            return workers;
        }

        public void setWorkers(int workers) {
            this.workers = workers;
        }

        public int getNewcomers() {
            return newcomers;
        }

        public void setNewcomers(int newcomers) {
            this.newcomers = newcomers;
        }

        public int getDismissals() {
            return dismissals;
        }

        public void setDismissals(int dismissals) {
            this.dismissals = dismissals;
        }

        @Override
        public String toString() {
            return "PeriodSummary{" +
                    "period=" + period +
                    ", workers=" + workers +
                    ", newcomers=" + newcomers +
                    ", dismissals=" + dismissals +
                    '}';
        }
    }

    // value provider for the horizontal display adapters
    private class AdapterValueProvider implements ValueProvider<HorizontalDisplayAdapter, Integer> {
        // column index is used to retrieve data from the correct summary
        private int columnIndex;

        public AdapterValueProvider(int columnIndex) {
            this.columnIndex = columnIndex;
        }

        @Override
        public Integer apply(HorizontalDisplayAdapter horizontalDisplayAdapter) {
            return horizontalDisplayAdapter.getValue(columnIndex);
        }
    }
}
</code>```

Result

Title: How to reverse vaadin Grid?

Body:
I'm trying to build a simple java application using Spring Boot and Vaadin.
I need to add a table on UI like this: https://www.screencast.com/t/1c4xkr4IE

It could be extended by periods.

Looks like Vaadin Grid element perfectly fits my requirements, but it adds my rows as columns. Is it possible to reverse grid or maybe there is another way to build needed table?

UPDATE

Here are my code:

@SpringComponent
@UIScope
public class MyDataEditor extends VerticalLayout {
private final MyDataRepository repository;
private MyData myData;

TextField month = new TextField("Period");
TextField numberOfWorkers = new TextField(" Number of workers");
TextField numberOfNewcomers = new TextField("Number of newcomers");
TextField numberOfDismissals = new TextField("Number of dismissals");

Button save = new Button("Save");
Button cancel = new Button("Cancel");
Button delete = new Button("Delete");
CssLayout actions = new CssLayout(save, cancel, delete);

Binder<MyData> binder = new Binder<>(MyData.class);

@Autowired
public MyDataEditor(MyDataRepository repository) {
    this.repository = repository;
    addComponents(month, numberOfWorkers, numberOfNewcomers, numberOfDismissals, actions);
    binder.bindInstanceFields(this);
    setSpacing(true);
    actions.setStyleName(ValoTheme.LAYOUT_COMPONENT_GROUP);
    save.setStyleName(ValoTheme.BUTTON_PRIMARY);
    save.setClickShortcut(ShortcutAction.KeyCode.ENTER);

    save.addClickListener(e -> repository.save(myData));
    delete.addClickListener(e -> repository.delete(myData));
    cancel.addClickListener(e -> editInputData(myData));
    setVisible(false);
}

public interface ChangeHandler {
    void onChange();
}

public final void editMyData(MyData c) {
    if (c == null) {
        setVisible(false);
        return;
    }
    final boolean persisted = c.getMonth() != null;
    if (persisted) {
        myData = repository.findOne(c.getMonth());
    } else {
        myData = c;
    }
    cancel.setVisible(persisted);
    binder.setBean(myData);
    save.focus();
    periodId.selectAll();
}

public void setChangeHandler(ChangeHandler h) {
    save.addClickListener(e -> h.onChange());
    delete.addClickListener(e -> h.onChange());
}

}

@SpringUI
@Theme("valo")
public class VaadinUI extends UI {
private final MyDataRepository repo;
private final MyDataEditor editor;
final Grid<MyData> grid;
private final Button addNewBtn;

@Autowired
public VaadinUI(MyDataRepository repo, MyDataEditor editor) {
    this.repo = repo;
    this.editor = editor;
    this.grid = new Grid<>(MyData.class);
    this.addNewBtn = new Button("Add new month");
}

@Override
protected void init(VaadinRequest request) {

    grid.setHeight(300, Unit.PIXELS);
    grid.setColumns("month", "numberOfWorkers", "numberOfNewcomers", "numberOfDismissals");
    grid.asSingleSelect().addValueChangeListener(e -> {
        editor.editMyData(e.getValue());
    });
    addNewBtn.addClickListener(e -> editor.editMyData(new MyData()));
    editor.setChangeHandler(() -> {
        editor.setVisible(false);
        grid.setItems(repo.findAll());
    });
}
}

So what I mean by this question is that I set

grid.setColumns("month", "numberOfWorkers", "numberOfNewcomers", "numberOfDismissals");

and do not find out method like setRows, so my table looks like: https://www.screencast.com/t/ndDY6tXp, but should be like on first picture.

Body:
I believe the Vaadin grid (or table) component was designed having the table concept as a starting point. Hence you'd have a unified structure defined by the columns and display any number of same-type data elements, 1 per row. And as far as I know, up to 8.0.4, you can't rotate the structure.

Furthermore, from the user experience perspective, if you have multiple time periods, it'll be easier to scroll them vertically (with the mouse wheel) than horizontally, so I'd suggest discussing the possibility of displaying them just as you started, with the "month", "numberOfWorkers", "numberOfNewcomers" and "numberOfDismissals" columns, and supplying rows of MyData. This also makes it easier to sort, filter, add or edit selected items, whereas for the workaround below, you'd have to do something extra.

If for some reason that's not acceptable at all, you should be able to fake the feature you want with a bit of work (see below sample), but performance and usability wise, there's no guarantees... after all, this is not what it's been designed for.

Code

package com.example.grid;

import com.vaadin.data.ValueProvider;
import com.vaadin.ui.Grid;
import com.vaadin.ui.Notification;
import com.vaadin.ui.VerticalLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.function.Function;

public class HorizontalGrid extends VerticalLayout {

    private static final String ROW_CAPTION = "row-caption";

    public HorizontalGrid() {
        // basic grid setup without column header
        Grid<HorizontalDisplayAdapter> grid = new Grid<>();
        grid.setSizeFull();
        grid.setSelectionMode(Grid.SelectionMode.NONE);
        grid.removeHeaderRow(0);

        // load some data from the DB or someplace else
        List<PeriodSummary> periods = loadPeriods();

        // add row headers
        grid.addColumn(HorizontalDisplayAdapter::getCaption).setId(ROW_CAPTION).setWidth(150);

        // add a column for each period
        for (int i = 0; i < periods.size(); i++) {
            // save the column index so we ca figure out what to edit later
            grid.addColumn(new AdapterValueProvider(i)).setId(String.valueOf(i)).setWidth(60);
        }

        // wrap the data in "horizontal display adapters"
        grid.setItems(
                new HorizontalDisplayAdapter("Period", periods, PeriodSummary::getPeriod),
                new HorizontalDisplayAdapter("Workers", periods, PeriodSummary::getWorkers),
                new HorizontalDisplayAdapter("Newcomers", periods, PeriodSummary::getNewcomers),
                new HorizontalDisplayAdapter("Dismissals", periods, PeriodSummary::getDismissals)
        );

        // retrieve the correct period summary to edit, based on the column that was clicked (unless it's the header)
        grid.addItemClickListener(event -> {
            if (!ROW_CAPTION.equals(event.getColumn().getId())) {
                Integer columnIndex = Integer.valueOf(event.getColumn().getId());
                Notification.show("Editing " + event.getItem().getSummary(columnIndex), Notification.Type.ERROR_MESSAGE);
            }
        });

        // freeze first column for scrolling purposes
        grid.setFrozenColumnCount(1);

        addComponent(grid);
        setSizeFull();
    }

    // generate some dummy data to simulate loading from the DB
    private List<PeriodSummary> loadPeriods() {
        Random random = new Random();
        ArrayList<PeriodSummary> periodSummaries = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            periodSummaries.add(new PeriodSummary(i, random.nextInt(100), random.nextInt(100), random.nextInt(100)));
        }
        return periodSummaries;
    }

    // adapter to display data in a "horizontal format"
    public class HorizontalDisplayAdapter {
        // row caption
        private final String caption;

        // periods for each column
        private final List<PeriodSummary> periods;

        // used for brevity, a class hierarchy is probably more elegant
        private Function<PeriodSummary, Integer> valueExtractor;

        public HorizontalDisplayAdapter(String caption, List<PeriodSummary> periods, Function<PeriodSummary, Integer> valueExtractor) {
            this.caption = caption;
            this.periods = periods;
            this.valueExtractor = valueExtractor;
        }

        public String getCaption() {
            return caption;
        }

        public PeriodSummary getSummary(int columnIndex) {
            return periods.get(columnIndex);
        }

        // extract the data for a certain column
        public Integer getValue(int columnIndex) {
            return valueExtractor.apply(periods.get(columnIndex));
        }
    }

    // basic bean
    public class PeriodSummary {
        int period;
        int workers;
        int newcomers;
        int dismissals;

        public PeriodSummary(int period, int workers, int newcomers, int dismissals) {
            this.period = period;
            this.workers = workers;
            this.newcomers = newcomers;
            this.dismissals = dismissals;
        }

        public int getPeriod() {
            return period;
        }

        public void setPeriod(int period) {
            this.period = period;
        }

        public int getWorkers() {
            return workers;
        }

        public void setWorkers(int workers) {
            this.workers = workers;
        }

        public int getNewcomers() {
            return newcomers;
        }

        public void setNewcomers(int newcomers) {
            this.newcomers = newcomers;
        }

        public int getDismissals() {
            return dismissals;
        }

        public void setDismissals(int dismissals) {
            this.dismissals = dismissals;
        }

        @Override
        public String toString() {
            return "PeriodSummary{" +
                    "period=" + period +
                    ", workers=" + workers +
                    ", newcomers=" + newcomers +
                    ", dismissals=" + dismissals +
                    '}';
        }
    }

    // value provider for the horizontal display adapters
    private class AdapterValueProvider implements ValueProvider<HorizontalDisplayAdapter, Integer> {
        // column index is used to retrieve data from the correct summary
        private int columnIndex;

        public AdapterValueProvider(int columnIndex) {
            this.columnIndex = columnIndex;
        }

        @Override
        public Integer apply(HorizontalDisplayAdapter horizontalDisplayAdapter) {
            return horizontalDisplayAdapter.getValue(columnIndex);
        }
    }
}

Result


问:
Prolog , return boolean from consecutive recursive checks
Hello everyone,

The following code does recursive checks. For each call , F gets a value of either 1 or 0 , due to a condition . I want my test_liars predicate return True if all checks had result 1 , and False if at least one call , set F's value to 0.

What test_liars actually does , is not something really eager to explain , but I can if asked.

test_liars should return True to Flag's argument, asked :

```<code>  test_liars(2,[3,2,1,4,2],[1,0,0,1,0],Flag)
</code>```

given different list ,rather than [1,0,0,1,0], it must return False

```<code>   test_liars(_,[],_,_) .
   test_liars(N,[HF|TF],[HT|TT],Flag) :-
         (HT == 0 -> ( N >= HF -> F = 1 ; F = 0)
                   ;   ( N <  HF -> F = 1 ; F = 0)),
          test_liars(N,TF,TT,Flag),
          write(F),
          (F == 0 -> Flag = 'True' ; Flag = 'False').
</code>```

答:
First of all, I think it is more elegant to transform the nested if-then-else structure into a predicate. For instance test_liar/4:

```<code>% test_liar(N,HT,HF,F).

test_liar(N,0,HF,1) :-
    N >= HF,
    !.
test_liar(N,1,HF,1) :-
    N < HF,
    !.
test_liar(_,_,_,0).
</code>```

Which makes things easier. Now you can write:

```<code>test_liars(_,[],_,_).
test_liars(N,[HF|TF],[HT|TT],Flag) :-
          <b>test_liar(N,HT,HF,F),</b>
          test_liars(N,TF,TT,Flag),
          write(F),
          (F == 0 -> Flag = 'True' ; Flag = 'False').</code>```

Nevertheless we are not there yet. Your Flag should return 'False' if at least one element is a liar. That means that in the base case, there are no liars, so we should return 'True':

```<code>test_liars(_,[],_,<b>'True'</b>).</code>```

In the inductive case we thus have to construct some kind of "and", like:

```<code>custom_and('True',1,'True') :-
    !.
custom_and(_,_,'False').</code>```

Now we only need to call this custom_and/3 on the outcome of the recursive test_liars and test_liar:

```<code>test_liars(N,[HF|TF],[HT|TT],Flag) :-
          test_liar(N,HT,HF,F),
          test_liars(N,TF,TT,<b>SubFlag</b>),
          write(F),
          <b>custom_and(SubFlag,F,Flag)</b>.</code>```

Or now the full code:

```<code>test_liar(N,0,HF,1) :-
    N >= HF,
    !.
test_liar(N,1,HF,1) :-
    N < HF,
    !.
test_liar(_,_,_,0).

custom_and('True',1,'True') :-
    !.
custom_and(_,_,'False').

test_liars(_,[],_,'True').
test_liars(N,[HF|TF],[HT|TT],Flag) :-
          test_liar(N,HT,HF,F),
          test_liars(N,TF,TT,SubFlag),
          write(F),
          custom_and(SubFlag,F,Flag).
</code>```

Body:
Hello everyone,

The following code does recursive checks. For each call , F gets a value of either 1 or 0 , due to a condition . I want my test_liars predicate return True if all checks had result 1 , and False if at least one call , set F's value to 0.

What test_liars actually does , is not something really eager to explain , but I can if asked.

test_liars should return True to Flag's argument, asked :

  test_liars(2,[3,2,1,4,2],[1,0,0,1,0],Flag)

given different list ,rather than [1,0,0,1,0], it must return False

   test_liars(_,[],_,_) .
   test_liars(N,[HF|TF],[HT|TT],Flag) :-
         (HT == 0 -> ( N >= HF -> F = 1 ; F = 0)
                   ;   ( N <  HF -> F = 1 ; F = 0)),
          test_liars(N,TF,TT,Flag),
          write(F),
          (F == 0 -> Flag = 'True' ; Flag = 'False').

Body:
First of all, I think it is more elegant to transform the nested if-then-else structure into a predicate. For instance test_liar/4:

% test_liar(N,HT,HF,F).

test_liar(N,0,HF,1) :-
    N >= HF,
    !.
test_liar(N,1,HF,1) :-
    N < HF,
    !.
test_liar(_,_,_,0).

Which makes things easier. Now you can write:

test_liars(_,[],_,_).
test_liars(N,[HF|TF],[HT|TT],Flag) :-
          test_liar(N,HT,HF,F),
          test_liars(N,TF,TT,Flag),
          write(F),
          (F == 0 -> Flag = 'True' ; Flag = 'False').

Nevertheless we are not there yet. Your Flag should return 'False' if at least one element is a liar. That means that in the base case, there are no liars, so we should return 'True':

test_liars(_,[],_,'True').

In the inductive case we thus have to construct some kind of "and", like:

custom_and('True',1,'True') :-
    !.
custom_and(_,_,'False').

Now we only need to call this custom_and/3 on the outcome of the recursive test_liars and test_liar:

test_liars(N,[HF|TF],[HT|TT],Flag) :-
          test_liar(N,HT,HF,F),
          test_liars(N,TF,TT,SubFlag),
          write(F),
          custom_and(SubFlag,F,Flag).

Or now the full code:

test_liar(N,0,HF,1) :-
    N >= HF,
    !.
test_liar(N,1,HF,1) :-
    N < HF,
    !.
test_liar(_,_,_,0).

custom_and('True',1,'True') :-
    !.
custom_and(_,_,'False').

test_liars(_,[],_,'True').
test_liars(N,[HF|TF],[HT|TT],Flag) :-
          test_liar(N,HT,HF,F),
          test_liars(N,TF,TT,SubFlag),
          write(F),
          custom_and(SubFlag,F,Flag).


问:
How can I temporarily swap ports to launch with a custom URL, then swap ports back to original in asp.net MVC Core?
I have 2 asp.net MVC Core Web projects in the same Visual Studio 2017 solution, and I need to launch them separately in a browser using my custom Launch URL. First, I added the following to my hosts file:

```<code>127.0.0.1   myurl.mybiz.org
</code>```

Initially, I set Project1 > Properties > Debug > Launch URL: to https://myurl.mybiz.org and left everything else alone. I was able to launch Project1 at https://myurl.mybiz.org successfully in IE11.

Next, I wanted to launch Project2 at https://myurl.mybiz.org, so I cut the Launch URL from Project1 and pasted it to Project2 > Properties > Debug > Launch URL:. That did not work, I got a "This page can't be displayed" error.

So I swapped the localhost ports under Web Server Settings > App URL: between Project1 and Project2. Originally, Project1 > Properties > Debug > App URL: was http://localhost:12345/, and Project2 > Properties > Debug > App URL: was http://localhost:54321/, so I set Project1 to 54321 and Project2 to 12345, and this worked. I was able to launch Project2 at https://myurl.mybiz.org.

When I was ready again to launch Project1 at my custom url, I cut the Launch URL: https://myurl.mybiz.org out of Project2 and pasted it back in Project1, and swapped the localhost ports back to their original numbers: Project1 > Properties > Debug > App URL: http://localhost:12345/ and Project2 > Properties > Debug > App URL: http://localhost:54321/. But Project1 will not launch at https://myurl.mybiz.org, I just get the error "This page can't be displayed." Afterward, when I switch everything back to how it worked when Project2 successfully launched at my custom url, Project2 still launches successfully at https://myurl.mybiz.org.

Why won't Project1 launch at my custom url anymore after changing the settings this way?

Here are my 2 launchSettings.json files after swapping back to run Project1 at my custom launch url, after running Project2 at the custom url (VS2017 indicates no change from original after swapping back to these settings):

Project1:

```<code>    {
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:12345/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "https://myurl.mybiz.org/",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "Project1": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}
</code>```

Project2:

```<code>    {
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:54321/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "Project2": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}
</code>```

答:
Swapping ports then swapping back like this did not update the IIS Express applicationhost.config file, which prevented my site from launching at my custom url. Once I located applicationhost.config, I saw that the bindings were clearly wrong and needed to be updated.

This is what I needed it to be to get back to the original state:

```<code><sites>
            . . .
            <site name="Project1" id="2">
                <application path="/" applicationPool="Clr4IntegratedAppPool">
                    <virtualDirectory path="/" physicalPath="C:\Repos\Projects\Project1" />
                </application>
                <bindings>
                    <binding protocol="https" bindingInformation="*:443:myurl.mybiz.org" />
                    <binding protocol="http" bindingInformation="*:12345:localhost" />
                </bindings>
            </site>
            <site name="Project2" id="3">
                <application path="/" applicationPool="Clr4IntegratedAppPool">
                    <virtualDirectory path="/" physicalPath="C:\Repos\Projects\Project2" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation="*:54321:localhost" />
                </bindings>
            </site>
            . . .
</sites>
</code>```

But this is what the binding actually was before I manually fixed it:

```<code><sites>
            . . .
            <site name="Project1" id="2">
                <application path="/" applicationPool="Clr4IntegratedAppPool">
                    <virtualDirectory path="/" physicalPath="C:\Repos\Projects\Project2" />
                </application>
                <bindings>
                    <binding protocol="https" bindingInformation="*:443:myurl.mybiz.org" />
                    <binding protocol="http" bindingInformation="*:54321:localhost" />
                </bindings>
            </site>
            <site name="Project2" id="3">
                <application path="/" applicationPool="Clr4IntegratedAppPool">
                    <virtualDirectory path="/" physicalPath="C:\Repos\Projects\Project1" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation="*:12345:localhost" />
                </bindings>
            </site>
            . . .
        </sites>
</code>```

Body:
I have 2 asp.net MVC Core Web projects in the same Visual Studio 2017 solution, and I need to launch them separately in a browser using my custom Launch URL. First, I added the following to my hosts file:

127.0.0.1   myurl.mybiz.org

Initially, I set Project1 > Properties > Debug > Launch URL: to https://myurl.mybiz.org and left everything else alone. I was able to launch Project1 at https://myurl.mybiz.org successfully in IE11.

Next, I wanted to launch Project2 at https://myurl.mybiz.org, so I cut the Launch URL from Project1 and pasted it to Project2 > Properties > Debug > Launch URL:. That did not work, I got a "This page can't be displayed" error.

So I swapped the localhost ports under Web Server Settings > App URL: between Project1 and Project2. Originally, Project1 > Properties > Debug > App URL: was http://localhost:12345/, and Project2 > Properties > Debug > App URL: was http://localhost:54321/, so I set Project1 to 54321 and Project2 to 12345, and this worked. I was able to launch Project2 at https://myurl.mybiz.org.

When I was ready again to launch Project1 at my custom url, I cut the Launch URL: https://myurl.mybiz.org out of Project2 and pasted it back in Project1, and swapped the localhost ports back to their original numbers: Project1 > Properties > Debug > App URL: http://localhost:12345/ and Project2 > Properties > Debug > App URL: http://localhost:54321/. But Project1 will not launch at https://myurl.mybiz.org, I just get the error "This page can't be displayed." Afterward, when I switch everything back to how it worked when Project2 successfully launched at my custom url, Project2 still launches successfully at https://myurl.mybiz.org.

Why won't Project1 launch at my custom url anymore after changing the settings this way?

Here are my 2 launchSettings.json files after swapping back to run Project1 at my custom launch url, after running Project2 at the custom url (VS2017 indicates no change from original after swapping back to these settings):

Project1:

    {
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:12345/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "https://myurl.mybiz.org/",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "Project1": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

Project2:

    {
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:54321/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "Project2": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

Body:
Swapping ports then swapping back like this did not update the IIS Express applicationhost.config file, which prevented my site from launching at my custom url. Once I located applicationhost.config, I saw that the bindings were clearly wrong and needed to be updated.

This is what I needed it to be to get back to the original state:

<sites>
            . . .
            <site name="Project1" id="2">
                <application path="/" applicationPool="Clr4IntegratedAppPool">
                    <virtualDirectory path="/" physicalPath="C:\Repos\Projects\Project1" />
                </application>
                <bindings>
                    <binding protocol="https" bindingInformation="*:443:myurl.mybiz.org" />
                    <binding protocol="http" bindingInformation="*:12345:localhost" />
                </bindings>
            </site>
            <site name="Project2" id="3">
                <application path="/" applicationPool="Clr4IntegratedAppPool">
                    <virtualDirectory path="/" physicalPath="C:\Repos\Projects\Project2" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation="*:54321:localhost" />
                </bindings>
            </site>
            . . .
</sites>

But this is what the binding actually was before I manually fixed it:

<sites>
            . . .
            <site name="Project1" id="2">
                <application path="/" applicationPool="Clr4IntegratedAppPool">
                    <virtualDirectory path="/" physicalPath="C:\Repos\Projects\Project2" />
                </application>
                <bindings>
                    <binding protocol="https" bindingInformation="*:443:myurl.mybiz.org" />
                    <binding protocol="http" bindingInformation="*:54321:localhost" />
                </bindings>
            </site>
            <site name="Project2" id="3">
                <application path="/" applicationPool="Clr4IntegratedAppPool">
                    <virtualDirectory path="/" physicalPath="C:\Repos\Projects\Project1" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation="*:12345:localhost" />
                </bindings>
            </site>
            . . .
        </sites>


问:
How can I combine elements from different arrays in java?
Suppose a={1,2,3} and b={4,5,6} and I want to return an array containing the middle elements of a and b, i.e., {2,5}. I tried to use "merge":

```<code>public int[] middleValueArray(int[] a, int[] b) {
 int[] both=merge(a[1],b[1]);
 return both;
}
</code>```

This does not seem to work. Is there a simple way to approach this? Thanks!

答:
you can do it like this:</p>

```<code>public int[] middleValueArray(int[] a, int[] b) {
 int[] both=new int[]{a[1],b[1]};
 return both;
}
</code>```

Body:
Suppose a={1,2,3} and b={4,5,6} and I want to return an array containing the middle elements of a and b, i.e., {2,5}. I tried to use "merge":

public int[] middleValueArray(int[] a, int[] b) {
 int[] both=merge(a[1],b[1]);
 return both;
}

This does not seem to work. Is there a simple way to approach this? Thanks!

Body:
you can do it like this:

public int[] middleValueArray(int[] a, int[] b) {
 int[] both=new int[]{a[1],b[1]};
 return both;
}


问:
didSelectItemAt not working from SCLAlertView
I am using SCLAlertView to create custom alert view. My alert view contains one text field and collection view of coloured cells

Problem is that UICollectionView's didSelectItemAt method is not working. I think problem is because it is like subview. But I can't fix it.
I have one collection view at UIViewController and that method is working. Here's my code

```<code>    var collectionViewAlert: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
        layout.itemSize = CGSize(width: 25, height: 25)

        collectionViewAlert = UICollectionView(frame: CGRect(x: 18, y: 10, width: 250, height: 25), collectionViewLayout: layout)
        collectionViewAlert.dataSource = self
        collectionViewAlert.delegate = self
        collectionViewAlert.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "CollCell")
        collectionViewAlert.backgroundColor = UIColor.white

    }

    @IBAction func addCategory(_ sender: Any) {
        let alertView = SCLAlertView()
        alertView.addTextField("Enter category name")

        let subview = UIView(frame: CGRect(x:0,y:0,width:216,height:70))
        subview.addSubview(self.collectionViewAlert)
        alertView.customSubview = subview
        alertView.showEdit("Choose color", subTitle: "This alert view has buttons")

    }

    let reuseIdentifier = "cell" // also enter this string as the cell identifier in the storyboard
    var colors = [UIColor.red, UIColor.yellow, UIColor.green, UIColor.blue, UIColor.cyan]

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.colors.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        // get a reference to our storyboard cell
        if (collectionView == self.collectionViewAlert) {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollCell", for: indexPath as IndexPath)
            cell.backgroundColor = self.colors[indexPath.item]
            return cell
        }
        else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath)

            cell.backgroundColor = self.colors[indexPath.item]// make cell more visible in our example project
            return cell
        }

    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("You selected cell #\(indexPath.item)!")
    }

}
</code>```

More screens here: screens

EDIT:

I still not found answer how to solve this problem. I think problem is subview interaction, because delegate method cellForItemAt is invoked on alert show. Someone know how to figure this out? screen from view hierarchy
Thanks for any help.

答:
You can also add extension for CollectionView delegate:

```<code>extension ViewController: UICollectionViewDelegate
{
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("You selected cell #\(indexPath.item)!")
    }

}
</code>```

If you have added any UIImageView or UILabel inside UICollectionViewCell make sure you have enabled UserIntraction, because for both UIImageView or UILabel default as false.

setUserIntraction for both UIImageView or UILabel as TRUE.

Body:
I am using SCLAlertView to create custom alert view. My alert view contains one text field and collection view of coloured cells

Problem is that UICollectionView's didSelectItemAt method is not working. I think problem is because it is like subview. But I can't fix it.
I have one collection view at UIViewController and that method is working. Here's my code

    var collectionViewAlert: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
        layout.itemSize = CGSize(width: 25, height: 25)

        collectionViewAlert = UICollectionView(frame: CGRect(x: 18, y: 10, width: 250, height: 25), collectionViewLayout: layout)
        collectionViewAlert.dataSource = self
        collectionViewAlert.delegate = self
        collectionViewAlert.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "CollCell")
        collectionViewAlert.backgroundColor = UIColor.white

    }

    @IBAction func addCategory(_ sender: Any) {
        let alertView = SCLAlertView()
        alertView.addTextField("Enter category name")

        let subview = UIView(frame: CGRect(x:0,y:0,width:216,height:70))
        subview.addSubview(self.collectionViewAlert)
        alertView.customSubview = subview
        alertView.showEdit("Choose color", subTitle: "This alert view has buttons")

    }

    let reuseIdentifier = "cell" // also enter this string as the cell identifier in the storyboard
    var colors = [UIColor.red, UIColor.yellow, UIColor.green, UIColor.blue, UIColor.cyan]

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.colors.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        // get a reference to our storyboard cell
        if (collectionView == self.collectionViewAlert) {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollCell", for: indexPath as IndexPath)
            cell.backgroundColor = self.colors[indexPath.item]
            return cell
        }
        else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath)

            cell.backgroundColor = self.colors[indexPath.item]// make cell more visible in our example project
            return cell
        }

    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("You selected cell #\(indexPath.item)!")
    }

}

More screens here: screens

EDIT:

I still not found answer how to solve this problem. I think problem is subview interaction, because delegate method cellForItemAt is invoked on alert show. Someone know how to figure this out? screen from view hierarchy
Thanks for any help.

Body:
You can also add extension for CollectionView delegate:

extension ViewController: UICollectionViewDelegate
{
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("You selected cell #\(indexPath.item)!")
    }

}

If you have added any UIImageView or UILabel inside UICollectionViewCell make sure you have enabled UserIntraction, because for both UIImageView or UILabel default as false.

setUserIntraction for both UIImageView or UILabel as TRUE.


问:
Deleting an object declared on the stack
I wanted to know what happens if we delete an object declared on the stack, two times. In order to test this I've written this simple program:

```<code>#include <iostream>
using namespace std;

class A {
public:
    A() {}
    virtual ~A() {
        cout << "test" << endl;
    }
};

int main()
{
    A a;
    a.~A();
}
</code>```

I was actually expecting a segmentation fault, as I'm deleting A once explicitly in the code, and it will be deleted again when it goes out of scope, however suprisingly the program produces the following ouput:

"test"

    "test"

Can anybody explain why this code is working??

答:
Your program has undefined behaviour, so it may just as easily have segfaulted, or stolen my car, or gone into space to start an exciting new colony of lesbian parrots.

But, in practice, the behaviour you've witnessed can be explained. Calling the destructor does not "delete" an object; it just calls the destructor. A destructor call is one part of object deletion; yours just prints to standard output, so there's really nothing to trigger a memory access violation here.

More generally, "expecting a segmentation fault" is always folly.

However, if you'd actually attempted to delete the object with delete, I would be surprised if your program didn't crash at runtime.

Body:
I wanted to know what happens if we delete an object declared on the stack, two times. In order to test this I've written this simple program:

#include <iostream>
using namespace std;

class A {
public:
    A() {}
    virtual ~A() {
        cout << "test" << endl;
    }
};

int main()
{
    A a;
    a.~A();
}

I was actually expecting a segmentation fault, as I'm deleting A once explicitly in the code, and it will be deleted again when it goes out of scope, however suprisingly the program produces the following ouput:

"test"

    "test"

Can anybody explain why this code is working??


问:
How to know which Image the MouseClick event occured?
I have 2 images for 2 players on my windows form.  I have added a MouseClick event for both of  them. Now when I mouse click, it activates both the events for both the players. I wanted to know only one player where I am clicking.
How do I do that?

```<code>this.MouseClick += new System.Windows.Forms.MouseEventHandler(this._player1_MouseClick);
this.MouseClick += new System.Windows.Forms.MouseEventHandler(this._player2_MouseClick);
</code>```

答:
Assume you have two PictureBox controls with images. Thus you have posted code from designer, I also assume that you are subscribing to events via designer.

Select one of PictureBox controls

In Events tab find Click property, type-in Player_Click as handler name and hit Enter. You have subscribed to Click event of first control.

Select second PictureBox

In Events tab find Click property, click on drop-down and select Player_Click as well. Hit Enter. You have used same event handler to subscribe to Click event of second control.

Now go to code view (you can double click any of those controls for that) and find Player_Click method

In order to find which control was clicked you need to cast sender argument to PictureBox type:

```<code>private void Player_Click(object sender, EventArgs e)
{
    var pictureBox = (PictureBox)sender;
    // use control which was clicked. e.g. get it's name
    var name = pictureBox.Name;
}
</code>```

Body:
I have 2 images for 2 players on my windows form.  I have added a MouseClick event for both of  them. Now when I mouse click, it activates both the events for both the players. I wanted to know only one player where I am clicking.
How do I do that?

this.MouseClick += new System.Windows.Forms.MouseEventHandler(this._player1_MouseClick);
this.MouseClick += new System.Windows.Forms.MouseEventHandler(this._player2_MouseClick);

Body:
Assume you have two PictureBox controls with images. Thus you have posted code from designer, I also assume that you are subscribing to events via designer.

Select one of PictureBox controls

In Events tab find Click property, type-in Player_Click as handler name and hit Enter. You have subscribed to Click event of first control.

Select second PictureBox

In Events tab find Click property, click on drop-down and select Player_Click as well. Hit Enter. You have used same event handler to subscribe to Click event of second control.

Now go to code view (you can double click any of those controls for that) and find Player_Click method

In order to find which control was clicked you need to cast sender argument to PictureBox type:

private void Player_Click(object sender, EventArgs e)
{
    var pictureBox = (PictureBox)sender;
    // use control which was clicked. e.g. get it's name
    var name = pictureBox.Name;
}


问:
Dynamically reference external cells using concatenation in Excel
I have a workbook in which I am trying to pull data into from an external excel document.

Ideally I would like to specify a file path in the master workbook, which is the location to pull data from and then use another cell to determine what cell inside that filepath to look for.

For example:

Cell A1 = C:\Documents\book.xlsx (the file path)

Cell A2 = sheet3 (the sheet inside book.xlsx that I want to look at)

Cell A3 = H8 (the cell I want to retrieve from book.xlsx)

Is there a way I can then pull these together to create a reference to that cell, using CONCATENATE and INDIRECT at the moment but it is just giving me a #REF error.

E.g.

```<code>=INDIRECT(CONCATENATE("[", A1, "]", A2, "!", A3))
</code>```

(would be giving a value of [C:\Documents\book.xlsx]sheet3!H8)

答:
Used an article from here to fix this, using this code:</p>

```<code>Dim XL As Excel.Application
Dim WBK As Excel.Workbook

Set XL = CreateObject("Excel.Application")
Set WBK = XL.Workbooks.Open("C:TempBook1.xls")
MsgBox WBK.Sheets("Sheet1").Range("A1").Value

WBK.Close
Set XL = Nothing
</code>```

Body:
I have a workbook in which I am trying to pull data into from an external excel document.

Ideally I would like to specify a file path in the master workbook, which is the location to pull data from and then use another cell to determine what cell inside that filepath to look for.

For example:

Cell A1 = C:\Documents\book.xlsx (the file path)

Cell A2 = sheet3 (the sheet inside book.xlsx that I want to look at)

Cell A3 = H8 (the cell I want to retrieve from book.xlsx)

Is there a way I can then pull these together to create a reference to that cell, using CONCATENATE and INDIRECT at the moment but it is just giving me a #REF error.

E.g.

=INDIRECT(CONCATENATE("[", A1, "]", A2, "!", A3))

(would be giving a value of [C:\Documents\book.xlsx]sheet3!H8)

Body:
Used an article from here to fix this, using this code:

Dim XL As Excel.Application
Dim WBK As Excel.Workbook

Set XL = CreateObject("Excel.Application")
Set WBK = XL.Workbooks.Open("C:TempBook1.xls")
MsgBox WBK.Sheets("Sheet1").Range("A1").Value

WBK.Close
Set XL = Nothing