问:
Derive status from a 24 value integer list representing 24 hours
I'm trying to come up with a way to represent 3 states of availability I have for an item within a single python object if possible.

I would like to try to maintain a consistent state of combined (24hours) along with status of the item (unavailable, available and booked)

Currently, I have to pull a json field with a schedule, any possible reservations and represent the availability and unavailability for the next 24 hours.

first thought was to do a list with the 3 status in it representing 24 hours.

24 hour clock with status in it

```<code>hours = [0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0] # example
</code>```

0 being not available,
1 being available (due to current time is within schedule)
2 being booked and not available

```<code># postgres json field of a single schedule cannot be altered

schedule = {
    'availability': {
        'mon': { 'start': '01:00:00', 'end': '13:00:00'},
        'tue': { 'start': '01:00:00', 'end': '13:00:00'},
        'wed': { 'start': '01:00:00', 'end': '13:00:00'},
        'thu': { 'start': '01:00:00', 'end': '13:00:00'},
        'fri': { 'start': '01:00:00', 'end': '13:00:00'},
        'sat': { 'start': '01:00:00', 'end': '13:00:00'},
        'sun': { 'start': '01:00:00', 'end': '13:00:00'},
    }
}

# example booking

booking_today_start = datetime.datetime(2017, 4, 1, 1, 0, 0) # postgres date field
booking_today_end = datetime.datetime(2017, 4, 1, 10, 0, 0) # postgres date field
</code>```

I'm finding it difficult with this kind of idea to update the list because the list may have to be shifted and recalculated every hour to maintain its state and it makes it error prone

Is there a better way to represent this kind of status within a python data structure given that I have to combine these three postgres fields into a usable object to represent the state of both hours and availability 3 different ways. Would it be better to scrap the json field and go with date fields for each day and try to do it in postgres rather than python? Anyone who might have had to tackle this before, I would appreciate any tips or even direction to go in, or how I might approach it better, Thanks!

```<code>class User(SurrogatePK, Model):

    __tablename__ = 'users'

    # Relationships.
    reservations = db.relationship('Reservation', backref='guest', uselist=False)

    addresses = db.relationship('Properties', backref='host', uselist=False)

    # other user props below

class Property(SurrogatePK, Model):
    __tablename__ = 'addresses'

    # relationships Property.host > User
    host_id = db.Column(db.Integer, db.ForeignKey('users.id',
                                                  onupdate='CASCADE',
                                                  ondelete='CASCADE'),
                                                  index=True, nullable=False)
    reservations = db.relationship('Reservation',
                                    backref='address_property', uselist=False)
    #schedule
    schedule = Column(JSON, nullable=True)
    avail_type = Column(db.Unicode(50), nullable=True) # hourly etc
    is_avail = Column(db.Boolean(), default=True)

class Reservation(SurrogatePK, Model):
    __tablename__ =  'reservations'

    # relationships
    # Reservation.guest > User
    guest_id = db.Column(db.ForeignKey('users.id',
                                    onupdate='CASCADE', ondelete='CASCADE'),
                                    nullable=False)
    address_id = db.Column(db.ForeignKey('addresses.id', onupdate='CASCADE',
                                    ondelete='CASCADE'), nullable=False)

    status = db.Column(db.Enum('pending', 'confirmed', 'rejected',
        name='reservation_status_enum'), default='confirmed')

    reserve_start = db.Column(db.DateTime)
    reserve_end = db.Column(db.DateTime)

    @classmethod
    def _time_in_range(self, x):
        if self.reserve_start <= self.reserve_end:
            return self.reserve_start <= x <= self.reserve_end
        else:
            return self.start <= x or x <= self.reserve_end
</code>```

答:
Your solution is nice because its very fast to find out "is this available at this particular hour" but it cannot support a range like 17:30 - 20:45 and you have to do a bit of extra calculation to ask "is it available at 04:15?"

Instead, I'd suggest doing the same thing as the Postgres database does: store the start and end time per day of week. Use datetime.time objects. Comparison is simple, choose the appropriate day of week, and check that start_time <= time && time <= end_time.

Body:
I'm trying to come up with a way to represent 3 states of availability I have for an item within a single python object if possible.

I would like to try to maintain a consistent state of combined (24hours) along with status of the item (unavailable, available and booked)

Currently, I have to pull a json field with a schedule, any possible reservations and represent the availability and unavailability for the next 24 hours.

first thought was to do a list with the 3 status in it representing 24 hours.

24 hour clock with status in it

hours = [0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0] # example

0 being not available,
1 being available (due to current time is within schedule)
2 being booked and not available

# postgres json field of a single schedule cannot be altered

schedule = {
    'availability': {
        'mon': { 'start': '01:00:00', 'end': '13:00:00'},
        'tue': { 'start': '01:00:00', 'end': '13:00:00'},
        'wed': { 'start': '01:00:00', 'end': '13:00:00'},
        'thu': { 'start': '01:00:00', 'end': '13:00:00'},
        'fri': { 'start': '01:00:00', 'end': '13:00:00'},
        'sat': { 'start': '01:00:00', 'end': '13:00:00'},
        'sun': { 'start': '01:00:00', 'end': '13:00:00'},
    }
}

# example booking

booking_today_start = datetime.datetime(2017, 4, 1, 1, 0, 0) # postgres date field
booking_today_end = datetime.datetime(2017, 4, 1, 10, 0, 0) # postgres date field

I'm finding it difficult with this kind of idea to update the list because the list may have to be shifted and recalculated every hour to maintain its state and it makes it error prone

Is there a better way to represent this kind of status within a python data structure given that I have to combine these three postgres fields into a usable object to represent the state of both hours and availability 3 different ways. Would it be better to scrap the json field and go with date fields for each day and try to do it in postgres rather than python? Anyone who might have had to tackle this before, I would appreciate any tips or even direction to go in, or how I might approach it better, Thanks!

class User(SurrogatePK, Model):

    __tablename__ = 'users'

    # Relationships.
    reservations = db.relationship('Reservation', backref='guest', uselist=False)

    addresses = db.relationship('Properties', backref='host', uselist=False)

    # other user props below

class Property(SurrogatePK, Model):
    __tablename__ = 'addresses'

    # relationships Property.host > User
    host_id = db.Column(db.Integer, db.ForeignKey('users.id',
                                                  onupdate='CASCADE',
                                                  ondelete='CASCADE'),
                                                  index=True, nullable=False)
    reservations = db.relationship('Reservation',
                                    backref='address_property', uselist=False)
    #schedule
    schedule = Column(JSON, nullable=True)
    avail_type = Column(db.Unicode(50), nullable=True) # hourly etc
    is_avail = Column(db.Boolean(), default=True)

class Reservation(SurrogatePK, Model):
    __tablename__ =  'reservations'

    # relationships
    # Reservation.guest > User
    guest_id = db.Column(db.ForeignKey('users.id',
                                    onupdate='CASCADE', ondelete='CASCADE'),
                                    nullable=False)
    address_id = db.Column(db.ForeignKey('addresses.id', onupdate='CASCADE',
                                    ondelete='CASCADE'), nullable=False)

    status = db.Column(db.Enum('pending', 'confirmed', 'rejected',
        name='reservation_status_enum'), default='confirmed')

    reserve_start = db.Column(db.DateTime)
    reserve_end = db.Column(db.DateTime)

    @classmethod
    def _time_in_range(self, x):
        if self.reserve_start <= self.reserve_end:
            return self.reserve_start <= x <= self.reserve_end
        else:
            return self.start <= x or x <= self.reserve_end


来源: stackexchange

问:
Eclipse PluginDevelopment: How to set ProblemMarker for IFolder?
When developing an Eclipse Plugin, what is the best way to set a ProblemMarker for empty IFolders?
What I am trying to achieve is the following:
Im using an own project type, and I want certain Folders in the Package Explorer to be marked and decorated with a warning when they are empty.

What I can do is to add markers when opening eclipse. But I dont know how to update the markers when changes occur.

I tried it this way:

using method : public void resourceChanged(IResourceChangeEvent event) (is called whenever something in workspace is changed)

I was checking the folders if they are empty (works)

then adding a ProblemMarker on the IFile instances. (does not work, because adding a ProblemMarker is locked while being in method resourceChanged)
This is because changing markers fires a resourceChanged event.

So what is the usual way to solve the problem?
I guess there is one because in eclipse whenever you change something in the package explorer the decorators are updated instantly.

答:
You could try to create a Builder which checks for problems and creates the markers as needed.

This article could help you

ContentLicense: CC BY-SA 2.5


问:
while(multiple array lengths > 0)
I've found similar questions about my problem though the answers contain suggestions which do half of what I need - none of them do it all.

I need to develop a function which will cope with both:

an unknown number of arrays, AND...

of differing lengths AND...

alternately merge the arrays (added as edit)

I'm trying to write a function based on two I've found and believe I just need to figure the while() out, but I'm totally stumped. I can't seem to track down any examples of while loops that use an array in their conditions... if you follow.

```<code>function alternately_merge_arrays() {
  $arrays = func_get_args();
  $new_array = array();
  //

  while( count($array) in $arrays is > 0  ) {

  //
    foreach($arrays as $array) {
      if ( count($array) > 0 )
         $new_array[] = array_shift($array);
     }
  }
 return $new_array;
}

var_dump(alternately_merge_arrays(array(1,4), array(2,5,7), array(3,6,8,9));
</code>```

Of course I may be completely wrong and it needs to be something other than a while() loop. I'm cool using for() and foreach(), though if the first array is the shortest these would stop looping where while() should continue...

Edit: The output I need would be:

```<code>array(1,2,3,4,5,6,7,8,9)
</code>```

答:
You want to merge more than 2 arrays? There are many ways to do that. This looks a bit like what you intended.

```<code><?php

function alternately_merge_arrays() {
  $arguments = func_get_args();
  $result    = [];
  foreach($arguments as $argument) {
    if (is_array($argument)) $result = array_merge($result,$argument);
                        else echo "ERROR: argument is not an array.";
  }
  return $result;
}

var_dump(alternately_merge_arrays(array(1,4), array(2,5,7), array(3,6,8,9)));
</code>```

The output is:

