问:
Pygame UI clearing and updating
At the request of Furas, below are the segments of code in a Pygame Project that I'm currently working on. What I'm trying to get to happen is essentially like clearing everything visible on the previous window so I can start fresh with a new UI. When the code is run, and the "Start Game" button is pressed on the startup screen, the background colour updates, but everything that was previously rendered (the title and all of the buttons) remain on the screen. If anyone could offer any general pointers - or advice based off the code below - that would a great help!

The game_loop function:

This first part is where I need the screen to be cleared/updated. The game_loop contains more game logic, which is irrelevant to the current question, and what is pasted below is the only part of the function that interacts with the window.

```<code>new_surface = pygame.Surface((1,1))

def game_loop():

      global clicked_game
      global game_running
      clicked_game = True
      game_running = True

      if clicked_game == True:
        screen.fill( (0,0,0) )

      screen.blit(new_surface, (0,0))
      pygame.display.update()
</code>```

User Interface Initialisation and Functions:

These are the rest of the functions which follow later on from the actual game logic in game_loop:

```<code>        def quit_game():
          pygame.quit()
          quit()

        def update_options():
          global clicked_options
          clicked_options = True

        def button(window, msg, x_coord, y_coord, width, height, initial_colour, highlight_colour, button_action):
            mouse = pygame.mouse.get_pos()
            click = pygame.mouse.get_pressed()

            if x_coord + width > mouse[0] > x_coord and y_coord + height > mouse[1] > y_coord:
                pygame.draw.rect(window, highlight_colour, (x_coord, y_coord, width, height))
                if click[0] == 1:
                  button_action()
            else:
                pygame.draw.rect(window, initial_colour, (x_coord, y_coord, width, height))

            button_Text = pygame.font.Font("freesansbold.ttf",20)
            text_Surf, text_Rect = text_objects(msg, button_Text)
            text_Rect.center = ((x_coord + (width / 2)), (y_coord + (height / 2)))
            window.blit(text_Surf, text_Rect)

        while play:

          for event in pygame.event.get():
              if event.type == pygame.QUIT:
                play = False

          button(screen, "Start Game", 231, 236, 250, 50, e_m_light, e_m_lighter, game_loop)
          button(screen, "Options", 231, 336, 250, 50, e_m_light, e_m_lighter, update_options)
          button(screen, "Exit", 231, 436, 250, 50, e_m_light, e_m_lighter, quit_game)

          if clicked_options == True:
            #update title colour for testing purposes
            text_Surface = Font1.render('BlackJack Blast!', True, e_m_lighter)
          else:
            text_Surface = Font1.render('BlackJack Blast!', True, white)

          screen.blit(textSurface,(106,100))
          pygame.display.update()
</code>```

Screenshots of the UI before and after pressing "Start Game":

User Interface - Before

User Interface - After

I'm still a bit of a pygame novice, so if you're unsure of how to fix this specific problem, but recognise something else that could do with improving, or if you need any more information to develop a solution, please let me know!

答:
You blit all buttons all the times - in every loop - so why the shoud disaper ?

You can use variables like display_menu = True, display_game = True, display_options = False to control what elements display - silimiar to clicked_options.

But cleaner is to create separated while True loop  for every scene - Menu, Game, Option.

You can use functions like in example: https://stackoverflow.com/a/47460947/1832058

It uses front_page(), menu() to run different while True loops for two different scenes.

Or you can create classes for differnt scenes/stages: stage-example

You can see this on image:

Title: Pygame UI clearing and updating

Body:
At the request of Furas, below are the segments of code in a Pygame Project that I'm currently working on. What I'm trying to get to happen is essentially like clearing everything visible on the previous window so I can start fresh with a new UI. When the code is run, and the "Start Game" button is pressed on the startup screen, the background colour updates, but everything that was previously rendered (the title and all of the buttons) remain on the screen. If anyone could offer any general pointers - or advice based off the code below - that would a great help!

The game_loop function:

This first part is where I need the screen to be cleared/updated. The game_loop contains more game logic, which is irrelevant to the current question, and what is pasted below is the only part of the function that interacts with the window.

new_surface = pygame.Surface((1,1))

def game_loop():

      global clicked_game
      global game_running
      clicked_game = True
      game_running = True

      if clicked_game == True:
        screen.fill( (0,0,0) )

      screen.blit(new_surface, (0,0))
      pygame.display.update()

User Interface Initialisation and Functions:

These are the rest of the functions which follow later on from the actual game logic in game_loop:

        def quit_game():
          pygame.quit()
          quit()

        def update_options():
          global clicked_options
          clicked_options = True

        def button(window, msg, x_coord, y_coord, width, height, initial_colour, highlight_colour, button_action):
            mouse = pygame.mouse.get_pos()
            click = pygame.mouse.get_pressed()

            if x_coord + width > mouse[0] > x_coord and y_coord + height > mouse[1] > y_coord:
                pygame.draw.rect(window, highlight_colour, (x_coord, y_coord, width, height))
                if click[0] == 1:
                  button_action()
            else:
                pygame.draw.rect(window, initial_colour, (x_coord, y_coord, width, height))

            button_Text = pygame.font.Font("freesansbold.ttf",20)
            text_Surf, text_Rect = text_objects(msg, button_Text)
            text_Rect.center = ((x_coord + (width / 2)), (y_coord + (height / 2)))
            window.blit(text_Surf, text_Rect)

        while play:

          for event in pygame.event.get():
              if event.type == pygame.QUIT:
                play = False

          button(screen, "Start Game", 231, 236, 250, 50, e_m_light, e_m_lighter, game_loop)
          button(screen, "Options", 231, 336, 250, 50, e_m_light, e_m_lighter, update_options)
          button(screen, "Exit", 231, 436, 250, 50, e_m_light, e_m_lighter, quit_game)

          if clicked_options == True:
            #update title colour for testing purposes
            text_Surface = Font1.render('BlackJack Blast!', True, e_m_lighter)
          else:
            text_Surface = Font1.render('BlackJack Blast!', True, white)

          screen.blit(textSurface,(106,100))
          pygame.display.update()

Screenshots of the UI before and after pressing "Start Game":

User Interface - Before

User Interface - After

I'm still a bit of a pygame novice, so if you're unsure of how to fix this specific problem, but recognise something else that could do with improving, or if you need any more information to develop a solution, please let me know!


来源: stackexchange

问:
How to pass an object from one controller to another controller
I want to pass the object (that is placed in the model of a function in the first controller) to be received by a function of the second controller and place the received object in the function's model.

I understand that HTTP is stateless but is there a way to pass an object from one controller to another without using sessions in Spring MVC? Thanks.

Please see the sample code that I have given below.

FirstController.java

```<code>@RequestMapping(value="search-user",method=RequestMethod.POST)
public ModelAndView searchUser (HttpServletRequest request) {
    //Retrieve the search query by request.getParameter
    String searchQuery = request.getParameter("searchQuery");

    //Search for the user (this is the object that I want to pass)
    User user = userDao.searchUser(searchQuery);

    ModelAndView mav = new ModelAndView(new RedirectView("display-searched-user"));
    mav.addObject("user",user);

    return mav;
}
</code>```

SecondController.java

```<code>@RequestMapping(value="display-searched-user",method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView displayResultUser (HttpServletRequest request) {
    ModelAndView mav = new ModelAndView();
    mav.setViewName("result");

    //I want to receive the object from the FirstController and set that object in this function's model.

    return mav;
}
</code>```

答:
You will need to to send 2 calls from the client and send "User" to the second controller (which you should modify to accept a user). So the first call to "/search-user" returns an object which includes a user. The client extracts the user and sends it to "/display-searched-user".

A different approach could be, that the request in the second controller also accepts the parameter "searchQuery". In this case just modify your second controller to look like this:

```<code>@RequestMapping(value="display-searched-user",method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView displayResultUser (HttpServletRequest request) {
    ModelAndView mav = new ModelAndView();
    mav.setViewName("result");

    FirstController fc = new FirstController();
    return fc.searchUser(request);
}
</code>```

EDIT:

I just read CrazySabbath's proposal to create a transportation class. Assuming both controllers have access to it, I'd implement the transportation class like this:

```<code>public class UserTransporter {

    private static boolean userAvailable = false;
    private static User user;

    public static boolean isUserAvailable() {
        return userAvailable;
    }

    public static void setUser(User user) {
        UserTransporter.user = user;
        userAvailable = true;
    }

    public static User getUser() {
        userAvailable = false;
        return user;
    }
}
</code>```

Just to be clear: I added the boolean variable, because I wanted to make it impossible to get null or to get a user, which was already obtained by a call before. If you do not wish to check for that, just delete the boolean and any lines in which I used it.

The first controller would need to be changed to this:

```<code>@RequestMapping(value="search-user",method=RequestMethod.POST)
public ModelAndView searchUser (HttpServletRequest request) {
    //Retrieve the search query by request.getParameter
    String searchQuery = request.getParameter("searchQuery");

    //Search for the user (this is the object that I want to pass)
    User user = userDao.searchUser(searchQuery);

    ModelAndView mav = new ModelAndView(new RedirectView("display-searched-user"));
    mav.addObject("user",user);

    UserTransporter.setUser(user);

    return mav;
}
</code>```

The second controller would need to be changed to this:

