问:
TypeError: Cannot read property 'state' of undefined - rendering contents
Getting the error: TypeError: Cannot read property 'state' of undefined when I tried to render the elements with togglePersonsHandler to get the content which is inside the personsState. The goal is to get the contents by clicking on the button.

Here is my App.js file

import React, { useState } from 'react';
import './App.css';
import Person from './person/Person';

const App = props => {
  const [ personsState ] = useState({
    persons: [
      { name: 'Maxmillian', age: 28 },
      { name: 'Manu', age: 18 },
      { name: 'Stephanie', age: 24 }
    ],
    otherState: 'some other value',
    showPersons: false
  });

  const switchNameHandler = (newName) => {
    // console.log('Was clicked!');
    this.setState({
      persons: [
        { name: newName, age: 28 },
        { name: 'Manu', age: 18 },
        { name: 'Stephanie', age: 24 }
      ]
    });
  };

  const nameChangedHandler = (event) => {
    this.setState({
      persons: [
        { name: 'Max', age: 28 },
        { name: event.target.value, age: 18 },
        { name: 'Stephanie', age: 24 }
      ]
    })
  };

  const togglePersonsHandler = () => {
    const doesShow = this.state.showPersons;
    this.setState({showPersons: !doesShow});
  }

    const style = {
      backgroundColor: 'white',
      font: 'inherit',
      border: '1px solid blue',
      padding: '8px',
      cursor: 'pointer'
    };

    return (

Hi, I'm a React App

This is really working!

          <button
            style={style}
            onClick={togglePersonsHandler}>Switch Name</button>
          {
            this.state.showPersons === true ?

              <Person
                name={personsState.persons[0].name}
                age={personsState.persons[0].age} />
              <Person
                name={personsState.persons[1].name}
                age={personsState.persons[1].age}
                click={switchNameHandler.bind(this, 'Max!')}
                changed={nameChangedHandler}>My Hobbies: Racing</Person>
              <Person
                name={personsState.persons[2].name}
                age={personsState.persons[2].age} />

 : null
          }

      );
    }

  // ein Element entwickeln
  // return React.createElement('div', {className: 'App'}, React.createElement('h1', null, 'Work'));

export default App;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script></code>```

And here the Person.js

import React from 'react';
import './Person.css';

const person = (props) => {
    return (

I'm {props.name} and I am {props.age} years old.

{props.children}

            <input type="text" onChange={props.changed} value={props.name} />

    )
};

export default person;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script></code>```

Thank you for the support!

答:
this.state and this.setState is only available in class components extending React.component. You're using a functional component, therefore you need to use hooks to update the state. I suggest to create a separate state for showPersons:

```<code>const [ showPersons, setShowPersons ] = useState(false);

const togglePersonsHandler = () => {
    setShowPersons(!showPersons);
}
</code>```

If you only want one state, add a setter:

```<code>const [ personsState, setPersonsState ] = useState({...});
</code>```

Body:
Getting the error: TypeError: Cannot read property 'state' of undefined when I tried to render the elements with togglePersonsHandler to get the content which is inside the personsState. The goal is to get the contents by clicking on the button.

Here is my App.js file

import React, { useState } from 'react';
import './App.css';
import Person from './person/Person';

const App = props => {
  const [ personsState ] = useState({
    persons: [
      { name: 'Maxmillian', age: 28 },
      { name: 'Manu', age: 18 },
      { name: 'Stephanie', age: 24 }
    ],
    otherState: 'some other value',
    showPersons: false
  });

  const switchNameHandler = (newName) => {
    // console.log('Was clicked!');
    this.setState({
      persons: [
        { name: newName, age: 28 },
        { name: 'Manu', age: 18 },
        { name: 'Stephanie', age: 24 }
      ]
    });
  };

  const nameChangedHandler = (event) => {
    this.setState({
      persons: [
        { name: 'Max', age: 28 },
        { name: event.target.value, age: 18 },
        { name: 'Stephanie', age: 24 }
      ]
    })
  };

  const togglePersonsHandler = () => {
    const doesShow = this.state.showPersons;
    this.setState({showPersons: !doesShow});
  }

    const style = {
      backgroundColor: 'white',
      font: 'inherit',
      border: '1px solid blue',
      padding: '8px',
      cursor: 'pointer'
    };

    return (

Hi, I'm a React App

This is really working!

          <button
            style={style}
            onClick={togglePersonsHandler}>Switch Name</button>
          {
            this.state.showPersons === true ?

              <Person
                name={personsState.persons[0].name}
                age={personsState.persons[0].age} />
              <Person
                name={personsState.persons[1].name}
                age={personsState.persons[1].age}
                click={switchNameHandler.bind(this, 'Max!')}
                changed={nameChangedHandler}>My Hobbies: Racing</Person>
              <Person
                name={personsState.persons[2].name}
                age={personsState.persons[2].age} />

 : null
          }

      );
    }

  // ein Element entwickeln
  // return React.createElement('div', {className: 'App'}, React.createElement('h1', null, 'Work'));

export default App;

And here the Person.js

import React from 'react';
import './Person.css';

const person = (props) => {
    return (

I'm {props.name} and I am {props.age} years old.

{props.children}

            <input type="text" onChange={props.changed} value={props.name} />

    )
};

export default person;

Thank you for the support!

Body:
this.state and this.setState is only available in class components extending React.component. You're using a functional component, therefore you need to use hooks to update the state. I suggest to create a separate state for showPersons:

const [ showPersons, setShowPersons ] = useState(false);

const togglePersonsHandler = () => {
    setShowPersons(!showPersons);
}

If you only want one state, add a setter:

const [ personsState, setPersonsState ] = useState({...});


来源: stackexchange

问:
Validate if 2 elements have same attribute value
In my e-commerce environment, I need a jQuery validation between 2 product attributes. Simplified it needs to check if the cart has a product which is present on the same page:

```<code><! –– Cart ––>
<ul class="woocommerce-mini-cart cart_list product_list_widget ">
    <li class="woocommerce-mini-cart-item mini_cart_item">
        <a href="/example-product/" class="remove remove_from_cart_button" data-product_id="6735" data-cart_item_key="..." ></a>
    </li>
</ul>

<! –– Product ––>
<article class="post-6735 product" data-id="6735">
    <div class="product_wrapper">
        <a href="?add-to-cart=6735" data-quantity="1" class="button add_to_cart_button" data-product_id="6735"</a>
    </div>
</article>
</code>```

I would like to be able to check if the attribute and its value from data-product_id within the cart is the exact same as in article a.button element. My approach:

```<code>jQuery('.woocommerce-mini-cart .remove_from_cart_button').attr('data-product_id').each( function() {
    if( jQuery('article a.button')/*check if it is the same*/){
        // do something here
    }
});
</code>```

As you can see the ID number 6735 is in more attributes. So perhaps a different way is also possible?

答:
If you only need help to clarify your solution it would be

```<code>$('.woocommerce-mini-cart .remove_from_cart_button').each( function() {
    if( $('article a.button').data('product_id') == $(this).data('product_id'){
        // do something here
    }
});
</code>```

each iterate through collection of jquery elements.

This

```<code>jQuery('.woocommerce-mini-cart .remove_from_cart_button').attr('data-product_id')
</code>```

is the single value, it would take the first element that finds and then executes attr on it.

UPDATE

To update all products button on site based on all products that are inside the card

```<code>var product_id = "";
var article = ".post-"; // class of article

$('.woocommerce-mini-cart .remove_from_cart_button').each( function() {
     product_id = $(this).data('product_id')
     article = article + product_id; // we add strings here, example .post-6225
     $(article + " .product_wrapper a").attr('disabled', 'disabled');
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In my e-commerce environment, I need a jQuery validation between 2 product attributes. Simplified it needs to check if the cart has a product which is present on the same page:

<! –– Cart ––>

<! –– Product ––>

        <a href="?add-to-cart=6735" data-quantity="1" class="button add_to_cart_button" data-product_id="6735"

I would like to be able to check if the attribute and its value from data-product_id within the cart is the exact same as in article a.button element. My approach:

jQuery('.woocommerce-mini-cart .remove_from_cart_button').attr('data-product_id').each( function() {
    if( jQuery('article a.button')/*check if it is the same*/){
        // do something here
    }
});

As you can see the ID number 6735 is in more attributes. So perhaps a different way is also possible?

Body:
If you only need help to clarify your solution it would be

$('.woocommerce-mini-cart .remove_from_cart_button').each( function() {
    if( $('article a.button').data('product_id') == $(this).data('product_id'){
        // do something here
    }
});

each iterate through collection of jquery elements.

This

jQuery('.woocommerce-mini-cart .remove_from_cart_button').attr('data-product_id')

is the single value, it would take the first element that finds and then executes attr on it.

UPDATE

To update all products button on site based on all products that are inside the card

var product_id = "";
var article = ".post-"; // class of article

$('.woocommerce-mini-cart .remove_from_cart_button').each( function() {
     product_id = $(this).data('product_id')
     article = article + product_id; // we add strings here, example .post-6225
     $(article + " .product_wrapper a").attr('disabled', 'disabled');
});


问:
ActiveRecord where results incorrect when rendered in view
Rails version 6, postgresql v 11, ruby 2.7.0

I'm struggling with strange behaviour when using ActiveRecord to populate an HTML table in the view based on a search field contained in a form.

If I request the base URL

```<code>localhost:3000/instui/search
</code>```

I get a results which contains (correctly) the first 20 records from the database (securities from the NYSE and NASDAQ):

If I put say BB in the search field, I can see the "where" has done its job and just retrieved the corresponding records from the puts to the console:

```<code>Processing by InstuiController#search as JS
  Parameters: {"utf8"=>"✓", "q"=>"BB", "commit"=>"Search"}
{"utf8"=>"✓", "commit"=>"Search", "q"=>"BB"}
  Instrument Load (1.1ms)  SELECT "instruments".* FROM "instruments" WHERE (ticker LIKE '%BB%') LIMIT $1  [["LIMIT", 20]]
  ↳ app/controllers/instui_controller.rb:19:in `search'
Asia Broadband Inc
ABB Ltd
Auburn Bancorp Inc
AbraPlata Resource Corp
AB DISCOVERY VALUE FUND CLASS B
AbbVie Inc
Abby Inc
AB GROWTH FUND CLASS B
Ambu A/S
Mercantil Bank Holding Corporation
BAB Inc
BlackBerry Limited
New York Health Care Inc
NORTHERN GLOBAL TACTICAL ASSET ALLOCATION FUND NORTHERN GLOBAL TACTICAL ASSET ALLOCATION FUND
BBA Aviation plc
BBA Aviation plc
JPMorgan BetaBuilders Dev Asia ex-JpnETF
BBH LIMITED DURATION FUND CLASS I SHARES
Baker Boyer Bancorp
BlueBird Battery Metals Inc
20
  Rendering instui/search.html.erb within layouts/application
  Rendered instui/search.html.erb within layouts/application (Duration: 0.4ms | Allocations: 339)
Completed 200 OK in 15ms (Views: 11.8ms | ActiveRecord: 1.1ms | Allocations: 11355)
</code>```