```<code>array(9) {
  [0]=> int(1)
  [1]=> int(4)
  [2]=> int(2)
  [3]=> int(5)
  [4]=> int(7)
  [5]=> int(3)
  [6]=> int(6)
  [7]=> int(8)
  [8]=> int(9)
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: while(multiple array lengths > 0)

Body:
I've found similar questions about my problem though the answers contain suggestions which do half of what I need - none of them do it all.

I need to develop a function which will cope with both:

an unknown number of arrays, AND...

of differing lengths AND...

alternately merge the arrays (added as edit)

I'm trying to write a function based on two I've found and believe I just need to figure the while() out, but I'm totally stumped. I can't seem to track down any examples of while loops that use an array in their conditions... if you follow.

function alternately_merge_arrays() {
  $arrays = func_get_args();
  $new_array = array();
  //

  while( count($array) in $arrays is > 0  ) {

  //
    foreach($arrays as $array) {
      if ( count($array) > 0 )
         $new_array[] = array_shift($array);
     }
  }
 return $new_array;
}

var_dump(alternately_merge_arrays(array(1,4), array(2,5,7), array(3,6,8,9));

Of course I may be completely wrong and it needs to be something other than a while() loop. I'm cool using for() and foreach(), though if the first array is the shortest these would stop looping where while() should continue...

Edit: The output I need would be:

array(1,2,3,4,5,6,7,8,9)

Body:
You want to merge more than 2 arrays? There are many ways to do that. This looks a bit like what you intended.

<?php

function alternately_merge_arrays() {
  $arguments = func_get_args();
  $result    = [];
  foreach($arguments as $argument) {
    if (is_array($argument)) $result = array_merge($result,$argument);
                        else echo "ERROR: argument is not an array.";
  }
  return $result;
}

var_dump(alternately_merge_arrays(array(1,4), array(2,5,7), array(3,6,8,9)));

The output is:

array(9) {
  [0]=> int(1)
  [1]=> int(4)
  [2]=> int(2)
  [3]=> int(5)
  [4]=> int(7)
  [5]=> int(3)
  [6]=> int(6)
  [7]=> int(8)
  [8]=> int(9)
}


问:
C# - how do I implement a data structure that contains ListViewItems?
So I'm doing a college project and my theme is web shop. What I have so far in C# is quite simple, I have a few ListViewItems (Articles) defined in WPF. Also when I change ComboBox index or click a button "New", other articles get inserted into my listview.

After that I needed to create an on click event that opens a new window with the listviewitem (article) details. I've hardcoded(if that's what it's called) this because I didn't know how to do it better.

The problem arises when I select a ComboBoxItem, which clears the listview and adds different items (articles) . When I click on the new articles, a window from the previous article opens when I click it.

I probably need to implement some kind of data structure that keeps ListViewItems, right? How would I approach doing this?

What I have so far:

```<code>namespace TRGOVINA
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void izhod(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

        private void btnNovosti(object sender, RoutedEventArgs e)
        {
            string[] artikli = { "Intel procesor Core i7 6800K", "Intel procesor Core i5 7400", "AMD procesor Ryzen 7 1800X" };

            Artikel artikel1 = new Artikel();
            artikel1.Naziv = artikli[0];
            lvDataBinding.Items.Add(artikel1);

            Artikel artikel2 = new Artikel();
            artikel2.Naziv = artikli[1];
            lvDataBinding.Items.Add(artikel2);

            Artikel artikel3 = new Artikel();
            artikel3.Naziv = artikli[2];
            lvDataBinding.Items.Add(artikel3);
        }

        private void cbKlik_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string[] izbira1 = { "Kingston 2, 5'' SSD disk 480 GB, SATA3", "DELL monitor LED UltraSharp U2412M", "Lenovo IdeaPad 110" };
            string[] izbira2 = { "PCX namizni računalnik Exam i5-7400/8GB/SSD120+1TB/Win10H", "Lenovo prenosnik V310", "Intel procesor Core i7-5820K" };
            string[] izbira3 = { "HP prenosnik Pavilion 17-ab004nm", "Intel procesor Core i7 6900K", "Gigabyte grafična kartica GTX 1080 OC" };
            string[] izbira4 = { "Asus prenosnik FX502VM-DM311T", "HP prenosnik Omen 17-w103nm", "DELL prenosnik Alienware 17" };

            ComboBox cmb = (ComboBox)sender;
            int izbranIndex = cmb.SelectedIndex;

            //lvDataBinding.Items.Clear();
            switch (izbranIndex)
            {
                case 0:
                    lvDataBinding.ItemsSource = null;
                    lvDataBinding.Items.Clear();
                    lvDataBinding.ItemsSource = izbira1;
                    break;
                case 1:
                    lvDataBinding.ItemsSource = null;
                    lvDataBinding.Items.Clear();
                    lvDataBinding.ItemsSource = izbira2;
                    break;
                case 2:
                    lvDataBinding.ItemsSource = null;
                    lvDataBinding.Items.Clear();
                    lvDataBinding.ItemsSource = izbira3;
                    break;
                case 3:
                    lvDataBinding.ItemsSource = null;
                    lvDataBinding.Items.Clear();
                    lvDataBinding.ItemsSource = izbira4;
                    break;
            }
          }

        private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            //INSTEAD OF MESSAGEBOX A WINDOW HAS TO OPEN WITH LISTVIEW ITEM DETAILS - messagebox is just a placeholder
            int indeks = lvDataBinding.SelectedIndex;
            if (indeks == 0)
                MessageBox.Show(ime1.Text, "Naziv artikla", MessageBoxButton.OK, MessageBoxImage.Information);
            if (indeks == 1)
                MessageBox.Show(ime2.Text, "Naziv artikla", MessageBoxButton.OK, MessageBoxImage.Information);
            if (indeks == 2)
                MessageBox.Show(ime3.Text, "Naziv artikla", MessageBoxButton.OK, MessageBoxImage.Information);
            if (indeks == 3)
                MessageBox.Show(ime4.Text, "Naziv artikla", MessageBoxButton.OK, MessageBoxImage.Information);
            if (indeks == 4)
                MessageBox.Show(ime5.Text, "Naziv artikla", MessageBoxButton.OK, MessageBoxImage.Information);
            if (indeks == 5)
                MessageBox.Show(ime6.Text, "Naziv artikla", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        private void btnKosarica(object sender, RoutedEventArgs e)
        {
            Kosarica kosarica = new Kosarica();
            kosarica.Show();
        }
    }

    public class Artikel
    {
        public string Naziv { get; set; }

        public override string ToString()
        {
            return Naziv;
        }
    }
}
</code>```

答:
I'm goint to use MVVM in this answer since it's almost required for a WPF experience that doesn't include questioning your life choices. MVVM stands for Model, View, ViewModel. Something like this should get you started...

First is the Model. This is your data structure.

```<code>class Item
{
    public string Name { get; set; }
    public Item(string name)
    {
        Name = name;
    }
    public override string ToString()
    {
        return Name;
    }
}
</code>```

Then, your window in XAML. This is considered your view.

```<code><Window x:Class="Wpf.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Wpf"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:ViewModel/>
    </Window.DataContext>
    <StackPanel>
        <ListView ItemsSource="{Binding ElementName=_combobox, Path=SelectedItem}"/>
        <ComboBox x:Name="_combobox" ItemsSource="{Binding ItemLists}"/>
    </StackPanel>
</Window>
</code>```

Last, this is what is called your ViewModel. This binds the View and Model together.

```<code>class ViewModel
{
    public List<List<Item>> ItemLists { get; private set; }
    public ViewModel()
    {
        string[] items = { "Intel procesor Core i7 6800K", "Intel procesor Core i5 7400", "AMD procesor Ryzen 7 1800X" };
        ItemLists = new List<List<Item>>();
        ItemLists.Add(new List<Item>());
        foreach (string item in items)
            ItemLists[0].Add(new Item(item));
    }
}
</code>```

Body:
So I'm doing a college project and my theme is web shop. What I have so far in C# is quite simple, I have a few ListViewItems (Articles) defined in WPF. Also when I change ComboBox index or click a button "New", other articles get inserted into my listview.

After that I needed to create an on click event that opens a new window with the listviewitem (article) details. I've hardcoded(if that's what it's called) this because I didn't know how to do it better.

The problem arises when I select a ComboBoxItem, which clears the listview and adds different items (articles) . When I click on the new articles, a window from the previous article opens when I click it.

I probably need to implement some kind of data structure that keeps ListViewItems, right? How would I approach doing this?

What I have so far:

namespace TRGOVINA
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void izhod(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

        private void btnNovosti(object sender, RoutedEventArgs e)
        {
            string[] artikli = { "Intel procesor Core i7 6800K", "Intel procesor Core i5 7400", "AMD procesor Ryzen 7 1800X" };

            Artikel artikel1 = new Artikel();
            artikel1.Naziv = artikli[0];
            lvDataBinding.Items.Add(artikel1);

            Artikel artikel2 = new Artikel();
            artikel2.Naziv = artikli[1];
            lvDataBinding.Items.Add(artikel2);

            Artikel artikel3 = new Artikel();
            artikel3.Naziv = artikli[2];
            lvDataBinding.Items.Add(artikel3);
        }

        private void cbKlik_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string[] izbira1 = { "Kingston 2, 5'' SSD disk 480 GB, SATA3", "DELL monitor LED UltraSharp U2412M", "Lenovo IdeaPad 110" };
            string[] izbira2 = { "PCX namizni računalnik Exam i5-7400/8GB/SSD120+1TB/Win10H", "Lenovo prenosnik V310", "Intel procesor Core i7-5820K" };
            string[] izbira3 = { "HP prenosnik Pavilion 17-ab004nm", "Intel procesor Core i7 6900K", "Gigabyte grafična kartica GTX 1080 OC" };
            string[] izbira4 = { "Asus prenosnik FX502VM-DM311T", "HP prenosnik Omen 17-w103nm", "DELL prenosnik Alienware 17" };

            ComboBox cmb = (ComboBox)sender;
            int izbranIndex = cmb.SelectedIndex;

            //lvDataBinding.Items.Clear();
            switch (izbranIndex)
            {
                case 0:
                    lvDataBinding.ItemsSource = null;
                    lvDataBinding.Items.Clear();
                    lvDataBinding.ItemsSource = izbira1;
                    break;
                case 1:
                    lvDataBinding.ItemsSource = null;
                    lvDataBinding.Items.Clear();
                    lvDataBinding.ItemsSource = izbira2;
                    break;
                case 2:
                    lvDataBinding.ItemsSource = null;
                    lvDataBinding.Items.Clear();
                    lvDataBinding.ItemsSource = izbira3;
                    break;
                case 3:
                    lvDataBinding.ItemsSource = null;
                    lvDataBinding.Items.Clear();
                    lvDataBinding.ItemsSource = izbira4;
                    break;
            }
          }

        private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            //INSTEAD OF MESSAGEBOX A WINDOW HAS TO OPEN WITH LISTVIEW ITEM DETAILS - messagebox is just a placeholder
            int indeks = lvDataBinding.SelectedIndex;
            if (indeks == 0)
                MessageBox.Show(ime1.Text, "Naziv artikla", MessageBoxButton.OK, MessageBoxImage.Information);
            if (indeks == 1)
                MessageBox.Show(ime2.Text, "Naziv artikla", MessageBoxButton.OK, MessageBoxImage.Information);
            if (indeks == 2)
                MessageBox.Show(ime3.Text, "Naziv artikla", MessageBoxButton.OK, MessageBoxImage.Information);
            if (indeks == 3)
                MessageBox.Show(ime4.Text, "Naziv artikla", MessageBoxButton.OK, MessageBoxImage.Information);
            if (indeks == 4)
                MessageBox.Show(ime5.Text, "Naziv artikla", MessageBoxButton.OK, MessageBoxImage.Information);
            if (indeks == 5)
                MessageBox.Show(ime6.Text, "Naziv artikla", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        private void btnKosarica(object sender, RoutedEventArgs e)
        {
            Kosarica kosarica = new Kosarica();
            kosarica.Show();
        }
    }

    public class Artikel
    {
        public string Naziv { get; set; }

        public override string ToString()
        {
            return Naziv;
        }
    }
}

Body:
I'm goint to use MVVM in this answer since it's almost required for a WPF experience that doesn't include questioning your life choices. MVVM stands for Model, View, ViewModel. Something like this should get you started...

First is the Model. This is your data structure.

class Item
{
    public string Name { get; set; }
    public Item(string name)
    {
        Name = name;
    }
    public override string ToString()
    {
        return Name;
    }
}

Then, your window in XAML. This is considered your view.

<Window x:Class="Wpf.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Wpf"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:ViewModel/>
    </Window.DataContext>
    <StackPanel>
        <ListView ItemsSource="{Binding ElementName=_combobox, Path=SelectedItem}"/>
        <ComboBox x:Name="_combobox" ItemsSource="{Binding ItemLists}"/>
    </StackPanel>
</Window>

Last, this is what is called your ViewModel. This binds the View and Model together.

class ViewModel
{
    public List<List<Item>> ItemLists { get; private set; }
    public ViewModel()
    {
        string[] items = { "Intel procesor Core i7 6800K", "Intel procesor Core i5 7400", "AMD procesor Ryzen 7 1800X" };
        ItemLists = new List<List<Item>>();
        ItemLists.Add(new List<Item>());
        foreach (string item in items)
            ItemLists[0].Add(new Item(item));
    }
}


问:
My nested for loop number pattern doesn't out put the correct pattern
I'm trying to print out this pattern but I'm having trouble arranging the numbers and spacing them out to achieve the expected out put.

```<code>Expected Output:
          1
        2 1
      3 2 1
    4 3 2 1
  5 4 3 2 1