```<code>@RequestMapping(value="display-searched-user",method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView displayResultUser (HttpServletRequest request) {
    ModelAndView mav = new ModelAndView();
    mav.setViewName("result");

    User user;
    if(UserTransporter.isUserAvailable()) user = UserTransporter.getUser();
    else return "ERROR, no user available to display";

    //do something with the obtained user object

    return mav;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to pass the object (that is placed in the model of a function in the first controller) to be received by a function of the second controller and place the received object in the function's model.

I understand that HTTP is stateless but is there a way to pass an object from one controller to another without using sessions in Spring MVC? Thanks.

Please see the sample code that I have given below.

FirstController.java

@RequestMapping(value="search-user",method=RequestMethod.POST)
public ModelAndView searchUser (HttpServletRequest request) {
    //Retrieve the search query by request.getParameter
    String searchQuery = request.getParameter("searchQuery");

    //Search for the user (this is the object that I want to pass)
    User user = userDao.searchUser(searchQuery);

    ModelAndView mav = new ModelAndView(new RedirectView("display-searched-user"));
    mav.addObject("user",user);

    return mav;
}

SecondController.java

@RequestMapping(value="display-searched-user",method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView displayResultUser (HttpServletRequest request) {
    ModelAndView mav = new ModelAndView();
    mav.setViewName("result");

    //I want to receive the object from the FirstController and set that object in this function's model.

    return mav;
}

Body:
You will need to to send 2 calls from the client and send "User" to the second controller (which you should modify to accept a user). So the first call to "/search-user" returns an object which includes a user. The client extracts the user and sends it to "/display-searched-user".

A different approach could be, that the request in the second controller also accepts the parameter "searchQuery". In this case just modify your second controller to look like this:

@RequestMapping(value="display-searched-user",method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView displayResultUser (HttpServletRequest request) {
    ModelAndView mav = new ModelAndView();
    mav.setViewName("result");

    FirstController fc = new FirstController();
    return fc.searchUser(request);
}

EDIT:

I just read CrazySabbath's proposal to create a transportation class. Assuming both controllers have access to it, I'd implement the transportation class like this:

public class UserTransporter {

    private static boolean userAvailable = false;
    private static User user;

    public static boolean isUserAvailable() {
        return userAvailable;
    }

    public static void setUser(User user) {
        UserTransporter.user = user;
        userAvailable = true;
    }

    public static User getUser() {
        userAvailable = false;
        return user;
    }
}

Just to be clear: I added the boolean variable, because I wanted to make it impossible to get null or to get a user, which was already obtained by a call before. If you do not wish to check for that, just delete the boolean and any lines in which I used it.

The first controller would need to be changed to this:

@RequestMapping(value="search-user",method=RequestMethod.POST)
public ModelAndView searchUser (HttpServletRequest request) {
    //Retrieve the search query by request.getParameter
    String searchQuery = request.getParameter("searchQuery");

    //Search for the user (this is the object that I want to pass)
    User user = userDao.searchUser(searchQuery);

    ModelAndView mav = new ModelAndView(new RedirectView("display-searched-user"));
    mav.addObject("user",user);

    UserTransporter.setUser(user);

    return mav;
}

The second controller would need to be changed to this:

@RequestMapping(value="display-searched-user",method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView displayResultUser (HttpServletRequest request) {
    ModelAndView mav = new ModelAndView();
    mav.setViewName("result");

    User user;
    if(UserTransporter.isUserAvailable()) user = UserTransporter.getUser();
    else return "ERROR, no user available to display";

    //do something with the obtained user object

    return mav;
}


问:
What relationships should be looked for when asked to create a normalized Entity-Relationship diagram?
The following ER Diagram was constructed and asked to be Normalized. I was curious as to was er symbols one should pay attention to when normalizing a database model?

https://i.stack.imgur.com/GFIFL.png

答:
In your tags, you have entity-relationship-model, and normalization, but not relational-model.  Strictly speaking, normalization pertains to the relational model of data, but not to the ER model of data.   ER diagrams are frequently used to depict either one of these two models,  or some kind of hybrid model that combines features of both ER and relational.

Your diagram appears to be a diagram of an ER model.  Consider the relationship "Must have/can have".  It has crows feet at both ends.  In a relational model, there would have to be another box, a junction box between the two entity boxes, to hold a table with two foreign keys.  In fact, there are no foreign keys in your diagram at all!  So it really looks like an ER model.

So what I'm going to say is that you have to convert this diagram from an ER model to a relational model, before you even think about normalization.  This may be the direct opposite of what your teacher is teaching you.  I can't help you with that.


问:
Why can't programs be proven?
Why can't a computer program be proven just as a mathematical statement can?  A mathematical proof is built up on other proofs, which are built up from yet more proofs and on down to axioms - those truths truths we hold as self evident.

Computer programs don't seem to have such a structure.  If you write a computer program, how is it that you can take previous proven works and use them to show the truth of your program?  You can't since none exist.  Further, what are the axioms of programming?  The very atomic truths of the field?

I don't have good answers to the above.  But it seems software can't be proven because it is art and not science.  How do you prove a Picasso?

答:
Theres much research in this area.. as others have said, the constructs within a program language are complex, and this only gets worse, when trying to validate or prove for any given inputs.

However, many languages allow for specifications, on what inputs are acceptable (preconditions), and also allow for specifying the end result (post conditions).

Such languages include: B, Event B, Ada, fortran.

And of course, there are many tools which are designed to help us prove certain properties about programs. For example, to prove deadlock freedom , one could crunch their program through SPIN.

There are also many tools out there that also help us detect logic errors. This can be done via static analysis (goanna, satabs) or actual execution of code (gnu valgrind?).

However, there is no one tool which really allows one to prove an entire program, from inception (specification), implementation and deployment. The B method comes close, but its implementation checking is very very weak. (It assumes that humans are infalible in the translation of speicficaiton into implmentation).

As a side note, when using the B method, you'll frequently find yourself building complex proofs from smaller axioms. (And the same applies for other exhasustive theorem provers).

ContentLicense: CC BY-SA 2.5

Title: Why can't programs be proven?

OwnerDisplayName: Alex Lim


问:
Automatic update a Windows application
How do I develop my Windows application so it will auto update on the client machine, like Firefox, Skype, etc.?

Is there any simple approach or any open source library which help me to do it just following some steps or a few lines of code?

答: There is also the Update Block in the Ent Lib by msft.</p>

Title: Automatic update a Windows application


问:
Laravel 5.3 & Crypt - invalid payload
I have an app I wrote in Laravel 5.23. In it I am encrypting certain sensitive user data before I store in a table using:

```<code>'Crypt'     => Illuminate\Support\Facades\Crypt::class,
</code>```

The field's migration is:

```<code>$table->string('field_account_name')->nullable();
</code>```

I have mutators set up in the class to do this:

```<code>public function getFieldAccountNameClearAttribute($value)
{
    if ($this->field_account_name) {
        try {
            return Crypt::decrypt($this->field_account_name);
        } catch (DecryptException $e) {
            return 'INVALID';
        }
    } else {
        return $this->field_account_name;
    }
}
</code>```

and

```<code>public function setFieldAccountNameClearAttribute($value)
{
    $this->attributes['field_account_name'] = Crypt::encrypt($value);
}
</code>```

This has been working for a long time perfectly but a user waived their magic a week ago and triggered:

```<code>Exception 'ErrorException' with message 'The payload is invalid
</code>```

I have managed to replicate the issue by placing special characters (such as ') in the field as part of a long string with spaces.

The date is encrypted and stored but it fails when retrieved.

Is there characters I should exclude from the encryption at the front end to avoid this? I cannot find an answer to this.

Or perhaps the field should be text instead of string?

答:
The issue could be related to the amount of data you're trying to encrypt and how it's stored in the database. If the encrypted text exceeds 255 characters, it will get truncated when it's added to the database, which means it's cannot be decrypted.

You should update your existing migration to:

```<code>$table->text('field_account_name')->nullable();
</code>```

or use the following in a new migration:

```<code>$table->text('field_account_name')->nullable()->change();
</code>```

Title: Laravel 5.3 & Crypt - invalid payload

Body:
I have an app I wrote in Laravel 5.23. In it I am encrypting certain sensitive user data before I store in a table using:

'Crypt'     => Illuminate\Support\Facades\Crypt::class,

The field's migration is:

$table->string('field_account_name')->nullable();

I have mutators set up in the class to do this:

public function getFieldAccountNameClearAttribute($value)
{
    if ($this->field_account_name) {
        try {
            return Crypt::decrypt($this->field_account_name);
        } catch (DecryptException $e) {
            return 'INVALID';
        }
    } else {
        return $this->field_account_name;
    }
}

and

public function setFieldAccountNameClearAttribute($value)
{
    $this->attributes['field_account_name'] = Crypt::encrypt($value);
}

This has been working for a long time perfectly but a user waived their magic a week ago and triggered:

Exception 'ErrorException' with message 'The payload is invalid

I have managed to replicate the issue by placing special characters (such as ') in the field as part of a long string with spaces.

The date is encrypted and stored but it fails when retrieved.

Is there characters I should exclude from the encryption at the front end to avoid this? I cannot find an answer to this.

Or perhaps the field should be text instead of string?

Body:
The issue could be related to the amount of data you're trying to encrypt and how it's stored in the database. If the encrypted text exceeds 255 characters, it will get truncated when it's added to the database, which means it's cannot be decrypted.

You should update your existing migration to:

$table->text('field_account_name')->nullable();

or use the following in a new migration:

$table->text('field_account_name')->nullable()->change();


问:
Gather boolean from repeating table
I'm having trouble finding the best way to achieve this. I'd like to solve it with just a select query if possible, but I'm not sure if it is solvable by just a select.

Customer Repeating Table:

- customer_id (PK)

- year (PK)

- code1

- code2

This is a repeating table, so a customer has multiple entries with their id number for the same year.

I need to some how gather a boolean or SELECT 'Y' to use as a flag where:

```<code>WHERE customer_id  = '1001'
AND year = '2017'
AND...
</code>```

If there is any case for this customer for each of there code2

where (sum(code1 LIKE 'D%') <= sum(code1 LIKE 'R%')) then I need to return TRUE or 'Y'

Example Table

```<code>id      year    code1   code2

1001    2017    RE      AB
1001    2017    D2      AB
1001    2017    RW      BC
</code>```

So here, it would return TRUE because for code2 that are AB,

```<code>sum(code1 LIKE 'D%') <= sum(code1 LIKE 'R%') = TRUE
</code>```

I need to compare the sum of the code1's for all the different code2's that a customer has.

答:
I think you just need to toss some CASE statements at this and aggregate:

```<code>SELECT
  CASE WHEN Sum(CASE WHEN code1 LIKE 'D%' THEN 1 ELSE 0 END) <= Sum(CASE WHEN code1 LIKE 'R%' THEN 1 ELSE 0 END) THEN 'True' ELSE 'False' END AS yourtest
