问:
MySQL nested SELECT query is taking too long to run
I have a MySQL query I wrote that displays the data I want it to, but it takes at least 30 secs - 1 min to run.

I researched to find out how to created the nested SELECT query with the COUNT that I needed in order to display the data I required. The SQL is also part of a web page I have, and when I go from page to page it takes the same amount of time to load. I am sure there is a more efficient way to write the query so it loads fast, as there are only about 1,500 records in the ttb_shows table and about 11k in the ttb_books table. Below is the query.

-- DDL
CREATE TABLE `ttb_books` (
  `book_id` int(11) NOT NULL,
  `book_name` varchar(255) NOT NULL DEFAULT '',
  `cover_image` varchar(255) DEFAULT NULL,
  `show_id` int(11) NOT NULL DEFAULT '0',
  `state_id` int(7) NOT NULL DEFAULT '0',
  `notes` text,
  `year` varchar(255) DEFAULT NULL,
  `publisher` varchar(255) DEFAULT NULL,
  `status_id` int(7) NOT NULL DEFAULT '0',
  `no_pages` varchar(255) DEFAULT NULL,
  `footer` text,
  `opt1` varchar(255) NOT NULL DEFAULT '$5-10',
  `opt2` varchar(255) DEFAULT NULL,
  `opt3` varchar(255) DEFAULT NULL,
  `opt4` varchar(255) DEFAULT NULL,
  `opt5` varchar(255) DEFAULT NULL,
  `owned` int(1) DEFAULT '0'
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

CREATE TABLE `ttb_shows` (
  `show_id` int(11) NOT NULL,
  `show_name` varchar(255) NOT NULL DEFAULT '',
  `date_added` datetime NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

-- QUERY
SELECT ttb_shows.show_id, ttb_shows.show_name, ttb_shows.date_added,
    COUNT(ttb_books.book_id) AS books,
    (SELECT COUNT(ttb_books.owned) AS owned FROM ttb_books WHERE (owned=1 AND ttb_books.show_id = ttb_shows.show_id))
FROM ttb_shows LEFT JOIN ttb_books ON ttb_shows.show_id = ttb_books.show_id
GROUP BY ttb_shows.show_id, ttb_shows.show_name, ttb_shows.date_added
```

Thank you to all who are able to help with this. It is really appreciated!

答:
You could avoid the subquery for owner using sum based on case  </p>

```<code>SELECT ttb_shows.show_id
  , ttb_shows.show_name
  , ttb_shows.date_added
  , COUNT(ttb_books.book_id) AS books
  , sum( case when  ttb_books.owned = 1 then 1 else  0 end) AS owned

FROM ttb_shows
LEFT JOIN ttb_books ON ttb_shows.show_id = ttb_books.show_id
GROUP BY ttb_shows.show_id, ttb_shows.show_name, ttb_shows.date_added
</code>```

Body:
I have a MySQL query I wrote that displays the data I want it to, but it takes at least 30 secs - 1 min to run.

I researched to find out how to created the nested SELECT query with the COUNT that I needed in order to display the data I required. The SQL is also part of a web page I have, and when I go from page to page it takes the same amount of time to load. I am sure there is a more efficient way to write the query so it loads fast, as there are only about 1,500 records in the ttb_shows table and about 11k in the ttb_books table. Below is the query.

-- DDL
CREATE TABLE `ttb_books` (
  `book_id` int(11) NOT NULL,
  `book_name` varchar(255) NOT NULL DEFAULT '',
  `cover_image` varchar(255) DEFAULT NULL,
  `show_id` int(11) NOT NULL DEFAULT '0',
  `state_id` int(7) NOT NULL DEFAULT '0',
  `notes` text,
  `year` varchar(255) DEFAULT NULL,
  `publisher` varchar(255) DEFAULT NULL,
  `status_id` int(7) NOT NULL DEFAULT '0',
  `no_pages` varchar(255) DEFAULT NULL,
  `footer` text,
  `opt1` varchar(255) NOT NULL DEFAULT '$5-10',
  `opt2` varchar(255) DEFAULT NULL,
  `opt3` varchar(255) DEFAULT NULL,
  `opt4` varchar(255) DEFAULT NULL,
  `opt5` varchar(255) DEFAULT NULL,
  `owned` int(1) DEFAULT '0'
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

CREATE TABLE `ttb_shows` (
  `show_id` int(11) NOT NULL,
  `show_name` varchar(255) NOT NULL DEFAULT '',
  `date_added` datetime NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

-- QUERY
SELECT ttb_shows.show_id, ttb_shows.show_name, ttb_shows.date_added,
    COUNT(ttb_books.book_id) AS books,
    (SELECT COUNT(ttb_books.owned) AS owned FROM ttb_books WHERE (owned=1 AND ttb_books.show_id = ttb_shows.show_id))
FROM ttb_shows LEFT JOIN ttb_books ON ttb_shows.show_id = ttb_books.show_id
GROUP BY ttb_shows.show_id, ttb_shows.show_name, ttb_shows.date_added

Thank you to all who are able to help with this. It is really appreciated!

Body:
You could avoid the subquery for owner using sum based on case

SELECT ttb_shows.show_id
  , ttb_shows.show_name
  , ttb_shows.date_added
  , COUNT(ttb_books.book_id) AS books
  , sum( case when  ttb_books.owned = 1 then 1 else  0 end) AS owned

FROM ttb_shows
LEFT JOIN ttb_books ON ttb_shows.show_id = ttb_books.show_id
GROUP BY ttb_shows.show_id, ttb_shows.show_name, ttb_shows.date_added


来源: stackexchange

问:
MicroEJ UART and other GPIO interrupt with STM32F746G-DISCO
I need to know how to use UART interrupt in MicroEJ(when data receive ,do my job) .
I dont want use a thread with while(true) (forever loop) to read input stream.
we have these functions in C

```<code>LLCOMM_UART_callback and LLCOMM_BUFFERED_CONNECTION_dataReceived

//main uart interrupt

void USART6_IRQHandler(void)
{
    LLCOMM_UART_callback(&LLCOMM_UARTs[UART6_INDEX]);
}
/* Interrupt callback --------------------------------------------------------*/
void LLCOMM_UART_callback(LLCOMM_UART* llcomm)
{
    // retrieve LLCOM environment for given comIndex
    LLCOMM_BUFFERED_CONNECTION* env = &llcomm->header;
    UART_HandleTypeDef* handle = &llcomm->hal_uart_handle;

    uint8_t leave = interrupt_enter();

    // check RX
    if (__HAL_UART_GET_IT(handle, UART_IT_RXNE))
    {
        // read data, clear the interrupt and send data to MicroEJ framework
        LLCOMM_BUFFERED_CONNECTION_dataReceived(env, handle->Instance->RDR);
    }
}
</code>```

but i cant find how to implement these interface to java ?

the 2nd part is how to use input pins interrupt and interface them to java? is there any API for this??

Thanks

答:
Implementing the LLCOM_UART native interface will allow you to use ECOM COMM in Java.

The UART interrupt is handled by the underlying BSP (in C) caching the data received in a buffer until the Java thread is awake to get back the data of the read. So there is no choice between an interrupt handling or a "loop forever", it is:

interrupt handling in C, data read then cached into a buffer

Java thread periodically waking up and checking if there is data in the buffer

Pins configuration and interrupts handling for UART are not done in Java but in C at the BSP level, using the UART in Java only as a Java stream.

You can find an example of use of the Java comm connectors in our GitHub [1].

As for implementing the LL_UART C side you can take a look at how it was done for an existing platform [2]. Inside the archive you will find an implementation of BSP for STM32F7476G-DISCO, this BSP contains a LL_UART implementation (in platformSource\STM32F746GDISCO-846SI-platformSource.zip\STM32F746GDISCO-846SI-3.1.5-bsp\Projects\STM32746G-Discovery\Applications\MicroEJ\src-comm).

For GPIOs a HAL library exists [3].

Gaëtan

[1] https://github.com/MicroEJ/Example-Standalone-Foundation-Libraries/tree/master/com.microej.example.foundation.ecom.reader

[2] http://developer.microej.com/packages/referenceimplementations/846SI/3.1.5/STM32F746GDISCO-846SI-fullPackaging-eval-3.1.5.zip

[3] https://developer.microej.com/javadoc/microej_4.1/foundation/ej/hal/gpio/package-summary.html

ContentLicense: CC BY-SA 4.0

Body:
I need to know how to use UART interrupt in MicroEJ(when data receive ,do my job) .
I dont want use a thread with while(true) (forever loop) to read input stream.
we have these functions in C

LLCOMM_UART_callback and LLCOMM_BUFFERED_CONNECTION_dataReceived

//main uart interrupt

void USART6_IRQHandler(void)
{
    LLCOMM_UART_callback(&LLCOMM_UARTs[UART6_INDEX]);
}
/* Interrupt callback --------------------------------------------------------*/
void LLCOMM_UART_callback(LLCOMM_UART* llcomm)
{
    // retrieve LLCOM environment for given comIndex
    LLCOMM_BUFFERED_CONNECTION* env = &llcomm->header;
    UART_HandleTypeDef* handle = &llcomm->hal_uart_handle;

    uint8_t leave = interrupt_enter();

    // check RX
    if (__HAL_UART_GET_IT(handle, UART_IT_RXNE))
    {
        // read data, clear the interrupt and send data to MicroEJ framework
        LLCOMM_BUFFERED_CONNECTION_dataReceived(env, handle->Instance->RDR);
    }
}

but i cant find how to implement these interface to java ?

the 2nd part is how to use input pins interrupt and interface them to java? is there any API for this??

Thanks


问:
How can I initialise an RGBA cv::Mat from a byte array?
I'm sending images over the network (from Python) and want to create OpenCV Mats from them on the receiving end (in C++).

They are created like this:

```<code>image = self.camera.capture_image()   # np.array of dtype np.uint8
h, w, c = image.shape   # 4 channels
image = np.transpose(image, (2, 0, 1)) # transpose because channels come first in OpenCV (?)
image = np.ascontiguousarray(image, dtype='>B')  # big-endian bytes
bytess = image.tobytes(order='C')
</code>```

After this, I should have an array where the 3 dimensions are flattened such that individual rows are appended together for each channel and then the channels are appended to form the final byte buffer. I have verified that my understanding is correct and the following holds

```<code>bytess[channel*height*width + i*wwidth + j] == image[channel, i, j]
</code>```

[I think the above part is actually unimportant, because if it's incorrect, I will get an incorrectly displayed image, but at least I would have an image, which is one step further than I am now.]

Now on the other side I am trying to do this:

```<code>char* pixel_data = … // retrieve array of bytes from message
// assume height, width and channels are known
const int sizes[3] = {channels, width, height};
const size_t steps[3] = {(size_t)height * (size_t)width, (size_t)height};
cv::Mat image(3, sizes, CV_8UC1, pixel_data, steps);
</code>```

So, I create a Matrix with three dimensions where the element type is byte. I am not so sure I'm determining the steps correctly, but I think it matches the documentation.

But running this just crashes with

```<code>error: (-5:Bad argument) Unknown array type in function 'cvarrToMat'
</code>```

What is the correct way to serialise an RGBA (or BGRA for OpenCV) image to  a byte buffer and create a cv::Mat from it with the C++ API?

答:
I have one solution, which circumvents the problem. This line here:

```<code>cv::Mat image(3, sizes, CV_8UC1, pixel_data, steps);
</code>```

makes the assumption that I can pass sizes of three dimensions with individual bytes, but I could not make this work.

Instead using a different constructor

```<code>cv::Mat image(height, width CV_8UC4, pixel_data);
</code>```

I can treat the image as two-dimensional but with a vector-datatype (4 bytes element size instead of scalar bytes). If the pixel_data pointer is in the correct layout, this works.

The correct layout is not really explicitly documented, but can be deduced from one of the official tutorials

So the data is stored such that one row comes after the other and each element of a row is split into n_channels elements. Using a data type such as CV_8UC4 makes the matrix read 4 bytes at each position in the raw data array, and advance the pointer 4 bytes.

So in this case, I just have to rearrange the numpy array into the appropriate sequence: append rows together, but interleave the channels. I did this like so, but I hope there's a way without looping.

```<code>def array_to_cv_bytes(ary):
    assert ary.ndim == 3, 'Array must have 3 dimensions'
    h, w, c = ary.shape
    ary = ary[..., (2, 1, 0, 3)]
    output = np.empty(h * c * w, dtype=np.uint8)
    for channeld_idx in range(c):
        output[channeld_idx::c] = ary[..., channeld_idx].reshape(h*w)
    return output.tobytes(order='C')
</code>```

Body:
I'm sending images over the network (from Python) and want to create OpenCV Mats from them on the receiving end (in C++).

They are created like this:

image = self.camera.capture_image()   # np.array of dtype np.uint8
h, w, c = image.shape   # 4 channels
image = np.transpose(image, (2, 0, 1)) # transpose because channels come first in OpenCV (?)
image = np.ascontiguousarray(image, dtype='>B')  # big-endian bytes
bytess = image.tobytes(order='C')

After this, I should have an array where the 3 dimensions are flattened such that individual rows are appended together for each channel and then the channels are appended to form the final byte buffer. I have verified that my understanding is correct and the following holds

bytess[channel*height*width + i*wwidth + j] == image[channel, i, j]

[I think the above part is actually unimportant, because if it's incorrect, I will get an incorrectly displayed image, but at least I would have an image, which is one step further than I am now.]

Now on the other side I am trying to do this:

char* pixel_data = … // retrieve array of bytes from message
// assume height, width and channels are known
const int sizes[3] = {channels, width, height};
const size_t steps[3] = {(size_t)height * (size_t)width, (size_t)height};
cv::Mat image(3, sizes, CV_8UC1, pixel_data, steps);

So, I create a Matrix with three dimensions where the element type is byte. I am not so sure I'm determining the steps correctly, but I think it matches the documentation.

But running this just crashes with

error: (-5:Bad argument) Unknown array type in function 'cvarrToMat'

What is the correct way to serialise an RGBA (or BGRA for OpenCV) image to  a byte buffer and create a cv::Mat from it with the C++ API?

Body:
I have one solution, which circumvents the problem. This line here:

cv::Mat image(3, sizes, CV_8UC1, pixel_data, steps);

makes the assumption that I can pass sizes of three dimensions with individual bytes, but I could not make this work.

Instead using a different constructor

cv::Mat image(height, width CV_8UC4, pixel_data);

I can treat the image as two-dimensional but with a vector-datatype (4 bytes element size instead of scalar bytes). If the pixel_data pointer is in the correct layout, this works.

The correct layout is not really explicitly documented, but can be deduced from one of the official tutorials

So the data is stored such that one row comes after the other and each element of a row is split into n_channels elements. Using a data type such as CV_8UC4 makes the matrix read 4 bytes at each position in the raw data array, and advance the pointer 4 bytes.

So in this case, I just have to rearrange the numpy array into the appropriate sequence: append rows together, but interleave the channels. I did this like so, but I hope there's a way without looping.

def array_to_cv_bytes(ary):
    assert ary.ndim == 3, 'Array must have 3 dimensions'
    h, w, c = ary.shape
    ary = ary[..., (2, 1, 0, 3)]
    output = np.empty(h * c * w, dtype=np.uint8)
    for channeld_idx in range(c):
        output[channeld_idx::c] = ary[..., channeld_idx].reshape(h*w)
    return output.tobytes(order='C')


问:
Rewrite by lua : Match host
I have this lua script that redirect the user based on his browser laungage.

```<code>location = / {
    rewrite_by_lua '
        for lang in (ngx.var.http_accept_language .. ","):gmatch("([^,]*),") do
            if string.sub(lang, 0, 2) == "en" then
                ngx.redirect("/en/index.html")
            end
            if string.sub(lang, 0, 2) == "nl" then
                ngx.redirect("/nl/index.html")
            end
            if string.sub(lang, 0, 2) == "de" then
                ngx.redirect("/de/index.html")
            end
        end
        ngx.redirect("/en/index.html")
    ';
}
</code>```

I only want to match url that ends with mysite.org
Any idea how I can add the criteria?

the result sould be something like this:

```<code>if string.sub(lang, 0, 2) == "nl" and host == "mysite.org" then
                    ngx.redirect("/nl")
                end
</code>```

答:
Without having full details of your exact input, I think the below should work:

```<code>location = / {
    rewrite_by_lua '
        for lang in (ngx.var.http_accept_language .. ","):gmatch("([^,]*),") do
          lang = lang:sub(1, 2)
          if host:match("mysite%.org$") then
            if lang == "en" then ngx.redirect("/en/index.html")
            elseif lang == "nl" then ngx.redirect("/nl/index.html")
            elseif lang == "de" then ngx.redirect("/de/index.html")
            end
          end
        end
        ngx.redirect("/en/index.html")
    ';
}
</code>```

Also note the use of elseif to make code shorter.  On another note, explicit checking for 'en' language could be omitted as it is the default fall-through case.

Title: Rewrite by lua : Match host

Body:
I have this lua script that redirect the user based on his browser laungage.

location = / {
    rewrite_by_lua '
        for lang in (ngx.var.http_accept_language .. ","):gmatch("([^,]*),") do
            if string.sub(lang, 0, 2) == "en" then
                ngx.redirect("/en/index.html")
            end
            if string.sub(lang, 0, 2) == "nl" then
                ngx.redirect("/nl/index.html")
            end
            if string.sub(lang, 0, 2) == "de" then
                ngx.redirect("/de/index.html")
            end
        end
        ngx.redirect("/en/index.html")
    ';
}

I only want to match url that ends with mysite.org
Any idea how I can add the criteria?

the result sould be something like this:

if string.sub(lang, 0, 2) == "nl" and host == "mysite.org" then
                    ngx.redirect("/nl")
                end

Body:
Without having full details of your exact input, I think the below should work:

location = / {
    rewrite_by_lua '
        for lang in (ngx.var.http_accept_language .. ","):gmatch("([^,]*),") do
          lang = lang:sub(1, 2)
          if host:match("mysite%.org$") then
            if lang == "en" then ngx.redirect("/en/index.html")
            elseif lang == "nl" then ngx.redirect("/nl/index.html")
            elseif lang == "de" then ngx.redirect("/de/index.html")
            end
          end
        end
        ngx.redirect("/en/index.html")
    ';
}

Also note the use of elseif to make code shorter.  On another note, explicit checking for 'en' language could be omitted as it is the default fall-through case.


问:
React not reordering array of components on render
I am trying to render a list of components in order with react, the component is updating this array of elements but is not re-ordering them.

Pseudo code;

```<code>class Form extends Component {
  //
  // .... other initialization code and logic
  //

  updatePositions() {
    //
    // re-order this.state.page.page_contents
    //
    this.setState({ page: this.state.page });
  }

  renderContents() {
    return this.state.page.page_content.map((c, i) => {
      return (<ContentItem
        key={ i }
        content={ c }
      />);
    });
  }

  render() {
    return (
      <div className="row">
        <div className="medium-12 columns">
          { this.renderContents() }
        </div>
      </div>
    );
  }
}
</code>```

If i log out the results of page.page_content the items are being reordered in the array, however the form render is not re-rendering the contents in its new order

答:
```<code>renderContents() {
    return this.state.page.page_content.map((c, i) => {
      return (<ContentItem
        key={ i }
        content={ c }
      />);
    });
  }
</code>```

it's your code here - key={i} i is not changing so it will not re-render the component - if you want to re-render the component - please make sure that - key should change.

```<code>renderContents() {
    return this.state.page.page_content.map(c => {
      return (<ContentItem
        key={ c }
        content={ c }
      />);
    });
  }
</code>```

c is content - if it's change then Component will re-render

this.setState({ page: this.state.page }) it's wrong - ur trying to set the same value in same variable again .

```<code>class Form extends Component {
  //
  // .... other initialization code and logic
  //

  updatePositions() {
    //
    // re-order this.state.page.page_contents
    //
    this.setState({ page: newValueFromAPI.page });
  }

  render() {
    const { page: { page_content } } = this.state
    return (
      <div className="row">
        <div className="medium-12 columns">
          { page_content.length > 0 && (
             page_content.map(c => <ContentItem key={c} content={c}/>)
          )}
        </div>
      </div>
    );
  }
}
</code>```

Body:
I am trying to render a list of components in order with react, the component is updating this array of elements but is not re-ordering them.

Pseudo code;

class Form extends Component {
  //
  // .... other initialization code and logic
  //

  updatePositions() {
    //
    // re-order this.state.page.page_contents
    //
    this.setState({ page: this.state.page });
  }

  renderContents() {
    return this.state.page.page_content.map((c, i) => {
      return (<ContentItem
        key={ i }
        content={ c }
      />);
    });
  }

  render() {
    return (

          { this.renderContents() }

    );
  }
}

If i log out the results of page.page_content the items are being reordered in the array, however the form render is not re-rendering the contents in its new order

Body:
renderContents() {
    return this.state.page.page_content.map((c, i) => {
      return (<ContentItem
        key={ i }
        content={ c }
      />);
    });
  }

it's your code here - key={i} i is not changing so it will not re-render the component - if you want to re-render the component - please make sure that - key should change.

renderContents() {
    return this.state.page.page_content.map(c => {
      return (<ContentItem
        key={ c }
        content={ c }
      />);
    });
  }

c is content - if it's change then Component will re-render

this.setState({ page: this.state.page }) it's wrong - ur trying to set the same value in same variable again .

class Form extends Component {
  //
  // .... other initialization code and logic
  //

  updatePositions() {
    //
    // re-order this.state.page.page_contents
    //
    this.setState({ page: newValueFromAPI.page });
  }

  render() {
    const { page: { page_content } } = this.state
    return (
      <div className="row">
        <div className="medium-12 columns">
          { page_content.length > 0 && (
             page_content.map(c => <ContentItem key={c} content={c}/>)
          )}
        </div>
      </div>
    );
  }
}


问:
How to ask user input from flask (I'm using react for front end)?
I already got some input into the flask from the forms using the fetch API POST method. Now depending on this input, I want to ask some more inputs (without rendering a new HTML page.) and process them again, so that I can finally return a string as the fetch response.

答: you should use JS on client side to handling user's first input to make next form/fields for him</p>


问:
OAuth client credentials (key + secret) needed in a desktop app even with valid token credentials
I was under the impression that once the authorization process is done, the access token and secret (token credentials) are all that is needed to use the target resource. According to this quote [in some cases, the client credentials cannot be trusted and can only be used for informational purposes only, such as in desktop application clients] this may not be the case. I am running into a problem that even after authorization consumer key and secret (client credentials) are still needed in order to access the resource. This does not seem right.

I have implemented OAuth in my desktop application looking up to the DotNetOpenAuth samples. I have basically used an unchanged InMemoryTokenManager and a DesktopConsumer and all works perfectly once authorized. When I restart the app and reuse the saved token credentials, the app fails to access the resource. If I used the saved token credentials + the client credentials, the resource is accessed alright. Is this by design? Sounds incorrect but I am no expert.

答: This is correct.  Per the OAuth 1.0 spec, the client credentials are required every time you use the access token.  This protects a leaked access token from being exploited by another client.  This reasoning primarily assumes the client secret is in fact a secret, which as you point out cannot be assumed for a desktop app.  Nevertheless, you can have a "secret" that isn't a secret, and maintain it across launches of your app, just to keep everything ticking along.</p>

ContentLicense: CC BY-SA 3.0


问:
unable to show doc file using google docs api with iframe
I want to show doc file on a browser. I am using Google Docs API with iframe. But it shows me error that google docs refused to connect. I want to get rid of this error kindly help me out..

Here is my code in php, $file is a variable where I am getting the file name and I have to concat it with my iframe..

```<code>   echo '<iframe src="http://docs.google.com/gview?url=http://192.168.0.56/orangehrm/admin/images/"'.$file.'&embedded=true" style="width:600px; height:500px;" frameborder="0"></iframe>';
</code>```

答:
Based from this blogpost - Embedding a Google Doc:

Google provides an iFrame to embed your Google Docs. By default, WordPress will strip out iFrame code for security reasons. The iFrame code will disappear when switching between Visual and Text mode or when Publishing. To prevent this, you will need to change the provided iFrame code.

For example:

Try to change:

to:

Body:
I want to show doc file on a browser. I am using Google Docs API with iframe. But it shows me error that google docs refused to connect. I want to get rid of this error kindly help me out..

Here is my code in php, $file is a variable where I am getting the file name and I have to concat it with my iframe..

   echo '';


问:
Java8 streams with Map?
I have the following Map (each key is a String and each value is a List<Message>)

My map is like this :

```<code>1st entry :"MONDAY" -> [message1, message2, message3]
2nd entry : "TUESDAY" -> [message4, message5]
...
</code>```

My goal is to change each message content :

I was thinking about this :

```<code>map.entrySet().stream().peek(entry -> {
    entry.getValue().stream().peek(m -> m.setMessage(changeMessage()))
})
</code>```

But don't know how to finish and do it properly.

答:
Iterate map, change each element of list again put the collected list on the same key of the map.    </p>

```<code>map.forEach((k,v)->{
                map.put(k, v.stream().map(i->i+"-changed").collect(Collectors.toList()));

            });
</code>```

Title: Java8 streams with Map?

Body:
I have the following Map (each key is a String and each value is a List<Message>)

My map is like this :

1st entry :"MONDAY" -> [message1, message2, message3]
2nd entry : "TUESDAY" -> [message4, message5]
...

My goal is to change each message content :

I was thinking about this :

map.entrySet().stream().peek(entry -> {
    entry.getValue().stream().peek(m -> m.setMessage(changeMessage()))
})

But don't know how to finish and do it properly.

Body:
Iterate map, change each element of list again put the collected list on the same key of the map.

map.forEach((k,v)->{
                map.put(k, v.stream().map(i->i+"-changed").collect(Collectors.toList()));

            });


问:
How to create a dictionary from an other dictionary?
I have a dictionary where I have a key with more than one value, I want to create a new dictionary with the same key but the value is the length of the previous

I have:

```<code>dict = {'key1': ['value1'], ['value2'], ['value3'], {'key2': ['value4'], ['value5']}
</code>```

I want:

```<code>dict_bis = {'key1': '3', 'key2': '2'}
</code>```

答:
Just use a for loop and dict.items() to loop over the existing dict, and len() to find the length of the values:

```<code>dict_bis = {}
for key, values in dict.items():
    dict_bis[key] = len(values)
</code>```

Or the same using a dict comprehension:

```<code>dict_bis = {key: len(values) for key, values in dict.items()}
</code>```

Body:
I have a dictionary where I have a key with more than one value, I want to create a new dictionary with the same key but the value is the length of the previous

I have:

dict = {'key1': ['value1'], ['value2'], ['value3'], {'key2': ['value4'], ['value5']}

I want:

dict_bis = {'key1': '3', 'key2': '2'}

Body:
Just use a for loop and dict.items() to loop over the existing dict, and len() to find the length of the values:

dict_bis = {}
for key, values in dict.items():
    dict_bis[key] = len(values)

Or the same using a dict comprehension:

dict_bis = {key: len(values) for key, values in dict.items()}


答: Your query can be optimized by you only. It seems that so many left outer will obviously slow the output. If you can either avoid so many left outers or make small chunks of cases to fetch out data and then fetch the Final output.</p>

Title: MySQL nested SELECT query is taking too long to run


问:
Get all visible columns
I'm struggling with angular ui grid.

Digging into their API I'm trying to find a way is it possible to get visible columns ( only visible ).

```<code>$scope.gridOptions.columnDefs
</code>```

returns all columns that are defined with all options. One solution will be that I iterate trough that array and filter out columns which have property "visible" : true, but I want to avoid that if it is possible.

Thanks in advance

答:
To get all visible columns:

```<code>options.columnApi.getAllDisplayedColumns()
</code>```

ag grid columnApi Reference

Title: Get all visible columns

Body:
I'm struggling with angular ui grid.

Digging into their API I'm trying to find a way is it possible to get visible columns ( only visible ).

$scope.gridOptions.columnDefs

returns all columns that are defined with all options. One solution will be that I iterate trough that array and filter out columns which have property "visible" : true, but I want to avoid that if it is possible.

Thanks in advance

Body:
To get all visible columns:

options.columnApi.getAllDisplayedColumns()

ag grid columnApi Reference


问:
Having problem in accessing values from state when traversing an array
i'm trying to traverse an Array and perform some operation. But cann't access the values as i want to.

```<code>inputObj.map(el => {
    const msg = this.state.validation[el.id].message;
    const msg2 = this.state.validation['name'].message;
})
</code>```

Here, el.id can be name, dob or address. When i use this.state.validation[el.id].message;, it shows TypeError: Cannot read property 'message' of undefined. But if i hardcode it like this.state.validation['name'].message;, it works fine. when comparing both el.id and 'name', they have same datatype and same value. So, why having problem when using el.id instead of hardcoding it.

NB: i'm using reactjs.

Edit:

this.state:

```<code>this.state = {
    super(props);
    this.validator = new FormValidator([
        {
            field: 'name',
            method: 'isEmpty',
            validWhen: false,
            message: 'Name is required'
        },
        ...
    ]);

    orderForm: {
        name: {
             elementType: 'input',
             elementConfig: ''
        },
        ...
    }

    validation: this.validator.setValid() // it will be the updated upon submitting form on submitHandler by calling validate() from FormValidator
}
</code>```

inputObj:

```<code>   const inputObj= [];
   for(let key in this.state.orderForm){
       inputObj.push({
           id : key,
           config: this.state.orderForm[key]
       });
   }
</code>```

FormValidator

```<code>import validator from 'validator';

class FormValidator {
    constructor(rules){
        this.rules = rules;
    }

    setValid(){
        const validation = {};
        this.rules.map(rule => (
            validation[rule.field] = {isValid: true, message: ''}
        ));
        return {isValid: true, ...validation};
    }

    validate(form){
        let validation = this.setValid();
        this.rules.forEach( rule => {
            if (validation[rule.field].isValid){
                const field = form[rule.field].toString();
                const args = rule.args || [];
                const validationMethod = typeof rule.method === 'string' ?
                    validator[rule.method] : rule.method;

                if (validationMethod(field, ...args, form) !== rule.validWhen){
                    validation[rule.field] = {isValid: false, message: rule.message};
                    validation.isValid = false;
                }
            }
        });
        return validation;
    }
}

export default FormValidator;
</code>```

答:
You can check if this.state.validation[el.id] is defined before getting message key.

Like that you can't get fatal error.

```<code>inputObj.map(el => {
  this.state.validation[el.id] && (
    const msg = this.state.validation[el.id].message
  );
})
</code>```

Body:
i'm trying to traverse an Array and perform some operation. But cann't access the values as i want to.

inputObj.map(el => {
    const msg = this.state.validation[el.id].message;
    const msg2 = this.state.validation['name'].message;
})

Here, el.id can be name, dob or address. When i use this.state.validation[el.id].message;, it shows TypeError: Cannot read property 'message' of undefined. But if i hardcode it like this.state.validation['name'].message;, it works fine. when comparing both el.id and 'name', they have same datatype and same value. So, why having problem when using el.id instead of hardcoding it.

NB: i'm using reactjs.

Edit:

this.state:

this.state = {
    super(props);
    this.validator = new FormValidator([
        {
            field: 'name',
            method: 'isEmpty',
            validWhen: false,
            message: 'Name is required'
        },
        ...
    ]);

    orderForm: {
        name: {
             elementType: 'input',
             elementConfig: ''
        },
        ...
    }

    validation: this.validator.setValid() // it will be the updated upon submitting form on submitHandler by calling validate() from FormValidator
}

inputObj:

   const inputObj= [];
   for(let key in this.state.orderForm){
       inputObj.push({
           id : key,
           config: this.state.orderForm[key]
       });
   }

FormValidator

import validator from 'validator';

class FormValidator {
    constructor(rules){
        this.rules = rules;
    }

    setValid(){
        const validation = {};
        this.rules.map(rule => (
            validation[rule.field] = {isValid: true, message: ''}
        ));
        return {isValid: true, ...validation};
    }

    validate(form){
        let validation = this.setValid();
        this.rules.forEach( rule => {
            if (validation[rule.field].isValid){
                const field = form[rule.field].toString();
                const args = rule.args || [];
                const validationMethod = typeof rule.method === 'string' ?
                    validator[rule.method] : rule.method;

                if (validationMethod(field, ...args, form) !== rule.validWhen){
                    validation[rule.field] = {isValid: false, message: rule.message};
                    validation.isValid = false;
                }
            }
        });
        return validation;
    }
}

export default FormValidator;

Body:
You can check if this.state.validation[el.id] is defined before getting message key.

Like that you can't get fatal error.

inputObj.map(el => {
  this.state.validation[el.id] && (
    const msg = this.state.validation[el.id].message
  );
})


问:
Application is unable to get command argument
I'm unable to get command line argument with int main(int argc, char* argv[]), No errors occurs but when further manipulation want to happen i see that argv[ ] and other related variables dont have any value and says Error reading characters of string then an Acces violation reading location error happens.

This is the sample code of my issue, I had to downsize it to make it readable:

```<code>#include "CommonHeaders.h"

void Start(char *input)
{
  lstrcpyA(host, input);
  // In this point i see in my Debugger "Locals/Autos" that nothing
  // is passed to function then a "Access violation ... " happens.
  // ...
}

int main(int argc, char *argv[])
{
  Start(argv[1]);
  return 0;
}
</code>```

I always use this int main(int argc, char* argv[]) and pass command arg with ProjectProperties->Debugging->Command Argument and works perfect everytime. Is it possible that proper headers aren't included or any changes in project configuration could make a conflict?

答: Be sure to set the subsystem to console Linker -> SubSytem -> Console (/SUBSYSTEM:CONSOLE) and dont set an Entry point set the Whole Program Optimization to No Whole Program Optimization and turn SDL check to off.

Body:
I'm unable to get command line argument with int main(int argc, char* argv[]), No errors occurs but when further manipulation want to happen i see that argv[ ] and other related variables dont have any value and says Error reading characters of string then an Acces violation reading location error happens.

This is the sample code of my issue, I had to downsize it to make it readable:

#include "CommonHeaders.h"

void Start(char *input)
{
  lstrcpyA(host, input);
  // In this point i see in my Debugger "Locals/Autos" that nothing
  // is passed to function then a "Access violation ... " happens.
  // ...
}

int main(int argc, char *argv[])
{
  Start(argv[1]);
  return 0;
}

I always use this int main(int argc, char* argv[]) and pass command arg with ProjectProperties->Debugging->Command Argument and works perfect everytime. Is it possible that proper headers aren't included or any changes in project configuration could make a conflict?


问:
Npm removing extraneous packages
If I run npm ls at the top level of my project, I get a number of extraneous errors. I tried running npm prune but when I run npm ls again the packages are still there.

How do I remove those extraneous packages?

I have package-lock file and I'm running npm 6.4.1.

答:
First, did you do a npm i to be sure to install all the packages? You can also delete your node_modules folder and your package-lock.json file to have a clean install.

Then if you want to remove packages, you need to npm uninstall them or manually remove them from your package.json file, then re-do a npm i.

Title: Npm removing extraneous packages


问:
React sharing components
I have two projects which will need to share components: headers, footers some inputs etc.
Those which will need to be shared are moved into a separate repo. All fine thus far.
In the common repo I currently have set-up webpack which builds and exports them, works like a charm.

Have one question though - could it be possible to export not-compiled react components?

答:
(Disclaimer - I am a maintainer of Bit)

You can use Bit to sync the source of components between different projects. It does not force you to maintain a separate repo for the shared code.
You can compile each component separately or have the consuming project build the imported components.

Title: React sharing components


问:
How do you set a DateTimePicker to be read only?
I have a DateTimePicker (nullable version) that I need to be read only.  I'm not happy with the display if it is disabled, so wanted to know if anyone had a nifty example of how to stop updates on the field?

Thanks.

答: dateTimePicker2.Enabled = false;

OwnerDisplayName: ck

ContentLicense: CC BY-SA 2.5

Body: dateTimePicker2.Enabled = false;


问:
How to fix several database contexts in asp scope
I have a hosted service which uses a DB context, and a scoped service that also uses a DB context. It looks more or less like this

```<code>public class HostedWorker : BackgroundService
{
    private readonly IServiceScopeFactory scopeFactory;

    public HostedWorker(IServiceScopeFactory scopeFactory)
    {
        this.scopeFactory = scopeFactory;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using (var scope = scopeFactory.CreateScope())
        {
            var database = scope.ServiceProvider
                .GetRequiredService<DatabaseContext>();
            var entity = database.GetSomeEntity();
            scope.ServiceProvider
                .GetRequiredService<ISomeScopedService>()
                .DoSomethingWithTheEntity(entity)
        }
    }
}

public class SomeScopedService: ISomeScopedService
{
    private readonly DatabaseContext context;

    public SomeScopedService(DatabaseContext context)
    {
        this.context = context;
    }

    public void DoSomethingWithTheEntity(SomeEntity entity)
    {
        // the context doesn't track the entity
    }
}
</code>```

The scoped service gets the database context from the dependency injection, and it turns out, it's not the same context as I get directly from the ServiceProvider. The result is, the DB context from the scoped service doesn't track the entities which I get from the context in the hosted service.

In all the other cases the context is the same: several scoped services which get the database through DI all share the same context, as well as when I pass the manually-created scope between singleton services, all of them get the same context through GetRequiredService. Only when I try to mix I get this result.

Is there any way to get the same DB context throughout the scope?

UPD The error ended up being unrelated to the DB context (which is indeed the same for different services in the scope), but I will leave the question here, since the answer may be helpful for some other cases.

答:
it's not the same context as I get directly from the ServiceProvider

First of all, you should never retrieve a database context directly from the service provider. You always should get it within a service scope, otherwise you will end up with a database context and a connection that won’t be disposed for the lifetime of your application.

So you should always consume database contexts within service scopes. This is done implicitly within the request pipeline (e.g. in controllers) but in hosted services, you will have to create the service scope yourself. You should also make sure that you don’t keep that scope open for a long period of time; it’s better to design your services so that they only access the database for a very limited amount of time and have multiple short-living service scopes instead of one long-living scope.

```<code>using (var scope = scopeFactory.CreateScope())
{
    var database = scope.ServiceProvider.GetRequiredService<DatabaseContext>();
    var entity = database.GetSomeEntity();
    scope.ServiceProvider.GetRequiredService<ISomeScopedService>()
        .DoSomethingWithTheEntity(entity)
}
</code>```

Assuming that ISomeScopedService is properly registered as a scoped dependency, this code should resolve the same database context instance. Database contexts are registered as scoped dependencies (by default) and thus this should resolve the same instance from both the scoped service provider and the constructor injection in your scoped service.

If this does not work for you, then your actual code probably looks different, uses different scopes (or no scopes), or the logic behind GetSomeEntity() retrieves a non-tracking entity.

Body:
I have a hosted service which uses a DB context, and a scoped service that also uses a DB context. It looks more or less like this

public class HostedWorker : BackgroundService
{
    private readonly IServiceScopeFactory scopeFactory;

    public HostedWorker(IServiceScopeFactory scopeFactory)
    {
        this.scopeFactory = scopeFactory;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using (var scope = scopeFactory.CreateScope())
        {
            var database = scope.ServiceProvider
                .GetRequiredService<DatabaseContext>();
            var entity = database.GetSomeEntity();
            scope.ServiceProvider
                .GetRequiredService<ISomeScopedService>()
                .DoSomethingWithTheEntity(entity)
        }
    }
}

public class SomeScopedService: ISomeScopedService
{
    private readonly DatabaseContext context;

    public SomeScopedService(DatabaseContext context)
    {
        this.context = context;
    }

    public void DoSomethingWithTheEntity(SomeEntity entity)
    {
        // the context doesn't track the entity
    }
}

The scoped service gets the database context from the dependency injection, and it turns out, it's not the same context as I get directly from the ServiceProvider. The result is, the DB context from the scoped service doesn't track the entities which I get from the context in the hosted service.

In all the other cases the context is the same: several scoped services which get the database through DI all share the same context, as well as when I pass the manually-created scope between singleton services, all of them get the same context through GetRequiredService. Only when I try to mix I get this result.

Is there any way to get the same DB context throughout the scope?

UPD The error ended up being unrelated to the DB context (which is indeed the same for different services in the scope), but I will leave the question here, since the answer may be helpful for some other cases.

Body:
it's not the same context as I get directly from the ServiceProvider

First of all, you should never retrieve a database context directly from the service provider. You always should get it within a service scope, otherwise you will end up with a database context and a connection that won’t be disposed for the lifetime of your application.

So you should always consume database contexts within service scopes. This is done implicitly within the request pipeline (e.g. in controllers) but in hosted services, you will have to create the service scope yourself. You should also make sure that you don’t keep that scope open for a long period of time; it’s better to design your services so that they only access the database for a very limited amount of time and have multiple short-living service scopes instead of one long-living scope.

using (var scope = scopeFactory.CreateScope())
{
    var database = scope.ServiceProvider.GetRequiredService<DatabaseContext>();
    var entity = database.GetSomeEntity();
    scope.ServiceProvider.GetRequiredService<ISomeScopedService>()
        .DoSomethingWithTheEntity(entity)
}

Assuming that ISomeScopedService is properly registered as a scoped dependency, this code should resolve the same database context instance. Database contexts are registered as scoped dependencies (by default) and thus this should resolve the same instance from both the scoped service provider and the constructor injection in your scoped service.

If this does not work for you, then your actual code probably looks different, uses different scopes (or no scopes), or the logic behind GetSomeEntity() retrieves a non-tracking entity.


问:
RMarkdown - Change Inline Code Color *without changing workflow*
I teach an introductory statistics course using R Markdown in RStudio (Server). We have students knit to html_notebooks, and we often have them use inline code to report various elements of their statistical analyses. It'd be really helpful for grading purposes if we could have the result of inline code output in a different color -- that way we could easily see if they were indeed using inline code or if they copy-pasted a number from their output into raw text.

There's a couple of ideas for solutions posted here, but these won't super work in my case. These are introductory students who are generally kinda afraid of RStudio to begin with, so asking them to do anything complicated with text_spec or sprintf will likely cause mild riots. I really need something that won't change students' workflow at all.

I wonder if there's any way to configure things either on the backend in RStudio Server (maybe by messing with knitr?), or through some kind of

答:
A way to achieve this without changing the workflow too much is to create your own format  (e.g. html_notebook2) that is derived from the original but modifies the inline hook of knitr.

To get started you can check out this document.

Basic steps include

Create a new R package

Within this project run usethis::use_rmarkdown_template(). This creates the folder structure for your new format.

Edit skeleton.rmd and template.yaml

Define your format in a R file which has the same name html_notebook2.R(kind of a convention).

The content of the html_notebook2.R file could be

```<code>#'@import knitr
set_hooks <- function() {
  default_hooks  <- knit_hooks$get()
  list(
    inline = function(x) {
      paste0("<span style=\"color: #FF0000;\">", x,"</span>")
  })
}

#' @importFrom rmarkdown output_format knitr_options pandoc_options html_notebook
#' @export
html_notebook2 = function() {
  output_format(
    knitr = knitr_options(knit_hooks = set_hooks()),
    pandoc = pandoc_options(to = "html"),
    clean_supporting = FALSE,
    base_format = html_notebook()
  )
}
</code>```

In the first part we define a new inline hook which only changes the font color.
The second part is the definition of the new format.

After building and installing the package you can create a new rmarkdown document and use output: packagename::html_notebook2 as the output format. All inline code output will be colored red using my code. Here is an example:

```<code>---
title: "Inline"
output: cformat::html_notebook2
---

## R Markdown

`r pi`
</code>```

I created such a package and you can find it on GitHub. Feel free to copy it and rename it (cformat is a pretty lame working title ;) ).

Notice though that your students could change the color manually using HTML/CSS anyways. A way around could be some kind of key generation using a certain rule (unknown to the students obviously). For each inline chunk a key is generated and embedded using

```<code>paste0("<span code=", key," style=\"color: #FF0000;\">", x,"</span>")
</code>```

If a valid key is embedded, the output was generated using R and not simply copied.

Body:
A way to achieve this without changing the workflow too much is to create your own format  (e.g. html_notebook2) that is derived from the original but modifies the inline hook of knitr.

To get started you can check out this document.

Basic steps include

Create a new R package

Within this project run usethis::use_rmarkdown_template(). This creates the folder structure for your new format.

Edit skeleton.rmd and template.yaml

Define your format in a R file which has the same name html_notebook2.R(kind of a convention).

The content of the html_notebook2.R file could be

#'@import knitr
set_hooks <- function() {
  default_hooks  <- knit_hooks$get()
  list(
    inline = function(x) {
      paste0("<span style=\"color: #FF0000;\">", x,"</span>")
  })
}

#' @importFrom rmarkdown output_format knitr_options pandoc_options html_notebook
#' @export
html_notebook2 = function() {
  output_format(
    knitr = knitr_options(knit_hooks = set_hooks()),
    pandoc = pandoc_options(to = "html"),
    clean_supporting = FALSE,
    base_format = html_notebook()
  )
}

In the first part we define a new inline hook which only changes the font color.
The second part is the definition of the new format.

After building and installing the package you can create a new rmarkdown document and use output: packagename::html_notebook2 as the output format. All inline code output will be colored red using my code. Here is an example:

---
title: "Inline"
output: cformat::html_notebook2
---

## R Markdown

`r pi`

I created such a package and you can find it on GitHub. Feel free to copy it and rename it (cformat is a pretty lame working title ;) ).

Notice though that your students could change the color manually using HTML/CSS anyways. A way around could be some kind of key generation using a certain rule (unknown to the students obviously). For each inline chunk a key is generated and embedded using

paste0("<span code=", key," style=\"color: #FF0000;\">", x,"</span>")

If a valid key is embedded, the output was generated using R and not simply copied.


问:
When using unittest.mock.patch, why is autospec not True by default?
When you patch a function using mock, you have the option to specify autospec as True:

If you set autospec=True then the mock with be created with a spec
  from the object being replaced. All attributes of the mock will also
  have the spec of the corresponding attribute of the object being
  replaced. Methods and functions being mocked will have their arguments
  checked and will raise a TypeError if they are called with the wrong
  signature.

(http://www.voidspace.org.uk/python/mock/patch.html)

I'm wondering why this isn't the default behaviour?  Surely we would almost always want to catch passing incorrect parameters to any function we patch?

答:
Answering my own question many years later - another reason is speed.

Depending on how complex your object is, it can be that using autospec can slow your test down significantly. I've found this particularly when patching Django models.


问:
Problems when creating a huge matrix
I am trying to create a kind of table with random characters and writing the into a file, but I have a problem. The problem appears when I want to create huge tables. For example for a table with 10 rows x 5 columns everything is perfect, but for a table with 1.000.000 rows and 100 columns I have errors. Do you have any idea how could I solvent this problem???

I attached you the code I have created:

```<code>#include<iostream>
#include<fstream>
#include<stdio.h>
#include<string>
#include<ctime>
#include<sstream>

using namespace std;

int main()
{
    int rows, columns, rowsMax, columnsMax;
    int element1;
    char word[10];

    cout<<"Write the number of rows of your table: ";
    cin>>rowsMax;

    cout<<"Write the number of columns of your table: ";
    cin>>columnsMax;

    string matriz[100000][5]; // Here I write the number of row and columns that must be the same than the numbers introduced as input

    string table ("Table1");

    ofstream myfile (table);
    if(myfile.is_open())
    srand(1);
    for(rows=0;rows<rowsMax;rows++)
    {
        for(columns=0;columns<columnsMax;columns++)
        {
            element1 = rand() % 100000 + 1;

            int len = rand () % 4 + 4;
            word [len] = 0;
            while (len) word [--len] = 'A' + rand () % 58;

            myfile<<element1<<word;
            myfile<<"|";

            std::stringstream ss;
            ss<<element1;

            string mat;
            mat +=ss.str();
            mat +=word;
            matriz[rows][columns]= mat;
        }
        myfile<<endl;

    }
    myfile.close();

    system("pause");
    return 0;

}
</code>```

Thanks in advance for all your help!

答: You're creating your matrix on the stack, which has a limited size. Try to allocate it on the heap, using "new", or a vector of strings.</p>

Title: Problems when creating a huge matrix

Body:
I am trying to create a kind of table with random characters and writing the into a file, but I have a problem. The problem appears when I want to create huge tables. For example for a table with 10 rows x 5 columns everything is perfect, but for a table with 1.000.000 rows and 100 columns I have errors. Do you have any idea how could I solvent this problem???

I attached you the code I have created:

#include<iostream>
#include<fstream>
#include<stdio.h>
#include<string>
#include<ctime>
#include<sstream>

using namespace std;

int main()
{
    int rows, columns, rowsMax, columnsMax;
    int element1;
    char word[10];

    cout<<"Write the number of rows of your table: ";
    cin>>rowsMax;

    cout<<"Write the number of columns of your table: ";
    cin>>columnsMax;

    string matriz[100000][5]; // Here I write the number of row and columns that must be the same than the numbers introduced as input

    string table ("Table1");

    ofstream myfile (table);
    if(myfile.is_open())
    srand(1);
    for(rows=0;rows<rowsMax;rows++)
    {
        for(columns=0;columns<columnsMax;columns++)
        {
            element1 = rand() % 100000 + 1;

            int len = rand () % 4 + 4;
            word [len] = 0;
            while (len) word [--len] = 'A' + rand () % 58;

            myfile<<element1<<word;
            myfile<<"|";

            std::stringstream ss;
            ss<<element1;

            string mat;
            mat +=ss.str();
            mat +=word;
            matriz[rows][columns]= mat;
        }
        myfile<<endl;

    }
    myfile.close();

    system("pause");
    return 0;

}

Thanks in advance for all your help!


问:
How to order an array of objects according to different properties?
I need to order an array where the elements are objects. I want to fill up a dropdown in a specific order

```<code>[{ id: 1, name: "Country", parent: null, level: 0 },
{ id: 48, name: "Village1", parent: 16, level: 2 },
{ id: 17, name: "City1", parent: 1, level: 1 },
{ id: 15, name: "Village4", parent: 16, level: 2 },
{ id: 61, name: "City2", parent: 1, level: 1 },
{ id: 16, name: "City3", parent: 1, level: 1 },
{ id: 85, name: "City6", parent: 1, level: 1 },
{ id: 31, name: "Village2", parent: 77, level: 2 },
{ id: 76, name: "City4", parent: 1, level: 1 },
{ id: 77, name: "City5", parent: 1, level: 1 },
{ id: 79, name: "Village3", parent: 77, level: 2 }]
</code>```

What I am trying to achieve is to to get a dropdown where first appear the Country (parent null), then its children, but immediately, if those children have also children, they should appear down below, kind of:

- Country

- City1

- City2

- City3

- Village1

- Village2

- City4

. . .
And so on..

Anyone can give me a hand? I am really struggling here...

答:
I think you want to create a tree, following is half answer, I think its help you.

let arrOfObjectData = [{ id: 1, name: "Country", parent: null, level: 0 },
{ id: 48, name: "Village1", parent: 16, level: 2 },
{ id: 17, name: "City1", parent: 1, level: 1 },
{ id: 15, name: "Village4", parent: 16, level: 2 },
{ id: 61, name: "City2", parent: 1, level: 1 },
{ id: 16, name: "City3", parent: 1, level: 1 },
{ id: 85, name: "City6", parent: 1, level: 1 },
{ id: 31, name: "Village2", parent: 77, level: 2 },
{ id: 76, name: "City4", parent: 1, level: 1 },
{ id: 77, name: "City5", parent: 1, level: 1 },
{ id: 79, name: "Village3", parent: 77, level: 2 }];

let allParent = arrOfObjectData.filter((ele) => ele.parent == 1);
let treeArrOfObject = [];
allParent.forEach(element => {
 let findChild = arrOfObjectData.filter((elm) => elm.parent == element.id);
 treeArrOfObject.push({ parent: findChild, children: findChild });
});
console.log(treeArrOfObject);```

Body:
I need to order an array where the elements are objects. I want to fill up a dropdown in a specific order

[{ id: 1, name: "Country", parent: null, level: 0 },
{ id: 48, name: "Village1", parent: 16, level: 2 },
{ id: 17, name: "City1", parent: 1, level: 1 },
{ id: 15, name: "Village4", parent: 16, level: 2 },
{ id: 61, name: "City2", parent: 1, level: 1 },
{ id: 16, name: "City3", parent: 1, level: 1 },
{ id: 85, name: "City6", parent: 1, level: 1 },
{ id: 31, name: "Village2", parent: 77, level: 2 },
{ id: 76, name: "City4", parent: 1, level: 1 },
{ id: 77, name: "City5", parent: 1, level: 1 },
{ id: 79, name: "Village3", parent: 77, level: 2 }]

What I am trying to achieve is to to get a dropdown where first appear the Country (parent null), then its children, but immediately, if those children have also children, they should appear down below, kind of:

- Country

- City1

- City2

- City3

- Village1

- Village2

- City4

. . .
And so on..

Anyone can give me a hand? I am really struggling here...


问:
Unable to run angular application
I installed node and npm in my local and @angular cli v6.1.1. and created application name with ANGULAR6. then try to run the application but i'm getting error.</p>

```<code>PS C:\Users\762739\Desktop\Local _test_Files\Angular\ANGULAR6> ng serve
** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
       10% building modules 6/6 modules 0 activei ｢wds｣: Project is running at http://localhost:4200/
i ｢wds｣: webpack output is served from /
i ｢wds｣: Content not from webpack is served from C:\Users\762739\Desktop\Local _test_Files\Angular\ANGULAR6
i ｢wds｣: 404s will fallback to //index.html
Date: 2019-05-29T12:03:00.535Z
Hash: 39bd7e13701cafb5c814
Time: 2887ms
chunk {main} main.js, main.js.map (main) 344 kB [entry] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 344 kB [entry] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 5.22 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 359 kB [entry] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 10.2 kB [initial] [rendered]

ERROR in node_modules/rxjs/internal/types.d.ts(81,44): error TS1005: ';' expected.
node_modules/rxjs/internal/types.d.ts(81,74): error TS1005: ';' expected.
node_modules/rxjs/internal/types.d.ts(81,77): error TS1109: Expression expected.
node_modules/rxjs/internal/types.d.ts(82,52): error TS1005: ';' expected.
node_modules/rxjs/internal/types.d.ts(82,88): error TS1005: ';' expected.
node_modules/rxjs/internal/types.d.ts(82,92): error TS1109: Expression expected.
</code>```

答:
```<code>npm install rxjs@6.0.0 --save
</code>```

this will solve the problem

Title: Unable to run angular application

Body:
I installed node and npm in my local and @angular cli v6.1.1. and created application name with ANGULAR6. then try to run the application but i'm getting error.

PS C:\Users\762739\Desktop\Local _test_Files\Angular\ANGULAR6> ng serve
** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
       10% building modules 6/6 modules 0 activei ｢wds｣: Project is running at http://localhost:4200/
i ｢wds｣: webpack output is served from /
i ｢wds｣: Content not from webpack is served from C:\Users\762739\Desktop\Local _test_Files\Angular\ANGULAR6
i ｢wds｣: 404s will fallback to //index.html
Date: 2019-05-29T12:03:00.535Z
Hash: 39bd7e13701cafb5c814
Time: 2887ms
chunk {main} main.js, main.js.map (main) 344 kB [entry] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 344 kB [entry] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 5.22 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 359 kB [entry] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 10.2 kB [initial] [rendered]

ERROR in node_modules/rxjs/internal/types.d.ts(81,44): error TS1005: ';' expected.
node_modules/rxjs/internal/types.d.ts(81,74): error TS1005: ';' expected.
node_modules/rxjs/internal/types.d.ts(81,77): error TS1109: Expression expected.
node_modules/rxjs/internal/types.d.ts(82,52): error TS1005: ';' expected.
node_modules/rxjs/internal/types.d.ts(82,88): error TS1005: ';' expected.
node_modules/rxjs/internal/types.d.ts(82,92): error TS1109: Expression expected.

Body:
npm install rxjs@6.0.0 --save

this will solve the problem


问:
How do I fix windows giving out the wrong AD identity to my application?
My application uses a Angular frontend paired with a C# backend.
For determining who's currently sitting in front of the pc, I use C#/ASP.NET's Current.User.Identity .

Now, there is not a coding issue, my problem is that windows keeps handing out the wrong Identity. This happens since yesterday. My website keeps telling me I am IISAdmin, instead of my User Account that I am using right now.

I am guessing this probably stands in some relation to me adding a couple of network shares (quick access to the servers) using the credentials of IISAdmin and ticking the checkbox "Save Credentials".

Normally when I deploy patches I just connect to the server manually via explorer, and enter the credentials by hand. I have done this multiple times, this has never been an issue.

This is where it gets a little odd. I have tried starting Chrome explicitly as my User, and it just merged the window into the existing Chrome window I had already. Opened my web-app, IISAdmin.

I closed Chrome entirely, started it explicitly as my user again, IISAdmin.
Starting Chrome as a dummy account that I have access to, Chrome correctly opens a new Chrome window, and User.Identity confirms that I am logged in as said Dummy.

Internet Explorer behaves exactly the same way, so this is not browser-specific.

Even after a complete reboot this keeps remaining an issue. The network shares were removed after the restart, I am assuming they were temporary.

Windows should hand out my standard issue user account auth, not a highly powered super admin that's just saved somewhere.

答:
After talking to some colleagues, they pointed me towards the solution.

If this happens to you:

Go to System Control / Credential Manager / Windows Credentials
(Golden Safe)

Delete the conflicting credentials

I was not aware of this at first, but when you create a network share and save the credentials, it saves them here.
What I didn't expect was that windows maps the file path to the server to the server's actual IP / DNS adress.

So whenever you connect to said server, Windows uses the saved creds it has, and because of the way Kerberos works, your existing token just get's handed around.

Hence making things a little mushy, even if you explicitly start Chrome as your normal user.


问:
How to configure usage of AWS profile during amplify init?
During amplify init there is a question:

"Do you want to use AWS profile"

What is "AWS profile in this context"? When should i choose yes, and when no? What is the decision impact on the project?

答:
After installation of AWS CLI, you can configure your CLI using aws configure command. You provide access key, secret access key and default region. Once you are done with this it creates a default profile for your CLI. All your aws commands use credentials from this default profile. Your amplify init command refers to this profile.

You can have multiple AWS profiles for your CLI to use.

Coming to your question.

1) If your aws default profile is configured for the same account where you want your amplify project to deploy you can say yes to that question.

2) If you are not sure what is there in your default profile you can opt for no and provide access key, secret key and other information by own.

Hope this will clear your doubt.


问:
CakePHP 3.6: Setup database session to logout user after 8 hours of inactivity
I am trying to setup a database session in CakePHP 3.6 in order to log out users after 8 hours of inactivity. I created the table and set in app.php:

```<code>'Session' => [
        'defaults' => 'database',
        'timeout'  => 480,  // 8 hours, refers to 'session.gc_maxlifetime' in PHP settings
        'cookieTimeout' => 10 * 480, // 80 hours, refers to 'session.cookie_lifetime' in PHP settings
    ]
</code>```

But in the database, after I log in I can see that expires value of my session is: 1559992416 which is 10 days after the last time of activity (modified value). But even if I set expires in 2 minutes after the current time, it doesn't log me out when I try to click a button in my application. How I can set it up correctly?

答:
You have to set cookie_lifetime

```<code>Configure::write('Session', [
    'defaults' => 'php',
    'ini' => [
        'session.cookie_lifetime' => 1800, // Valid for 30 minutes
    ]
]);
</code>```

For more explanation you can check below link

https://book.cakephp.org/3.0/en/development/sessions.html#setting-ini-directives

Body:
I am trying to setup a database session in CakePHP 3.6 in order to log out users after 8 hours of inactivity. I created the table and set in app.php:

'Session' => [
        'defaults' => 'database',
        'timeout'  => 480,  // 8 hours, refers to 'session.gc_maxlifetime' in PHP settings
        'cookieTimeout' => 10 * 480, // 80 hours, refers to 'session.cookie_lifetime' in PHP settings
    ]

But in the database, after I log in I can see that expires value of my session is: 1559992416 which is 10 days after the last time of activity (modified value). But even if I set expires in 2 minutes after the current time, it doesn't log me out when I try to click a button in my application. How I can set it up correctly?

Body:
You have to set cookie_lifetime

Configure::write('Session', [
    'defaults' => 'php',
    'ini' => [
        'session.cookie_lifetime' => 1800, // Valid for 30 minutes
    ]
]);

For more explanation you can check below link

https://book.cakephp.org/3.0/en/development/sessions.html#setting-ini-directives


问:
how to refresh view pager data?
When I got data from service I reload all data in array list and pass to adapter but adapter display my old data.I pass new data in adapter when I print array list in adapter.show me old data.when I load new data I clear all data base also.

I load data in view pager so I create newInstance.so below code I get data from service and Store in arraylist and pass to adapter

```<code>adapter = new PagerAdapter(activity.getSupportFragmentManager(),"TotalCount",firstCountArrayList,secondAcoountArrayList,totalCountArrayList);
        pager.setPageMargin(-400);
        pager.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        pager.setOffscreenPageLimit(firstCountArrayList.size());

        tabs.setViewPager(pager,selected);
</code>```

In PagerAdapter I got old arraylist data

```<code>public class PagerAdapter extends FragmentPagerAdapter {

    String TotalCount = "";
    ArrayList<String> firstCountArrayList,secondAcoountArrayList,totalCountArrayList;

    public PagerAdapter(FragmentManager fm, String TotalCount, ArrayList<String> firstCountArrayList, ArrayList<String> secondAcoountArrayList, ArrayList<String> totalCountArrayList
                        ) {
        super(fm);
        //super(fm);
        this.TotalCount=TotalCount;

        this.firstCountArrayList=firstCountArrayList;
        this.secondAcoountArrayList=secondAcoountArrayList;
this.totalCountArrayList=totalCountArrayList;

    }

    @Override
    public CharSequence getPageTitle(int position) {
        return firstCountArrayList.get(position);
    }

    @Override
    public int getCount() {
        return firstCountArrayList.size();
    }
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }
    @Override
    public Fragment getItem(int position) {

        Log.e(TAG," PagerAdapter firstCountArrayList==>"+firstCountArrayList.toString());
        return NewPageInstance.newInstance(position,firstCountArrayList,secondAcoountArrayList,totalCountArrayList);
</code>```

after all data pass to NewPageInstance and display on TextView like

```<code>   public static NewPageInstance newInstance(int position, String totalCount, ArrayList<String> firstCountArrayList, ArrayList<String> secondAcoountArrayList, ArrayList<String> totalCountArrayList) {

    totalCount=totalCount;
    firstCountArrayList=firstCountArrayList;
    secondAcoountArrayList=secondAcoountArrayList;
    totalCountArrayList=totalCountArrayList;
    }
</code>```

and all data display textview

this is working only first time .not refresh view pager data.

答:
add below code in your view pager adapter:-

```<code>public int getItemPosition(Object object) {
return POSITION_NONE;
</code>```

}