6 5 4 3 2 1

1 2 3 4 5 6
  1 2 3 4 5
    1 2 3 4
      1 2 3
        1 2
          1
</code>```

Here is my Code. I don't know how to space the numbers and put the correct numbers in the order that the out put has specified.

```<code>import java.util.Scanner;

public class patterns{
 public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);

   for (int i = 6; i >= 1; i--)
    {

        for (int j = 1; j < i; j++)
        {
            System.out.print(" ");
        }

        for (int j = i; j <= 6; j++)
        {
            System.out.print(j);
        }

        System.out.println();
    }

                System.out.println();

   for (int i = 1; i <= 6; i++)
    {

        for (int j = 1; j < i; j++)
        {
            System.out.print(" ");
        }

        for (int j = i; j <= 6; j++)
        {
            System.out.print(j);
        }

        System.out.println();
    }

   }
 }
</code>```

This is the Output I'm Getting

```<code>run:
     6
    56
   456
  3456
 23456
123456

123456
 23456
  3456
   456
    56
     6
</code>```

答:
You should think that each triangle block actually has 6x6 square cells. So it means you need 2 nested loops, each will iterate 6 times.

Then inside you will decide whether you print a number or space, depending on some condition.

```<code>for (int i = 6; i >= 1; i--)
    {
        for (int j = 1; j <= 6; j++)
        {
            if (j < i)
            {
                System.out.print("  ");
            } else
            {
                System.out.print(7 - j + " ");
            }
        }

        System.out.println("");
    }

    System.out.println("");

    for (int i = 1; i <= 6; i++)
    {
        for (int j = 1; j <= 6; j++)
        {
            if (j < i)
            {
                System.out.print("  ");
            } else
            {
                System.out.print(j-i+1 + " ");
            }
        }

        System.out.println("");
    }

          1
        2 1
      3 2 1
    4 3 2 1
  5 4 3 2 1
6 5 4 3 2 1

1 2 3 4 5 6
  1 2 3 4 5
    1 2 3 4
      1 2 3
        1 2
          1
</code>```

Body:
I'm trying to print out this pattern but I'm having trouble arranging the numbers and spacing them out to achieve the expected out put.

Expected Output:
          1
        2 1
      3 2 1
    4 3 2 1
  5 4 3 2 1
6 5 4 3 2 1

1 2 3 4 5 6
  1 2 3 4 5
    1 2 3 4
      1 2 3
        1 2
          1

Here is my Code. I don't know how to space the numbers and put the correct numbers in the order that the out put has specified.

import java.util.Scanner;

public class patterns{
 public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);

   for (int i = 6; i >= 1; i--)
    {

        for (int j = 1; j < i; j++)
        {
            System.out.print(" ");
        }

        for (int j = i; j <= 6; j++)
        {
            System.out.print(j);
        }

        System.out.println();
    }

                System.out.println();

   for (int i = 1; i <= 6; i++)
    {

        for (int j = 1; j < i; j++)
        {
            System.out.print(" ");
        }

        for (int j = i; j <= 6; j++)
        {
            System.out.print(j);
        }

        System.out.println();
    }

   }
 }

This is the Output I'm Getting

run:
     6
    56
   456
  3456
 23456
123456

123456
 23456
  3456
   456
    56
     6

Body:
You should think that each triangle block actually has 6x6 square cells. So it means you need 2 nested loops, each will iterate 6 times.

Then inside you will decide whether you print a number or space, depending on some condition.

for (int i = 6; i >= 1; i--)
    {
        for (int j = 1; j <= 6; j++)
        {
            if (j < i)
            {
                System.out.print("  ");
            } else
            {
                System.out.print(7 - j + " ");
            }
        }

        System.out.println("");
    }

    System.out.println("");

    for (int i = 1; i <= 6; i++)
    {
        for (int j = 1; j <= 6; j++)
        {
            if (j < i)
            {
                System.out.print("  ");
            } else
            {
                System.out.print(j-i+1 + " ");
            }
        }

        System.out.println("");
    }

          1
        2 1
      3 2 1
    4 3 2 1
  5 4 3 2 1
6 5 4 3 2 1

1 2 3 4 5 6
  1 2 3 4 5
    1 2 3 4
      1 2 3
        1 2
          1


问:
Implement Pure Class mixins with Typescript
Im trying to define a pure class based mixin function, but I cannot get the type signature right for this one.

The intent is to provide a function that accepts any Class A as parameter and returns a new Class B that extends the original Class A.

```<code>export function mixin<A>(myclass: A) {
  return class B extends A {
    newMethod() {
      //stuff
    }
  }
}
</code>```

As I said, I cannot figure this out.

I need a way to express that A needs to be a class.

I also need to express the return type, which yields several errors, among:

error TS4060: Return type of exported function has or is using private name 'B'.

Additional information:

This is inside a utils.ts module that is exported so that other modules can use it

This is all being worked in the context of a library I am writing

答:
I wanted to use mixins in TypeScript 2.2 with

abstract base class

decorators on mixins properties (@Parameter)

export mixin definition (Feature) and mixin application (Derived) from module

generate declaration file ("declaration": true in tsconfig.json)

I started with following code which unfortunately does NOT work:

export type Constructor<T> = new(...args: any[]) => T;

export abstract class AbstractBase {
    fieldA = "a";
}

export function Feature<T extends Constructor<object>>(Base: T) {
    return class extends Base {
        @Parameter()
        fieldB = "b";
    };
}

export class Derived extends Feature(AbstractBase) {
    fieldC = "c";
}
```

<p>Finally I ended up with following code which is more complicated but <strong>works as expected</strong>:</p>

<pre class="lang-js prettyprint-override"><code>export type Constructor<T> = new(...args: any[]) => T;

export abstract class AbstractBase {
    fieldA = "a";
}

export interface Feature {
    fieldB: string;
}

export function Feature<T extends Constructor<object>>(Base: T): T & Constructor<Feature> {
    class TWithFeature extends Base implements Feature {
        @Parameter()
        fieldB = "b";
    }
    return TWithFeature;
}

export const AbstractBaseWithFeature = Feature(AbstractBase as Constructor<AbstractBase>);

export class Derived extends AbstractBaseWithFeature {
    fieldC = "c";
}
</code>```

In addition to @bruno-grieder answer see following links:

abstract constructor type - https://github.com/Microsoft/TypeScript/issues/5843

decorators within mixins - https://github.com/Microsoft/TypeScript/issues/14607

mixin classes - https://github.com/Microsoft/TypeScript/pull/13743

Body:
Im trying to define a pure class based mixin function, but I cannot get the type signature right for this one.

The intent is to provide a function that accepts any Class A as parameter and returns a new Class B that extends the original Class A.

export function mixin(myclass: A) {
  return class B extends A {
    newMethod() {
      //stuff
    }
  }
}

As I said, I cannot figure this out.

I need a way to express that A needs to be a class.

I also need to express the return type, which yields several errors, among:

error TS4060: Return type of exported function has or is using private name 'B'.

Additional information:

This is inside a utils.ts module that is exported so that other modules can use it

This is all being worked in the context of a library I am writing

Body:
I wanted to use mixins in TypeScript 2.2 with

abstract base class

decorators on mixins properties (@Parameter)

export mixin definition (Feature) and mixin application (Derived) from module

generate declaration file ("declaration": true in tsconfig.json)

I started with following code which unfortunately does NOT work:

export type Constructor<T> = new(...args: any[]) => T;

export abstract class AbstractBase {
    fieldA = "a";
}

export function Feature<T extends Constructor<object>>(Base: T) {
    return class extends Base {
        @Parameter()
        fieldB = "b";
    };
}

export class Derived extends Feature(AbstractBase) {
    fieldC = "c";
}

Finally I ended up with following code which is more complicated but works as expected:

export type Constructor<T> = new(...args: any[]) => T;

export abstract class AbstractBase {
    fieldA = "a";
}

export interface Feature {
    fieldB: string;
}

export function Feature<T extends Constructor<object>>(Base: T): T & Constructor<Feature> {
    class TWithFeature extends Base implements Feature {
        @Parameter()
        fieldB = "b";
    }
    return TWithFeature;
}

export const AbstractBaseWithFeature = Feature(AbstractBase as Constructor<AbstractBase>);

export class Derived extends AbstractBaseWithFeature {
    fieldC = "c";
}

In addition to @bruno-grieder answer see following links:

abstract constructor type - https://github.com/Microsoft/TypeScript/issues/5843

decorators within mixins - https://github.com/Microsoft/TypeScript/issues/14607

mixin classes - https://github.com/Microsoft/TypeScript/pull/13743


问:
subtracting time in R
I've recently starting working in R to manipulate and query through excel files. I have an excel file called my_File.csv saved to my desktop. Here's what i have so far:

```<code>fileOpened <- sprintf("/Users/JimToby/Desktop/my_File.csv")