FROM yourTable
WHERE id=1001 AND year=2017
</code>```

Title: Gather boolean from repeating table

Body:
I'm having trouble finding the best way to achieve this. I'd like to solve it with just a select query if possible, but I'm not sure if it is solvable by just a select.

Customer Repeating Table:

- customer_id (PK)

- year (PK)

- code1

- code2

This is a repeating table, so a customer has multiple entries with their id number for the same year.

I need to some how gather a boolean or SELECT 'Y' to use as a flag where:

WHERE customer_id  = '1001'
AND year = '2017'
AND...

If there is any case for this customer for each of there code2

where (sum(code1 LIKE 'D%') <= sum(code1 LIKE 'R%')) then I need to return TRUE or 'Y'

Example Table

id      year    code1   code2

1001    2017    RE      AB
1001    2017    D2      AB
1001    2017    RW      BC

So here, it would return TRUE because for code2 that are AB,

sum(code1 LIKE 'D%') <= sum(code1 LIKE 'R%') = TRUE

I need to compare the sum of the code1's for all the different code2's that a customer has.

Body:
I think you just need to toss some CASE statements at this and aggregate:

SELECT
  CASE WHEN Sum(CASE WHEN code1 LIKE 'D%' THEN 1 ELSE 0 END) <= Sum(CASE WHEN code1 LIKE 'R%' THEN 1 ELSE 0 END) THEN 'True' ELSE 'False' END AS yourtest
FROM yourTable
WHERE id=1001 AND year=2017


问:
How to use Redirect in React Router v4 in right way?
I have routes like that:

```<code><Router history={this.props.history}>
  <div>
    <Route exact path="/" name="Home" component={Index} />
    <Route path="/colors" component={Palette} />
    <Route path="/icons" component={Icons} />
    <Route path="/forms" component={Forms} />
    <Route path="/other" component={Other} />
    <Route path="/dashboard" component={Dashboard} />
    <Switch>
      <Redirect from="/dashboard" to="/dashboard/my-account" />
      <Route exact path="/dashboard/my-account" />
      <Route exact path="/dashboard/service-request" />
      <Route exact path="/dashboard/payments" />
      <Route exact path="/dashboard/settings" />
    </Switch>
  </div>
</Router>
</code>```

When user goes to /dashboard I want to redirect them to /dashboard/my-account.

So in my case all /dashboard/* routes redirect to /dashboard/my-account

How to use React Router v4 similar to  feature in the prev. version?

Thanks.

答:
I just hit this situation too. Here's what I did with the <Switch>:

```<code><Switch>
  <Route exact path="/dashboard" render={() => <Redirect to="dashboard/my-account" />} />
  <Route path="/dashboard/my-account" />
  <Route path="/dashboard/service-request" />
  <Route path="/dashboard/payments" />
  <Route path="/dashboard/settings" />
</Switch>
</code>```

With this. /dashboard will redirect to /dashboard/my-account but /dashboard/foo wont match anything. I recommend adding a NotFound component or something to catch the 404s.

Body:
I have routes like that:

<Router history={this.props.history}>

    <Route exact path="/" name="Home" component={Index} />
    <Route path="/colors" component={Palette} />
    <Route path="/icons" component={Icons} />
    <Route path="/forms" component={Forms} />
    <Route path="/other" component={Other} />
    <Route path="/dashboard" component={Dashboard} />
    <Switch>
      <Redirect from="/dashboard" to="/dashboard/my-account" />
      <Route exact path="/dashboard/my-account" />
      <Route exact path="/dashboard/service-request" />
      <Route exact path="/dashboard/payments" />
      <Route exact path="/dashboard/settings" />
    </Switch>

</Router>

When user goes to /dashboard I want to redirect them to /dashboard/my-account.

So in my case all /dashboard/* routes redirect to /dashboard/my-account

How to use React Router v4 similar to  feature in the prev. version?

Thanks.

Body:
I just hit this situation too. Here's what I did with the <Switch>:

<Switch>
  <Route exact path="/dashboard" render={() => <Redirect to="dashboard/my-account" />} />
  <Route path="/dashboard/my-account" />
  <Route path="/dashboard/service-request" />
  <Route path="/dashboard/payments" />
  <Route path="/dashboard/settings" />
</Switch>

With this. /dashboard will redirect to /dashboard/my-account but /dashboard/foo wont match anything. I recommend adding a NotFound component or something to catch the 404s.


问:
vue.js $emit not received by parent when multiple calls in short amount of time
I tried to implement a simple notification system with notification Store inspired by this snippet form Linus Borg :  https://jsfiddle.net/Linusborg/wnb6tdg8/

It is working fine when you add one notification at a time, but when you add a second notification before the first one disappears the notificationMessage emit its "close-notification" event but the parent notificationBox component does not execute the "removeNotification" function.  removeNotification is called after the emit if you use the click event on the notification though. So there is probably a issue with the timeout but i can't figure out what.

NotificationStore.js

```<code>class NotificationStore {
  constructor () {
    this.state = {
      notifications: []
    }
  }
  addNotification (notification) {
    this.state.notifications.push(notification)
  }
  removeNotification (notification) {
    console.log('remove from store')
    this.state.notifications.splice(this.state.notifications.indexOf(notification), 1)
  }
}

export default new NotificationStore()
</code>```

App.vue

```<code><template>
  <div id="app">
    <notification-box></notification-box>
    <div @click="createNotif">
      create new notification
    </div>
  </div>
</template>

<script>
  import notificationMessage from './components/notificationMessage.vue'
  import notificationBox from './components/notificationBox.vue'
  import NotificationStore from './notificationStore'

  export default {
    name: 'app',
    methods: {
      createNotif () {
        NotificationStore.addNotification({
          name: 'test',
          message: 'this is a test notification',
          type: 'warning'
        })
      }
    },
    components: {
      notificationMessage,
      notificationBox
    }
  }
</script>
</code>```

notificationBox.vue

```<code><template>
  <div :class="'notification-box'">
      <notification-message v-for="(notification, index) in notifications" :notification="notification" :key="index" v-on:closeNotification="removeNotification"></notification-message>
  </div>
</template>

<script>
  import notificationMessage from './notificationMessage.vue'
  import NotificationStore from '../notificationStore'

  export default {
    name: 'notificationBox',
    data () {
      return {
        notifications: NotificationStore.state.notifications
      }
    },
    methods: {
      removeNotification: function (notification) {
        console.log('removeNotification')
        NotificationStore.removeNotification(notification)
      }
    },
    components: {
      notificationMessage
    }
  }
</script>
</code>```

notificationMessage.vue

```<code><template>
    <div :class="'notification-message ' + notification.type" @click="triggerClose(notification)">
      {{ notification.message }}
    </div>
</template>

<script>
  export default {
    name: 'notificationMessage',
    props: {
      notification: {
        type: Object,
        required: true
      },
      delay: {
        type: Number,
        required: false,
        default () {
          return 3000
        }
      }
    },
    data () {
      return {
        notificationTimer: null
      }
    },
    methods: {
      triggerClose (notification) {
        console.log('triggerClose')
        clearTimeout(this.notificationTimer)
        this.$emit('closeNotification', notification)
      }
    },
    mounted () {
      this.notificationTimer = setTimeout(() => {
        console.log('call trigger close ' + this.notification.name)
        this.triggerClose(this.notification)
      }, this.delay)
    }
  }
</script>
</code>```

thanks for the help

答:
my small fiddle from back in the days is still making the rounds I see :D

That fiddle is still using Vue 1. In Vue 2, you have to key your list elements, and you tried to do that.

But a key should be a unique value identifying a data item reliably. You are using the array index, which does not do that - as soon as an element is removed, indices of the following items change.

That's why you see the behaviour you are seeing: Vue can't reliably remove the right element because our keys don't do their job.

So I would suggest to use a package like nanoid to create a really unique id per notification - but a simple counter would probably work as well:

```<code>let _id = 0
class NotificationStore {
  constructor () {
    this.state = {
      notifications: []
    }
  }
  addNotification (notification) {
    this.state.notifications.push({ ...notification, id: _id++ })
  }
  removeNotification (notification) {
    console.log('remove from store')
    this.state.notifications.splice(this.state.notifications.indexOf(notification), 1)
  }
}
</code>```

and in the notification component:

```<code><notification-message
  v-for="(notification, index) in notifications"
  :notification="notification"
  :key="notification.id"
  v-on:closeNotification="removeNotification"