or view pager changed listener notify your view pager adapter:-

```<code>mPagerAdapter.notifyDataSetChanged();
</code>```

Title: how to refresh view pager data?

Body:
When I got data from service I reload all data in array list and pass to adapter but adapter display my old data.I pass new data in adapter when I print array list in adapter.show me old data.when I load new data I clear all data base also.

I load data in view pager so I create newInstance.so below code I get data from service and Store in arraylist and pass to adapter

adapter = new PagerAdapter(activity.getSupportFragmentManager(),"TotalCount",firstCountArrayList,secondAcoountArrayList,totalCountArrayList);
        pager.setPageMargin(-400);
        pager.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        pager.setOffscreenPageLimit(firstCountArrayList.size());

        tabs.setViewPager(pager,selected);

In PagerAdapter I got old arraylist data

public class PagerAdapter extends FragmentPagerAdapter {

    String TotalCount = "";
    ArrayList<String> firstCountArrayList,secondAcoountArrayList,totalCountArrayList;

    public PagerAdapter(FragmentManager fm, String TotalCount, ArrayList<String> firstCountArrayList, ArrayList<String> secondAcoountArrayList, ArrayList<String> totalCountArrayList
                        ) {
        super(fm);
        //super(fm);
        this.TotalCount=TotalCount;

        this.firstCountArrayList=firstCountArrayList;
        this.secondAcoountArrayList=secondAcoountArrayList;
this.totalCountArrayList=totalCountArrayList;

    }