myFile <- as.data.frame(table(fileOpened[, c('user', 'time', 'event')]))
</code>```

myFile leaves me with a table looking like this:

user | time |

use1 |2011-07-25 13:08 |

use1 |2011-08-06 2:37 |

use2 |2011-07-25 13:08 |

.....

What I want to do is add another column that has the difference in time per each user. For instance the column could be called timeDiff and for use1 would have only one result by doing 2011-08-06 2:37 - 2011-07-25 13:08. How would i compute this and incorporate it into my table?

Thanks in advance.

答:
Here is solution with shift in data.table:

```<code>dt <- read.table(text = "user | time
           use1 |2011-07-25 13:08
           use1 |2011-08-06 2:37
           use2 |2011-07-25 13:08", header = T, sep = "|")
library(data.table)
dt <- data.table(dt)
dt[, time := as.POSIXct(time)]
dt[, time.diff := time - shift(time, type = "lag"), by = user]
#               user                time     time.diff
# 1:            use1  2011-07-25 13:08:00       NA secs
# 2:            use1  2011-08-06 02:37:00 11.56181 secs
# 3:            use2  2011-07-25 13:08:00       NA secs
</code>```

Title: subtracting time in R

Body:
I've recently starting working in R to manipulate and query through excel files. I have an excel file called my_File.csv saved to my desktop. Here's what i have so far:

fileOpened <- sprintf("/Users/JimToby/Desktop/my_File.csv")

myFile <- as.data.frame(table(fileOpened[, c('user', 'time', 'event')]))

myFile leaves me with a table looking like this:

user | time |

use1 |2011-07-25 13:08 |

use1 |2011-08-06 2:37 |

use2 |2011-07-25 13:08 |

.....

What I want to do is add another column that has the difference in time per each user. For instance the column could be called timeDiff and for use1 would have only one result by doing 2011-08-06 2:37 - 2011-07-25 13:08. How would i compute this and incorporate it into my table?

Thanks in advance.

Body:
Here is solution with shift in data.table:

dt <- read.table(text = "user | time
           use1 |2011-07-25 13:08
           use1 |2011-08-06 2:37
           use2 |2011-07-25 13:08", header = T, sep = "|")
library(data.table)
dt <- data.table(dt)
dt[, time := as.POSIXct(time)]
dt[, time.diff := time - shift(time, type = "lag"), by = user]
#               user                time     time.diff
# 1:            use1  2011-07-25 13:08:00       NA secs
# 2:            use1  2011-08-06 02:37:00 11.56181 secs
# 3:            use2  2011-07-25 13:08:00       NA secs


问:
Which is the best way to redirect 2 different users to 2 different Activities after they login using their email and password?
I'm creating an application with 2 different users.

The first one is the student and the second one is the professor/teacher.

Which is the best way to redirect them to a different Activity after they login using their email and password?

All the students who will login will redirect in a different Activity from the teacher or professor.

答:
Store some boolean value with each account that says "isTeacher" (for example) </p>

<p>Make an if-else statement around the call to start another activity to check said value </p>

Body:
Store some boolean value with each account that says "isTeacher" (for example)

Make an if-else statement around the call to start another activity to check said value


答:
Once you convert the data to an actual time format, you can just subtract. Your sample data only had a start for user2 so I added an end time so that there is a real example. I assumed that you have the times as strings and that you wanted to store the time difference back in the same data.frame

```<code>myFile = read.table(text='user  time
use1 "2011-07-25 13:08"
use1 "2011-08-06 2:37"
use2 "2011-07-25 13:08"
use2 "2011-08-04 3:45"',
header=TRUE, stringsAsFactors=FALSE)

T2 = as.POSIXct(myFile$time)
EndTime = seq(2,length(T2),2)
myFile$timeDiff[EndTime] = T2[EndTime] - T2[EndTime-1]
myFile
  user             time  timeDiff
1 use1 2011-07-25 13:08        NA
2 use1  2011-08-06 2:37 11.561806
3 use2 2011-07-25 13:08        NA
4 use2  2011-08-04 3:45  9.609028
</code>```

Note that the resulting time differences are in days.

Title: subtracting time in R

Body:
Once you convert the data to an actual time format, you can just subtract. Your sample data only had a start for user2 so I added an end time so that there is a real example. I assumed that you have the times as strings and that you wanted to store the time difference back in the same data.frame

myFile = read.table(text='user  time
use1 "2011-07-25 13:08"
use1 "2011-08-06 2:37"
use2 "2011-07-25 13:08"
use2 "2011-08-04 3:45"',
header=TRUE, stringsAsFactors=FALSE)

T2 = as.POSIXct(myFile$time)
EndTime = seq(2,length(T2),2)
myFile$timeDiff[EndTime] = T2[EndTime] - T2[EndTime-1]
myFile
  user             time  timeDiff
1 use1 2011-07-25 13:08        NA
2 use1  2011-08-06 2:37 11.561806
3 use2 2011-07-25 13:08        NA
4 use2  2011-08-04 3:45  9.609028

Note that the resulting time differences are in days.


问:
Laravel sessions; Are they cached from when a method is first called?
I have  two methods that are called via ajax:
The slow one that is called first (sleep is just used to illustrate a method that takes longer to return):

```<code>sleep(10);
return Session::get('bucket');
</code>```

The second one that is called and finishes before the above method:

```<code>Session::push('bucket', 'Test');
return Session::get('bucket');
</code>```

The second one returns the bucket with 'test' in it but when the slow one finishes it returns nothing because it thinks the array is empty even though the second method added something to it.

So is the session cached from when a controller method is first called? It seems like it but I'm not sure.

Cheers!

答:
The sessions are started by the StartSession middleware. As it is a middleware, it is executed before the action is invoked, and completed afterwards.

What your second fast requests adds to the session will not be seen to the slower request since the slow request has already read the entire session content (which was empty at that time).

Here's a related fact; your slower request will also write the session content to disk at the end of the request. It will overwrite what your faster request has written to disk. This can easily bring problems when using concurrent requests (usually ajax requests) that modifies the session.

Relevant issues:

[5.0] Session Persistance Issues

[5.1] Concurrent requests wiping out the session

[5.*] Session Persistance Issues

Body:
I have  two methods that are called via ajax:
The slow one that is called first (sleep is just used to illustrate a method that takes longer to return):

sleep(10);
return Session::get('bucket');

The second one that is called and finishes before the above method:

Session::push('bucket', 'Test');
return Session::get('bucket');

The second one returns the bucket with 'test' in it but when the slow one finishes it returns nothing because it thinks the array is empty even though the second method added something to it.

So is the session cached from when a controller method is first called? It seems like it but I'm not sure.

Cheers!


问:
C# Multi-form coding practice
My question is, in general is it allowable and maintainable to have a multi-form program. More specifically in C# is it good practice to have a button go to another form(each button would be in a separate class). Here is an example:
(In this example I create a programmers reference application, where I need to go from page to page gathering information from the web and put it on an application for quick reference)

Main form:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProgramersReference
{
public partial class main : Form
{
    public main()
    {
        InitializeComponent();
    }

    //About button click
    private void btnAbout_Click(object sender, EventArgs e)
    {
        MessageBox.Show("Author: anon \n"
            +"Version Number: 00.00.01 \n"
            ,"Information");    //Version Key quickreference: 00(high profile change).00(Medium profile change).00(low profile change)
    }

    private void btnWebsites_Click(object sender, EventArgs e)
    {
        websiteForm websiteFormObj = new websiteForm();
        websiteFormObj.Show();
    }
 }
}
</code>```

Second form(IN A DIFFERENT CLASS):

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProgramersReference
{
  public partial class websiteForm : Form
   {
    public websiteForm()
    {
        InitializeComponent();
    }
   }
}
</code>```

If this is not a good way can you answer what is a better way, is tab control a better way, or using panels to show and hide new content in an application?

答:
I agree with what Timon said in general, but it always depends on what you are trying to achieve. Programming is a creative process and rules should be viewed as guidelines. If your application works better with tabs use tabs if it works better with forms use forms. If your writing this application for a client discuss the issue with them. As to best practice, I don't see an issue with either option.

Hope me ramblings help
Danny

Title: C# Multi-form coding practice

Body:
My question is, in general is it allowable and maintainable to have a multi-form program. More specifically in C# is it good practice to have a button go to another form(each button would be in a separate class). Here is an example:
(In this example I create a programmers reference application, where I need to go from page to page gathering information from the web and put it on an application for quick reference)

Main form:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProgramersReference
{
public partial class main : Form
{
    public main()
    {
        InitializeComponent();
    }

    //About button click
    private void btnAbout_Click(object sender, EventArgs e)
    {
        MessageBox.Show("Author: anon \n"
            +"Version Number: 00.00.01 \n"
            ,"Information");    //Version Key quickreference: 00(high profile change).00(Medium profile change).00(low profile change)
    }

    private void btnWebsites_Click(object sender, EventArgs e)
    {
        websiteForm websiteFormObj = new websiteForm();
        websiteFormObj.Show();
    }
 }
}

Second form(IN A DIFFERENT CLASS):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ProgramersReference
{
  public partial class websiteForm : Form
   {
    public websiteForm()
    {
        InitializeComponent();
    }
   }
}

If this is not a good way can you answer what is a better way, is tab control a better way, or using panels to show and hide new content in an application?


问:
public static void main () access non static variable
It is said that non-static variables cannot be used in a static method.  But public static void main does.  How is that?

答: **Here you can see table that clear the access of static and non-static data members in static and non-static methods. **

ContentLicense: CC BY-SA 4.0


问:
How can I remove p tags that are auto added within tinymce
I am using tinymce 4.0.1 and it automatically adds p tags when you either start typing or hit enter. How can I dynamically remove these p tags and then reinsert the content into the editor.</p>

答:
Add this only in call javascript:</p>

```<code>forced_root_block : false
</code>```

Body:
Add this only in call javascript:

forced_root_block : false


问:
Type checking and range checking
In one of the textbooks I'm reading is stated "While types are checked for compatibility at compile time, subranges require run-time range checking."
If I'm getting it right, a runtime check must be performed when new values are assigned to a variable that is defined in a certain subrange (subtype). Isn't it the same for types? Why this difference? Is this just a default of the compiler?</p>

答:
It’s true that assigning from a subtype P of a type U won’t require checks, since there can’t be a mismatch (even if the subtype has the same range as the type; subtype P is U; is perfectly legal and can be useful!)

The other way, from the type to the subtype, will involve checks, at least if the subtype is a subrange.

From the outside, the same is true of another type with a different range. However, there’s a subtle difference; with type/subtype, you can assign one to the other without conversion, if not without checks, but with type/type you must type-convert before the assignment, and any constraint violation will be checked at the conversion, not the assignment.

This may help to illustrate the point:

procedure Drimades is
   type Upper is range 10 .. 20;
   subtype Part is Upper range 10 .. 15;
   type Lower is new Upper range 10 .. 15;

   procedure Assign_U_To_P (U : Upper; To : out Part) is
   begin
      To := U;  -- requires check
   end Assign_U_To_P;

   procedure Assign_P_To_U (P : Part; To : out Upper) is
   begin
      To := P;  -- no check needed
   end Assign_P_To_U;

   procedure Assign_U_To_L (U : Upper; To : out Lower) is
   begin
      To := Lower (U);  -- requires check
   end Assign_U_To_L;

   procedure Assign_L_To_U (L : Lower; To : out Upper) is
   begin
   To := Upper (L);  -- no check required
   end Assign_L_To_U;

   U : Upper;
   P : Part;
   L : Lower;
begin
   Assign_U_To_P (20, P);
   Assign_P_To_U (15, U);
   Assign_U_To_L (20, L);
   Assign_L_To_U (15, U);
end Drimades;
```

<p>Compiling this with GNAT and the switch <code>-gnatG</code> produces this intermediate representation, not too hard to interpret I hope:</p>

<pre class="lang-ada prettyprint-override"><code>procedure drimades is
   type drimades__upper is range 10 .. 20;
   [type drimades__TupperB is new short_short_integer]
   freeze drimades__TupperB []
   subtype drimades__part is drimades__upper range 10 .. 15;
   [type drimades__TlowerB is new drimades__TupperB]
   freeze drimades__TlowerB []
   type drimades__lower is new drimades__upper range 10 .. 15;

   procedure drimades__assign_u_to_p (u : drimades__upper; to : out
     drimades__part) is
   begin
      [constraint_error when
        not (u in 10 .. 15)
        "range check failed"]
      to := u;
      return;
   end drimades__assign_u_to_p;

   procedure drimades__assign_p_to_u (p : drimades__part; to : out
     drimades__upper) is
   begin
      to := p;
      return;
   end drimades__assign_p_to_u;

   procedure drimades__assign_u_to_l (u : drimades__upper; to : out
     drimades__lower) is
   begin
      [constraint_error when
        not (u in 10 .. 15)
        "range check failed"]
      to := drimades__lower(u);
      return;
   end drimades__assign_u_to_l;

   procedure drimades__assign_l_to_u (l : drimades__lower; to : out
     drimades__upper) is
   begin
      to := drimades__upper(l);
      return;
   end drimades__assign_l_to_u;

   u : drimades__upper;
   p : drimades__part;
   l : drimades__lower;
begin
   drimades__assign_u_to_p (20, p);
   drimades__assign_p_to_u (15, u);
   drimades__assign_u_to_l (20, l);
   drimades__assign_l_to_u (15, u);
   return;
end drimades;
</code>```

Title: Type checking and range checking

Body:
It’s true that assigning from a subtype P of a type U won’t require checks, since there can’t be a mismatch (even if the subtype has the same range as the type; subtype P is U; is perfectly legal and can be useful!)

The other way, from the type to the subtype, will involve checks, at least if the subtype is a subrange.

From the outside, the same is true of another type with a different range. However, there’s a subtle difference; with type/subtype, you can assign one to the other without conversion, if not without checks, but with type/type you must type-convert before the assignment, and any constraint violation will be checked at the conversion, not the assignment.

This may help to illustrate the point:

procedure Drimades is
   type Upper is range 10 .. 20;
   subtype Part is Upper range 10 .. 15;
   type Lower is new Upper range 10 .. 15;

   procedure Assign_U_To_P (U : Upper; To : out Part) is
   begin
      To := U;  -- requires check
   end Assign_U_To_P;

   procedure Assign_P_To_U (P : Part; To : out Upper) is
   begin
      To := P;  -- no check needed
   end Assign_P_To_U;

   procedure Assign_U_To_L (U : Upper; To : out Lower) is
   begin
      To := Lower (U);  -- requires check
   end Assign_U_To_L;

   procedure Assign_L_To_U (L : Lower; To : out Upper) is
   begin
   To := Upper (L);  -- no check required
   end Assign_L_To_U;

   U : Upper;
   P : Part;
   L : Lower;
begin
   Assign_U_To_P (20, P);
   Assign_P_To_U (15, U);
   Assign_U_To_L (20, L);
   Assign_L_To_U (15, U);
end Drimades;

Compiling this with GNAT and the switch -gnatG produces this intermediate representation, not too hard to interpret I hope:

procedure drimades is
   type drimades__upper is range 10 .. 20;
   [type drimades__TupperB is new short_short_integer]
   freeze drimades__TupperB []
   subtype drimades__part is drimades__upper range 10 .. 15;
   [type drimades__TlowerB is new drimades__TupperB]
   freeze drimades__TlowerB []
   type drimades__lower is new drimades__upper range 10 .. 15;

   procedure drimades__assign_u_to_p (u : drimades__upper; to : out
     drimades__part) is
   begin
      [constraint_error when
        not (u in 10 .. 15)
        "range check failed"]
      to := u;
      return;
   end drimades__assign_u_to_p;

   procedure drimades__assign_p_to_u (p : drimades__part; to : out
     drimades__upper) is
   begin
      to := p;
      return;
   end drimades__assign_p_to_u;

   procedure drimades__assign_u_to_l (u : drimades__upper; to : out
     drimades__lower) is
   begin
      [constraint_error when
        not (u in 10 .. 15)
        "range check failed"]
      to := drimades__lower(u);
      return;
   end drimades__assign_u_to_l;

   procedure drimades__assign_l_to_u (l : drimades__lower; to : out
     drimades__upper) is
   begin
      to := drimades__upper(l);
      return;
   end drimades__assign_l_to_u;

   u : drimades__upper;
   p : drimades__part;
   l : drimades__lower;
begin
   drimades__assign_u_to_p (20, p);
   drimades__assign_p_to_u (15, u);
   drimades__assign_u_to_l (20, l);
   drimades__assign_l_to_u (15, u);
   return;
end drimades;


问:
Zipcode to city/state look-up XML file?
Trying to find an XML file I can use in lieu of a look-up database table until we get our web hosting switched over to the right DB.

Can anyone refer me to an XML file with elements whose children have zipcodes, states, and cities? E.g.:

```<code><zip code="98117">
    <state>WA</state>
    <city>Seattle</state>
</zip>
</code>```

Or

```<code><entry>
    <zip>98117</zip>
    <state>WA</state>
    <city>Seattle</city>
</entry>
</code>```

I'll be using LINQ in C# to query this data.

答:
Check out this one, it provides several different free ones.

https://stackoverflow.com/questions/24471/zip-code-database

OwnerDisplayName: Chris

Title: Zipcode to city/state look-up XML file?

Body:
Trying to find an XML file I can use in lieu of a look-up database table until we get our web hosting switched over to the right DB.

Can anyone refer me to an XML file with elements whose children have zipcodes, states, and cities? E.g.:

<zip code="98117">
    <state>WA</state>
    <city>Seattle</state>
</zip>

Or

<entry>
    <zip>98117</zip>
    <state>WA</state>
    <city>Seattle</city>
</entry>

I'll be using LINQ in C# to query this data.

LastEditorDisplayName: Chris

OwnerDisplayName: Tom Anderson


问:
How to subclass DefaultTableModel and change its dataVector
I want to extend the DefaultTableModel and change its dataVector.
I want to make the dataVector to show only specific fields of DataHolder in the column:

```<code> public class MyTableModel extends DefaultTableModel {

    /**
     * The data vector
     */
    private Vector<DataHolder>   dataVector_;

    //overridden method to add row in the table model
    public void addRow(DataHolder rowData) {
        insertRow(getRowCount(), rowData);
    }

    public void insertRow(int row, DataHolder rowData) {
            dataVector_.insertElementAt(rowData, row);
            fireTableRowsInserted(row, row);
        }

    ...} //end of MyTableModel

   class DataHolder{
     private int age;
     private int year;
     private int month;
     private int day;
    }
</code>```

How can i display specific DataHolder fields in my jtable? My table has 3 columns for month, day, and year.

答:
You need to create a custom model for this. The DefaultTableModel is not the best place to start.

Generally you would extend AbstractTableModel and use an ArrayList to store your DataHolder Objects. Then you need to implement the other methods of the TableModel interface. The Swing tutorial on How to Use Tables shows you the basics of how to do this.

Or you can use the Bean Table Model which does all the work for you.

Body:
I want to extend the DefaultTableModel and change its dataVector.
I want to make the dataVector to show only specific fields of DataHolder in the column:

 public class MyTableModel extends DefaultTableModel {

    /**
     * The data vector
     */
    private Vector<DataHolder>   dataVector_;

    //overridden method to add row in the table model
    public void addRow(DataHolder rowData) {
        insertRow(getRowCount(), rowData);
    }

    public void insertRow(int row, DataHolder rowData) {
            dataVector_.insertElementAt(rowData, row);
            fireTableRowsInserted(row, row);
        }

    ...} //end of MyTableModel

   class DataHolder{
     private int age;
     private int year;
     private int month;
     private int day;
    }

How can i display specific DataHolder fields in my jtable? My table has 3 columns for month, day, and year.


问:
OpenCV transformation from two images
Theres is a MATLAB example that matches two images and outputs the rotation and scale:
https://de.mathworks.com/help/vision/examples/find-image-rotation-and-scale-using-automated-feature-matching.html?requestedDomain=www.mathworks.com

My goal is to recreate this example using C++. I am using the same method of keypoint detection (Harris) and the keypoints seem to be mostly identical to the ones Matlab finds. So far so good.

```<code>cv::goodFeaturesToTrack(image_grayscale, corners, number_of_keypoints, 0.01, 5, mask, 3, true, 0.04);
    for (int i = 0; i < corners.size(); i++) {
        keypoints.push_back(cv::KeyPoint(corners[i], 5));
    }
</code>```

BRISK is used to extract features from the keypoints.

```<code>int Threshl = 120;
int Octaves = 8;
float PatternScales = 1.0f;

cv::Ptr<cv::Feature2D> extractor = cv::BRISK::create(Threshl, Octaves, PatternScales);
extractor->compute(image, mykeypoints, descriptors);
</code>```

These descriptors are then matched using flannbasedmatcher.

```<code>cv::FlannBasedMatcher matcher;
matcher.match(descriptors32A, descriptors32B, matches);
</code>```

Now the problem is that about 80% of my matches are wrong and unusable. For the identical set of images Matlab returns only a couple of matches from which only ~20% are wrong. I have tried sorting the Matches in C++ based on their distance value with no success. The values range between 300 and 700 and even the matches with the lowest distance are almost entirely incorrect.

Now 20% of good matches are enough to calculate the offset but a lot of processing power is wasted on checking wrong matches. What would be a better way to sort the correct matches or is there something obvious I am doing wrong?

EDIT:

I have switched from Harris/BRISK to AKAZE which seems to deliver much better features and matches that can easily be sorted by their distance value. The only downside is the much higher computation time. With two 1000px wide images AKAZE needs half a minute to find the keypoints (on a PC). I reducted this by scaling down the images which makes for an acceptable ~3-5 seconds.

答:
The method you are using finds for each point an nearest neighbour no matter how close it is. Two strategies are common:
1. Match set A to set B and set B to A and keep only matches which exist in both matchings.
2. Use 2 knnMatch and perform a ratio check, i.e. keep only the matches where the 1 NN is a lot closer than the 2 NN, e.g.
d1 < 0.8 * d2.

The MATLAB code uses SURF. OpenCV also provides SURF, SIFT and AKAZE, try one of these. Especially SURF would be interesting for a comparison.

Title: OpenCV transformation from two images

Body:
Theres is a MATLAB example that matches two images and outputs the rotation and scale:
https://de.mathworks.com/help/vision/examples/find-image-rotation-and-scale-using-automated-feature-matching.html?requestedDomain=www.mathworks.com

My goal is to recreate this example using C++. I am using the same method of keypoint detection (Harris) and the keypoints seem to be mostly identical to the ones Matlab finds. So far so good.

cv::goodFeaturesToTrack(image_grayscale, corners, number_of_keypoints, 0.01, 5, mask, 3, true, 0.04);
    for (int i = 0; i < corners.size(); i++) {
        keypoints.push_back(cv::KeyPoint(corners[i], 5));
    }

BRISK is used to extract features from the keypoints.

int Threshl = 120;
int Octaves = 8;
float PatternScales = 1.0f;

cv::Ptr<cv::Feature2D> extractor = cv::BRISK::create(Threshl, Octaves, PatternScales);
extractor->compute(image, mykeypoints, descriptors);

These descriptors are then matched using flannbasedmatcher.

cv::FlannBasedMatcher matcher;
matcher.match(descriptors32A, descriptors32B, matches);

Now the problem is that about 80% of my matches are wrong and unusable. For the identical set of images Matlab returns only a couple of matches from which only ~20% are wrong. I have tried sorting the Matches in C++ based on their distance value with no success. The values range between 300 and 700 and even the matches with the lowest distance are almost entirely incorrect.

Now 20% of good matches are enough to calculate the offset but a lot of processing power is wasted on checking wrong matches. What would be a better way to sort the correct matches or is there something obvious I am doing wrong?

EDIT:

I have switched from Harris/BRISK to AKAZE which seems to deliver much better features and matches that can easily be sorted by their distance value. The only downside is the much higher computation time. With two 1000px wide images AKAZE needs half a minute to find the keypoints (on a PC). I reducted this by scaling down the images which makes for an acceptable ~3-5 seconds.


问:
SQL Having Clause with Two Counts
I have a table with two columns: AUTHOR and PUBLISHER.
I want to get all authors that have been published by all the authors in the table.

```<code>SELECT AUTHOR AS
FROM TEMP1
HAVING COUNT(AUTHOR) = 2
GROUP BY AUTHOR;
</code>```

So this will give me the result set that I currently want because I know that there's only two publishers in the data, and they all have only published one of each author's books.

```<code>SELECT AUTHOR AS
FROM TEMP1
HAVING COUNT(AUTHOR) = COUNT(PUBLISHER)
GROUP BY AUTHOR, PUBLISHER;
</code>```

This doesn't work, as it just returns all authors. I'm guessing one (or both) of the counts might not be doing what I'm hoping for because the group by is wrong?

答:
You seem to want authors that have all publishers in the table:</p>

```<code>SELECT AUTHOR
FROM TEMP1
GROUP BY AUTHOR;
HAVING COUNT(*) = (SELECT COUNT(DISTINCT PUBNAME) FROM TEMP1);
</code>```

Title: SQL Having Clause with Two Counts

Body:
I have a table with two columns: AUTHOR and PUBLISHER.
I want to get all authors that have been published by all the authors in the table.

SELECT AUTHOR AS
FROM TEMP1
HAVING COUNT(AUTHOR) = 2
GROUP BY AUTHOR;

So this will give me the result set that I currently want because I know that there's only two publishers in the data, and they all have only published one of each author's books.

SELECT AUTHOR AS
FROM TEMP1
HAVING COUNT(AUTHOR) = COUNT(PUBLISHER)
GROUP BY AUTHOR, PUBLISHER;

This doesn't work, as it just returns all authors. I'm guessing one (or both) of the counts might not be doing what I'm hoping for because the group by is wrong?

Body:
You seem to want authors that have all publishers in the table:

SELECT AUTHOR
FROM TEMP1
GROUP BY AUTHOR;
HAVING COUNT(*) = (SELECT COUNT(DISTINCT PUBNAME) FROM TEMP1);


问:
How to reverse a git repository
There is a complete source code of a simple app, and a need to create teaching material based on it. So, I was thinking, init a git repository from complete sources, then start simplifying and removing parts in reverse order, and commit each subsequently simpler working version, until only a "Hello, World!" remains.

Question: how to reverse commits in a git repository, preserving commit messages etc, so that it looks like it was originally committed in this order?

It is acceptable to use any other VCS to do the simplifying part, as long as final result is a git repo.

答:
I wrote a script, "git-reverse.sh," that completely reverses all branches of a git repo.

It uses the a combination of git log --pretty="%T" to extract the tree hashes, and git commit-tree to make new commit objects against the original tree objects (the files), but with the parent edges reversed.

It seems to get stuck with some repos. I don't know why.

You can find it here:

https://github.com/gsylvie/git-reverse.sh

Example Usage

```<code>git clone --mirror [git-clone-url]
cd [repo.git]
./git-reverse.sh
git log --all --date-order --graph --decorate
</code>```

Example Output

```<code>$ ./git-reverse.sh
be0923ece8f73281e5e54906c29debb852894b92 - Reversed 1 of 360 (0%)
061bca59b29e75becbde66d2e510fc2b4059ccb2 - Reversed 2 of 360 (0%)
6a19039e05e3a0186187d0a6943634e8499b5a65 - Reversed 3 of 360 (0%)
7afe25e8caf93eb7107471a1bd078d4adc3f6999 - Reversed 4 of 360 (1%)
8b556f6fe97c5357c2328467a5ba01b77931ff82 - Reversed 5 of 360 (1%)
71fd0883975154f48059ca929db8ccb659c5049a - Reversed 6 of 360 (1%)
[etc...]
Switched to branch 'master'
Your branch and 'origin/master' have diverged,
and have 199 and 159 different commits each, respectively.
  (use "git pull" to merge the remote branch into yours)

*********************************************
| Git repo successfully reversed!!! :-) (-: |
*********************************************
To push the reversed repo:
  rm .git/packed-refs
  rm -rf .git/refs/remotes
  git push --mirror [new-git-clone-url]

WARNING:
========
Pushing a reversed git repo is a profoundly destructive and confusing operation.

You have a full 'git clone --mirror' backup stored somewhere safe, right?
</code>```

Title: How to reverse a git repository

Body:
I wrote a script, "git-reverse.sh," that completely reverses all branches of a git repo.

It uses the a combination of git log --pretty="%T" to extract the tree hashes, and git commit-tree to make new commit objects against the original tree objects (the files), but with the parent edges reversed.

It seems to get stuck with some repos. I don't know why.

You can find it here:

https://github.com/gsylvie/git-reverse.sh

Example Usage

git clone --mirror [git-clone-url]
cd [repo.git]
./git-reverse.sh
git log --all --date-order --graph --decorate

Example Output

$ ./git-reverse.sh
be0923ece8f73281e5e54906c29debb852894b92 - Reversed 1 of 360 (0%)
061bca59b29e75becbde66d2e510fc2b4059ccb2 - Reversed 2 of 360 (0%)
6a19039e05e3a0186187d0a6943634e8499b5a65 - Reversed 3 of 360 (0%)
7afe25e8caf93eb7107471a1bd078d4adc3f6999 - Reversed 4 of 360 (1%)
8b556f6fe97c5357c2328467a5ba01b77931ff82 - Reversed 5 of 360 (1%)
71fd0883975154f48059ca929db8ccb659c5049a - Reversed 6 of 360 (1%)
[etc...]
Switched to branch 'master'
Your branch and 'origin/master' have diverged,
and have 199 and 159 different commits each, respectively.
  (use "git pull" to merge the remote branch into yours)

*********************************************
| Git repo successfully reversed!!! :-) (-: |
*********************************************
To push the reversed repo:
  rm .git/packed-refs
  rm -rf .git/refs/remotes
  git push --mirror [new-git-clone-url]

WARNING:
========
Pushing a reversed git repo is a profoundly destructive and confusing operation.

You have a full 'git clone --mirror' backup stored somewhere safe, right?


问:
password authentication failed in postgresql with django
I'm trying to learn web development with Django and I was following this guide to do so.

Everything works fine until I run the following:

```<code>python manage.py makemigrations
</code>```

I get this error message:

```<code>password authentication failed for user "myprojectuser"
</code>```

I have checked and rechecked many times and the password is correct in the settings.py file.

Below is the content of the file (settings.py):

```<code>DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'myproject',
    'USER': 'myprojectuser',
    'PASSWORD': 'password',
    'HOST': 'localhost',
    'PORT': '',
    }
}
</code>```

I am using postgreSQL 9.5, python 2.7, and Django 1.10.

答: In case the "DATABASES" setting you showed are not the one you actually use - check if the "NAME" and the "USER" are in lowercase</p>

Body:
I'm trying to learn web development with Django and I was following this guide to do so.

Everything works fine until I run the following:

python manage.py makemigrations

I get this error message:

password authentication failed for user "myprojectuser"

I have checked and rechecked many times and the password is correct in the settings.py file.

Below is the content of the file (settings.py):

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'myproject',
    'USER': 'myprojectuser',
    'PASSWORD': 'password',
    'HOST': 'localhost',
    'PORT': '',
    }
}

I am using postgreSQL 9.5, python 2.7, and Django 1.10.


问:
How do you test code without uploading to the web server?
(This is a high level software development question)

I'm running a web app.  In the past, to test new features, I have uploaded under a subdirectory such as test/.  This generally broke all the URLs, so I'd have to redo the URLs in the test code. Then I'd have to rename all the URLs when I pushed it to the main site.  I'm sure there's a better way but don't know what people usually do.

Do you install a web server on your laptop?  I could always buy a cheap computer and run it as a test web server, I suppose.

Eventually I'd like to have a version control system with a friend also coding, so maybe we'd both need to install Apache and MySQL on our laptops?  That way we don't interfere with each other when testing new code.

答:
Any particular language or technology, or just in general?

My work now is mostly web applications in Java and Python

For the Java code, I have the entire company source tree checked out and built on my local machine, and when I want to test, I run the jetty webserver locally to test the deployment.

All our code also has unit tests written for them, and there are unit testing packages for pretty much any of the common languages in use.

For Python, my work is mostly in django so I use the included test server.

I run a local instance of lighttpd to test web stuff in general. Light weight, easy to configure.

If you want to test actual UIs to see if things behave as you expect, or to ensure you didn't break them, you can set up Selenium locally, or Mechanize.

For the company at large, we have two environments - a QA sandbox, and the production environment. The QA sandbox is a server where developers deploy their applications to first, and then they test to make sure everything works as expected before deploying to production.

As version control, we use subversion, but most developers use either git-svn or hg-svn to be able to do version control on their local machine before pushing changes back to the central subversion server.

OwnerDisplayName: anon


问:
Modal loading the header and footer instead of the just the attended page
I'm trying to use http://jquerymodal.com/ for a simple sign in modal. But for some reason clicking the link_to the modal. open up another view of the application html. Here is a screenshot:

Highlighted in blue there is the only thing that should be displayed but for some reason the entire application is being rendered... Here is my HTML for the page I want to render:

```<code><div id="modal">
  <h2>Sign In</h2>

  <%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
    <div class="field">
      <%= f.email_field :email, class: "form-input", autofocus: true, placeholder: "Email" %>
    </div>

    <div class="field">
      <%= f.password_field :password, class: "form-input", autocomplete: "off", placeholder: "Password" %>
    </div>

    <% if devise_mapping.rememberable? -%>
      <div class="field">
        <%= f.check_box :remember_me %>
        <%= f.label :remember_me %>
      </div>
    <% end -%>

    <div class="actions">
      <%= f.submit "Log in" %>
    </div>
  <% end %>

  <%= render "devise/shared/links" %>