However the view continues to render the same result from the previous request - i.e. all of the records as if the view hasn't received the new instance variable from the controller. I cannot see where I'm going wrong. Help appreciated.

The View is:

```<code><h2>Search</h2>
  <%= form_with(url: "search", method: "get") do %>
    <%= label_tag(:q, "Search for:") %>
    <%= text_field_tag(:q) %>
    <%= submit_tag("Search") %>
  <% end %>

<table class="table table-striped">

<tr><th>ID</th><th>Name</th><th>Country</th><th>Ticker</th>

<%  @search_results.each do |i| %>
<tr>

<td><%= i.id %></td>
<td><%= i.name %></td>
<td><%= i.country  %></td>
<td><%= i.ticker  %></td>
</tr>
<% end %>

</table>
</code>```

Controller is:

```<code>class InstuiController < ApplicationController
  def index
  end

  def search

    @searchTerms = params.permit(:utf8, :commit, :q)

        puts(@searchTerms)

        query  = @searchTerms[:q]

        if query == nil
                query = "%%"
        end

        @search_results = Instrument.where("ticker LIKE ?",  "%#{query}%").limit(20)
        @search_results.each { |i| puts(i.name) }
        puts @search_results.length

  end

end
</code>```

routes:

```<code>Rails.application.routes.draw do
  get 'test/index'
  get 'instui/index'
  get 'instui/search'
  get 'assetmaster/csvlist'
  resources :instruments

    get 'instruments/csvlist'
    get 'prices/priceservice'

  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
</code>```

答:
OK so the problem was I had not set local: true on the form. Form rewritten as:

```<code><%= form_with(url: "search", method: "get", local: true) do %>
<%= label_tag(:q, "Search for:") %>
<%= text_field_tag(:q) %>
<%= submit_tag("Search") %>
<% end %>
</code>```

And the problem disappears.

Body:
Rails version 6, postgresql v 11, ruby 2.7.0

I'm struggling with strange behaviour when using ActiveRecord to populate an HTML table in the view based on a search field contained in a form.

If I request the base URL

localhost:3000/instui/search

I get a results which contains (correctly) the first 20 records from the database (securities from the NYSE and NASDAQ):

If I put say BB in the search field, I can see the "where" has done its job and just retrieved the corresponding records from the puts to the console:

Processing by InstuiController#search as JS
  Parameters: {"utf8"=>"✓", "q"=>"BB", "commit"=>"Search"}
{"utf8"=>"✓", "commit"=>"Search", "q"=>"BB"}
  Instrument Load (1.1ms)  SELECT "instruments".* FROM "instruments" WHERE (ticker LIKE '%BB%') LIMIT $1  [["LIMIT", 20]]
  ↳ app/controllers/instui_controller.rb:19:in `search'
Asia Broadband Inc
ABB Ltd
Auburn Bancorp Inc
AbraPlata Resource Corp
AB DISCOVERY VALUE FUND CLASS B
AbbVie Inc
Abby Inc
AB GROWTH FUND CLASS B
Ambu A/S
Mercantil Bank Holding Corporation
BAB Inc
BlackBerry Limited
New York Health Care Inc
NORTHERN GLOBAL TACTICAL ASSET ALLOCATION FUND NORTHERN GLOBAL TACTICAL ASSET ALLOCATION FUND
BBA Aviation plc
BBA Aviation plc
JPMorgan BetaBuilders Dev Asia ex-JpnETF
BBH LIMITED DURATION FUND CLASS I SHARES
Baker Boyer Bancorp
BlueBird Battery Metals Inc
20
  Rendering instui/search.html.erb within layouts/application
  Rendered instui/search.html.erb within layouts/application (Duration: 0.4ms | Allocations: 339)
Completed 200 OK in 15ms (Views: 11.8ms | ActiveRecord: 1.1ms | Allocations: 11355)

However the view continues to render the same result from the previous request - i.e. all of the records as if the view hasn't received the new instance variable from the controller. I cannot see where I'm going wrong. Help appreciated.

The View is:

Search

  <%= form_with(url: "search", method: "get") do %>
    <%= label_tag(:q, "Search for:") %>
    <%= text_field_tag(:q) %>
    <%= submit_tag("Search") %>
  <% end %>

ID	Name	Country	Ticker

<%  @search_results.each do |i| %>

<%= i.id %>
<%= i.name %>
<%= i.country  %>
<%= i.ticker  %>

<% end %>

Controller is:

class InstuiController < ApplicationController
  def index
  end

  def search

    @searchTerms = params.permit(:utf8, :commit, :q)

        puts(@searchTerms)

        query  = @searchTerms[:q]

        if query == nil
                query = "%%"
        end

        @search_results = Instrument.where("ticker LIKE ?",  "%#{query}%").limit(20)
        @search_results.each { |i| puts(i.name) }
        puts @search_results.length

  end

end

routes:

Rails.application.routes.draw do
  get 'test/index'
  get 'instui/index'
  get 'instui/search'
  get 'assetmaster/csvlist'
  resources :instruments

    get 'instruments/csvlist'
    get 'prices/priceservice'

  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

Body:
OK so the problem was I had not set local: true on the form. Form rewritten as:

<%= form_with(url: "search", method: "get", local: true) do %>
<%= label_tag(:q, "Search for:") %>
<%= text_field_tag(:q) %>
<%= submit_tag("Search") %>
<% end %>

And the problem disappears.


问:
Is it possible to archive logs based on size and on time using NLog
I am using NLog.

I would like to have a size-based file archival and a time-based file archival.

Meaning, every time the log file exceeds 10 MB a new log file is created. Also, every day a new log file is created.

It is clear how to do each of the above separately (https://github.com/NLog/NLog/wiki/FileTarget-Archive-Examples) but not how to use them in tandem.

答:
Without any details of the expected fileName-Layout, then this will work just fine in NLog 4.5 (and newer):

```<code><target type="file" name="logfile" fileName="App-${shortdate}.log" archiveAboveSize="1000000" maxArchiveFiles="30" />
</code>```

It will produce the following filenames (newest first)

App-20200216.log

App-20200216.2.log

App-20200216.1.log

App-20200215.log

App-20200214.log

App-20200214.1.log

See also: https://github.com/NLog/NLog/wiki/File-target#archive-old-log-files

Body:
Without any details of the expected fileName-Layout, then this will work just fine in NLog 4.5 (and newer):

<target type="file" name="logfile" fileName="App-${shortdate}.log" archiveAboveSize="1000000" maxArchiveFiles="30" />

It will produce the following filenames (newest first)

App-20200216.log

App-20200216.2.log

App-20200216.1.log

App-20200215.log

App-20200214.log

App-20200214.1.log

See also: https://github.com/NLog/NLog/wiki/File-target#archive-old-log-files


问:
Show hidden div in order
I have this code:

CODE

$('button').click(function(){
    var a = $(this).text();
    $('.'+a).show();
    $('.'+a).css("order", "1");

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <div class='1' style='display:none'><input type='text' value='1'></input>
  </div>
  <div class='2' style='display:none'><input type='text' value='2'></input>
  </div>
  <div class='3' style='display:none'><input type='text' value='3'></input>
  </div>

  <button>1</button>
  <button>2</button>
  <button>3</button></code>```

I need them to be in the order in which I click the button.
I tried to use .css('order','1'), but it doesn't seem to work

答:
Since you're using jQuery, you can create a wrapper and use appendTo instead of relying on the order property.