    @Override
    public CharSequence getPageTitle(int position) {
        return firstCountArrayList.get(position);
    }

    @Override
    public int getCount() {
        return firstCountArrayList.size();
    }
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }
    @Override
    public Fragment getItem(int position) {

        Log.e(TAG," PagerAdapter firstCountArrayList==>"+firstCountArrayList.toString());
        return NewPageInstance.newInstance(position,firstCountArrayList,secondAcoountArrayList,totalCountArrayList);

after all data pass to NewPageInstance and display on TextView like

   public static NewPageInstance newInstance(int position, String totalCount, ArrayList<String> firstCountArrayList, ArrayList<String> secondAcoountArrayList, ArrayList<String> totalCountArrayList) {

    totalCount=totalCount;
    firstCountArrayList=firstCountArrayList;
    secondAcoountArrayList=secondAcoountArrayList;
    totalCountArrayList=totalCountArrayList;
    }

and all data display textview

this is working only first time .not refresh view pager data.

Body:
add below code in your view pager adapter:-

public int getItemPosition(Object object) {
return POSITION_NONE;

}

or view pager changed listener notify your view pager adapter:-

mPagerAdapter.notifyDataSetChanged();


问:
Values in one column based on condition in another column
I have a dataframe:

```<code>Data = {'group':  ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'],
        'value1': [2, 0, 0, 5, 5, 5, 6, 31, 7, 5, 0, 99],
        'value2': [25, 12 ,15, 11, 36, 3, 65, 6, 89, 8, 74, 5]
        }

current_result = pd.DataFrame(Data, columns = ['group','value1', 'value2'])
</code>```

I want to set value2 to zero if corresponding value1 is equal to zero while keeping all other values the same. So my desired result would be:

```<code>Data = {'group':  ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'],
        'value1': [2, 0, 0, 5, 5, 5, 6, 31, 7, 5, 0, 99],
        'value2': [25, 0 ,0, 11, 36, 3, 65, 6, 89, 8, 0, 5]
        }

current_result = pd.DataFrame(Data, columns = ['group','value1', 'value2'])
</code>```

How could I do this?

答:
Use  this:</p>

```<code>current_result.loc[current_result['value1'] == 0, ['value2']] = 0
</code>```

Body:
I have a dataframe:

Data = {'group':  ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'],
        'value1': [2, 0, 0, 5, 5, 5, 6, 31, 7, 5, 0, 99],
        'value2': [25, 12 ,15, 11, 36, 3, 65, 6, 89, 8, 74, 5]
        }

current_result = pd.DataFrame(Data, columns = ['group','value1', 'value2'])

I want to set value2 to zero if corresponding value1 is equal to zero while keeping all other values the same. So my desired result would be:

Data = {'group':  ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'],
        'value1': [2, 0, 0, 5, 5, 5, 6, 31, 7, 5, 0, 99],
        'value2': [25, 0 ,0, 11, 36, 3, 65, 6, 89, 8, 0, 5]
        }

current_result = pd.DataFrame(Data, columns = ['group','value1', 'value2'])

How could I do this?

Body:
Use  this:

current_result.loc[current_result['value1'] == 0, ['value2']] = 0


问:
VBA, Excel. Execute code that offsets & resizes a range & then copies it. "Compile error: Invalid watch expression"
I'm trying to offset,resize and copy a range containing data and is typing this line of code in the immediate window:

```<code>shAll.Range("A1:I78").Offset(1).Resize(.Rows.Count - 1, .Columns.Count -
1).SpecialCells(xlCellTypeVisible).copy
</code>```

When I press enter I get this error: "Compile error: Invalid watch expression"

Is it a syntax issue?

This part of the code it working fine when executed in the immediate window:

```<code>shAll.Range("A1:I78").Offset(1).select
</code>```

It's getting offseted the way I want. The remaining part is to resize and copy it.

By the way, the range shAll.Range("A1:I78") contains data in all cells.

Thanks in advance!

答:
You can do a name range or put the actual range that you need. </p>

```<code>Worksheets("Sheet").Range("namedrange_d").Resize(, 4).Offset(6, 0).Copy _
  Worksheets("Sheet1").Range("namedrange").Resize(, 4).Offset(6, 0)
</code>```

Body:
I'm trying to offset,resize and copy a range containing data and is typing this line of code in the immediate window:

shAll.Range("A1:I78").Offset(1).Resize(.Rows.Count - 1, .Columns.Count -
1).SpecialCells(xlCellTypeVisible).copy

When I press enter I get this error: "Compile error: Invalid watch expression"

Is it a syntax issue?

This part of the code it working fine when executed in the immediate window:

shAll.Range("A1:I78").Offset(1).select

It's getting offseted the way I want. The remaining part is to resize and copy it.

By the way, the range shAll.Range("A1:I78") contains data in all cells.

Thanks in advance!

Body:
You can do a name range or put the actual range that you need.

Worksheets("Sheet").Range("namedrange_d").Resize(, 4).Offset(6, 0).Copy _
  Worksheets("Sheet1").Range("namedrange").Resize(, 4).Offset(6, 0)


问:
Need to run Lucene Analyzer offline from servlet
This might be quite a meaty question but my problem is that I have a Spring servlet that is used for real-time searching.  I need to strip out the Lucene analyzer so that it runs offline and is called by the servlet everytime a query comes in to it, rather than having the analyzer within the servlet.  However, I don't quite know how to do this, and call the analyzer service from the servlet.  Can anyone point me in the right direction?

At the moment, I have this:

```<code>RAMDirectory ramDirectory = new RAMDirectory();
StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_31);

IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_31, analyzer);
IndexWriter indexWriter = new IndexWriter(ramDirectory, config);
Document document = new Document();

// TEST DATA
document.add(new Field("firstName", "John", Field.Store.YES, Field.Index.ANALYZED));
document.add(new Field("occupation", "Engineer", Field.Store.YES, Field.Index.ANALYZED));

document.add(new Field("firstName", "Mary", Field.Store.YES, Field.Index.ANALYZED));
document.add(new Field("occupation", "Field Engineer", Field.Store.YES, Field.Index.ANALYZED));

document.add(new Field("firstName", "Jamie", Field.Store.YES, Field.Index.ANALYZED));
document.add(new Field("occupation", "Primary teacher", Field.Store.YES, Field.Index.ANALYZED));
// END TEST DATA

indexWriter.addDocument(document);
indexWriter.optimize();
indexWriter.close();

IndexSearcher indexSearcher = new IndexSearcher(ramDirectory);
String[] fields = {"firstName", "occupation"};
MultiFieldQueryParser parser = new MultiFieldQueryParser(null, fields, analyzer);
Query query = parser.parse(searchQuery);

// Parsing of results here
</code>```

Thanks.

答:
Why do you find your current design poor in terms of performance? What problem are you running into exactly?

I believe that what you're looking for is some form of inter-process communications. Two options that come to mind are:

Synchronous: offload processing to another server (HTTP or plain TCP) that envelopes Lucene and responds with the query results.
This will be useful for scaling your system since it lets you easily separate Lucene to another machine, but other than that, there are no immediate performance gains.

Asynchronous: offload it to a queue (e.g. ZeroMQ) that some other process listens on, runs Lucene, then returns the result through some other queue.
This is less advantageous if you need to respond to a user on the other end, and in any case will be hard to implement with java servlets (though if anyone knows otherwise, I'd love to hear about it).

Body:
This might be quite a meaty question but my problem is that I have a Spring servlet that is used for real-time searching.  I need to strip out the Lucene analyzer so that it runs offline and is called by the servlet everytime a query comes in to it, rather than having the analyzer within the servlet.  However, I don't quite know how to do this, and call the analyzer service from the servlet.  Can anyone point me in the right direction?

At the moment, I have this:

RAMDirectory ramDirectory = new RAMDirectory();
StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_31);

IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_31, analyzer);
IndexWriter indexWriter = new IndexWriter(ramDirectory, config);
Document document = new Document();