</div>
</code>```

MODAL OPEN

```<code><%= link_to "Sign In", new_user_session_path, class: "button", rel: "modal:open" %>
</code>```

I feel like I'm missing something obvious here. What could it be?

答:
Presumably the modal open is going back to the server to fetch the code to render (on new_user_session_path) ?

This will be re-rendering your layout application.html.erb, which is why you are seeing the header and footer also appear.

The solution here is to turn off the layout in your user_sessions controller, or (if you're rendering to an iframe for example) replace it with a secondary layout e.g. application_modal.html.erb that doesn't do anything but set up the stylesheets.

You can find more info on working with layouts in this question.

Body:
I'm trying to use http://jquerymodal.com/ for a simple sign in modal. But for some reason clicking the link_to the modal. open up another view of the application html. Here is a screenshot:

Highlighted in blue there is the only thing that should be displayed but for some reason the entire application is being rendered... Here is my HTML for the page I want to render:

Sign In

  <%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>

      <%= f.email_field :email, class: "form-input", autofocus: true, placeholder: "Email" %>

      <%= f.password_field :password, class: "form-input", autocomplete: "off", placeholder: "Password" %>

    <% if devise_mapping.rememberable? -%>

        <%= f.check_box :remember_me %>
        <%= f.label :remember_me %>

    <% end -%>

      <%= f.submit "Log in" %>

  <% end %>

  <%= render "devise/shared/links" %>

MODAL OPEN

<%= link_to "Sign In", new_user_session_path, class: "button", rel: "modal:open" %>

I feel like I'm missing something obvious here. What could it be?


问:
Finding Multiple Values in Google Spread-Sheets
I have a list of roughly 800 VIN numbers that are each in a separate cell. I can and have already created a partial list of these so that they are separated by a comma thinking the find function would be able to highlight multiple cells if comma delineated, but this did not work. Instead of going one by one and using copy/paste plus find to locate each VIN in the second spreadsheet (which is understandably quite tedious and time consuming) I have been trying to find a way so that I can find multiple cells at once. Ex: 123456789, 234567891, 345678912, etc. so that each cell that contains those values will be located. I have tried the power tools improved search function by Adlebits, but it does not have this capability, which leads me to believe the only possible way to achieve this would be through the script editor, if at all. Any recommendations?</p>

答:
If you have a list of 800 vins and you want to search that list for a list of vins and create a new sheet of the found vins, this will do it. You can run it from the created menu.

```<code>function onOpen() {
 SpreadsheetApp.getActiveSpreadsheet().addMenu(
    'Vins', [
      { name: 'Find Vins', functionName: 'findVins' },
      ]);
}
function findVins() {
  var ss=SpreadsheetApp.getActiveSpreadsheet()
  var s=ss.getSheetByName("Sheet1")//get sheet with vin list
  var lr = s.getLastRow()
    s.getRange(2, 1, lr-1, 1).clearFormat()//clear background color
  var vinToSearch=s.getRange(2, 1, lr-1, 4).getValues()//get vin list values
  var s1=ss.getSheetByName("Sheet2")//get sheet with vins to find
  var lr1=s1.getLastRow()
  var vinToFind=s1.getRange(2, 1, lr1-1, 1).getValues()//get vins to find
  var found=[]
  for(var i=0;i<vinToFind.length;i++){
     for(var j=0;j<vinToSearch.length;j++){
      if(vinToFind[i][0]== vinToSearch[j][0]){//if numbers match
        found.push([vinToSearch[j][0],vinToSearch[j][1],vinToSearch[j]
[2],vinToSearch[j][3]])
       }}}
  var s2=ss.getSheetByName("Sheet3")
  var lr2 = s2.getLastRow()
  var lc2 =s2.getLastColumn()
  s2.getRange(2, 1, lr2, lc2).clearContent()
  s2.getRange(2, 1, found.length, found[0].length).setValues(found)
}
</code>```

Here is a shared spreadsheet you can copy and try.

https://docs.google.com/spreadsheets/d/1bC8SP6vVY0cMoZVg3lpo2ZtI2ch4FJ7kztlNHAVBWF8/edit?usp=sharing

Body:
If you have a list of 800 vins and you want to search that list for a list of vins and create a new sheet of the found vins, this will do it. You can run it from the created menu.

function onOpen() {
 SpreadsheetApp.getActiveSpreadsheet().addMenu(
    'Vins', [
      { name: 'Find Vins', functionName: 'findVins' },
      ]);
}
function findVins() {
  var ss=SpreadsheetApp.getActiveSpreadsheet()
  var s=ss.getSheetByName("Sheet1")//get sheet with vin list
  var lr = s.getLastRow()
    s.getRange(2, 1, lr-1, 1).clearFormat()//clear background color
  var vinToSearch=s.getRange(2, 1, lr-1, 4).getValues()//get vin list values
  var s1=ss.getSheetByName("Sheet2")//get sheet with vins to find
  var lr1=s1.getLastRow()
  var vinToFind=s1.getRange(2, 1, lr1-1, 1).getValues()//get vins to find
  var found=[]
  for(var i=0;i<vinToFind.length;i++){
     for(var j=0;j<vinToSearch.length;j++){
      if(vinToFind[i][0]== vinToSearch[j][0]){//if numbers match
        found.push([vinToSearch[j][0],vinToSearch[j][1],vinToSearch[j]
[2],vinToSearch[j][3]])
       }}}
  var s2=ss.getSheetByName("Sheet3")
  var lr2 = s2.getLastRow()
  var lc2 =s2.getLastColumn()
  s2.getRange(2, 1, lr2, lc2).clearContent()
  s2.getRange(2, 1, found.length, found[0].length).setValues(found)
}

Here is a shared spreadsheet you can copy and try.

https://docs.google.com/spreadsheets/d/1bC8SP6vVY0cMoZVg3lpo2ZtI2ch4FJ7kztlNHAVBWF8/edit?usp=sharing


问:
My nested for loop number pattern doesn't out put the correct pattern
I'm trying to print out this pattern but I'm having trouble arranging the numbers and spacing them out to achieve the expected out put.

```<code>Expected Output:
          1
        2 1
      3 2 1
    4 3 2 1
  5 4 3 2 1