></notification-message>
</code>```

Body:
I tried to implement a simple notification system with notification Store inspired by this snippet form Linus Borg :  https://jsfiddle.net/Linusborg/wnb6tdg8/

It is working fine when you add one notification at a time, but when you add a second notification before the first one disappears the notificationMessage emit its "close-notification" event but the parent notificationBox component does not execute the "removeNotification" function.  removeNotification is called after the emit if you use the click event on the notification though. So there is probably a issue with the timeout but i can't figure out what.

NotificationStore.js

class NotificationStore {
  constructor () {
    this.state = {
      notifications: []
    }
  }
  addNotification (notification) {
    this.state.notifications.push(notification)
  }
  removeNotification (notification) {
    console.log('remove from store')
    this.state.notifications.splice(this.state.notifications.indexOf(notification), 1)
  }
}

export default new NotificationStore()

App.vue

<template>

    <notification-box></notification-box>

      create new notification

</template>

notificationBox.vue

<template>

      <notification-message v-for="(notification, index) in notifications" :notification="notification" :key="index" v-on:closeNotification="removeNotification"></notification-message>

</template>

notificationMessage.vue

<template>

      {{ notification.message }}

</template>

thanks for the help

Body:
my small fiddle from back in the days is still making the rounds I see :D

That fiddle is still using Vue 1. In Vue 2, you have to key your list elements, and you tried to do that.

But a key should be a unique value identifying a data item reliably. You are using the array index, which does not do that - as soon as an element is removed, indices of the following items change.

That's why you see the behaviour you are seeing: Vue can't reliably remove the right element because our keys don't do their job.

So I would suggest to use a package like nanoid to create a really unique id per notification - but a simple counter would probably work as well:

let _id = 0
class NotificationStore {
  constructor () {
    this.state = {
      notifications: []
    }
  }
  addNotification (notification) {
    this.state.notifications.push({ ...notification, id: _id++ })
  }
  removeNotification (notification) {
    console.log('remove from store')
    this.state.notifications.splice(this.state.notifications.indexOf(notification), 1)
  }
}

and in the notification component:

<notification-message
  v-for="(notification, index) in notifications"
  :notification="notification"
  :key="notification.id"
  v-on:closeNotification="removeNotification"
></notification-message>


问:
Dealing with Thread, Handler and message: "Restart" a thread
public class Connection extends Activity implements Runnable {

```<code>            public static final int CONNECTION_ERROR = 1;
            public static final int CONNECTION_DONE = 3;

            @Override
            public void onCreate(Bundle icicle) {
                super.onCreate(icicle);
                createConnection();
            }

            public void createConnection() {
                m_ProgressDialog = ProgressDialog.show(this, "Please wait...","Connection ...", true, false);
                thread = new Thread(this);
                thread.start();
            }

            public void run() {
                int i = connecTion();
                handler.sendEmptyMessage(i);
            }

            private Handler handler = new Handler() {

                @Override
                public void handleMessage(Message msg) {
                 if (msg.what == CONNECTION_ERROR) {
                        m_ProgressDialog.dismiss();

                        AlertDialog.Builder alt_bld = new AlertDialog.Builder(thisA);
                        alt_bld.setMessage("Failed to connect to the server");
                        alt_bld.setCancelable(false);
                        alt_bld.setNegativeButton("Quit",new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int id) {finish();}});
                        alt_bld.setPositiveButton("Try Again",new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
//HERE IS THE PROBLEM
                                        /*m_ProgressDialog.show(thisA, "Please wait...", "Connection ...", true, false);
                                        connecTion();*/
                                    }
                                });

                        AlertDialog alert = alt_bld.create();
                        alert.setTitle("ChatApp");
                        alert.setIcon(R.drawable.icon);
                        alert.show();
                    }
                    else {
                    m_ProgressDialog.dismiss();
                    finish();
                    }
                }
            };

            private int connecTion() {
                /** Create a connection */
                try {

                           //Function to create the connection (throwing error if there is a pb)

                } catch (Exception e) {
                    Log.e("App","Failed to connect");
                    return CONNECTION_ERROR;
                }
                //If no error left, everything is OK
                return CONNECTION_DONE;

            }
</code>```

I want to realize a "Try Again" button which launch again the thread to create the connection and the ProgressDialog in parallel.
How can I kill the "old" thread and create the new one properly?
Is it better to keep the same thread alive and just dealing with Handler and Messages? Use service?

Thank you !

答:
You could setup a pipeline thread; I've detailed how you can do this on my blog (Threading 5).  Also note that once a thread completes, it cannot be restarted again.  You can however, keep a single thread alive and schedule work to it.

Another approach is to instantiate a single thread each time you offload the background task; it'll complete and expire - this is the simpler way of going about it.  It might be worth looking into AsyncTask.

Body:
public class Connection extends Activity implements Runnable {

            public static final int CONNECTION_ERROR = 1;
            public static final int CONNECTION_DONE = 3;

            @Override
            public void onCreate(Bundle icicle) {
                super.onCreate(icicle);
                createConnection();
            }

            public void createConnection() {
                m_ProgressDialog = ProgressDialog.show(this, "Please wait...","Connection ...", true, false);
                thread = new Thread(this);
                thread.start();
            }

            public void run() {
                int i = connecTion();
                handler.sendEmptyMessage(i);
            }

            private Handler handler = new Handler() {

                @Override
                public void handleMessage(Message msg) {
                 if (msg.what == CONNECTION_ERROR) {
                        m_ProgressDialog.dismiss();

                        AlertDialog.Builder alt_bld = new AlertDialog.Builder(thisA);
                        alt_bld.setMessage("Failed to connect to the server");
                        alt_bld.setCancelable(false);
                        alt_bld.setNegativeButton("Quit",new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int id) {finish();}});
                        alt_bld.setPositiveButton("Try Again",new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
//HERE IS THE PROBLEM
                                        /*m_ProgressDialog.show(thisA, "Please wait...", "Connection ...", true, false);
                                        connecTion();*/
                                    }
                                });

                        AlertDialog alert = alt_bld.create();
                        alert.setTitle("ChatApp");
                        alert.setIcon(R.drawable.icon);
                        alert.show();
                    }
                    else {
                    m_ProgressDialog.dismiss();
                    finish();
                    }
                }
            };

            private int connecTion() {
                /** Create a connection */
                try {

                           //Function to create the connection (throwing error if there is a pb)

                } catch (Exception e) {
                    Log.e("App","Failed to connect");
                    return CONNECTION_ERROR;
                }
                //If no error left, everything is OK
                return CONNECTION_DONE;

            }

I want to realize a "Try Again" button which launch again the thread to create the connection and the ProgressDialog in parallel.
How can I kill the "old" thread and create the new one properly?
Is it better to keep the same thread alive and just dealing with Handler and Messages? Use service?

Thank you !


问:
How to deploy a docker container on a remote ubuntu server?
I have implemented an API inside a docker container and I want to deploy this container to a remote ubuntu server. How can I do that exactly?
My API uses many resources and I have used MLDB framework to implement it. I want to deploy the container containing the API on this remote ubuntu server.
So far, I have found many guides to deploy the API on AWS and DigitalOcean, but since I already have access to a remote ubuntu server than I don't need those right?
So how can I deploy my container in order for someone else to be able to test my API? If there is a better way to deploy my API (hopefully for free or with cheap cost) then please let me know.

Thanks in advance.

答:
Setup passwordless SSH on the target machine

Run the following command to remotely manage Docker on the target VM (also installs Docker if needed):

docker-machine create --driver generic
  --generic-ip-address=10.123.2.74 --generic-ssh-user=docker --generic-ssh-key ~/.ssh/id_rsa some_name

You can find more information about the generic driver here.

Set the needed environment variables for the newly configured docker machine:

eval $(docker-machine env some_name)

Any Docker command run in this terminal/cmd window will be run on the remote machine. To test run:

docker ps

Now you can run your docker containers exactly as you would locally.

PS - If you need to remotely manage a docker instance running on Windows through the Docker Toolbox things get a little complicated. (you need to solve network access to your needed ports in the docker linux VM (ssh, docker engine, container ports) either through VirtualBox's bridged network adapter or through port forwarding; also solve windows firewall issues)


问:
Shiny conditionalpanel not evaluating at startup
I'm using conditionalpanels to build up my Shiny app dynamically. It seems that the condition the panel is based on is not evaluated at startup. The panel is visible by default, and only disappears after some actions. The panel is visible, even though the condition is not met (input.select1.length = 0, which is less than 1...).

Minimal working example:

Server.R:

```<code>shinyServer(function(input, output,session){
  output$selectInput1 <- renderUI({
    selectInput(
      inputId = "select1",
      label = "Select",
      choices = c('1','2','3'),
      selected = NULL,
      multiple = TRUE
    )
  })
})
</code>```

UI.R:

```<code>dashboardPage(
  title = "",

  ## Header content + dropdownMenu
  dashboardHeader(
    title = tags$b(""),
    titleWidth = 250
  ),

  ## Sidebar content
  dashboardSidebar(
    width = 250,
    sidebarMenu(
      id = "tabs",
      menuItem("tab1", tabName = "tab", icon = icon("table"))
    )
  ),

  ## Body content
  dashboardBody(
    tabItems(
      tabItem(tabName = "tab",
        div(
          div(
            style="float: left; padding-left: 20px; padding-right: 20px; width: 350px; background-color: #F4F4F4; height: calc(100vh - 50px) !important;",
            uiOutput('selectInput1')
          ),
          div(
            conditionalPanel(
              condition = "input.select1.length > 1",
              p('hi')
            )
          )
        )
      )
    )
  )
)
</code>```

答:
As @porkchop pointed out, you can create the condition in the renderUI function of server.R:

Server.R:

```<code>shinyServer(function(input, output,session){
  output$selectInput1 <- renderUI({
    selectInput(
      inputId = "select1",
      label = "Select",
      choices = c('1','2','3'),
      selected = NULL,
      multiple = TRUE
    )
  })
  output$panel1 <- renderUI({
    if(!is.null(input$select1) && length(input$select1) > 0){
      condition1 = 'true'
    } else {
      condition1 = 'false'
    }
    conditionalPanel(
      condition1,
      p('hi')
    )
  })
})
</code>```

UI.R:

```<code>dashboardPage(
  title = "",

  ## Header content + dropdownMenu
  dashboardHeader(
    title = tags$b(""),
    titleWidth = 250
  ),

  ## Sidebar content
  dashboardSidebar(
    width = 250,
    sidebarMenu(
      id = "tabs",
      menuItem("tab1", tabName = "tab", icon = icon("table"))
    )
  ),

  ## Body content
  dashboardBody(
    tabItems(
      tabItem(tabName = "tab",
        div(
          div(
            style="float: left; padding-left: 20px; padding-right: 20px; width: 350px; background-color: #F4F4F4; height: calc(100vh - 50px) !important;",
            uiOutput('selectInput1')
          ),
          div(
            uiOutput('panel1')
          )
        )
      )
    )
  )
)
</code>```

Body:
I'm using conditionalpanels to build up my Shiny app dynamically. It seems that the condition the panel is based on is not evaluated at startup. The panel is visible by default, and only disappears after some actions. The panel is visible, even though the condition is not met (input.select1.length = 0, which is less than 1...).

Minimal working example:

Server.R:

shinyServer(function(input, output,session){
  output$selectInput1 <- renderUI({
    selectInput(
      inputId = "select1",
      label = "Select",
      choices = c('1','2','3'),
      selected = NULL,
      multiple = TRUE
    )
  })
})

UI.R:

dashboardPage(
  title = "",

  ## Header content + dropdownMenu
  dashboardHeader(
    title = tags$b(""),
    titleWidth = 250
  ),

  ## Sidebar content
  dashboardSidebar(
    width = 250,
    sidebarMenu(
      id = "tabs",
      menuItem("tab1", tabName = "tab", icon = icon("table"))
    )
  ),

  ## Body content
  dashboardBody(
    tabItems(
      tabItem(tabName = "tab",
        div(
          div(
            style="float: left; padding-left: 20px; padding-right: 20px; width: 350px; background-color: #F4F4F4; height: calc(100vh - 50px) !important;",
            uiOutput('selectInput1')
          ),
          div(
            conditionalPanel(
              condition = "input.select1.length > 1",
              p('hi')
            )
          )
        )
      )
    )
  )
)

Body:
As @porkchop pointed out, you can create the condition in the renderUI function of server.R:

Server.R:

shinyServer(function(input, output,session){
  output$selectInput1 <- renderUI({
    selectInput(
      inputId = "select1",
      label = "Select",
      choices = c('1','2','3'),
      selected = NULL,
      multiple = TRUE
    )
  })
  output$panel1 <- renderUI({
    if(!is.null(input$select1) && length(input$select1) > 0){
      condition1 = 'true'
    } else {
      condition1 = 'false'
    }
    conditionalPanel(
      condition1,
      p('hi')
    )
  })
})

UI.R:

dashboardPage(
  title = "",

  ## Header content + dropdownMenu
  dashboardHeader(
    title = tags$b(""),
    titleWidth = 250
  ),

  ## Sidebar content
  dashboardSidebar(
    width = 250,
    sidebarMenu(
      id = "tabs",
      menuItem("tab1", tabName = "tab", icon = icon("table"))
    )
  ),

  ## Body content
  dashboardBody(
    tabItems(
      tabItem(tabName = "tab",
        div(
          div(
            style="float: left; padding-left: 20px; padding-right: 20px; width: 350px; background-color: #F4F4F4; height: calc(100vh - 50px) !important;",
            uiOutput('selectInput1')
          ),
          div(
            uiOutput('panel1')
          )
        )
      )
    )
  )
)


问:
firestore auth rule: for google signed in client
I'm trying to establish a rule to fetch firestore data, that can be accessed by a google signed in client.
So the problem I'm facing is when I'm using this rule

```<code>match /helpers/customer/data/{document=**}{
  allow read: if request.auth != null;
}
</code>```

An error pops in logcat

onFailure:
  Errorcom.google.firebase.firestore.FirebaseFirestoreException:
  PERMISSION_DENIED: Missing or insufficient permissions.

also it is only working when I'm using

```<code>match /helpers/customer/data/{document=**}{
  allow read: if true;
}
</code>```

That means the path is write.

```<code>GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(this);

    if(acct != null){
        Log.i(TAG, "onCreate: Database Working");
        mFirestoreDB
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            for (DocumentSnapshot document : task.getResult()) {
                                Log.d(TAG, document.getId() + " => " + document.getData());
                            }
                        } else {
                            Log.d(TAG, "Error getting documents: ", task.getException());
                        }
                    }
                });
    }else{
        Log.i(TAG, "onCreate: Database not Working");
    }