// TEST DATA
document.add(new Field("firstName", "John", Field.Store.YES, Field.Index.ANALYZED));
document.add(new Field("occupation", "Engineer", Field.Store.YES, Field.Index.ANALYZED));

document.add(new Field("firstName", "Mary", Field.Store.YES, Field.Index.ANALYZED));
document.add(new Field("occupation", "Field Engineer", Field.Store.YES, Field.Index.ANALYZED));

document.add(new Field("firstName", "Jamie", Field.Store.YES, Field.Index.ANALYZED));
document.add(new Field("occupation", "Primary teacher", Field.Store.YES, Field.Index.ANALYZED));
// END TEST DATA

indexWriter.addDocument(document);
indexWriter.optimize();
indexWriter.close();

IndexSearcher indexSearcher = new IndexSearcher(ramDirectory);
String[] fields = {"firstName", "occupation"};
MultiFieldQueryParser parser = new MultiFieldQueryParser(null, fields, analyzer);
Query query = parser.parse(searchQuery);

// Parsing of results here

Thanks.


问:
Change an object passed by pointer to a function
I need:

Create reference to object.

Pass it to a function that calls the constructor of the object's class and make some calculation over the object.

Pass the object to another function that also make some stuff with it.

My object that goes to the second function is always empty.

I slightly know the difference between stack and heap memory and the use of new operator but can't handle with it. I don't understand why g doesn't change after the func1 is over.