6 5 4 3 2 1

1 2 3 4 5 6
  1 2 3 4 5
    1 2 3 4
      1 2 3
        1 2
          1
</code>```

Here is my Code. I don't know how to space the numbers and put the correct numbers in the order that the out put has specified.

```<code>import java.util.Scanner;

public class patterns{
 public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);

   for (int i = 6; i >= 1; i--)
    {

        for (int j = 1; j < i; j++)
        {
            System.out.print(" ");
        }

        for (int j = i; j <= 6; j++)
        {
            System.out.print(j);
        }

        System.out.println();
    }

                System.out.println();

   for (int i = 1; i <= 6; i++)
    {

        for (int j = 1; j < i; j++)
        {
            System.out.print(" ");
        }

        for (int j = i; j <= 6; j++)
        {
            System.out.print(j);
        }

        System.out.println();
    }

   }
 }
</code>```

This is the Output I'm Getting

```<code>run:
     6
    56
   456
  3456
 23456
123456

123456
 23456
  3456
   456
    56
     6
</code>```

答:
One way to do this would be to do:

```<code>import java.util.Scanner;

public class pattern{
 public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);

   for (int i = 1; i <= 6; i++)
    {

       String val = "";

        for (int j = i; j >= 1; j--)
        {
            val += j+ " ";

        }

        System.out.printf("%12s", val);
        System.out.println();
    }

                System.out.println();

   for (int i = 6; i >= 1; i--)
{
   String val = "";

   int ii=1;
    for (int j = i; j >= 1; j--)
    {
        val +=   ii + " ";
        ii++;
    }

    System.out.printf("%12s", val);
    System.out.println();
}

   }