$('button').click(function() {
  var a = $(this).text();
  $('.' + a).show();
  $('.' + a).appendTo('.wrapper');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="wrapper">
  <div class='a' style='display:none'><input type='text' value='1'>
  </div>
  <div class='b' style='display:none'><input type='text' value='2'>
  </div>
  <div class='c' style='display:none'><input type='text' value='3'>
  </div>
</div>

<button>a</button>
<button>b</button>
<button>c</button></code>```

Title: Show hidden div in order

Body:
I have this code:

CODE

$('button').click(function(){
    var a = $(this).text();
    $('.'+a).show();
    $('.'+a).css("order", "1");

});

<input type='text' value='1'></input>

<input type='text' value='2'></input>

<input type='text' value='3'></input>

  <button>1</button>
  <button>2</button>
  <button>3</button>

I need them to be in the order in which I click the button.
I tried to use .css('order','1'), but it doesn't seem to work

Body:
Since you're using jQuery, you can create a wrapper and use appendTo instead of relying on the order property.

$('button').click(function() {
  var a = $(this).text();
  $('.' + a).show();
  $('.' + a).appendTo('.wrapper');
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="wrapper">
  <div class='a' style='display:none'><input type='text' value='1'>
  </div>
  <div class='b' style='display:none'><input type='text' value='2'>
  </div>
  <div class='c' style='display:none'><input type='text' value='3'>
  </div>
</div>

<button>a</button>
<button>b</button>
<button>c</button>


问:
convert string to time-format in R language
I have strings like this:

```<code>100
200
...
2300
</code>```

how to transfer this to time format?

```<code>01:00:00
02:00:00
...
23:00:00
</code>```

do I have to add 0 to the string?
I have tried

```<code>Data$Time <- formatC(Data$Time, digits = 6, flag = "0")
</code>```

But it's not working

答:
We can use sprintf to do the formatting and then convert to Time with as.ITime

```<code>library(data.table)
as.ITime(sub("(..)", "\\1:", sprintf("%04d:00", v1)))
#[1] "01:00:00" "02:00:00" "23:00:00"
</code>```

As @Claudio mentioned, if it is a vector of strings, replace the %04d with %04s

data

```<code>v1 <- c(100, 200, 2300)
</code>```

Body:
I have strings like this:

100
200
...
2300

how to transfer this to time format?

01:00:00
02:00:00
...
23:00:00

do I have to add 0 to the string?
I have tried

Data$Time <- formatC(Data$Time, digits = 6, flag = "0")

But it's not working

Body:
We can use sprintf to do the formatting and then convert to Time with as.ITime

library(data.table)
as.ITime(sub("(..)", "\\1:", sprintf("%04d:00", v1)))
#[1] "01:00:00" "02:00:00" "23:00:00"

As @Claudio mentioned, if it is a vector of strings, replace the %04d with %04s

data

v1 <- c(100, 200, 2300)


答:
Found this discussion here including some useful hints: webclient logging

And this useful article baeldung webclient logging

But, be careful: logging human readable will under circumstances  have some impact to the reactive approach of streaming data in byte parts...

Title: How to pretty print http body in Netty client?

Body:
If I enable debug logging and use the following configuration, I will get soem kind of hex-dump to the console:

HttpClient.create().wiretap(true);

Shows:

         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 49 70 73 6f 20 66 61 63 74 6f 20 69 73 20 61 20 |Ipso facto is a |
|00000010| 4c 61 74 69 6e 20 70 68 72 61 73 65 2c 20 64 69 |Latin phrase, di|
|00000020| 72 65 63 74 6c 79 20 74 72 61 6e 73 6c 61 74 65 |rectly translate|
|00000030| 64 20 61 73 20 22 62 79 20 74 68 65 20 66 61 63 |d as "by the fac|
|00000040| 74 20 69 74 73 65 6c 66 22 2c 5b 31 5d 20 77 68 |t itself",[1] wh|
|00000050| 69 63 68 20 6d 65 61 6e 73 20 74 68 61 74 20 61 |ich means that a|
|00000060| 20 73 70 65 63 69 66 69 63 20 70 68 65 6e 6f 6d | specific phenom|
|00000070| 65 6e 6f 6e 20 69 73 20 61 20 64 69 72 65 63 74 |enon is a direct|
|00000080| 20 63 6f 6e 73 65 71 75 65 6e 63 65 2c 20 61 20 | consequence, a |
|00000090| 72 65 73 75 6c 74 61 6e 74 20 65 66 66 65 63 74 |resultant effect|

Question: how can I tell netty to convert the hex dump just to plain string (eg so that I can see the real json output only)?

And especially the message body is compressed, I'd like to log it uncompressed. But how?


问:
Can I render a text string as a partial in Rails 3?
I am storing customer-specific partials on S3. When I render the value of the S3 object, it renders as text. How can I render it so that it appears within my main layout?</p>

答:
Looks like I just need to:

```<code>render :text => myTextFromS3, :layout => true
</code>```

And it works!

Update: Since 2013 rails changed

There is 3 different ways:

render html: 'HTML String' # render with `text/html` MIME type

render plain: 'plain text' # render with `text/plain` MIME type

render body: 'raw body' # render raw content, does not set content type, inherits
                        # default content type, which currently is `text/html`
```

Source https://github.com/rails/rails/issues/12374

ContentLicense: CC BY-SA 3.0

Body:
Looks like I just need to:

render :text => myTextFromS3, :layout => true

And it works!

Update: Since 2013 rails changed

There is 3 different ways:

render html: '<strong>HTML String</strong>' # render with `text/html` MIME type

render plain: 'plain text' # render with `text/plain` MIME type

render body: 'raw body' # render raw content, does not set content type, inherits
                        # default content type, which currently is `text/html`

Source https://github.com/rails/rails/issues/12374


问:
How to display image for particular time in a video using ffmpeg
I am trying to created a video from the sequence of images. But i have to display each image with different numbers of seconds. How to do this with FFMPEG.

Thanks in advance.

答:
The ffmpeg includes a section on exactly this: https://trac.ffmpeg.org/wiki/Slideshow

Here is an example:

Example content of input.txt:

```<code>file '/path/to/dog.png'
duration 5
file '/path/to/cat.png'
duration 1
file '/path/to/rat.png'
duration 3
file '/path/to/tapeworm.png'
duration 2
file '/path/to/tapeworm.png'
</code>```

Then run:

ffmpeg -f concat -i input.txt -vsync vfr -pix_fmt yuv420p -framerate 30 output.mp4

Body:
The ffmpeg includes a section on exactly this: https://trac.ffmpeg.org/wiki/Slideshow

Here is an example:

Example content of input.txt:

file '/path/to/dog.png'
duration 5
file '/path/to/cat.png'
duration 1
file '/path/to/rat.png'
duration 3
file '/path/to/tapeworm.png'
duration 2
file '/path/to/tapeworm.png'

Then run:

ffmpeg -f concat -i input.txt -vsync vfr -pix_fmt yuv420p -framerate 30 output.mp4


问:
Array.map() doesn't render React component
I am having a problem where i'm trying to render pass an array's data to a card component but it doesn't appear on the page, the card component renders normally on its own:

```<code>import React, { Component } from 'react'
import { Container, Grid, Card, Segment, Header } from 'semantic-ui-react';
import ArticleCard from './ArticleCard';

export default class NewsGrid extends Component {
    render() {
        const {News} = this.props
        console.log(News)

        return (
            <div>
                <Container style={{marginTop: '7%'}}>
                <Grid stackable divided >
                    <Grid.Column style={{width: '66.66%'}}>
                        <Card.Group>
                            {
                                News.map(({id, ...otherArticleProps}) => (
                                    <ArticleCard key={id} {...otherArticleProps} />
                                ))
                            }
                        </Card.Group>
                    </Grid.Column>

                </Grid>
            </Container>
            </div>
        )
    }
}
</code>```

console.log() shows that the data is actually there

and i'm passing the array as props from the parent page component, the data is delivered through the flamelink API in useEffect as shown bellow:

```<code>import React, { useEffect, useState } from 'react';
import NewsGrid from '../components/NewsGrid';
import BusinessContainer from '../components/BusinessContainer';
import PolitiqueContainer from './../components/PolitiqueContainer';
import app from '../Firebase';
import { withRouter } from 'react-router-dom';

const Homepage = () => {
    const [News] = useState([])
    const [Business] = useState([])
    const [Politique] = useState([])
    const [Opinion] = useState([])
    const [Blog] = useState([])

    useEffect(() => {
        app.content.get({schemaKey: 'articles',
                        fields: ['title', 'author', 'date', 'thumbnail', 'slug', 'summary', 'category', 'id'],
                        orderBy:{field: 'date',
                        order: 'desc'},
                         })
        .then(articles => {
            for(var propName in articles) {
                const propValue = articles[propName]

                switch(propValue.category) {
                    default :
                        break;
                    case 'News':
                        News.push(propValue)
                        break;
                    case 'Business':
                        Business.push(propValue)
                        break;
                    case 'Politique':
                        Politique.push(propValue)
                        break;
                    case 'Opinion':
                        Opinion.push(propValue)
                        break;
                    case 'Blog':
                        Blog.push(propValue)
                        break;

                }
            }
        })
    })

    return (
        <div >
            <NewsGrid  News={News} Opinion={Opinion} Blog={Blog} />
            <BusinessContainer  content={Business} />
            <PolitiqueContainer  content={Politique} />

        </div>
    );
};

export default withRouter(Homepage);
</code>```

I am using firebase as a backend combined with Flamelink for the CMS.
Thanks in advance.

答:
When you use const [News] = React.useState([]), any changes you make to News will not be reflected in your React application, since mutating News will not update the state of your component. If you want to update the state of News, you need to use the state dispatch function provided by React.useState. Try this instead:

const [News, updateNews] = React.useState([])

// We can't use News.push('Some news'), but we can update News this way:
updateNews([...News, 'Some news'])
```

Body:
I am having a problem where i'm trying to render pass an array's data to a card component but it doesn't appear on the page, the card component renders normally on its own:

import React, { Component } from 'react'
import { Container, Grid, Card, Segment, Header } from 'semantic-ui-react';
import ArticleCard from './ArticleCard';

export default class NewsGrid extends Component {
    render() {
        const {News} = this.props
        console.log(News)

        return (

                <Container style={{marginTop: '7%'}}>
                <Grid stackable divided >
                    <Grid.Column style={{width: '66.66%'}}>
                        <Card.Group>
                            {
                                News.map(({id, ...otherArticleProps}) => (
                                    <ArticleCard key={id} {...otherArticleProps} />
                                ))
                            }
                        </Card.Group>
                    </Grid.Column>

                </Grid>
            </Container>

        )
    }
}

console.log() shows that the data is actually there

and i'm passing the array as props from the parent page component, the data is delivered through the flamelink API in useEffect as shown bellow:

import React, { useEffect, useState } from 'react';
import NewsGrid from '../components/NewsGrid';
import BusinessContainer from '../components/BusinessContainer';
import PolitiqueContainer from './../components/PolitiqueContainer';
import app from '../Firebase';
import { withRouter } from 'react-router-dom';

const Homepage = () => {
    const [News] = useState([])
    const [Business] = useState([])
    const [Politique] = useState([])
    const [Opinion] = useState([])
    const [Blog] = useState([])

    useEffect(() => {
        app.content.get({schemaKey: 'articles',
                        fields: ['title', 'author', 'date', 'thumbnail', 'slug', 'summary', 'category', 'id'],
                        orderBy:{field: 'date',
                        order: 'desc'},
                         })
        .then(articles => {
            for(var propName in articles) {
                const propValue = articles[propName]

                switch(propValue.category) {
                    default :
                        break;
                    case 'News':
                        News.push(propValue)
                        break;
                    case 'Business':
                        Business.push(propValue)
                        break;
                    case 'Politique':
                        Politique.push(propValue)
                        break;
                    case 'Opinion':
                        Opinion.push(propValue)
                        break;
                    case 'Blog':
                        Blog.push(propValue)
                        break;

                }
            }
        })
    })

    return (

            <NewsGrid  News={News} Opinion={Opinion} Blog={Blog} />
            <BusinessContainer  content={Business} />
            <PolitiqueContainer  content={Politique} />

    );
};

export default withRouter(Homepage);

I am using firebase as a backend combined with Flamelink for the CMS.
Thanks in advance.


问:
Can't connect activities in activity diagram in EA
Hi I'm currently stuck with a problem with Activity diagram in EA. I'm trying to describe a code. When I add Start controll node and activity node I'm not able to connect them by control flow.

The same problem happens when I try to connect two activities together with control flow - I'm getting following error:

The requested connection is not UML compliant

Anybody can give some advice on this?

Thanks

答:
Enterprise Architect is right. Control flows are not allowed from or to Activities in the UML metamodel. (I'm actually glad they finally start following the UML metamodel more)

What you are doing wrong (and you are not alone) is that you are putting Activities on an Activity Diagram.

An Activity is supposed to be the owner of your Activity Diagram. On the diagram itself you only use Actions

You can compare this to State Machines and State Machine Diagrams. The State Machine is the owner of the diagram an on the diagram itself you only use States, not State Machines.

An Activity is more like a State Machine, where an Action is more like a State.

See also the article I wrote about this subject: UML Best Practice: There are no Activities on an Activity Diagram


问:
GCP Cloud Build - deploying a scheduler job
We have the following in our cloudbuild.yaml file and it is creating our cloud scheduler job as expected.

```<code>    steps:
    # deploy cloud scheduler job
    - name: "gcr.io/cloud-builders/gcloud"
      args: ["scheduler", "jobs", "create", "pubsub", "my_job_name", "--schedule=0 0 * * 1-5", "--topic=my_topic", "--message-body=My Message", "--description=My Description", "--time-zone=America/MyTimeZone"]
</code>```

However, once cloud build is triggered again we get the following error:

```<code>    ERROR: (gcloud.scheduler.jobs.create.pubsub) ALREADY_EXISTS: ....
</code>```

We would like to keep this in our cloudbuild rather than manually creating in console. How would we, if possible, restructure the build steps and/or maybe add a cloud function in python37 that would check if the job exists, if not create. If job exists and no changes, continue. If changes are present then update.

Any feedback, suggestions or examples provided will be appreciated!

Thanks

答:
You can build conditionals with the gcloud Cloud Builder and bash within your cloudbuild.yaml. See this creative answer for inspiration.

I.E. you use a check with gcloud beta scheduler jobs list and/or gcloud beta scheduler jobs describe as a conditional before you create the schedule.

Body:
We have the following in our cloudbuild.yaml file and it is creating our cloud scheduler job as expected.

    steps:
    # deploy cloud scheduler job
    - name: "gcr.io/cloud-builders/gcloud"
      args: ["scheduler", "jobs", "create", "pubsub", "my_job_name", "--schedule=0 0 * * 1-5", "--topic=my_topic", "--message-body=My Message", "--description=My Description", "--time-zone=America/MyTimeZone"]

However, once cloud build is triggered again we get the following error:

    ERROR: (gcloud.scheduler.jobs.create.pubsub) ALREADY_EXISTS: ....

We would like to keep this in our cloudbuild rather than manually creating in console. How would we, if possible, restructure the build steps and/or maybe add a cloud function in python37 that would check if the job exists, if not create. If job exists and no changes, continue. If changes are present then update.

Any feedback, suggestions or examples provided will be appreciated!

Thanks


问:
Load image from URL
I've searched and tried a couple different methods. I am coming up short on both. This is my current method:

```<code>package com.dop.mobilevforum;

import java.io.InputStream;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.VideoView;

public class Vforum extends Activity
{
    private String imgPath = "http://mysite.com/mv/vfdemo1/slides/slide1.jpg";

    private ImageView slideHolder;

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.vforum);

        slideHolder = (ImageView) findViewById(R.id.slideHolder);

        Drawable drawable = LoadImageFromWebOperations(imgPath);
        slideHolder.setImageDrawable(drawable);
    }

    private Drawable LoadImageFromWebOperations(String url)
    {
        try
        {
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable d = Drawable.createFromStream(is, "src name");
            return d;
        }
        catch (Exception e)
        {
            Log.w("LoadImageFromWebOperations",e.toString());
            return null;
        }
    }
}
</code>```

the LoadImageFromWebOperations method is returning a bitmap, so I know that part is working. It is the slideHolder.setImageDrawable(drawable); that I think it failing. This is my XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/mobile_vforum_bg">
    <ImageView
        android:id="@+id/slideHolder"
        android:layout_width="320px"
        android:layout_height="240px">
    </ImageView>
</FrameLayout>
</code>```