```<code>#include <iostream>

class Grid
{
    public:
        int a;

        Grid()
        {
            a = 2;
        }
};

void func1(Grid * g);
void func2(Grid * g);

int
main ()
{
    Grid g;
    func1(&g);
    func2(&g);
}

void
func1 (Grid * g)
{
    g = new Grid();
    g->a = 5;
}

void
func2 (Grid * g)
{
    std::cout << g->a << std::endl;
}
</code>```

How make the output in the func2 5, cause now it's 2?

答:
If you want to use pointers to "pass by reference", then just do that:

```<code>void
func1 (Grid * g)
{
    g->a = 5;
}

void
func2 (const Grid * g)
{
    std::cout << g->a << std::endl;
}

int
main ()
{
    Grid g;
    func1(&g);
    func2(&g);
}
</code>```

Currently you're taking a pointer (and remember that the pointer itself is passed by value), then overwriting the locally-scoped copy of that pointer with a pointer to a new, dynamically-allocated Grid object. You set a property on that object then leak it.

In C++ we often use actual references instead, which can be clearer (though perhaps not as clear at the callsite!):

```<code>void
func1 (Grid& g)
{
    g.a = 5;
}

void
func2 (const Grid& g)
{
    std::cout << g.a << std::endl;
}

int
main ()
{
    Grid g;
    func1(g);
    func2(g);
}
</code>```