</code>```

What I need is a rule where I can allow only a google signed in user to access.

答:
Signing in with Google does not automatically sign the user in with Firebase. You will need to also sign them in with Firebase Authentication, before your security rules will have its auth variable set.

From the Firebase documentation in signing in with Google:

```<code>private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d(TAG, "signInWithCredential:success");
                        FirebaseUser user = mAuth.getCurrentUser();
                        updateUI(user);
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        Toast.makeText(GoogleSignInActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                        updateUI(null);
                    }

                    // ...
                }
            });
}
</code>```

But I recommend you read the entire page I linked.

Body:
I'm trying to establish a rule to fetch firestore data, that can be accessed by a google signed in client.
So the problem I'm facing is when I'm using this rule

match /helpers/customer/data/{document=**}{
  allow read: if request.auth != null;
}

An error pops in logcat

onFailure:
  Errorcom.google.firebase.firestore.FirebaseFirestoreException:
  PERMISSION_DENIED: Missing or insufficient permissions.

also it is only working when I'm using

match /helpers/customer/data/{document=**}{
  allow read: if true;
}

That means the path is write.

GoogleSignInAccount acct = GoogleSignIn.getLastSignedInAccount(this);

    if(acct != null){
        Log.i(TAG, "onCreate: Database Working");
        mFirestoreDB
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            for (DocumentSnapshot document : task.getResult()) {
                                Log.d(TAG, document.getId() + " => " + document.getData());
                            }
                        } else {
                            Log.d(TAG, "Error getting documents: ", task.getException());
                        }
                    }
                });
    }else{
        Log.i(TAG, "onCreate: Database not Working");
    }

What I need is a rule where I can allow only a google signed in user to access.

Body:
Signing in with Google does not automatically sign the user in with Firebase. You will need to also sign them in with Firebase Authentication, before your security rules will have its auth variable set.

From the Firebase documentation in signing in with Google:

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success, update UI with the signed-in user's information
                        Log.d(TAG, "signInWithCredential:success");
                        FirebaseUser user = mAuth.getCurrentUser();
                        updateUI(user);
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        Toast.makeText(GoogleSignInActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                        updateUI(null);
                    }

                    // ...
                }
            });
}

But I recommend you read the entire page I linked.


问:
Is it posssible to click on a listing after a dynamic search is run?
I have a dynamic search form that searches 8 fields. Depending on the field selection made by the user, that is what is shown in the form. When the user clicks on a particular listing, I would like the record related to that listing to be shown. I.e. McDonalds is selected & the record for the particular McDonalds is shown. The fields in the search are: Business Name, Address, City, State, zip, Phone Number, Major City, Employer Type. Major city is a field where jobs are in a particular area.

I have googled & have not found an answer to my question. Is what I am asking possible?

答:
I placed the following code on after click. It opens a form that shows all the data for that particular record. A friend of mine assisted me.</p>

```<code>Private Sub SearchResults_Click()
Dim strCriteria As String
'"ID" is the list box's BoundColumn, as would usually be the case, a hidden numeric EmployerID value.
'SearchResults is the list box's name.
 strCriteria = "ID = " & Me.SearchResults
'EMPLOYER_DATA_ENTRY_FORM is the name of the form that opens.
 DoCmd.OpenForm " EMPLOYER_DATA_ENTRY_FORM", WhereCondition:=strCriteria
 End Sub