any ideas? I just get a black screen, no errors.

答: Your best bet is using a WebView, but if you really want to do it this way don't use setImageDrawable. You should use setImageBitmap. If your LoadImageFromWebOperations returns a Bitmap then you shouldn't change anything, but the function you are using and it should work smoothly.

Title: Load image from URL

Body:
I've searched and tried a couple different methods. I am coming up short on both. This is my current method:

package com.dop.mobilevforum;

import java.io.InputStream;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.VideoView;

public class Vforum extends Activity
{
    private String imgPath = "http://mysite.com/mv/vfdemo1/slides/slide1.jpg";

    private ImageView slideHolder;

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.vforum);

        slideHolder = (ImageView) findViewById(R.id.slideHolder);

        Drawable drawable = LoadImageFromWebOperations(imgPath);
        slideHolder.setImageDrawable(drawable);
    }

    private Drawable LoadImageFromWebOperations(String url)
    {
        try
        {
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable d = Drawable.createFromStream(is, "src name");
            return d;
        }
        catch (Exception e)
        {
            Log.w("LoadImageFromWebOperations",e.toString());
            return null;
        }
    }
}

the LoadImageFromWebOperations method is returning a bitmap, so I know that part is working. It is the slideHolder.setImageDrawable(drawable); that I think it failing. This is my XML:

<?xml version="1.0" encoding="UTF-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/mobile_vforum_bg">
    <ImageView
        android:id="@+id/slideHolder"
        android:layout_width="320px"
        android:layout_height="240px">
    </ImageView>
</FrameLayout>

any ideas? I just get a black screen, no errors.


问:
How to zip each element from a 1D array with the elements from each row of a 2D array?
I am trying to plot a dataset using matplotlib which contains multiple y coordinates per x. To plot them I have to combine these arrays to show them in a single plot. How do I zip each element from a 1D array with the elements from each row of a 2D array (corresponding with the index for the element of the 1D array)? Without using explicit for-loops. Using built-ins (eg. zip/list comprehension) or even better: numpy?

Turning:

```<code>x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]
</code>```

Into:

```<code>r = [(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]
</code>```

Body:
I am trying to plot a dataset using matplotlib which contains multiple y coordinates per x. To plot them I have to combine these arrays to show them in a single plot. How do I zip each element from a 1D array with the elements from each row of a 2D array (corresponding with the index for the element of the 1D array)? Without using explicit for-loops. Using built-ins (eg. zip/list comprehension) or even better: numpy?

Turning:

x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]

Into:

r = [(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]

Body:
x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]

result = [(i[0], i[1][0]) for i in zip(x,y)] + [(i[0], i[1][1]) for i in zip(x,y)]

Output:

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


问:
Swift Codable - How to encode custom array
That's my JSON case

{
    "image_id" : 11101,
    "image_source_id" : 9,
    "image_author" : "",
    "image_copyright" : "",
    "image_format_list" : [
        {
            "image_format" : {
                "image_url" : "https://static.musixmatch.com/images-storage/mxmimages/1/0/1/1/1/11101_2.jpg",
                "image_format_id" : 2,
                "width" : 150,
                "height" : 150
            }
        },
        {
            "image_format" : {
                "image_url" : "https://static.musixmatch.com/images-storage/mxmimages/1/0/1/1/1/11101_16.jpg",
                "image_format_id" : 16,
                "width" : 451,
                "height" : 500
            }
        }
    ]
}
```
<p>I correctly decode my custom object in two different classes: MXMImage & MXMImageFormat.
But I can't figure out how to re-encode my object to rebuild the same JSON</p>
<p>That's my code:</p>
<pre class="lang-swift prettyprint-override"><code>struct MXMImage : Codable, Equatable {
    let imageId: Int
    let imageSourceId: Int
    let imageAuthor: String?
    let imageCopyright: String?
    let imageFormatList: [MXMImageFormat]?

    enum CodingKeys: String, Swift.CodingKey {
        case imageId
        case imageSourceId
        case imageAuthor
        case imageCopyright
        case imageFormatList

        enum ImageFormatListKey: String, CodingKey {
            case imageFormat
        }
    }

    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        imageId = try (container.decodeIfPresent(Int.self, forKey: .imageId) ?? 0)
        imageSourceId = try (container.decodeIfPresent(Int.self, forKey: .imageSourceId) ?? 0)
        imageAuthor = try? container.decodeIfPresent(String.self, forKey: .imageAuthor)
        imageCopyright = try? container.decodeIfPresent(String.self, forKey: .imageCopyright)

        var imagesFormatListContainer = try container.nestedUnkeyedContainer(forKey: .imageFormatList)
        var imagesList:[MXMImageFormat] = []
        while !imagesFormatListContainer.isAtEnd {
            let imageFormatContainer = try imagesFormatListContainer.nestedContainer(keyedBy: CodingKeys.ImageFormatListKey.self)
            let imageFormat = try? imageFormatContainer.decode(MXMImageFormat.self, forKey: .imageFormat)
            if let imageFormat = imageFormat {
                imagesList.append(imageFormat)
            }
        }
        self.imageFormatList = imagesList
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)

        try container.encodeIfPresent(imageId, forKey: .imageId)
        try container.encodeIfPresent(imageSourceId, forKey: .imageSourceId)
        try container.encodeIfPresent(imageAuthor, forKey: .imageAuthor)
        try container.encodeIfPresent(imageCopyright, forKey: .imageCopyright)

        var imageContainer = container.nestedUnkeyedContainer(forKey: .imageFormatList)
        try imageFormatList?.forEach { imgFormat in
            var nested = imageContainer.nestedContainer(keyedBy: CodingKeys.ImageFormatListKey.self)
            let data = try imgFormat.encoded()
            try nested.encode(data, forKey: .imageFormat)

        }
    }
}
</code>```

In particular, I don't know how to re-indent my MXMImageFormat objects inside the key image_format and then encode the custom array. Is it possible to do that? Thanks in advance

答:
Instead of nestedContainers you could decode/encode a [[String:MXMImageFormat]] array and map it

```<code>struct MXMImage : Codable, Equatable {
    let imageId: Int
    let imageSourceId: Int
    let imageAuthor: String?
    let imageCopyright: String?
    let imageFormatList: [MXMImageFormat]?

    private enum CodingKeys : String, CodingKey { case imageId,  imageSourceId,  imageAuthor, imageCopyright, imageFormatList}

    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        imageId = try container.decode(Int.self, forKey: .imageId)
        imageSourceId = try container.decode(Int.self, forKey: .imageSourceId)
        imageAuthor = try container.decodeIfPresent(String.self, forKey: .imageAuthor)
        imageCopyright = try container.decodeIfPresent(String.self, forKey: .imageCopyright)
        if let imageFormatListData = try container.decodeIfPresent([[String:MXMImageFormat]].self, forKey: .imageFormatList) {
            imageFormatList = imageFormatListData.compactMap{$0["image_format"]}
        } else {
            imageFormatList = nil
        }
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(imageId, forKey: .imageId)
        try container.encode(imageSourceId, forKey: .imageSourceId)
        try container.encodeIfPresent(imageAuthor, forKey: .imageAuthor)
        try container.encodeIfPresent(imageCopyright, forKey: .imageCopyright)
        if let imageFormatListData = imageFormatList {
            try container.encode(imageFormatListData.map{["image_format":$0]}, forKey: .imageFormatList)
        }
    }
}

struct MXMImageFormat : Codable, Equatable {
    let imageUrl : URL
    let imageFormatId, width, height : Int
}
</code>```

Body:
That's my JSON case