</code>```

Output:

```<code>          1
        2 1
      3 2 1
    4 3 2 1
  5 4 3 2 1
6 5 4 3 2 1

1 2 3 4 5 6
  1 2 3 4 5
    1 2 3 4
      1 2 3
        1 2
          1
</code>```

One thing to keep in mind is that when you are trying to format text like you are, you should use printf rather than adding print lines.

Body:
I'm trying to print out this pattern but I'm having trouble arranging the numbers and spacing them out to achieve the expected out put.

Expected Output:
          1
        2 1
      3 2 1
    4 3 2 1
  5 4 3 2 1
6 5 4 3 2 1

1 2 3 4 5 6
  1 2 3 4 5
    1 2 3 4
      1 2 3
        1 2
          1

Here is my Code. I don't know how to space the numbers and put the correct numbers in the order that the out put has specified.

import java.util.Scanner;

public class patterns{
 public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);

   for (int i = 6; i >= 1; i--)
    {

        for (int j = 1; j < i; j++)
        {
            System.out.print(" ");
        }

        for (int j = i; j <= 6; j++)
        {
            System.out.print(j);
        }

        System.out.println();
    }

                System.out.println();

   for (int i = 1; i <= 6; i++)
    {

        for (int j = 1; j < i; j++)
        {
            System.out.print(" ");
        }

        for (int j = i; j <= 6; j++)
        {
            System.out.print(j);
        }

        System.out.println();
    }

   }
 }

This is the Output I'm Getting

run:
     6
    56
   456
  3456
 23456
123456

123456
 23456
  3456
   456
    56
     6

Body:
One way to do this would be to do:

import java.util.Scanner;

public class pattern{
 public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);

   for (int i = 1; i <= 6; i++)
    {

       String val = "";

        for (int j = i; j >= 1; j--)
        {
            val += j+ " ";

        }

        System.out.printf("%12s", val);
        System.out.println();
    }

                System.out.println();

   for (int i = 6; i >= 1; i--)
{
   String val = "";

   int ii=1;
    for (int j = i; j >= 1; j--)
    {
        val +=   ii + " ";
        ii++;
    }

    System.out.printf("%12s", val);
    System.out.println();
}

   }

Output:

          1
        2 1
      3 2 1
    4 3 2 1
  5 4 3 2 1
6 5 4 3 2 1

1 2 3 4 5 6
  1 2 3 4 5
    1 2 3 4
      1 2 3
        1 2
          1

One thing to keep in mind is that when you are trying to format text like you are, you should use printf rather than adding print lines.


问:
Rails - Generating multiple pages dynamically based on database records
I have a rails app and I need to loop through records in a database and match them with records in the same database then render a page with content that is based on the words present in the URL.

So imagine we have this database:

```<code>1 Basketball
2 Soccer
3 Baseball
4 Swimming
</code>```

I need to build a function that generates a page for each:

```<code>domain.com/basketball-soccer
domain.com/basketball-baseball
domain.com/basketball-swimming
domain.com/soccer-baseball
domain.com/soccer-swimming
domain.com/baseball-swimming
</code>```

This shouldn't generate pages for basketball-basketball, etc. and if it generates a page for basketball-soccer, page for soccer-basketball

also a page like domain.com/basketball-cricket because cricket isn't listed in the database

Example of how the content should display on each page:
This page is for a Basketball / Soccer match.

Looking for suggestions or resources on getting started with this. I'm not sure if it's possible to generate pages on the fly like this. I don't want to build each of these pages individually.

答:
You can do something like having a regex in your routes. Put this in your routes.rb:

```<code>match '/:regex', to: 'your_controller#your_action', constraints: {regex: /[a-zA-Z]+-[a-zA-Z]+?/}, via: :get
</code>```

Then in your controller, you will get a param called regex, which you can access with params[:regex] and handle properly.

Body:
I have a rails app and I need to loop through records in a database and match them with records in the same database then render a page with content that is based on the words present in the URL.

So imagine we have this database:

1 Basketball
2 Soccer
3 Baseball
4 Swimming

I need to build a function that generates a page for each:

domain.com/basketball-soccer
domain.com/basketball-baseball
domain.com/basketball-swimming
domain.com/soccer-baseball
domain.com/soccer-swimming
domain.com/baseball-swimming

This shouldn't generate pages for basketball-basketball, etc. and if it generates a page for basketball-soccer, page for soccer-basketball

also a page like domain.com/basketball-cricket because cricket isn't listed in the database

Example of how the content should display on each page:
This page is for a Basketball / Soccer match.

Looking for suggestions or resources on getting started with this. I'm not sure if it's possible to generate pages on the fly like this. I don't want to build each of these pages individually.

Body:
You can do something like having a regex in your routes. Put this in your routes.rb:

match '/:regex', to: 'your_controller#your_action', constraints: {regex: /[a-zA-Z]+-[a-zA-Z]+?/}, via: :get

Then in your controller, you will get a param called regex, which you can access with params[:regex] and handle properly.


问:
Android: Get all PendingIntents set with AlarmManager
I'm setting an alarm like this:

```<code>alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingEvent);
</code>```

I'm interested in removing all the alarms that where previously set, clearing them.

Is there a way for me to do that or to get all the alarms that are currently set so that I can delete them manually ?

答:
You need to create your pending intent and then cancel it</p>

```<code> AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    Intent updateServiceIntent = new Intent(context, MyPendingIntentService.class);
    PendingIntent pendingUpdateIntent = PendingIntent.getService(context, 0, updateServiceIntent, 0);

    // Cancel alarms
    try {
        alarmManager.cancel(pendingUpdateIntent);
    } catch (Exception e) {
        Log.e(TAG, "AlarmManager update was not canceled. " + e.toString());
    }