</code>```

Body:
I placed the following code on after click. It opens a form that shows all the data for that particular record. A friend of mine assisted me.

Private Sub SearchResults_Click()
Dim strCriteria As String
'"ID" is the list box's BoundColumn, as would usually be the case, a hidden numeric EmployerID value.
'SearchResults is the list box's name.
 strCriteria = "ID = " & Me.SearchResults
'EMPLOYER_DATA_ENTRY_FORM is the name of the form that opens.
 DoCmd.OpenForm " EMPLOYER_DATA_ENTRY_FORM", WhereCondition:=strCriteria
 End Sub


问:
I need an algorithm that can fit n rectangles of any size in a larger one minimizing its area
I need an algorithm that would take n rectangles of any sizes, and calculate a rectangle big enough to fit them all, minimizing its area so the wasted area is minimum, and also returning the position of all the smaller rectangles within.

The specific task I need this to implement on is in a sprite sheet compiler that would take individual PNG files and make a large PNG with all the images in it, so individual frames can be blitted  from this surface at run time.

A nice to have feature would be that it aims to a specific given width/height ratio, but it's not mandatory.

I'd prefer simple, generic code I can port to another language.

答:
This is what I put together for my own needs.  The T parameter is whatever object you want associated with the results (think of it like the Tag property).  It takes a list of sizes and returns a list of Rects that are arranged</p>

```<code>static class LayoutHelper
{

    /// <summary>
    /// Determines the best fit of a List of Sizes, into the desired rectangle shape
    /// </summary>
    /// <typeparam name="T">Holder for an associated object (e.g., window, UserControl, etc.)</typeparam>
    /// <param name="desiredWidthToHeightRatio">the target rectangle shape</param>
    /// <param name="rectsToArrange">List of sizes that have to fit in the rectangle</param>
    /// <param name="lossiness">1 = non-lossy (slow).  Greater numbers improve speed, but miss some best fits</param>
    /// <returns>list of arranged rects</returns>
    static public List<Tuple<T, Rect>> BestFitRects<T>(double desiredWidthToHeightRatio,
        List<Tuple<Size, T>> rectsToArrange, int lossiness = 10)
    {
        // helper anonymous function that tests for rectangle intersections or boundary violations
        var CheckIfRectsIntersect = new Func<Rect, List<Rect>, double, bool>((one, list, containerHeight) =>
        {
            if (one.Y + one.Height > containerHeight) return true;
            return list.Any(two =>
            {
                if ((one.Top > two.Bottom) ||
                    (one.Bottom < two.Top) ||
                    (one.Left > two.Right) ||
                    (one.Right < two.Left)) return false; // no intersection
                return true; // intersection found
            });
        });

        // helper anonymous function for adding drop points
        var AddNewPotentialDropPoints = new Action<SortedDictionary<Point, object>, Rect>(
            (potentialDropPoints, newRect) =>
            {
                // Only two locations make sense for placing a new rectangle, underneath the
                // bottom left corner or to the right of a top right corner
                potentialDropPoints[new Point(newRect.X + newRect.Width + 1,
                    newRect.Y)] = null;
                potentialDropPoints[new Point(newRect.X,
                    newRect.Y + newRect.Height + 1)] = null;
            });

        var sync = new object();
        // the outer boundary that limits how high the rectangles can stack vertically
        var containingRectHeight = Convert.ToInt32(rectsToArrange.Max(a => a.Item1.Height));
        // always try packing using the tallest rectangle first, working down in height
        var largestToSmallest = rectsToArrange.OrderByDescending(a => a.Item1.Height).ToList();
        // find the maximum possible container height needed
        var totalHeight = Convert.ToInt32(rectsToArrange.Sum(a => a.Item1.Height));
        List<Tuple<T, Rect>> bestResults = null;
        // used to find the best packing arrangement that approximates the target container dimensions ratio
        var bestResultsProximityToDesiredRatio = double.MaxValue;
        // try all arrangements for all suitable container sizes
        Parallel.For(0, ((totalHeight + 1) - containingRectHeight) / lossiness,
            //new ParallelOptions() { MaxDegreeOfParallelism = 1},
            currentHeight =>
        {
            var potentialDropPoints = new SortedDictionary<Point, object>(Comparer<Point>.Create((p1, p2) =>
            {
                // choose the leftmost, then highest point as earlier in the sort order
                if (p1.X != p2.X) return p1.X.CompareTo(p2.X);
                return p1.Y.CompareTo(p2.Y);
            }));
            var localResults = new List<Tuple<T, Rect>>();
            // iterate through the rectangles from largest to smallest
            largestToSmallest.ForEach(currentSize =>
            {
                // check to see if the next rectangle fits in with the currently arranged rectangles
                if (!potentialDropPoints.Any(dropPoint =>
                {
                    var workingPoint = dropPoint.Key;
                    Rect? lastFittingRect = null;
                    var lowY = workingPoint.Y;
                    var highY = workingPoint.Y - 1;
                    var boundaryFound = false;
                    // check if it fits in the current arrangement of rects
                    do
                    {
                        // create a positioned rectangle out of the size dimensions
                        var workingRect = new Rect(workingPoint,
                                new Point(workingPoint.X + currentSize.Item1.Width,
                                workingPoint.Y + currentSize.Item1.Height));
                        // keep moving it up in binary search fashion until it bumps the higher rect
                        if (!CheckIfRectsIntersect(workingRect, localResults.Select(a => a.Item2).ToList(),
                            containingRectHeight + (currentHeight * lossiness)))
                        {
                            lastFittingRect = workingRect;
                            if (!boundaryFound)
                            {
                                highY = Math.Max(lowY - ((lowY - highY) * 2), 0);
                                if (highY == 0) boundaryFound = true;
                            }
                            else
                            {
                                lowY = workingPoint.Y;
                            }
                        }
                        else
                        {
                            boundaryFound = true;
                            highY = workingPoint.Y;
                        }
                        workingPoint = new Point(workingPoint.X, lowY - (lowY - highY) / 2);
                    } while (lowY - highY > 1);

                    if (lastFittingRect.HasValue) // found the sweet spot for this rect
                    {
                        var newRect = lastFittingRect.Value;
                        potentialDropPoints.Remove(dropPoint.Key);
                        // successfully found the best location for the new rectangle, so add it to the pending results
                        localResults.Add(Tuple.Create(currentSize.Item2, newRect));
                        AddNewPotentialDropPoints(potentialDropPoints, newRect);
                        return true;
                    }
                    return false;
                }))
                {
                    // this only occurs on the first square
                    var newRect = new Rect(0, 0, currentSize.Item1.Width, currentSize.Item1.Height);
                    localResults.Add(Tuple.Create(currentSize.Item2, newRect));
                    AddNewPotentialDropPoints(potentialDropPoints, newRect);
                }
            });
            //  layout is complete, now see if this layout is the best one found so far
            var layoutHeight = localResults.Max(a => a.Item2.Y + a.Item2.Height);
            var layoutWidth = localResults.Max(a => a.Item2.X + a.Item2.Width);
            var widthMatchingDesiredRatio = desiredWidthToHeightRatio * layoutHeight;
            double ratioProximity;
            if (layoutWidth < widthMatchingDesiredRatio)
                ratioProximity = widthMatchingDesiredRatio / layoutWidth;
            else
                ratioProximity = layoutWidth / widthMatchingDesiredRatio;
            lock (sync)
            {
                if (ratioProximity < bestResultsProximityToDesiredRatio)
                {
                    // this layout is the best approximation of the desired container dimensions, so far
                    bestResults = localResults;
                    bestResultsProximityToDesiredRatio = ratioProximity;
                }
            }
        });
        return bestResults ?? new List<Tuple<T, Rect>>() {Tuple.Create(rectsToArrange[0].Item2,
            new Rect(new Point(0, 0), new Point(rectsToArrange[0].Item1.Width, rectsToArrange[0].Item1.Height))) };
    }
}
</code>```

Body:
This is what I put together for my own needs.  The T parameter is whatever object you want associated with the results (think of it like the Tag property).  It takes a list of sizes and returns a list of Rects that are arranged

static class LayoutHelper
{

    /// <summary>
    /// Determines the best fit of a List of Sizes, into the desired rectangle shape
    /// </summary>
    /// <typeparam name="T">Holder for an associated object (e.g., window, UserControl, etc.)</typeparam>
    /// <param name="desiredWidthToHeightRatio">the target rectangle shape</param>
    /// <param name="rectsToArrange">List of sizes that have to fit in the rectangle</param>
    /// <param name="lossiness">1 = non-lossy (slow).  Greater numbers improve speed, but miss some best fits</param>
    /// <returns>list of arranged rects</returns>
    static public List<Tuple<T, Rect>> BestFitRects<T>(double desiredWidthToHeightRatio,
        List<Tuple<Size, T>> rectsToArrange, int lossiness = 10)
    {
        // helper anonymous function that tests for rectangle intersections or boundary violations
        var CheckIfRectsIntersect = new Func<Rect, List<Rect>, double, bool>((one, list, containerHeight) =>
        {
            if (one.Y + one.Height > containerHeight) return true;
            return list.Any(two =>
            {
                if ((one.Top > two.Bottom) ||
                    (one.Bottom < two.Top) ||
                    (one.Left > two.Right) ||
                    (one.Right < two.Left)) return false; // no intersection
                return true; // intersection found
            });
        });

        // helper anonymous function for adding drop points
        var AddNewPotentialDropPoints = new Action<SortedDictionary<Point, object>, Rect>(
            (potentialDropPoints, newRect) =>
            {
                // Only two locations make sense for placing a new rectangle, underneath the
                // bottom left corner or to the right of a top right corner
                potentialDropPoints[new Point(newRect.X + newRect.Width + 1,
                    newRect.Y)] = null;
                potentialDropPoints[new Point(newRect.X,
                    newRect.Y + newRect.Height + 1)] = null;
            });

        var sync = new object();
        // the outer boundary that limits how high the rectangles can stack vertically
        var containingRectHeight = Convert.ToInt32(rectsToArrange.Max(a => a.Item1.Height));
        // always try packing using the tallest rectangle first, working down in height
        var largestToSmallest = rectsToArrange.OrderByDescending(a => a.Item1.Height).ToList();
        // find the maximum possible container height needed
        var totalHeight = Convert.ToInt32(rectsToArrange.Sum(a => a.Item1.Height));
        List<Tuple<T, Rect>> bestResults = null;
        // used to find the best packing arrangement that approximates the target container dimensions ratio
        var bestResultsProximityToDesiredRatio = double.MaxValue;
        // try all arrangements for all suitable container sizes
        Parallel.For(0, ((totalHeight + 1) - containingRectHeight) / lossiness,
            //new ParallelOptions() { MaxDegreeOfParallelism = 1},
            currentHeight =>
        {
            var potentialDropPoints = new SortedDictionary<Point, object>(Comparer<Point>.Create((p1, p2) =>
            {
                // choose the leftmost, then highest point as earlier in the sort order
                if (p1.X != p2.X) return p1.X.CompareTo(p2.X);
                return p1.Y.CompareTo(p2.Y);
            }));
            var localResults = new List<Tuple<T, Rect>>();
            // iterate through the rectangles from largest to smallest
            largestToSmallest.ForEach(currentSize =>
            {
                // check to see if the next rectangle fits in with the currently arranged rectangles
                if (!potentialDropPoints.Any(dropPoint =>
                {
                    var workingPoint = dropPoint.Key;
                    Rect? lastFittingRect = null;
                    var lowY = workingPoint.Y;
                    var highY = workingPoint.Y - 1;
                    var boundaryFound = false;
                    // check if it fits in the current arrangement of rects
                    do
                    {
                        // create a positioned rectangle out of the size dimensions
                        var workingRect = new Rect(workingPoint,
                                new Point(workingPoint.X + currentSize.Item1.Width,
                                workingPoint.Y + currentSize.Item1.Height));
                        // keep moving it up in binary search fashion until it bumps the higher rect
                        if (!CheckIfRectsIntersect(workingRect, localResults.Select(a => a.Item2).ToList(),
                            containingRectHeight + (currentHeight * lossiness)))
                        {
                            lastFittingRect = workingRect;
                            if (!boundaryFound)
                            {
                                highY = Math.Max(lowY - ((lowY - highY) * 2), 0);
                                if (highY == 0) boundaryFound = true;
                            }
                            else
                            {
                                lowY = workingPoint.Y;
                            }
                        }
                        else
                        {
                            boundaryFound = true;
                            highY = workingPoint.Y;
                        }
                        workingPoint = new Point(workingPoint.X, lowY - (lowY - highY) / 2);
                    } while (lowY - highY > 1);

                    if (lastFittingRect.HasValue) // found the sweet spot for this rect
                    {
                        var newRect = lastFittingRect.Value;
                        potentialDropPoints.Remove(dropPoint.Key);
                        // successfully found the best location for the new rectangle, so add it to the pending results
                        localResults.Add(Tuple.Create(currentSize.Item2, newRect));
                        AddNewPotentialDropPoints(potentialDropPoints, newRect);
                        return true;
                    }
                    return false;
                }))
                {
                    // this only occurs on the first square
                    var newRect = new Rect(0, 0, currentSize.Item1.Width, currentSize.Item1.Height);
                    localResults.Add(Tuple.Create(currentSize.Item2, newRect));
                    AddNewPotentialDropPoints(potentialDropPoints, newRect);
                }
            });
            //  layout is complete, now see if this layout is the best one found so far
            var layoutHeight = localResults.Max(a => a.Item2.Y + a.Item2.Height);
            var layoutWidth = localResults.Max(a => a.Item2.X + a.Item2.Width);
            var widthMatchingDesiredRatio = desiredWidthToHeightRatio * layoutHeight;
            double ratioProximity;
            if (layoutWidth < widthMatchingDesiredRatio)
                ratioProximity = widthMatchingDesiredRatio / layoutWidth;
            else
                ratioProximity = layoutWidth / widthMatchingDesiredRatio;
            lock (sync)
            {
                if (ratioProximity < bestResultsProximityToDesiredRatio)
                {
                    // this layout is the best approximation of the desired container dimensions, so far
                    bestResults = localResults;
                    bestResultsProximityToDesiredRatio = ratioProximity;
                }
            }
        });
        return bestResults ?? new List<Tuple<T, Rect>>() {Tuple.Create(rectsToArrange[0].Item2,
            new Rect(new Point(0, 0), new Point(rectsToArrange[0].Item1.Width, rectsToArrange[0].Item1.Height))) };
    }
}


问:
how to resolve a fakepath with google chrome using angular2
I need to get a path from my application with angular2 typescript
the path that I get is (c:\fakepath\img.png )
I ask if there is any solution
thanks</p>

答:
Below is the example

ts file

```<code>upload(file)
 { console.log('file'+':'+file.value)
   const inputNode = file.value.replace("C:\\fakepath\\", "");
   console.log(inputNode);
 }