{
    "image_id" : 11101,
    "image_source_id" : 9,
    "image_author" : "",
    "image_copyright" : "",
    "image_format_list" : [
        {
            "image_format" : {
                "image_url" : "https://static.musixmatch.com/images-storage/mxmimages/1/0/1/1/1/11101_2.jpg",
                "image_format_id" : 2,
                "width" : 150,
                "height" : 150
            }
        },
        {
            "image_format" : {
                "image_url" : "https://static.musixmatch.com/images-storage/mxmimages/1/0/1/1/1/11101_16.jpg",
                "image_format_id" : 16,
                "width" : 451,
                "height" : 500
            }
        }
    ]
}

I correctly decode my custom object in two different classes: MXMImage & MXMImageFormat.
But I can't figure out how to re-encode my object to rebuild the same JSON

That's my code:

struct MXMImage : Codable, Equatable {
    let imageId: Int
    let imageSourceId: Int
    let imageAuthor: String?
    let imageCopyright: String?
    let imageFormatList: [MXMImageFormat]?

    enum CodingKeys: String, Swift.CodingKey {
        case imageId
        case imageSourceId
        case imageAuthor
        case imageCopyright
        case imageFormatList

        enum ImageFormatListKey: String, CodingKey {
            case imageFormat
        }
    }

    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        imageId = try (container.decodeIfPresent(Int.self, forKey: .imageId) ?? 0)
        imageSourceId = try (container.decodeIfPresent(Int.self, forKey: .imageSourceId) ?? 0)
        imageAuthor = try? container.decodeIfPresent(String.self, forKey: .imageAuthor)
        imageCopyright = try? container.decodeIfPresent(String.self, forKey: .imageCopyright)

        var imagesFormatListContainer = try container.nestedUnkeyedContainer(forKey: .imageFormatList)
        var imagesList:[MXMImageFormat] = []
        while !imagesFormatListContainer.isAtEnd {
            let imageFormatContainer = try imagesFormatListContainer.nestedContainer(keyedBy: CodingKeys.ImageFormatListKey.self)
            let imageFormat = try? imageFormatContainer.decode(MXMImageFormat.self, forKey: .imageFormat)
            if let imageFormat = imageFormat {
                imagesList.append(imageFormat)
            }
        }
        self.imageFormatList = imagesList
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)

        try container.encodeIfPresent(imageId, forKey: .imageId)
        try container.encodeIfPresent(imageSourceId, forKey: .imageSourceId)
        try container.encodeIfPresent(imageAuthor, forKey: .imageAuthor)
        try container.encodeIfPresent(imageCopyright, forKey: .imageCopyright)

        var imageContainer = container.nestedUnkeyedContainer(forKey: .imageFormatList)
        try imageFormatList?.forEach { imgFormat in
            var nested = imageContainer.nestedContainer(keyedBy: CodingKeys.ImageFormatListKey.self)
            let data = try imgFormat.encoded()
            try nested.encode(data, forKey: .imageFormat)

        }
    }
}

In particular, I don't know how to re-indent my MXMImageFormat objects inside the key image_format and then encode the custom array. Is it possible to do that? Thanks in advance

Body:
Instead of nestedContainers you could decode/encode a [[String:MXMImageFormat]] array and map it

struct MXMImage : Codable, Equatable {
    let imageId: Int
    let imageSourceId: Int
    let imageAuthor: String?
    let imageCopyright: String?
    let imageFormatList: [MXMImageFormat]?

    private enum CodingKeys : String, CodingKey { case imageId,  imageSourceId,  imageAuthor, imageCopyright, imageFormatList}

    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        imageId = try container.decode(Int.self, forKey: .imageId)
        imageSourceId = try container.decode(Int.self, forKey: .imageSourceId)
        imageAuthor = try container.decodeIfPresent(String.self, forKey: .imageAuthor)
        imageCopyright = try container.decodeIfPresent(String.self, forKey: .imageCopyright)
        if let imageFormatListData = try container.decodeIfPresent([[String:MXMImageFormat]].self, forKey: .imageFormatList) {
            imageFormatList = imageFormatListData.compactMap{$0["image_format"]}
        } else {
            imageFormatList = nil
        }
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(imageId, forKey: .imageId)
        try container.encode(imageSourceId, forKey: .imageSourceId)
        try container.encodeIfPresent(imageAuthor, forKey: .imageAuthor)
        try container.encodeIfPresent(imageCopyright, forKey: .imageCopyright)
        if let imageFormatListData = imageFormatList {
            try container.encode(imageFormatListData.map{["image_format":$0]}, forKey: .imageFormatList)
        }
    }
}

struct MXMImageFormat : Codable, Equatable {
    let imageUrl : URL
    let imageFormatId, width, height : Int
}


问:
Group by each unique id and then find number of purchases for each brand
I have customer purchase data for the last 3 years. A sample below:

```<code> customer_id|date      |sales_amount|product_type
 479485     |20190120  | 500        | bags
 479485     |20180320  | 200        | clothes
 479485     |20180321  | 200        | clothes
 472848     |20191020  | 100        | clothes
</code>```

I want to find for each unique customer id, number of transactions they had over the three years for the different product type. Ideally a value count on product type for each unique customer id. So for customer_id = 479485 the output :

```<code> customer_id
 479485     |bags      | 1
            |clothes   | 2
</code>```

I have tried doing a pivot table but it is not giving me my ideal result:

pd.pivot_table(clusters, index=['customer_id', 'product_type'], aggfunc='sum')

bonus: If I wanted to do the same thing but look at it but separate it by year is that possible?

答:
This should work:</p>

```<code>temp = df.groupby(['customer_id', 'product_type'])['date'].count()

temp
customer_id  product_type
472848       clothes         1
479485       bags            1
             clothes         2
</code>```

Body:
I have customer purchase data for the last 3 years. A sample below:

 customer_id|date      |sales_amount|product_type
 479485     |20190120  | 500        | bags
 479485     |20180320  | 200        | clothes
 479485     |20180321  | 200        | clothes
 472848     |20191020  | 100        | clothes

I want to find for each unique customer id, number of transactions they had over the three years for the different product type. Ideally a value count on product type for each unique customer id. So for customer_id = 479485 the output :

 customer_id
 479485     |bags      | 1
            |clothes   | 2

I have tried doing a pivot table but it is not giving me my ideal result:

pd.pivot_table(clusters, index=['customer_id', 'product_type'], aggfunc='sum')

bonus: If I wanted to do the same thing but look at it but separate it by year is that possible?

Body:
This should work:

temp = df.groupby(['customer_id', 'product_type'])['date'].count()

temp
customer_id  product_type
472848       clothes         1
479485       bags            1
             clothes         2