As for this bit:

Pass it to a function that calls the constructor of the object's class

The object is already constructed. You can copy-assign from a fresh, temporary object if you really want to "reset" it in that way:

```<code>void
func1 (Grid& g)
{
    g = Grid();
    g.a = 5;
}
</code>```

But I'd advise reconsidering whether you really want/need to reset the object like this. And, if you do, perhaps a nice reset() member function?

Body:
I need:

Create reference to object.

Pass it to a function that calls the constructor of the object's class and make some calculation over the object.

Pass the object to another function that also make some stuff with it.

My object that goes to the second function is always empty.

I slightly know the difference between stack and heap memory and the use of new operator but can't handle with it. I don't understand why g doesn't change after the func1 is over.

#include <iostream>

class Grid
{
    public:
        int a;

        Grid()
        {
            a = 2;
        }
};

void func1(Grid * g);
void func2(Grid * g);

int
main ()
{
    Grid g;
    func1(&g);
    func2(&g);
}

void
func1 (Grid * g)
{
    g = new Grid();
    g->a = 5;
}

void
func2 (Grid * g)
{
    std::cout << g->a << std::endl;
}

How make the output in the func2 5, cause now it's 2?

Body:
If you want to use pointers to "pass by reference", then just do that:

void
func1 (Grid * g)
{
    g->a = 5;
}