</code>```

In the above function i have  passed file value as a parameter and used javascript replace function to replace "C:\fakepath\" with a blank space

html file

```<code><input  class="file" (click)="file.click()"  type="file" accept="image/*" #file >

<button mat-raised-button (click)="upload(file)">Upload</button>
</code>```

Body:
Below is the example

ts file

upload(file)
 { console.log('file'+':'+file.value)
   const inputNode = file.value.replace("C:\\fakepath\\", "");
   console.log(inputNode);
 }

In the above function i have  passed file value as a parameter and used javascript replace function to replace "C:\fakepath\" with a blank space

html file

<input  class="file" (click)="file.click()"  type="file" accept="image/*" #file >

<button mat-raised-button (click)="upload(file)">Upload</button>


问:
The html td is not updating via jquery
I have this little method which, on the first load, created a
 and some 's. That works.  But if the underlying data changes, the 's are not updated. I'm not sure why.

```<code>    function ParseJson(json, isFirstLoad)
    {
        json = $.parseJSON(json);
        var tr;
        for (var i = 0; i < json.length; i++) {
            if (isFirstLoad === 1)
            {
                tr = $('<tr/>');
                tr.append("<td id='" + json[i].LocationName + "'>" + json[i].LocationName + "</td>");
                tr.append("<td id='" + json[i].LocationName + "Count'>" + json[i].Count + "</td>");
                $('#MainTable').append(tr);
            }
            else
            {
                var td =  $("#" + json[i].LocationName + "Count");
                td.html = json[i].Count;
            }
        }
</code>```

When isFirstLoad is 1, the html is rendered as I would expect. Example:

```<code><tr>
    <td id="ChemLab">ChemLab</td>
    <td id="ChemLabCount">24</td>
</tr>
</code>```

But the next time around, if the data has changed and someone has left the Chem Lab, the html for ChemLabCount does not change.

I have verified that the json being passed into this method is correct.  Meaning, the count DOES indeed change.  It just doesn't get displayed on the screen.

答:
jQuery .html() is a function, not a property.

```<code>td.html(json[i].Count);
</code>```

Title: The html td is not updating via jquery

Body:
I have this little method which, on the first load, created a
 and some 's. That works.  But if the underlying data changes, the 's are not updated. I'm not sure why.

    function ParseJson(json, isFirstLoad)
    {
        json = $.parseJSON(json);
        var tr;
        for (var i = 0; i < json.length; i++) {
            if (isFirstLoad === 1)
            {
                tr = $('
');
                tr.append("" + json[i].LocationName + "	");
                tr.append("" + json[i].Count + "	");
                $('#MainTable').append(tr);
            }
            else
            {
                var td =  $("#" + json[i].LocationName + "Count");
                td.html = json[i].Count;
            }
        }

When isFirstLoad is 1, the html is rendered as I would expect. Example:

    ChemLab
    24

But the next time around, if the data has changed and someone has left the Chem Lab, the html for ChemLabCount does not change.

I have verified that the json being passed into this method is correct.  Meaning, the count DOES indeed change.  It just doesn't get displayed on the screen.

Body:
jQuery .html() is a function, not a property.

td.html(json[i].Count);


问:
Django - importing dynamically
I'm trying to do a dynamic import of a python module in django.  I have two different apps that I want to import from, and I want to replace these import statements:

```<code>from app1.forms import App1ProfileForm
from app2.forms import App2ProfileForm
</code>```

I am dynamically able to create the strings App1ProfileForm and App2ProfileForm and then instantiate them like so:

```<code>globals()[form]()
</code>```

I tried following some of the instructions in this post: Dynamically import class by name for static access

and so I tried doing this:

```<code>theModule = __import__("app1.forms.App1ProfileForm")
</code>```

but I'm getting an error that says No module named App1ProfileForm

EDIT:::
Ok I tried this code:

```<code> theModule = __import__("app1")
    print theModule
    theClass = getattr(theModule,'forms')
    print theClass
    theForm = getattr(theClass,'App1ProfileForm')
    print theForm
    theForm.initialize()
</code>```

but I get an error that type object 'App1ProfileForm' has no attribute 'initialize'

答:
You don't want to do this. Imports are done when the relevant code is first executed - in the case of module-level imports, it's when the module itself is imported. If you're depending on something in the request, or some other run-time element, to determine what class you want, then this will not work.

Instead, just import them both, and get the code to choose which one you need:

```<code>from app1.forms import App1ProfileForm
from app2.forms import App2ProfileForm

forms = {'app1': App1ProfileForm,
         'app2': App2ProfileForm}
relevant_form = forms[whatever_the_dependent_value_is]
</code>```

Title: Django - importing dynamically

Body:
I'm trying to do a dynamic import of a python module in django.  I have two different apps that I want to import from, and I want to replace these import statements:

from app1.forms import App1ProfileForm
from app2.forms import App2ProfileForm

I am dynamically able to create the strings App1ProfileForm and App2ProfileForm and then instantiate them like so:

globals()[form]()

I tried following some of the instructions in this post: Dynamically import class by name for static access

and so I tried doing this:

theModule = __import__("app1.forms.App1ProfileForm")

but I'm getting an error that says No module named App1ProfileForm

EDIT:::
Ok I tried this code:

 theModule = __import__("app1")
    print theModule
    theClass = getattr(theModule,'forms')
    print theClass
    theForm = getattr(theClass,'App1ProfileForm')
    print theForm
    theForm.initialize()

but I get an error that type object 'App1ProfileForm' has no attribute 'initialize'

Body:
You don't want to do this. Imports are done when the relevant code is first executed - in the case of module-level imports, it's when the module itself is imported. If you're depending on something in the request, or some other run-time element, to determine what class you want, then this will not work.

Instead, just import them both, and get the code to choose which one you need:

from app1.forms import App1ProfileForm
from app2.forms import App2ProfileForm

forms = {'app1': App1ProfileForm,
         'app2': App2ProfileForm}
relevant_form = forms[whatever_the_dependent_value_is]


问:
How to prevent a svn user to avoid accessing other projects
Environment:-
OS:Ubundu 16.4
svn server version:1.9.3 (r1718519)

Issue:-

I have 2 projects in the svn and there are different access permissions for different users. I have updated the authuz file as below

```<code>[groups]

project1 = admin,user1,user2,user3
project2 = user4,user5

[/]
* = r
admin = rw
[project1:/]
@project1 = rw
admin = rw

[project2:/]
@project2 = rw
admin = rw
</code>```

But still the user1 is able to checkout the project2 into his PC.(but he cannot commit changes). how to block this user1 from accessing the project2.

答:
```<code>[/]
* = r
</code>```

This is your issue. * = r means all users are given read access. And since this command is underneath the [/] (or root) directory, that means they have read access to everything in the repository.

You have two options:

Remove the * = r line from underneath the root directory.

Underneath [project2:/] you can add a line that says @project1 =

With option #2, you have the ability to forbid certain users/groups from accessing a directory completely, however, doing this means they will still have access to any additional projects you may add to the repository and thus, you would need to continuously do option #2 for every project you add. I personally recommend option #1 and then only adding authenticated users to each project. Only admins should have root access in my opinion/experience.

Also, since you've added admin = rw underneath [/] you don't need to add admin = rw underneath any projects, because they inherently get read/write access to the entire repository.

Body:
Environment:-
OS:Ubundu 16.4
svn server version:1.9.3 (r1718519)

Issue:-

I have 2 projects in the svn and there are different access permissions for different users. I have updated the authuz file as below

[groups]

project1 = admin,user1,user2,user3
project2 = user4,user5

[/]
* = r
admin = rw
[project1:/]
@project1 = rw
admin = rw

[project2:/]
@project2 = rw
admin = rw

But still the user1 is able to checkout the project2 into his PC.(but he cannot commit changes). how to block this user1 from accessing the project2.

Body:
[/]
* = r

This is your issue. * = r means all users are given read access. And since this command is underneath the [/] (or root) directory, that means they have read access to everything in the repository.

You have two options:

Remove the * = r line from underneath the root directory.

Underneath [project2:/] you can add a line that says @project1 =

With option #2, you have the ability to forbid certain users/groups from accessing a directory completely, however, doing this means they will still have access to any additional projects you may add to the repository and thus, you would need to continuously do option #2 for every project you add. I personally recommend option #1 and then only adding authenticated users to each project. Only admins should have root access in my opinion/experience.

Also, since you've added admin = rw underneath [/] you don't need to add admin = rw underneath any projects, because they inherently get read/write access to the entire repository.


问:
Tensorflow Serving: Large model, protobuf error
I am trying to make serve a big (1.2 GB in size) model with Tensorflow Serving, but I am getting a:

```<code>2017-12-02 21:55:57.711317: I external/org_tensorflow/tensorflow/cc/saved_model/loader.cc:236] Loading SavedModel from: ...
[libprotobuf ERROR external/protobuf_archive/src/google/protobuf/io/coded_stream.cc:193] A protocol message was rejected because it was too big (more than 1073741824 bytes).  To increase the limit (or to disable these warnings), see CodedInputStream::SetTotalBytesLimit() in google/protobuf/io/coded_stream.h.
2017-12-02 21:55:58.563507: I external/org_tensorflow/tensorflow/cc/saved_model/loader.cc:284] Loading SavedModel: fail. Took 852178 microseconds.
2017-12-02 21:55:58.563567: E tensorflow_serving/util/retrier.cc:38] Loading servable: {name: 2 version: 2} failed: Data loss: Can't parse .../saved_model.pb as binary proto
</code>```

I read through a few related issues on Github from a few years ago, but ultimately it turned unrelated, since Serving is using the C++ version of the protobuf. There is little information on deploying large models with Serving, so any information would suffice.

Tensorflow Serving was compiled on the host machine, so was the model, but using python3 (I wonder if it has to do with anything at all).
Is there a quick fix for this, or I have to dig through the Serving C++ sources and increase the size of the message?

Edit per request in the comments:

I save the model according to the official tutorial. The reason why the model is so big is that I have an embedding layer saved along. Here is the saving code anyway:

```<code>export_path = 'model/1'
builder = saved_model_builder.SavedModelBuilder(export_path)