</code>```

Body:
I'm setting an alarm like this:

alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingEvent);

I'm interested in removing all the alarms that where previously set, clearing them.

Is there a way for me to do that or to get all the alarms that are currently set so that I can delete them manually ?

Body:
You need to create your pending intent and then cancel it

 AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    Intent updateServiceIntent = new Intent(context, MyPendingIntentService.class);
    PendingIntent pendingUpdateIntent = PendingIntent.getService(context, 0, updateServiceIntent, 0);

    // Cancel alarms
    try {
        alarmManager.cancel(pendingUpdateIntent);
    } catch (Exception e) {
        Log.e(TAG, "AlarmManager update was not canceled. " + e.toString());
    }


问:
Django Rest_framework "Got AttributeError when attempting to get a value for field Process"
I have encountered the error which I cannot solve when browsing towards my rest_framework api page.

The full error (Django Error) is :

```<code> Got AttributeError when attempting to get a value for field `process` on
 serializer `ResultSerializer`.
 The serializer field might be named incorrectly and not match any attribute
 or key on the `Shop` instance.
 Original exception text was: 'Shop' object has no attribute 'process'.
</code>```

It seems that the serializer trying to get a value in the field given in another serializer called ResultSerializer but could not found it. I have checked all the fields are all of them are correct.

Here is my models.py

```<code>from django.db import models

class ResultSet(models.Model):
    process = models.CharField(max_length=10)
    subprocess = models.CharField(max_length=10)

class Shop(models.Model):
    Establishment = models.CharField(max_length=100)
    Address = models.CharField(max_length=100)
    Suburb = models.CharField(max_length=50)
    Postcode = models.CharField(max_length=10)
    State = models.CharField(max_length=5)
    Establishment_Type = models.CharField(max_length=20)
    latitude = models.DecimalField(decimal_places=6, max_digits=12)
    longtitude = models.DecimalField(decimal_places=6, max_digits=12)
    class Meta:
        ordering = ('Establishment',)

class EntirelyResult(models.Model):
    Result = models.ManyToManyField(Shop, related_name='fullresult')
    Status = models.ManyToManyField(ResultSet, related_name='status')
</code>```

Here is my serializers.py

```<code>from rest_framework.serializers import ModelSerializer
from .models import Shop, ResultSet, EntirelyResult

class ResultSerializer(ModelSerializer):
    class Meta:
        model = ResultSet
        fields = ('process', 'subprocess')

class ShopSerializer(ModelSerializer):
   class Meta:
       model = Shop
       fields = ('__all__')

class ShopDetailSerializer(ModelSerializer):
    Result = ResultSerializer(many=True, read_only=True)
    Status = ShopSerializer(many=True, read_only=True)
    class Meta:
        model = EntirelyResult
        fields = ('Result', 'Status')
</code>```

Here is my views.py

```<code>from rest_framework.generics import ListAPIView
from .models import EntirelyResult
from .serializers import ShopDetailSerializer

class ShopDetailAPIView(ListAPIView):
    queryset = EntirelyResult.objects.all()
    serializer_class = ShopDetailSerializer
</code>```

Was there anything i miss to make the rest_framework properly?

答:
You got a typo in you serializer ShopDetailSerializer should be:

```<code>class ShopDetailSerializer(ModelSerializer):
    Result = ShopSerializer(many=True, read_only=True)
    Status = ResultSerializer(many=True, read_only=True)
</code>```

Edit:
EntirelyResult maps Result field to Shop and Status field to ResultSet while serializer initially mapped Result field to ResultSet and Status field to Shop

Body:
I have encountered the error which I cannot solve when browsing towards my rest_framework api page.

The full error (Django Error) is :

 Got AttributeError when attempting to get a value for field `process` on
 serializer `ResultSerializer`.
 The serializer field might be named incorrectly and not match any attribute
 or key on the `Shop` instance.
 Original exception text was: 'Shop' object has no attribute 'process'.

It seems that the serializer trying to get a value in the field given in another serializer called ResultSerializer but could not found it. I have checked all the fields are all of them are correct.

Here is my models.py

from django.db import models

class ResultSet(models.Model):
    process = models.CharField(max_length=10)
    subprocess = models.CharField(max_length=10)

class Shop(models.Model):
    Establishment = models.CharField(max_length=100)
    Address = models.CharField(max_length=100)
    Suburb = models.CharField(max_length=50)
    Postcode = models.CharField(max_length=10)
    State = models.CharField(max_length=5)
    Establishment_Type = models.CharField(max_length=20)
    latitude = models.DecimalField(decimal_places=6, max_digits=12)
    longtitude = models.DecimalField(decimal_places=6, max_digits=12)
    class Meta:
        ordering = ('Establishment',)

class EntirelyResult(models.Model):
    Result = models.ManyToManyField(Shop, related_name='fullresult')
    Status = models.ManyToManyField(ResultSet, related_name='status')

Here is my serializers.py

from rest_framework.serializers import ModelSerializer
from .models import Shop, ResultSet, EntirelyResult

class ResultSerializer(ModelSerializer):
    class Meta:
        model = ResultSet
        fields = ('process', 'subprocess')

class ShopSerializer(ModelSerializer):
   class Meta:
       model = Shop
       fields = ('__all__')

class ShopDetailSerializer(ModelSerializer):
    Result = ResultSerializer(many=True, read_only=True)
    Status = ShopSerializer(many=True, read_only=True)
    class Meta:
        model = EntirelyResult
        fields = ('Result', 'Status')

Here is my views.py

from rest_framework.generics import ListAPIView
from .models import EntirelyResult
from .serializers import ShopDetailSerializer

class ShopDetailAPIView(ListAPIView):
    queryset = EntirelyResult.objects.all()
    serializer_class = ShopDetailSerializer

Was there anything i miss to make the rest_framework properly?

Body:
You got a typo in you serializer ShopDetailSerializer should be:

class ShopDetailSerializer(ModelSerializer):
    Result = ShopSerializer(many=True, read_only=True)
    Status = ResultSerializer(many=True, read_only=True)

Edit:
EntirelyResult maps Result field to Shop and Status field to ResultSet while serializer initially mapped Result field to ResultSet and Status field to Shop


问:
python: calculation of time progress
I am writing python code that handles a text file and, for each line of input, calculates the time involved with the action described in that line, then reports a "running time". Required output like

```<code>        lapse     time
start            12:00
action1  0:37    12:37
action2  1:01    13:38
action3  0:30    14:08
</code>```

I came to some possible approaches but all looked awkward. Most of all I am confused about using either "time" or "strftime" or "datetime" or perhaps even something else. I am sure a simple elegant solution must exist.

NB timezones and DST are of no concern, if I can get to show UTC that is sufficient, at least for a beginning. In a later stage the last column (UTC) might be augmented by a column "local time" but that is secondary.

Edited, for apparent lack of clarity, to add example pseudo-code:

```<code> TIME='12:00'
 PCS_PER_HOUR=750
 with infile:
  read line of data
  process data, including calc of PCS_DONE
  LAPSE=PCS_DONE/PCS_PER_HOUR
  TIME += LAPSE
  print(' .....   ' ,format(data, data, data, LAPSE, TIME))
</code>```

My question is how to make the "TIME='12:00" into something that python can easily handle, and increment with a calculated integer number of seconds or minutes or whatever.

答:
Use datetime.timedelta.

Set the start time.

```<code>In [1]: import datetime
</code>```

The initial time is 12 hours.

```<code>In [2]: start = datetime.timedelta(hours=12)

In [3]: start
Out[3]: datetime.timedelta(0, 43200)
</code>```

Let's say that LAPSE is 0.23 hours (pieces divided by pieces per hour yields hours).

```<code>In [4]: action1 = datetime.timedelta(hours=0.23)
</code>```

Now you can format the times like you want. The standard representation is hours, minutes and seconds:

```<code>In [5]: str(start)
Out[5]: '12:00:00'

In [6]: str(start+action1)
Out[6]: '12:13:48'
</code>```

Title: python: calculation of time progress

Body:
I am writing python code that handles a text file and, for each line of input, calculates the time involved with the action described in that line, then reports a "running time". Required output like

        lapse     time
start            12:00
action1  0:37    12:37
action2  1:01    13:38
action3  0:30    14:08

I came to some possible approaches but all looked awkward. Most of all I am confused about using either "time" or "strftime" or "datetime" or perhaps even something else. I am sure a simple elegant solution must exist.

NB timezones and DST are of no concern, if I can get to show UTC that is sufficient, at least for a beginning. In a later stage the last column (UTC) might be augmented by a column "local time" but that is secondary.

Edited, for apparent lack of clarity, to add example pseudo-code:

 TIME='12:00'
 PCS_PER_HOUR=750
 with infile:
  read line of data
  process data, including calc of PCS_DONE
  LAPSE=PCS_DONE/PCS_PER_HOUR
  TIME += LAPSE
  print(' .....   ' ,format(data, data, data, LAPSE, TIME))

My question is how to make the "TIME='12:00" into something that python can easily handle, and increment with a calculated integer number of seconds or minutes or whatever.

Body:
Use datetime.timedelta.

Set the start time.

In [1]: import datetime

The initial time is 12 hours.

In [2]: start = datetime.timedelta(hours=12)

In [3]: start
Out[3]: datetime.timedelta(0, 43200)

Let's say that LAPSE is 0.23 hours (pieces divided by pieces per hour yields hours).

In [4]: action1 = datetime.timedelta(hours=0.23)

Now you can format the times like you want. The standard representation is hours, minutes and seconds:

In [5]: str(start)
Out[5]: '12:00:00'

In [6]: str(start+action1)
Out[6]: '12:13:48'