void
func2 (const Grid * g)
{
    std::cout << g->a << std::endl;
}

int
main ()
{
    Grid g;
    func1(&g);
    func2(&g);
}

Currently you're taking a pointer (and remember that the pointer itself is passed by value), then overwriting the locally-scoped copy of that pointer with a pointer to a new, dynamically-allocated Grid object. You set a property on that object then leak it.

In C++ we often use actual references instead, which can be clearer (though perhaps not as clear at the callsite!):

void
func1 (Grid& g)
{
    g.a = 5;
}

void
func2 (const Grid& g)
{
    std::cout << g.a << std::endl;
}

int
main ()
{
    Grid g;
    func1(g);
    func2(g);
}

As for this bit:

Pass it to a function that calls the constructor of the object's class

The object is already constructed. You can copy-assign from a fresh, temporary object if you really want to "reset" it in that way:

void
func1 (Grid& g)
{
    g = Grid();
    g.a = 5;
}

But I'd advise reconsidering whether you really want/need to reset the object like this. And, if you do, perhaps a nice reset() member function?


问:
Add Element to XML
I want to add a element (connector) to a existing XML, this was succesfull but I need to remove the xmlns= and want to add an value to it. The connector blaat is added with my code.

The XML:

<?xml version="1.0"?>
<configuration xmlns="urn:activemq" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xi="http://www.w3.org/2001/XInclude" xsi:schemaLocation="urn:activemq /schema/artemis-configuration.xsd">
  <core xmlns="urn:activemq:core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:activemq:core ">
    <connectors>

      <connector name="artemis">tcp://xxxxxxx:61616</connector>
      <connector name="blaat" xmlns="" />
    </connectors>
  </core>