signature = predict_signature_def(inputs={'input': input},
                                  outputs={'sent': output})

builder.add_meta_graph_and_variables(sess=session,
                                     tags=[tag_constants.SERVING],
                                     signature_def_map={'predict': signature})
builder.save()
</code>```

The model is read by a compiled TF Serving from GitHub on a Ubuntu 16.04 host.

答:
Hope it helps someone, but I "found" a solution.

The major problem was obvious; his is an NLP model, thus it has a big vocabulary that goes along with it. Leaving the vocabulary in the graph definition bloats the metagraphdef, and protobuf is giving an error when faced with such a big protocol.

The solution would to put the dictionary in the assets_collection. There is little documentation to what you actually have to do, but looking at the saved_model_test.py at the official repo is worth looking at.

As to utilize the assets with Tensorflow Serving, one has to create a custom Servable, as described in the Creating a new kind of servable  official documentation. Cannot provide a specific example, because I simply containerized the model for the time being.

If anyone has examples, or has a better strategy when it comes to NLP models deployment, I would be happy to discuss it further.

Body:
I am trying to make serve a big (1.2 GB in size) model with Tensorflow Serving, but I am getting a:

2017-12-02 21:55:57.711317: I external/org_tensorflow/tensorflow/cc/saved_model/loader.cc:236] Loading SavedModel from: ...
[libprotobuf ERROR external/protobuf_archive/src/google/protobuf/io/coded_stream.cc:193] A protocol message was rejected because it was too big (more than 1073741824 bytes).  To increase the limit (or to disable these warnings), see CodedInputStream::SetTotalBytesLimit() in google/protobuf/io/coded_stream.h.
2017-12-02 21:55:58.563507: I external/org_tensorflow/tensorflow/cc/saved_model/loader.cc:284] Loading SavedModel: fail. Took 852178 microseconds.
2017-12-02 21:55:58.563567: E tensorflow_serving/util/retrier.cc:38] Loading servable: {name: 2 version: 2} failed: Data loss: Can't parse .../saved_model.pb as binary proto

I read through a few related issues on Github from a few years ago, but ultimately it turned unrelated, since Serving is using the C++ version of the protobuf. There is little information on deploying large models with Serving, so any information would suffice.

Tensorflow Serving was compiled on the host machine, so was the model, but using python3 (I wonder if it has to do with anything at all).
Is there a quick fix for this, or I have to dig through the Serving C++ sources and increase the size of the message?

Edit per request in the comments:

I save the model according to the official tutorial. The reason why the model is so big is that I have an embedding layer saved along. Here is the saving code anyway:

export_path = 'model/1'
builder = saved_model_builder.SavedModelBuilder(export_path)

signature = predict_signature_def(inputs={'input': input},
                                  outputs={'sent': output})

builder.add_meta_graph_and_variables(sess=session,
                                     tags=[tag_constants.SERVING],
                                     signature_def_map={'predict': signature})
builder.save()

The model is read by a compiled TF Serving from GitHub on a Ubuntu 16.04 host.


问:
Convert Array of Dictionary to custom object swift
I have:

```<code>    let countries : [[String : Any]] = [
            [
                "name" : "Afghanistan",
                "dial_code": "+93",
                "code": "AF"
            ],
            [
                "name": "Aland Islands",
                "dial_code": "+358",
                "code": "AX"
            ],
            [
                "name": "Albania",
                "dial_code": "+355",
                "code": "AL"
            ],
            [
                "name": "Algeria",
                "dial_code": "+213",
                "code": "DZ"
            ]
]
</code>```

I want to add all this array of dictionary to my custom object like

```<code>let country:[Country] = countries
</code>```

My custom object looks like this:

```<code>class Country: NSObject {
        let name: String
        let dial_code : String
        let code: String

        init(name: String, dial_code: String, code: String) {
            self.name = name
            self.dial_code = dial_code
            self.code = code
        }
    }
</code>```

I understand that I need a loop thru the array but idk what is the next step. Would be great to have an example.

答:
Create a custom country class with param json [String : Any]

```<code>class Country: NSObject {
    var name: String?
    var dialCode: String?
    var code: String?

    init(json: [String : Any]) {
       self.name = json["name"] as? String
       self.dialCode = json["dial_code"] as? String
       self.code = json["code"] as? String
    }
}
</code>```

Later you can map the dictionary into the array of country using

```<code>let _ = countries.flatMap { Country.init }
</code>```

Body:
I have:

    let countries : [[String : Any]] = [
            [
                "name" : "Afghanistan",
                "dial_code": "+93",
                "code": "AF"
            ],
            [
                "name": "Aland Islands",
                "dial_code": "+358",
                "code": "AX"
            ],
            [
                "name": "Albania",
                "dial_code": "+355",
                "code": "AL"
            ],
            [
                "name": "Algeria",
                "dial_code": "+213",
                "code": "DZ"
            ]
]

I want to add all this array of dictionary to my custom object like

let country:[Country] = countries

My custom object looks like this:

class Country: NSObject {
        let name: String
        let dial_code : String
        let code: String

        init(name: String, dial_code: String, code: String) {
            self.name = name
            self.dial_code = dial_code
            self.code = code
        }
    }

I understand that I need a loop thru the array but idk what is the next step. Would be great to have an example.

Body:
Create a custom country class with param json [String : Any]

class Country: NSObject {
    var name: String?
    var dialCode: String?
    var code: String?

    init(json: [String : Any]) {
       self.name = json["name"] as? String
       self.dialCode = json["dial_code"] as? String
       self.code = json["code"] as? String
    }
}

Later you can map the dictionary into the array of country using

let _ = countries.flatMap { Country.init }


问:
vuejs application with different layouts (e.g. login layout, page layout, signup etc.)
I generated a project using vue-cli. I see project has one App.vue which is kinda main layout of the app - if I'm not mistaken. Here I put my basic HTML layout and <router-view></router-view>. Now the issue is that I need completely different layout for login (different wrappers , body has different classes) but I can't change it since App.vue has template which is kinda "fixed" as a layout. How to approach this issue? Is there recommended way?

Should I create new component that represents layout so in that case my App.vue template would only have <router-view></router-view> and then LoginLayout.vue would be included into it?

答:
A nice solution for this is using slots

First create your "layout component"

src/components/layouts/basic.vue

```<code><template>
  <div class="basic-layout">
    <header>[Company logo]</header>
    <hr>

    <slot/>

    <hr>
    <footer>
      Made with ❤ at Acme
    </footer>
  </div>
</template>
</code>```

Then use it in another component:

```<code><template>
  <layout-basic>
    <p>Hello world!</p>
  </layout-basic>
</template>

<script>
  import LayoutBasic from '@/components/layouts/basic'
  export default {
    components: {
      LayoutBasic
    }
  }
</script>
</code>```

"Hello world" will appear where the <slot/> tag is.

You can also have multiple slots with names, see the complete docs.

ContentLicense: CC BY-SA 4.0

Body:
A nice solution for this is using slots

First create your "layout component"

src/components/layouts/basic.vue

<template>
  <div class="basic-layout">
    <header>[Company logo]</header>
    <hr>

    <slot/>

    <hr>
    <footer>
      Made with ❤ at Acme
    </footer>
  </div>
</template>

Then use it in another component:

<template>
  <layout-basic>
    <p>Hello world!</p>
  </layout-basic>
</template>

<script>
  import LayoutBasic from '@/components/layouts/basic'
  export default {
    components: {
      LayoutBasic
    }
  }
</script>

"Hello world" will appear where the <slot/> tag is.

You can also have multiple slots with names, see the complete docs.


问:
Why is IValidatableObject.Validate only called if property validation passes?
In my model, it seems that Validate() is only called AFTER both properties pass validation.

```<code>public class MyModel : IValidatableObject
{
    [Required]
    public string Name { get; set;}

    [Required]
    public string Nicknames {get; set;}

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if(Nicknames != null && Nicknames.Split(Environment.NewLine.ToCharArray()).Count() < 2)
            return yield result new ValidationResult("Enter at least two nicknames, new [] { "Nicknames" });
    }
}
</code>```

When a user enters a single line of text in the Nicknames text area but leaves the Name text box empty, only the Required error message for the Name property is displayed. The error message that should be displayed from the Validate() function never shows up.

Only after entering a name in the Name text box and some text in the Nicknames text is the Validate() function called.

Is this how it's supposed to work? It seems odd that a user is shown an error message on a subsequent page when the error is being caused on the current page.

答: This is by design. Object-level validation does not fire until all the properties pass validation because otherwise it is possible that the object is incomplete. The Validate method is meant for thing like comparing one property to another. In your case you should write a custom property validator. </p>

Body:
In my model, it seems that Validate() is only called AFTER both properties pass validation.

public class MyModel : IValidatableObject
{
    [Required]
    public string Name { get; set;}

    [Required]
    public string Nicknames {get; set;}

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if(Nicknames != null && Nicknames.Split(Environment.NewLine.ToCharArray()).Count() < 2)
            return yield result new ValidationResult("Enter at least two nicknames, new [] { "Nicknames" });
    }
}

When a user enters a single line of text in the Nicknames text area but leaves the Name text box empty, only the Required error message for the Name property is displayed. The error message that should be displayed from the Validate() function never shows up.

Only after entering a name in the Name text box and some text in the Nicknames text is the Validate() function called.

Is this how it's supposed to work? It seems odd that a user is shown an error message on a subsequent page when the error is being caused on the current page.