问:
Problems with JDBC URL in tomcat 9 context.xml for treeAnno
I have a fresh tomcat 9 installation on a server (Ubuntu 18.04). I am trying to set up treeanno (https://github.com/nilsreiter/treeanno/releases) and deploy the web application archive (war) which is given in the github repos.
I used the tomcat manager app in order to deploy the war-file, and followed this description to configure tomcat to use the respective database resource: https://github.com/nilsreiter/treeanno/blob/master/INSTALL.md.
According to the meagre description, this shall be added in the context.xml of the tomcat installation:

```<code><Resource name="treeanno/jdbc" auth="Container" type="javax.sql.DataSource"
           maxActive="100" maxIdle="30" maxWait="10000"
           username="USERNAME" password="PASSWORD" driverClassName="com.mysql.jdbc.Driver"
           url="DATABASE URL"/>
</code>```

As I am new to tomcat, it is unclear to me what properties I need to set, especially the "url".
If I try to access the app, I get the following error, pointing at that no data base connection can be build since the url is not adequate:

```<code>    Type Exception Report

    Message An exception occurred processing [/index.jsp] at line [12]

    Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.apache.jasper.JasperException: An exception occurred processing [/index.jsp] at line [12]

9:      doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
10:         doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
11:         omit-xml-declaration="false" />
12: <sql:query var="rs" dataSource="treeanno/jdbc" sql="select id, username from treeanno_users">
13: </sql:query>
14: <html xmlns="http://www.w3.org/1999/xhtml">
15: <head>

Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:626)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:500)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Root Cause

javax.servlet.ServletException: javax.servlet.jsp.JspException: Unable to get connection, DataSource invalid: "java.sql.SQLException: Cannot create JDBC driver of class 'com.mysql.jdbc.Driver' for connect URL 'jdbc:mysql:3306'"
    org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:666)
    org.apache.jsp.index_jsp._jspService(index_jsp.java:270)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:477)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Root Cause

javax.servlet.jsp.JspException: Unable to get connection, DataSource invalid: "java.sql.SQLException: Cannot create JDBC driver of class 'com.mysql.jdbc.Driver' for connect URL 'jdbc:mysql:3306'"
    org.apache.taglibs.standard.tag.common.sql.QueryTagSupport.getConnection(QueryTagSupport.java:285)
    org.apache.taglibs.standard.tag.common.sql.QueryTagSupport.doStartTag(QueryTagSupport.java:168)
    org.apache.jsp.index_jsp._jspx_meth_sql_005fquery_005f0(index_jsp.java:296)
    org.apache.jsp.index_jsp._jspService(index_jsp.java:134)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:477)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
</code>```

I already figured out that the url is supposed to link to a database server including password and user, but this does not seem to be appropriate for this config file.

The following I found here (https://ci.apache.org/projects/tomcat/tomcat9/docs/jndi-datasource-examples-howto.html):

```<code>url=jdbc:mysql://localhost:3306/javatest"/
</code>```

but adjusting the port etc. does not work:
    url=jdbc:mysql://localhost:8080/TreeAnno-1.0.2"/

Now, how do I need to formulate the url to allow the app to connect to / initiate a MySQL database?

答:
First of all , you need to install MySQL (Or install with docker if you are familiar with it) .

During installation , I remember it will ask you to set the password for the root (which is the default username). After installation , create a new database .

Assume you name the database as foo , the <Resource/> in context.xml should update to :

<Resource name="treeanno/jdbc" auth="Container" type="javax.sql.DataSource"
           maxActive="100" maxIdle="30" maxWait="10000"
           username="root" password="passwordOfTheRoot" driverClassName="com.mysql.jdbc.Driver"
           url="jdbc:mysql://localhost:3306/foo"/>
```

Then download MySQL JDBC driver, and put it inside the $TOMCAT_ROOT_FOLDER/lib .Then restart Tomcat and I believe the application will then connect to the foo database and create the tables for you.

Body:
I have a fresh tomcat 9 installation on a server (Ubuntu 18.04). I am trying to set up treeanno (https://github.com/nilsreiter/treeanno/releases) and deploy the web application archive (war) which is given in the github repos.
I used the tomcat manager app in order to deploy the war-file, and followed this description to configure tomcat to use the respective database resource: https://github.com/nilsreiter/treeanno/blob/master/INSTALL.md.
According to the meagre description, this shall be added in the context.xml of the tomcat installation:

<Resource name="treeanno/jdbc" auth="Container" type="javax.sql.DataSource"
           maxActive="100" maxIdle="30" maxWait="10000"
           username="USERNAME" password="PASSWORD" driverClassName="com.mysql.jdbc.Driver"
           url="DATABASE URL"/>

As I am new to tomcat, it is unclear to me what properties I need to set, especially the "url".
If I try to access the app, I get the following error, pointing at that no data base connection can be build since the url is not adequate:

    Type Exception Report

    Message An exception occurred processing [/index.jsp] at line [12]

    Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.apache.jasper.JasperException: An exception occurred processing [/index.jsp] at line [12]

9:      doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
10:         doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
11:         omit-xml-declaration="false" />
12: <sql:query var="rs" dataSource="treeanno/jdbc" sql="select id, username from treeanno_users">
13: </sql:query>
14:
15:

Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:626)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:500)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Root Cause

javax.servlet.ServletException: javax.servlet.jsp.JspException: Unable to get connection, DataSource invalid: "java.sql.SQLException: Cannot create JDBC driver of class 'com.mysql.jdbc.Driver' for connect URL 'jdbc:mysql:3306'"
    org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:666)
    org.apache.jsp.index_jsp._jspService(index_jsp.java:270)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:477)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Root Cause

javax.servlet.jsp.JspException: Unable to get connection, DataSource invalid: "java.sql.SQLException: Cannot create JDBC driver of class 'com.mysql.jdbc.Driver' for connect URL 'jdbc:mysql:3306'"
    org.apache.taglibs.standard.tag.common.sql.QueryTagSupport.getConnection(QueryTagSupport.java:285)
    org.apache.taglibs.standard.tag.common.sql.QueryTagSupport.doStartTag(QueryTagSupport.java:168)
    org.apache.jsp.index_jsp._jspx_meth_sql_005fquery_005f0(index_jsp.java:296)
    org.apache.jsp.index_jsp._jspService(index_jsp.java:134)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:477)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

I already figured out that the url is supposed to link to a database server including password and user, but this does not seem to be appropriate for this config file.

The following I found here (https://ci.apache.org/projects/tomcat/tomcat9/docs/jndi-datasource-examples-howto.html):

url=jdbc:mysql://localhost:3306/javatest"/

but adjusting the port etc. does not work:
    url=jdbc:mysql://localhost:8080/TreeAnno-1.0.2"/

Now, how do I need to formulate the url to allow the app to connect to / initiate a MySQL database?

Body:
First of all , you need to install MySQL (Or install with docker if you are familiar with it) .

During installation , I remember it will ask you to set the password for the root (which is the default username). After installation , create a new database .

Assume you name the database as foo , the <Resource/> in context.xml should update to :

<Resource name="treeanno/jdbc" auth="Container" type="javax.sql.DataSource"
           maxActive="100" maxIdle="30" maxWait="10000"
           username="root" password="passwordOfTheRoot" driverClassName="com.mysql.jdbc.Driver"
           url="jdbc:mysql://localhost:3306/foo"/>

Then download MySQL JDBC driver, and put it inside the $TOMCAT_ROOT_FOLDER/lib .Then restart Tomcat and I believe the application will then connect to the foo database and create the tables for you.


问:
Probable bug in java compiler for openjdk8, how to report and get it fixed?
I've prepared docker image that demonstrate the problem:

https://drive.google.com/uc?id=1i04_dVL0Rp5rxXCMuHaS4LYREkZjAAW1&export=download

This image is basically alpine:3.11 + apk add openjdk8 maven + my maven project containing sample minimal java class that shows problem

Which you can try with following commands:

```<code># docker load -i bugexample.img
# docker run -w /root/bug-example --name bugtest bugexample /bin/ash build-until-sha-different.sh
</code>```

If you are lucky enough (sometimes require several attempts) you will get following output:

```<code>Found! Sha1 of two subsequent otherwise identical builds are different!
--- 1.sha1
+++ 2.sha1
@@ -1,3 +1,3 @@
 d8d46555c93da579adefc629f1764965a5493edb  com/SimpleBug$1.class
 75007242aab1e1877d24124d432cb246a79476a8  com/SimpleBug$SimpleBugBuilder.class
-23e8d0ea909b95a7955e0ec0adb4d12ae2193dd1  com/SimpleBug.class
+6a303d69d3f382b23ca04caee4102ee1cd7151e3  com/SimpleBug.class
</code>```

The core issue with this build is that it produce different bytecode almost each time it get build even though nothing else (neither environment, nor code itself) had changed.

When I do compare these different class files I see that they differ in one single byte:

```<code># cmp -lb 1_SimpleBug.class 2_SimpleBug.class
4053  66 6     65 5
</code>```

Digging deeper into class file structure I've found that this difference come from stackmapframe constant pool pointers (StackMapTable attribute -> stack_map_frame entry with tag Object_variable_info -> cpool_index)

```<code>1_SimpleBug.class
   #35 = Utf8               supSetStringParameter10
   #36 = Utf8               Lcom/google/common/base/Supplier;

2_SimpleBug.class
   #35 = Utf8               supSetStringParameter10
   #36 = Utf8               Lcom/google/common/base/Supplier;
</code>```

So one file points to #35 and another to #36. I don't think this is correct behavior.

I would like to sumbit this to a proper issue tracker but I don't know how to do that since all related JDK trackers are for devs only.

```<code># java -version
openjdk version "1.8.0_242"
OpenJDK Runtime Environment (IcedTea 3.15.0) (Alpine 8.242.08-r0)
OpenJDK 64-Bit Server VM (build 25.242-b08, mixed mode)

# mvn -version
Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f)
Maven home: /usr/share/java/maven-3
Java version: 1.8.0_242, vendor: IcedTea, runtime: /usr/lib/jvm/java-1.8-openjdk/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.15.0-1050-kvm", arch: "amd64", family: "unix"
</code>```

And here is archive with java project:

https://drive.google.com/uc?id=1ZBdRzUk00QtpkGGnKAzipMjMtcnkKGN4&export=download

答:
Well... The Mountain in Labour...

All of this was for nothing. Maven was main culprit. First time I ran my build it downloads lots of stuff that maven require (apart from my project dependencies) and then start compilation in same jvm. Second time build runs there is no need to download so compilation starts immediately. I don't know exactly why but first invocation of compiler is somehow affected by state of the jvm and this cause it to produce slightly different bytecode.

Solution was to add <fork>true<fork> to my pom.xml file and build now is totally reproducible... though takes ~2x more time :)

I still believe that this should not happen even if initial compilation happened inside maven jvm, and it may still be topic for improvement in javac but this "workaround" is acceptable.

Body:
I've prepared docker image that demonstrate the problem:

https://drive.google.com/uc?id=1i04_dVL0Rp5rxXCMuHaS4LYREkZjAAW1&export=download

This image is basically alpine:3.11 + apk add openjdk8 maven + my maven project containing sample minimal java class that shows problem

Which you can try with following commands:

# docker load -i bugexample.img
# docker run -w /root/bug-example --name bugtest bugexample /bin/ash build-until-sha-different.sh

If you are lucky enough (sometimes require several attempts) you will get following output:

Found! Sha1 of two subsequent otherwise identical builds are different!
--- 1.sha1
+++ 2.sha1
@@ -1,3 +1,3 @@
 d8d46555c93da579adefc629f1764965a5493edb  com/SimpleBug$1.class
 75007242aab1e1877d24124d432cb246a79476a8  com/SimpleBug$SimpleBugBuilder.class
-23e8d0ea909b95a7955e0ec0adb4d12ae2193dd1  com/SimpleBug.class
+6a303d69d3f382b23ca04caee4102ee1cd7151e3  com/SimpleBug.class

The core issue with this build is that it produce different bytecode almost each time it get build even though nothing else (neither environment, nor code itself) had changed.

When I do compare these different class files I see that they differ in one single byte:

# cmp -lb 1_SimpleBug.class 2_SimpleBug.class
4053  66 6     65 5

Digging deeper into class file structure I've found that this difference come from stackmapframe constant pool pointers (StackMapTable attribute -> stack_map_frame entry with tag Object_variable_info -> cpool_index)

1_SimpleBug.class
   #35 = Utf8               supSetStringParameter10
   #36 = Utf8               Lcom/google/common/base/Supplier;

2_SimpleBug.class
   #35 = Utf8               supSetStringParameter10
   #36 = Utf8               Lcom/google/common/base/Supplier;

So one file points to #35 and another to #36. I don't think this is correct behavior.

I would like to sumbit this to a proper issue tracker but I don't know how to do that since all related JDK trackers are for devs only.

# java -version
openjdk version "1.8.0_242"
OpenJDK Runtime Environment (IcedTea 3.15.0) (Alpine 8.242.08-r0)
OpenJDK 64-Bit Server VM (build 25.242-b08, mixed mode)

# mvn -version
Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f)
Maven home: /usr/share/java/maven-3
Java version: 1.8.0_242, vendor: IcedTea, runtime: /usr/lib/jvm/java-1.8-openjdk/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.15.0-1050-kvm", arch: "amd64", family: "unix"

And here is archive with java project:

https://drive.google.com/uc?id=1ZBdRzUk00QtpkGGnKAzipMjMtcnkKGN4&export=download


问:
Save and run at the same time in Vim
I do a lot of Python quick simulation stuff and I'm constantly saving (:w) and then running (:!!). Is there a way to combine these actions?

Maybe a "save and run" command.

答:
Use the autowrite option:

```<code>:set autowrite
</code>```

Write the contents of the file, if it has been modified, on each :next, :rewind, :last, :first, :previous, :stop, :suspend, :tag, :!, :make, CTRL-] and CTRL-^ command [...]

OwnerDisplayName: Casey

Title: Save and run at the same time in Vim

Body:
Use the autowrite option:

:set autowrite

Write the contents of the file, if it has been modified, on each :next, :rewind, :last, :first, :previous, :stop, :suspend, :tag, :!, :make, CTRL-] and CTRL-^ command [...]

OwnerDisplayName: strager

ContentLicense: CC BY-SA 2.5


问:
UIApplicationDelegate question
In my AppDelegate I have a reference to an NSObject like this:

```<code>@interface MyAppDelegate : NSObject <UIApplicationDelegate>
{
    MyObjectManager * myObjectManager;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;

@property (nonatomic, retain) MyObjectManager * myObjectManager;
</code>```

I want to access this from my UIViewController, so I do this:

```<code>MyAppDelegate * appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
MyObjectManager * myObjectManager = appDelegate.myObjectManager;
maMyArray = [[NSMutableArray alloc] init];

[[appDelegate myObjectManager] findMyStuff:5 foundArray:maMyArray];
//[myObjectManager findMyStuff:5 foundArray:maMyArray];
</code>```

However, I think I am not understanding the syntax in Objective C correctly because I throw an exception, EXC_BAD_ACCESS.   When I look at the values, they seem correct.

Can someone please explain what I am doing wrong?

Thanks

答:
Where is the code that allocates a MyObjectManager  and assigns it to your myObjectManager property?

Until you do that, it's nil.

Title: UIApplicationDelegate question

Body:
In my AppDelegate I have a reference to an NSObject like this:

@interface MyAppDelegate : NSObject <UIApplicationDelegate>
{
    MyObjectManager * myObjectManager;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;

@property (nonatomic, retain) MyObjectManager * myObjectManager;

I want to access this from my UIViewController, so I do this:

MyAppDelegate * appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
MyObjectManager * myObjectManager = appDelegate.myObjectManager;
maMyArray = [[NSMutableArray alloc] init];

[[appDelegate myObjectManager] findMyStuff:5 foundArray:maMyArray];
//[myObjectManager findMyStuff:5 foundArray:maMyArray];

However, I think I am not understanding the syntax in Objective C correctly because I throw an exception, EXC_BAD_ACCESS.   When I look at the values, they seem correct.

Can someone please explain what I am doing wrong?

Thanks


问:
Difference between heuristic function and evaluation function
I'm reading about searching algorithms and heuristic search and I am slightly confused about heuristic and evaluation functions. People seem to use them quite freely to describe seemingly same things. What am I missing?</p>

答:
There can be confusion around this issue because heuristics mean different things in different contexts. So, let me talk about the different meaning of heuristics. Then we can return to evaluation functions.

Single Agent Heuristic Search

In single-agent heuristic search (eg A*, IDA*) heuristics are usually qualified with the words admissible or consistent. In this context heuristics are lower bounds on the cost to reach the goal. That is, they are the result of a function which returns a numerical value. If the heuristic is admissible, the value returned does not overestimate the true distance to the goal. If the heuristic is consistent, the heuristic between adjacent states never changes more than the edge cost. Consistent heuristics are admissible if the goal has a heuristic of 0, but not all admissible heuristics are consistent.

There are many properties proven on the combinations of heuristics and algorithms. A* and IDA* will find optimal paths with a consistent heuristic. A* is optimal in necessary node expansions with a consistent heuristic, but with a inconsistent heuristic A* can perform 2^N expansions of N states. (See this demo for an example of where this occurs.)

Game Playing

In game playing programs using algorithms like alpha-beta or Monte Carlo tree search (MCTS), heuristics represent approximations of the win/loss value of a game. For instance, the value might be scaled between -1 (loss) and +1 (win), with values in between representing uncertainty about the true value. Here there are no guarantees on underestimate or overestimation, but the better ordering of values (wins > draws > losses) the better the performance of the algorithms. Alpha-beta pruning will return the same result even if an affine transform is applied to the heuristic, because alpha-beta uses the relative ordering of values to search. See, this paper for an example of heuristics in MCTS. Note that in this context a heuristic still has a numerical value.

Optimization

In search for optimization problems like SAT (satisfiability problems) or CSP (constraint satisfaction problems), algorithms are much more efficient if they can find good solutions quickly. Thus, instead of searching in a naive manner, they order their search in a way that is expected to be more efficient. If the ordering is good the search might be able to terminate earlier, but this isn't guaranteed. In this context a heuristic is a way of ordering choices that is likely to end up with finding a solution more quickly. (A satisfying assignment of variables in SAT or in a CSP.) Here is an example of work that explores different ordering heuristics for these problems.

In this context a heuristic is used for ordering, so it doesn't have to be numerically based. If it is numerically based, the numbers would not necessarily have global meaning as heuristics do in other types of search. There are many, many variants of optimizations problems besides SAT and CSP where heuristics are used in this manner.

Evaluation Function

So, then, what is an evaluation function? It is probably most commonly used in the second context of games, where heuristic and evaluation function can be interchanged, but it is more generally referring to the numerical evaluation of a state. The primary point would be that an evaluation function is more specific than a heuristic function, as a heuristic has broad use in wider contexts.


问:
Sidebar partials for multilevel user in Codeigniter
what is the best code for sidebar partial for multilevel?

Is it just do in Controller like :

```<code>public function tambahNota()
{
    $head['title'] = 'Tambah Nota';

    if($this->session->userdata('userLevel') == 1){
        $this->load->view('partials/sidebarAdmin');
    } elseif($this->session->userdata('userLevel') == 2){
        $this->load->view('partials/sidebarUser');
    }

    $this->load->view('partials/footer');
    $this->load->view('nota/tambahNota');
</code>```

.. or in View partials/sidebar?

```<code><?php if ($this->session->userdata('userLevel') == 1) {?>
     ..script of admin sidebar..
<?php } else if($this->session->userdata('userLevel') == 2) {?>
     ..script of user sidebar..
<?php } ?>
</code>```

Thank you.

答:
Hi @Goldplate it is good to keep it at the view. Although both ways works, keeping it in the view makes it easy to change filenames when you need to.

You can create a helper function to keep things simple, for example:

Create a helper with the name template_helper.php in the helpers directory.

Add the code below.

```<code><?php
defined('BASEPATH') or exit('No direct script access allowed');

function load_partial($view_path, $view_data = null)
{

    $ci =& get_instance(); //get_instance is an instance of codeigniter object

    if (strstr($view_path, '.')) {
        $view_path = str_replace('.', '/', $view_path);
    }

    $ci->load->view($view_path, $view_data);
}
</code>```

And you can use it like this:

```<code><?php if ($this->session->userdata('userLevel') == 1) {?>
     load_partial('sidebars.level_one');
<?php } else if($this->session->userdata('userLevel') == 2) {?>
    load_partial('sidebars.level_two');
<?php } ?>
</code>```

So here "sidebars" is a directory that contains files level_one.php and level_two.php

If you see a dot in 'sidebars.level_one' it is just replacing a forward slash '/' and for easy access.

This is just to give you an idea. Let me know if it helps.

Body:
what is the best code for sidebar partial for multilevel?

Is it just do in Controller like :

public function tambahNota()
{
    $head['title'] = 'Tambah Nota';

    if($this->session->userdata('userLevel') == 1){
        $this->load->view('partials/sidebarAdmin');
    } elseif($this->session->userdata('userLevel') == 2){
        $this->load->view('partials/sidebarUser');
    }

    $this->load->view('partials/footer');
    $this->load->view('nota/tambahNota');

.. or in View partials/sidebar?

<?php if ($this->session->userdata('userLevel') == 1) {?>
     ..script of admin sidebar..
<?php } else if($this->session->userdata('userLevel') == 2) {?>
     ..script of user sidebar..
<?php } ?>

Thank you.

Body:
Hi @Goldplate it is good to keep it at the view. Although both ways works, keeping it in the view makes it easy to change filenames when you need to.

You can create a helper function to keep things simple, for example:

Create a helper with the name template_helper.php in the helpers directory.

Add the code below.

<?php
defined('BASEPATH') or exit('No direct script access allowed');

function load_partial($view_path, $view_data = null)
{

    $ci =& get_instance(); //get_instance is an instance of codeigniter object

    if (strstr($view_path, '.')) {
        $view_path = str_replace('.', '/', $view_path);
    }

    $ci->load->view($view_path, $view_data);
}

And you can use it like this:

<?php if ($this->session->userdata('userLevel') == 1) {?>
     load_partial('sidebars.level_one');
<?php } else if($this->session->userdata('userLevel') == 2) {?>
    load_partial('sidebars.level_two');
<?php } ?>

So here "sidebars" is a directory that contains files level_one.php and level_two.php

If you see a dot in 'sidebars.level_one' it is just replacing a forward slash '/' and for easy access.

This is just to give you an idea. Let me know if it helps.


问:
How to query a datetime column to find dates that may be out of order in a case statement?
I have a table that displays orders with a pickup and sometimes multiple deliveries. All stops on the order are giving a sequence number based on how it was entered. Sometimes we can fat finger a date and the 3rd stop out of 5 is not in chronological order with the rest. I need a case statement that populates either 'Yes' or 'No' if there is a date entered out of order. I tried the to create the following Case statement, but it doesn't work, it returns Yes, when it is no, and sometimes is just blank.</p>

```<code>Select Top 1 Case
When Exists (Select Count(*) from stops having Count(*) = '2') Then Case
When s1.stp_schdtlatest<s2.stp_schdtlatest
Then 'Yes'
When Exists (Select Count(*) from stops having Count(*) = '3') Then Case
When s1.stp_schdtlatest < s2.stp_schdtlatest and s2.stp_schdtlatest < s3.stp_schdtlatest
Then 'Yes'
When Exists (Select Count(*) from stops having Count(*) = '4') Then Case
When (s1.stp_schdtlatest < s2.stp_schdtlatest) and (s2.stp_schdtlatest < s3.stp_schdtlatest) and (s3.stp_schdtlatest < s4.stp_schdtlatest)
Then 'Yes'
When Exists (Select Count(*) from stops having Count(*) >= '5') Then Case
When (s1.stp_schdtlatest<s2.stp_schdtlatest) and (s2.stp_schdtlatest<s3.stp_schdtlatest) and (s3.stp_schdtlatest<s4.stp_schdtlatest) and (s4.stp_schdtlatest<s5.stp_schdtlatest)
Then 'Yes'
Else 'No-Out of Sequence'
End
End
End
End
End as 'Sequenced?'
from legheader l
Inner Join stops on stops.lgh_number = l.lgh_number
Inner join stops s1 on s1.lgh_number = l.lgh_number and s1.stp_mfh_sequence = '1'
Inner join stops s2 on s2.lgh_number = l.lgh_number and s2.stp_mfh_sequence = '2'
Inner join stops s3 on s3.lgh_number = l.lgh_number and s3.stp_mfh_sequence = '3'
Inner join stops s4 on s4.lgh_number = l.lgh_number and s4.stp_mfh_sequence = '4'
Inner join stops s5 on s5.lgh_number = l.lgh_number and s5.stp_mfh_sequence = '5'
where lgh_outstatus in ('AVL','PLN','DSP','STD') and l.lgh_number = 276735
</code>```

答:
It might be easier to use a windowing function like ROW_NUMBER. It is difficult for me to determine from your current query exactly how you need the data. But something like this should get you some usable results, and hopefully point you in the direction to get exactly the results you need...

```<code>SELECT relevant_data
   , CASE WHEN ROW_NUMBER() OVER (ORDER BY s.stp_mfh_sequence) <> ROW_NUMBER() OVER (ORDER BY s.stp_schdtlatest )
          THEN 'Out of Sequence'
          ELSE 'In Sequence'
     END AS seqState
FROM legheader AS l
INNER JOIN stops AS ON l.lgh_number = s.lgh_number
WHERE l.lgh_outstatus in ('AVL','PLN','DSP','STD')
   AND l.lgh_number = 276735
;
</code>```

Note: As I write this, I realize that once you have one out of order, many that follow it will be considered out of order. (If seq 2 entry has a time > seq 4, then the "out of order" state will persist until seq 5.)

You can also extend this to multiple lgh_numbers with ROW_NUMBER() OVER (PARTITION BY s.lgh_number ORDER BY ...)

Body:
I have a table that displays orders with a pickup and sometimes multiple deliveries. All stops on the order are giving a sequence number based on how it was entered. Sometimes we can fat finger a date and the 3rd stop out of 5 is not in chronological order with the rest. I need a case statement that populates either 'Yes' or 'No' if there is a date entered out of order. I tried the to create the following Case statement, but it doesn't work, it returns Yes, when it is no, and sometimes is just blank.

Select Top 1 Case
When Exists (Select Count(*) from stops having Count(*) = '2') Then Case
When s1.stp_schdtlatest<s2.stp_schdtlatest
Then 'Yes'
When Exists (Select Count(*) from stops having Count(*) = '3') Then Case
When s1.stp_schdtlatest < s2.stp_schdtlatest and s2.stp_schdtlatest < s3.stp_schdtlatest
Then 'Yes'
When Exists (Select Count(*) from stops having Count(*) = '4') Then Case
When (s1.stp_schdtlatest < s2.stp_schdtlatest) and (s2.stp_schdtlatest < s3.stp_schdtlatest) and (s3.stp_schdtlatest < s4.stp_schdtlatest)
Then 'Yes'
When Exists (Select Count(*) from stops having Count(*) >= '5') Then Case
When (s1.stp_schdtlatest<s2.stp_schdtlatest) and (s2.stp_schdtlatest<s3.stp_schdtlatest) and (s3.stp_schdtlatest<s4.stp_schdtlatest) and (s4.stp_schdtlatest<s5.stp_schdtlatest)
Then 'Yes'
Else 'No-Out of Sequence'
End
End
End
End
End as 'Sequenced?'
from legheader l
Inner Join stops on stops.lgh_number = l.lgh_number
Inner join stops s1 on s1.lgh_number = l.lgh_number and s1.stp_mfh_sequence = '1'
Inner join stops s2 on s2.lgh_number = l.lgh_number and s2.stp_mfh_sequence = '2'
Inner join stops s3 on s3.lgh_number = l.lgh_number and s3.stp_mfh_sequence = '3'
Inner join stops s4 on s4.lgh_number = l.lgh_number and s4.stp_mfh_sequence = '4'
Inner join stops s5 on s5.lgh_number = l.lgh_number and s5.stp_mfh_sequence = '5'
where lgh_outstatus in ('AVL','PLN','DSP','STD') and l.lgh_number = 276735

Body:
It might be easier to use a windowing function like ROW_NUMBER. It is difficult for me to determine from your current query exactly how you need the data. But something like this should get you some usable results, and hopefully point you in the direction to get exactly the results you need...

SELECT relevant_data
   , CASE WHEN ROW_NUMBER() OVER (ORDER BY s.stp_mfh_sequence) <> ROW_NUMBER() OVER (ORDER BY s.stp_schdtlatest )
          THEN 'Out of Sequence'
          ELSE 'In Sequence'
     END AS seqState
FROM legheader AS l
INNER JOIN stops AS ON l.lgh_number = s.lgh_number
WHERE l.lgh_outstatus in ('AVL','PLN','DSP','STD')
   AND l.lgh_number = 276735
;

Note: As I write this, I realize that once you have one out of order, many that follow it will be considered out of order. (If seq 2 entry has a time > seq 4, then the "out of order" state will persist until seq 5.)

You can also extend this to multiple lgh_numbers with ROW_NUMBER() OVER (PARTITION BY s.lgh_number ORDER BY ...)


问:
Indexing only an attribute on a json array - Postgres
I have a table with a jsonb field named "data" with the following content:

```<code>{
  customerId: 1,
  something: "..."
  list: [{ nestedId: 1, attribute: "a" }, { nestedId: 2, attribute: "b" }]
}
</code>```

I need to retrieve the whole row based on its 'nestedId' attribute, note that the field is inside an array.

After checking the query plans I found out I could benefit from an index. So I added:

```<code>CREATE INDEX i1 ON mytable using gin ((data->'list') jsonb_path_ops))
</code>```

From what I understood from the doc, this creates index items for the values in the "list", the solution solves my problem.

For the sake of completion follow the query I can use to retrieve my data

```<code>SELECT data FROM mytable where data->'list' @> '[{"nestedId": 1}]'
</code>```

Tho, I wonder if there are more optimal indexing I could do. Is it possible to create an index only for the "nestedId" field for example?

答:
You can index only the numeric values and not also the keys, using functional indexes.  You probably need to make a helper function to do so.

```<code>create function jsonb_objarray_to_intarray(jsonb,text) returns int[] immutable language sql as
  $$ select array_agg((x->>$2)::int) from jsonb_array_elements($1) f(x) $$;

create index on mytable using gin (jsonb_objarray_to_intarray(data->'list','nestedId'));

SELECT data FROM mytable where jsonb_objarray_to_intarray(data->'list','nestedId') @> ARRAY[3];
</code>```

I wrote it this way so the function could be reused in other similar situations.  If you don't care about it being re-used, you can make the code that uses it look prettier by hard coding the dereference and the key value into the function:

```<code>create function mytable_to_intarray(jsonb) returns int[] immutable language sql as
  $$ select array_agg((x->>'nestedId')::int) from jsonb_array_elements($1->'list') f(x) $$;

create index on mytable using gin (mytable_to_intarray(data));

SELECT data FROM mytable where mytable_to_intarray(data) @> ARRAY[3];
</code>```

Now those indexes do take longer to make than your original, but they are about half the size and are at least as fast to query.  More importantly, the planner has better statistics about the selectivity, and so in more complicated queries is likely to come up with better query plans.

Body:
I have a table with a jsonb field named "data" with the following content:

{
  customerId: 1,
  something: "..."
  list: [{ nestedId: 1, attribute: "a" }, { nestedId: 2, attribute: "b" }]
}

I need to retrieve the whole row based on its 'nestedId' attribute, note that the field is inside an array.

After checking the query plans I found out I could benefit from an index. So I added:

CREATE INDEX i1 ON mytable using gin ((data->'list') jsonb_path_ops))

From what I understood from the doc, this creates index items for the values in the "list", the solution solves my problem.

For the sake of completion follow the query I can use to retrieve my data

SELECT data FROM mytable where data->'list' @> '[{"nestedId": 1}]'

Tho, I wonder if there are more optimal indexing I could do. Is it possible to create an index only for the "nestedId" field for example?

Body:
You can index only the numeric values and not also the keys, using functional indexes.  You probably need to make a helper function to do so.

create function jsonb_objarray_to_intarray(jsonb,text) returns int[] immutable language sql as
  $$ select array_agg((x->>$2)::int) from jsonb_array_elements($1) f(x) $$;

create index on mytable using gin (jsonb_objarray_to_intarray(data->'list','nestedId'));

SELECT data FROM mytable where jsonb_objarray_to_intarray(data->'list','nestedId') @> ARRAY[3];

I wrote it this way so the function could be reused in other similar situations.  If you don't care about it being re-used, you can make the code that uses it look prettier by hard coding the dereference and the key value into the function:

create function mytable_to_intarray(jsonb) returns int[] immutable language sql as
  $$ select array_agg((x->>'nestedId')::int) from jsonb_array_elements($1->'list') f(x) $$;

create index on mytable using gin (mytable_to_intarray(data));

SELECT data FROM mytable where mytable_to_intarray(data) @> ARRAY[3];

Now those indexes do take longer to make than your original, but they are about half the size and are at least as fast to query.  More importantly, the planner has better statistics about the selectivity, and so in more complicated queries is likely to come up with better query plans.


问:
Auto Generate HTML Text inputs based on selection value
i have a selection with 3 options values . i want to auto generate html input based on selection if user select 2 it show to him two text inputs with same id for both shown.</p>

```<code><option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</code>```

答:
try this  i used jquery

https://jsfiddle.net/rkv88/grym5fqv/

```<code>On event .change() {
hide every text input;
for loop N times   N is the option number{
      show that text element  until N index
        }
}
</code>```

Body:
i have a selection with 3 options values . i want to auto generate html input based on selection if user select 2 it show to him two text inputs with same id for both shown.

<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>

Body:
try this  i used jquery

https://jsfiddle.net/rkv88/grym5fqv/

On event .change() {
hide every text input;
for loop N times   N is the option number{
      show that text element  until N index
        }
}


问:
Using npm to install or update required packages just like bundler for rubygems
I love Bundler, it's great at dependency management.  I love npm, installing node packages is easy!  I have a nodejs app and would love to be able to specify my apps dependencies and easily install / update them wherever I deploy my app. This isn't a library I'm releasing, it's a full fledged web-app.

I'm aware of the npm bundle command, but that just seems to simply override the directory where packages are installed.

I'm used to using bundler in this fashion:

```<code># Gemfile
gem "rails", "3.0.3"
</code>```

Installs rails v3.0.3 and any other required gems on the host machine only if it doesn't already exist

```<code>> bundle install
</code>```

How can I achieve something similar with npm?

答:
As of npm 1.0 (which is now what you get by default if you follow the steps in the README file), "bundle" is no longer a segregated thing -- it's just "how it works".

So:

Put a package.json file in the root of your project

List your deps in that file

```<code>{ "name" : "my-project"
, "version" : "1.0.0"
, "dependencies" : { "express" : "1.0.0" } }
</code>```

npm install  Since you're calling this with no args, and not in global mode, it'll just install all your deps locally.

require("express") and be happy.

Body:
I love Bundler, it's great at dependency management.  I love npm, installing node packages is easy!  I have a nodejs app and would love to be able to specify my apps dependencies and easily install / update them wherever I deploy my app. This isn't a library I'm releasing, it's a full fledged web-app.

I'm aware of the npm bundle command, but that just seems to simply override the directory where packages are installed.

I'm used to using bundler in this fashion:

# Gemfile
gem "rails", "3.0.3"

Installs rails v3.0.3 and any other required gems on the host machine only if it doesn't already exist

> bundle install

How can I achieve something similar with npm?

Body:
As of npm 1.0 (which is now what you get by default if you follow the steps in the README file), "bundle" is no longer a segregated thing -- it's just "how it works".

So:

Put a package.json file in the root of your project

List your deps in that file

{ "name" : "my-project"
, "version" : "1.0.0"
, "dependencies" : { "express" : "1.0.0" } }

npm install  Since you're calling this with no args, and not in global mode, it'll just install all your deps locally.

require("express") and be happy.