</configuration>
```

<pre class="lang-bsh prettyprint-override"><code>[xml]$xml = Get-Content d:\data\test-broker\etc\broker.xml

$xml.configuration.core.connectors.connector.ChildNodes.Item(0).value

$Node = $xml.CreateElement("connector");
$Node.SetAttribute("name", "blaat");
$xml.configuration.core.connectors.AppendChild($node)
$xml.configuration.core.connectors.connector.SetValue("tcp://");
$xml.Save("d:\data\test-broker\etc\broker.xml")
</code>```

I want the XML to be like this:

<?xml version="1.0"?>
<configuration xmlns="urn:activemq" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xi="http://www.w3.org/2001/XInclude" xsi:schemaLocation="urn:activemq /schema/artemis-configuration.xsd">
  <core xmlns="urn:activemq:core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:activemq:core ">
    <connectors>

      <connector name="artemis">tcp://xxxx1:61616</connector>
      <connector name="blaat">tcp://xxxxx2:61616</connector>
    </connectors>
  </core>
</configuration>
```

答:
Your XML data uses namespaces, so you need to take care of that. The <core> node defines a default namespace (xmlns="urn:activemq:core") that applies to all of its child nodes. Create a namespace manager and add that namespace to it:

```<code>$nm = New-Object Xml.XmlNamespaceManager $xml.NameTable
$nm.AddNamespace('foo', 'urn:activemq:core')
</code>```

Select the node to which you want to append your new node:

```<code>$cn = $xml.SelectSingleNode('//foo:connectors', $nm)
</code>```

When creating the new node specify its default namespace, then set the node's attribute(s) and value:

```<code>$node = $xml.CreateElement('connector', $cn.NamespaceURI)
$node.SetAttribute('name', 'blaat')
$node.InnerText = 'tcp://xxxxx2:61616'
</code>```

Now you can append the new node to the intended parent without getting a spurious xmlns attribute:

```<code>[void]$cn.AppendChild($node)
</code>```

Title: Add Element to XML

Body:
I want to add a element (connector) to a existing XML, this was succesfull but I need to remove the xmlns= and want to add an value to it. The connector blaat is added with my code.

The XML:

<?xml version="1.0"?>
<configuration xmlns="urn:activemq" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xi="http://www.w3.org/2001/XInclude" xsi:schemaLocation="urn:activemq /schema/artemis-configuration.xsd">
  <core xmlns="urn:activemq:core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:activemq:core ">
    <connectors>

      <connector name="artemis">tcp://xxxxxxx:61616</connector>
      <connector name="blaat" xmlns="" />
    </connectors>
  </core>
</configuration>

[xml]$xml = Get-Content d:\data\test-broker\etc\broker.xml

$xml.configuration.core.connectors.connector.ChildNodes.Item(0).value

$Node = $xml.CreateElement("connector");
$Node.SetAttribute("name", "blaat");
$xml.configuration.core.connectors.AppendChild($node)
$xml.configuration.core.connectors.connector.SetValue("tcp://");
$xml.Save("d:\data\test-broker\etc\broker.xml")

I want the XML to be like this:

<?xml version="1.0"?>
<configuration xmlns="urn:activemq" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xi="http://www.w3.org/2001/XInclude" xsi:schemaLocation="urn:activemq /schema/artemis-configuration.xsd">
  <core xmlns="urn:activemq:core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:activemq:core ">
    <connectors>

      <connector name="artemis">tcp://xxxx1:61616</connector>
      <connector name="blaat">tcp://xxxxx2:61616</connector>
    </connectors>
  </core>
</configuration>

Body:
Your XML data uses namespaces, so you need to take care of that. The <core> node defines a default namespace (xmlns="urn:activemq:core") that applies to all of its child nodes. Create a namespace manager and add that namespace to it:

$nm = New-Object Xml.XmlNamespaceManager $xml.NameTable
$nm.AddNamespace('foo', 'urn:activemq:core')

Select the node to which you want to append your new node:

$cn = $xml.SelectSingleNode('//foo:connectors', $nm)

When creating the new node specify its default namespace, then set the node's attribute(s) and value:

$node = $xml.CreateElement('connector', $cn.NamespaceURI)
$node.SetAttribute('name', 'blaat')
$node.InnerText = 'tcp://xxxxx2:61616'

Now you can append the new node to the intended parent without getting a spurious xmlns attribute:

[void]$cn.AppendChild($node)


问:
iText / BouncyCastle throws "java.lang.VerifyError: class overrides final method equals"
We have an application that creates PDFs unsing jasperreports.

It also manipulates said PDFs using iText after they have been created.

We recently started using encryption on some PDF. That means before the app can handle the PDF after its creation, it has to be decrypted. While attempting to do so using iText's PdfReader(String path, byte[] password) I get the following exception:

```<code>java.lang.VerifyError: class org.bouncycastle.asn1.ASN1Primitive overrides final method equals.(Ljava/lang/Object;)Z
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(Unknown Source)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at com.simontuffs.onejar.JarClassLoader.defineClass(JarClassLoader.java:561)
    at com.simontuffs.onejar.JarClassLoader.findClass(JarClassLoader.java:475)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at com.itextpdf.text.pdf.PdfEncryption.<init>(PdfEncryption.java:148)
    at com.itextpdf.text.pdf.PdfReader.readDecryptedDocObj(PdfReader.java:914)
    at com.itextpdf.text.pdf.PdfReader.readDocObj(PdfReader.java:1294)
    at com.itextpdf.text.pdf.PdfReader.readPdf(PdfReader.java:643)
    at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:187)
    at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:212)
    at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:202)
</code>```

The project is built as a runnable .jar using Maven and uses the following dependencies:

iText 5.4.2

bouncycastle 1.48

I should mention that jasperreports has its own dependency of iText and bouncycastle:

iText 2.1.7

bouncycastle 1.38

I can't figure out what's going on on and need help.

答:
I had similiar problem because I had two different artifacts on my classpath:

```<code><groupId>org.bouncycastle</groupId>
<artifactId>bcprov</artifactId>
</code>```

and

```<code> <groupId>org.bouncycastle</groupId>
 <artifactId>bcprov-jdk15on</artifactId>
</code>```

I have excluded the bcprov, which solved the issue for me.

Body:
We have an application that creates PDFs unsing jasperreports.

It also manipulates said PDFs using iText after they have been created.

We recently started using encryption on some PDF. That means before the app can handle the PDF after its creation, it has to be decrypted. While attempting to do so using iText's PdfReader(String path, byte[] password) I get the following exception:

java.lang.VerifyError: class org.bouncycastle.asn1.ASN1Primitive overrides final method equals.(Ljava/lang/Object;)Z
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(Unknown Source)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at com.simontuffs.onejar.JarClassLoader.defineClass(JarClassLoader.java:561)
    at com.simontuffs.onejar.JarClassLoader.findClass(JarClassLoader.java:475)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at com.itextpdf.text.pdf.PdfEncryption.<init>(PdfEncryption.java:148)
    at com.itextpdf.text.pdf.PdfReader.readDecryptedDocObj(PdfReader.java:914)
    at com.itextpdf.text.pdf.PdfReader.readDocObj(PdfReader.java:1294)
    at com.itextpdf.text.pdf.PdfReader.readPdf(PdfReader.java:643)
    at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:187)
    at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:212)
    at com.itextpdf.text.pdf.PdfReader.<init>(PdfReader.java:202)

The project is built as a runnable .jar using Maven and uses the following dependencies:

iText 5.4.2

bouncycastle 1.48

I should mention that jasperreports has its own dependency of iText and bouncycastle:

iText 2.1.7

bouncycastle 1.38

I can't figure out what's going on on and need help.

Body:
I had similiar problem because I had two different artifacts on my classpath:

<groupId>org.bouncycastle</groupId>
<artifactId>bcprov</artifactId>

and

 <groupId>org.bouncycastle</groupId>
 <artifactId>bcprov-jdk15on</artifactId>

I have excluded the bcprov, which solved the issue for me.


问:
Update Dataframe column value based on other Dataframe column value
I have a pandas Dataframe which has a couple of columns.
I want to get the first 3 elements out of the Information Column based on a value in Protocol.

For example: I want the first 3 elements in Information IF the protocol is TCP.

Using below code I can separate the columns needed for my operation. But I have no clue how to adapt the next piece of code to this.

```<code>chunk[['Protocol', 'Information']] = chunk[['Protocol', 'Information']]
</code>```

EDIT:

I wish to update the values. Not separate them.

答:
I have been able to update the values based on a given value:

```<code>chunk.loc[chunk['Protocol'] == tcp, 'Information'] = 5
</code>```

But right now I just change the value to the number 5. I would rather use a lambda expression or function to get the first three elements and only keep these values.

Body:
I have a pandas Dataframe which has a couple of columns.
I want to get the first 3 elements out of the Information Column based on a value in Protocol.

For example: I want the first 3 elements in Information IF the protocol is TCP.

Using below code I can separate the columns needed for my operation. But I have no clue how to adapt the next piece of code to this.

chunk[['Protocol', 'Information']] = chunk[['Protocol', 'Information']]

EDIT:

I wish to update the values. Not separate them.

Body:
I have been able to update the values based on a given value:

chunk.loc[chunk['Protocol'] == tcp, 'Information'] = 5

But right now I just change the value to the number 5. I would rather use a lambda expression or function to get the first three elements and only keep these values.