问:
Wordpress - Pagination
i'm creating a blog page in my custom theme wordpress, i would like use pagination in my list posts, my query with list of posts work well but the pagination doesn't work. i see always the same first 2 posts.

page-blog.php

```<code>/*
 * Template Name: Pagina Blog
 */

<?php get_header(); ?>

<?php

$posts_per_page = 2;

$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;

$args = array(
  'posts_per_page' => $posts_per_page,
    'paged' => $paged,
  'offset'           => 0,
  'category'         => '',
  'category_name'    => '',
  'orderby'          => 'date',
  'order'            => 'DESC',
  'include'          => '',
  'exclude'          => '',
  'meta_key'         => '',
  'meta_value'       => '',
  'post_type'        => 'post',
  'post_mime_type'   => '',
  'post_parent'      => '',
  'author'     => '',
  'author_name'    => '',
  'post_status'      => 'publish',
  'suppress_filters' => true
);
//$posts_array = get_posts( $args );
$wp_query = new WP_Query( $args );
//query_posts( $args );

?>

  <?php while ( have_posts() ) : the_post(); ?>

  <!-- Title -->

    <h1 class="my-4"><?php the_title() ?></h1>

    <h2 class="card-title">
      <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    </h2>

  <!-- Content -->

    <?php the_content() ?>

  <!-- Pagination -->

    <?php next_posts_link(); ?>
    <?php previous_posts_link(); ?>

  <?php endwhile;

  // Reset Query
  wp_reset_query(); ?>

<?php get_footer(); ?>
</code>```

I think there some issue with the loop, but i'm not sure, i can see "Newer" and "Older" links but when i go on older i see the same posts, so "www.mysite.com/blog" have the same post of "www.mysite.com/blog/2" :(

答:
Here lies your problem:

'offset'           => 0,

Replace that with:

'offset' => $posts_per_page * ($paged - 1)

Alternativley, if I'm reading the documentation correctly, you can maybe just remove the offset value entirely.

Title: Wordpress - Pagination

Body:
i'm creating a blog page in my custom theme wordpress, i would like use pagination in my list posts, my query with list of posts work well but the pagination doesn't work. i see always the same first 2 posts.

page-blog.php

/*
 * Template Name: Pagina Blog
 */

<?php get_header(); ?>

<?php

$posts_per_page = 2;

$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;

$args = array(
  'posts_per_page' => $posts_per_page,
    'paged' => $paged,
  'offset'           => 0,
  'category'         => '',
  'category_name'    => '',
  'orderby'          => 'date',
  'order'            => 'DESC',
  'include'          => '',
  'exclude'          => '',
  'meta_key'         => '',
  'meta_value'       => '',
  'post_type'        => 'post',
  'post_mime_type'   => '',
  'post_parent'      => '',
  'author'     => '',
  'author_name'    => '',
  'post_status'      => 'publish',
  'suppress_filters' => true
);
//$posts_array = get_posts( $args );
$wp_query = new WP_Query( $args );
//query_posts( $args );

?>

  <?php while ( have_posts() ) : the_post(); ?>

<?php the_title() ?>

      <a href="<?php the_permalink(); ?>"><?php the_title(); ?>

    <?php the_content() ?>

    <?php next_posts_link(); ?>
    <?php previous_posts_link(); ?>

  <?php endwhile;

  // Reset Query
  wp_reset_query(); ?>

<?php get_footer(); ?>

I think there some issue with the loop, but i'm not sure, i can see "Newer" and "Older" links but when i go on older i see the same posts, so "www.mysite.com/blog" have the same post of "www.mysite.com/blog/2" :(


来源: stackexchange

问:
get the min value from a count subquery
I working on 2 tables in a trial database stock and sales, I am trying to find the stock item(s) that have had the least number of sales.

The sales table has the following fields: sales_id, transaction_id, stock_id, amount
The stock table has : sid, upc, name, description, amount, price
when I run the following SQL:

```<code>  SELECT st.name,
    COUNT( s.stock_id ) AS num_of_individual_sales
    FROM sales AS s
    JOIN stock as st
    ON st.sid = s.stock_id
    GROUP BY s.stock_id
</code>```

I get:

```<code>banana  7
mars bar    4
fiery hot monster munch 2
WWII hand grenade   4
cheese toastie  2
fish paste  3
belly fluff 2
Unicorn tears   2
spag sauce  4
cooking oil 2
</code>```

So I then try and wrap it up as a sub query:

```<code>SELECT ans.name, MIN(ans.num_of_individual_sales)
FROM
(

SELECT st.name,
COUNT( s.stock_id ) AS num_of_individual_sales
FROM sales AS s
JOIN stock as st
ON st.sid = s.stock_id
GROUP BY s.stock_id

) AS ans
</code>```

The result I'm getting is

banana 2

which even with my non-functioning brain is wrong, I was expecting to get a a recordset with all the 2's (monstermuch, cheese toastie etc)

I have tried loads of different combos but this seems to give the nearest result just not the one I want...

where am I going wrong?

cheers

Zen

UPDATE
worked out at about the same time as Bill Karwin posted that my understanding of the MIN and MAX commands was inaccurate.

I already understood the idea of using an ORDER BY ASC and then I could have used PHP to cut off the data when the COUNT value changed but I'm kind of doing this as a learning exercise so although there may be an easier route I was hoping that it was still possible to do it via the MIN command, I think I need to do a double sub query but have got lost somewhere, this is the newest variant.

```<code>SELECT st.name, st.price,
s.sales_id
From stock AS st
JOIN sales AS s
ON  st.sid = s.stock_id
WHERE COUNT(s.stock_id)=(

SELECT MIN(ans.num_of_individual_sales)
FROM
(

SELECT st.name,
COUNT( s.stock_id ) AS num_of_individual_sales
FROM sales AS s
JOIN stock as st
ON st.sid = s.stock_id
GROUP BY s.stock_id

) AS ans
)GROUP BY s.stock_id
</code>```

but I am getting an invalid group function error

答:
Using sub query:</p>

```<code>SELECT temp1.name, temp1.sales

FROM (SELECT st.stock_name as name,
      COUNT( s.sale_stock_id ) AS sales
      FROM test_sales AS s
      JOIN test_stock as st ON st.stock_id = s.sale_stock_id
      GROUP BY s.sale_stock_id) as temp1

LEFT JOIN (SELECT st.stock_name as name,
           COUNT(s.sale_stock_id ) AS sales
           FROM test_sales AS s
           JOIN test_stock as st ON st.stock_id = s.sale_stock_id
           GROUP BY s.sale_stock_id) as temp2

ON temp1.sales > temp2.sales

WHERE temp2.sales is null
</code>```

ContentLicense: CC BY-SA 3.0

Title: get the min value from a count subquery

Body:
I working on 2 tables in a trial database stock and sales, I am trying to find the stock item(s) that have had the least number of sales.

The sales table has the following fields: sales_id, transaction_id, stock_id, amount
The stock table has : sid, upc, name, description, amount, price
when I run the following SQL:

  SELECT st.name,
    COUNT( s.stock_id ) AS num_of_individual_sales
    FROM sales AS s
    JOIN stock as st
    ON st.sid = s.stock_id
    GROUP BY s.stock_id

I get:

banana  7
mars bar    4
fiery hot monster munch 2
WWII hand grenade   4
cheese toastie  2
fish paste  3
belly fluff 2
Unicorn tears   2
spag sauce  4
cooking oil 2

So I then try and wrap it up as a sub query:

SELECT ans.name, MIN(ans.num_of_individual_sales)
FROM
(

SELECT st.name,
COUNT( s.stock_id ) AS num_of_individual_sales
FROM sales AS s
JOIN stock as st
ON st.sid = s.stock_id
GROUP BY s.stock_id

) AS ans

The result I'm getting is

banana 2

which even with my non-functioning brain is wrong, I was expecting to get a a recordset with all the 2's (monstermuch, cheese toastie etc)

I have tried loads of different combos but this seems to give the nearest result just not the one I want...

where am I going wrong?

cheers

Zen

UPDATE
worked out at about the same time as Bill Karwin posted that my understanding of the MIN and MAX commands was inaccurate.

I already understood the idea of using an ORDER BY ASC and then I could have used PHP to cut off the data when the COUNT value changed but I'm kind of doing this as a learning exercise so although there may be an easier route I was hoping that it was still possible to do it via the MIN command, I think I need to do a double sub query but have got lost somewhere, this is the newest variant.

SELECT st.name, st.price,
s.sales_id
From stock AS st
JOIN sales AS s
ON  st.sid = s.stock_id
WHERE COUNT(s.stock_id)=(

SELECT MIN(ans.num_of_individual_sales)
FROM
(

SELECT st.name,
COUNT( s.stock_id ) AS num_of_individual_sales
FROM sales AS s
JOIN stock as st
ON st.sid = s.stock_id
GROUP BY s.stock_id

) AS ans
)GROUP BY s.stock_id

but I am getting an invalid group function error

Body:
Using sub query:

SELECT temp1.name, temp1.sales

FROM (SELECT st.stock_name as name,
      COUNT( s.sale_stock_id ) AS sales
      FROM test_sales AS s
      JOIN test_stock as st ON st.stock_id = s.sale_stock_id
      GROUP BY s.sale_stock_id) as temp1

LEFT JOIN (SELECT st.stock_name as name,
           COUNT(s.sale_stock_id ) AS sales
           FROM test_sales AS s
           JOIN test_stock as st ON st.stock_id = s.sale_stock_id
           GROUP BY s.sale_stock_id) as temp2

ON temp1.sales > temp2.sales

WHERE temp2.sales is null


问:
Is it faster to use two separate SQL statements or one SQL statement with JOIN?
I'm in doubt about the performance by "two or more individual SQL commands" or "1 but using 'join' SQL command".

Here is the thing:

For example, I have two tables: post, user

post has a user_id indicating this post is issued by some user in user

and I'm going to extract both post and username.

I can either

```
SELECT * FROM `post` LEFT JOIN `user` on post.user_id = user.id WHERE 1
```

or

```
$rows = $db->sql("SELEFT * FROM `post` WHERE 1")
for $row in $rows:
    $db->sql("SELECT * FROM `user` WHERE id = $row['user_id']")
```

I'm wondering which one will have better performance?

And what if I have 3 or more tables to join, which way will be better (from the performance perspective)?

答:
Note that you are not executing 2 queries.  You are executing the first query once and the second query N times, where N is the number of rows returned by the first query.  This is going to be vastly more expensive than letting the query optimizer deal with a single join query.

Database optimizers are carefully written by experts to minimize the cost of operations.  If you try to second guess the optimizer by running the separate queries, you should lose, badly, every time - unless the optimizer has severely blown it.  All else apart, the DBMS has to prepare the variations on the second statement each time it is invoked, instead of just once.  The optimizer would have to be so diabolically wrong that it simply won't happen.

Body:
I'm in doubt about the performance by "two or more individual SQL commands" or "1 but using 'join' SQL command".

Here is the thing:

For example, I have two tables: post, user

post has a user_id indicating this post is issued by some user in user

and I'm going to extract both post and username.

I can either

SELECT * FROM `post` LEFT JOIN `user` on post.user_id = user.id WHERE 1

or

$rows = $db->sql("SELEFT * FROM `post` WHERE 1")
for $row in $rows:
    $db->sql("SELECT * FROM `user` WHERE id = $row['user_id']")

I'm wondering which one will have better performance?

And what if I have 3 or more tables to join, which way will be better (from the performance perspective)?

ContentLicense: CC BY-SA 2.5


问:
Handling PATCH requests with javax.servlet.http.HttpServlet?
We are using our implementation of the javax.servlet.http.HttpServlet class as an error page(defined in the web.xml) in our Spring Web application in order to filter error information, sent to users of our API for security reasons.

As of recently we also have to handle PATCH requests to our API. As the HttpServlet was implemented with HTTP version 1.1 in mind, it does not support PATCH request("PATCH" string as a request method name). If we were to add the functionality, we have to override the whole HttpServlet implementation, which also has negative security connotations for us.

Is there an out of the box way to achieve what we are trying or do we have to switch to another implementation(also viable)?

答:
Try overriding the HttpServlet.service method.
For "DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT", and "TRACE" pass the request to the super implementation of service.

For "PATCH" call a doPatch method that you define in the overriding class.

Implement doPatch in the actual class.

More info about message body:

Checkout an HTTP reference to see which methods support a method body and which do not.
There is a nice table on the HTTP Wikipedia Page

ContentLicense: CC BY-SA 4.0


问:
Firebase. Change `username`(email) of registered user
My iOS application uses Firebase login by username and password. But I would like to give a possibility to change the username in settings.

The question is, does Firebase support changing a username?

Update

username means email

答:
I guess you're talking about the email and password auth method.
You can change the email (which is the username) by updating it directly from code. Hope this helps!</p>


问:
Using f:event to inject a ConversationScoped bean into a ViewScoped bean
I can't inject a ConversationScoped bean into a ViewScoped bean, because the ConversationScoped bean could be shorter lived than the ViewScoped one, or vice versa, depending on whether or not the ConversationScoped bean is long-lived.

To get over this limitation, I tried using an f:event to perform the injection as a preRenderView listener:

```<code><f:metadata>
   <f:event type="preRenderView" listener="#{taskController.initializeTask(workPackageConversation.workPackage)}" />
</f:metadata>
</code>```

This howver is not working, neither the listener initializeTask, nor the getter getWorkPackage are being called.

I realize I can lookup one managed bean from another, using the FacesContext, but I am curious why this isn't working.  Is it because the f:event listener isn't called when I navigate to a view from another view?  ie. without a redirect or direct page view?

I also tried the s:viewAction tag from Seam 3 Faces, to no avail.   It does not get called either.

Thanks in advance.

答: I would think the lifetime issues would not come into play since you've always got a proxy to the normal-scoped bean anyway.  You either dereference the conversation-scoped bean while the conversation is active, or it's not active -- but you'll always get the right conversation.

Body:
I can't inject a ConversationScoped bean into a ViewScoped bean, because the ConversationScoped bean could be shorter lived than the ViewScoped one, or vice versa, depending on whether or not the ConversationScoped bean is long-lived.

To get over this limitation, I tried using an f:event to perform the injection as a preRenderView listener:

<f:metadata>
   <f:event type="preRenderView" listener="#{taskController.initializeTask(workPackageConversation.workPackage)}" />
</f:metadata>

This howver is not working, neither the listener initializeTask, nor the getter getWorkPackage are being called.

I realize I can lookup one managed bean from another, using the FacesContext, but I am curious why this isn't working.  Is it because the f:event listener isn't called when I navigate to a view from another view?  ie. without a redirect or direct page view?

I also tried the s:viewAction tag from Seam 3 Faces, to no avail.   It does not get called either.

Thanks in advance.


问:
Unexpected directive 'MatSpinner' imported by the module 'AppModule'. Please add a @NgModule annotation
Angular 5 -

here are the npm modules (package.json)-

```<code>   "@angular/animations": "^5.0.0",
    "@angular/cdk": "^5.0.0-rc.2",
    "@angular/common": "^5.0.0",
    "@angular/compiler": "^5.0.0",
    "@angular/core": "^5.0.0",
    "@angular/forms": "^5.0.0",
    "@angular/http": "^5.0.0",
    "@angular/material": "^5.0.0-rc.2",
    "@angular/platform-browser": "^5.0.0",
    "@angular/platform-browser-dynamic": "^5.0.0",
    "@angular/router": "^5.0.0",
    "core-js": "^2.4.1",
    "hammerjs": "^2.0.8",
    "rxjs": "^5.5.2",
    "zone.js": "^0.8.14"
</code>```

I am using Angular material Spinner as MatSpinner Directive from Material module

```<code>import { MatSpinner } from "@angular/material";
@NgModule({
imports: [

MatSpinner
],
declarations: [],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Here is the HTML:

```<code><mat-spinner></mat-spinner>
</code>```

I am Getting an ERROR-

Unexpected directive 'MatSpinner' imported by the module 'AppModule'. Please add a @NgModule annotation.

答:
MatSpinner & MatProgressSpinner are component and already part of MatProgressSpinnerModule.

In Angular,

A component can not be added in imports of @NgModule

A component can not be part of declarations of more than one @NgModule

As both the components are available in MatProgressSpinnerModule, you should add MatProgressSpinnerModule in imports of your @NgModule.

Example

```<code>import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';

@NgModule({
  imports: [
    MatProgressSpinnerModule
  ],
  declarations: [],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Body:
Angular 5 -

here are the npm modules (package.json)-

   "@angular/animations": "^5.0.0",
    "@angular/cdk": "^5.0.0-rc.2",
    "@angular/common": "^5.0.0",
    "@angular/compiler": "^5.0.0",
    "@angular/core": "^5.0.0",
    "@angular/forms": "^5.0.0",
    "@angular/http": "^5.0.0",
    "@angular/material": "^5.0.0-rc.2",
    "@angular/platform-browser": "^5.0.0",
    "@angular/platform-browser-dynamic": "^5.0.0",
    "@angular/router": "^5.0.0",
    "core-js": "^2.4.1",
    "hammerjs": "^2.0.8",
    "rxjs": "^5.5.2",
    "zone.js": "^0.8.14"

I am using Angular material Spinner as MatSpinner Directive from Material module

import { MatSpinner } from "@angular/material";
@NgModule({
imports: [

MatSpinner
],
declarations: [],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Here is the HTML:

<mat-spinner></mat-spinner>

I am Getting an ERROR-

Unexpected directive 'MatSpinner' imported by the module 'AppModule'. Please add a @NgModule annotation.

Body:
MatSpinner & MatProgressSpinner are component and already part of MatProgressSpinnerModule.

In Angular,

A component can not be added in imports of @NgModule

A component can not be part of declarations of more than one @NgModule

As both the components are available in MatProgressSpinnerModule, you should add MatProgressSpinnerModule in imports of your @NgModule.

Example

import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';

@NgModule({
  imports: [
    MatProgressSpinnerModule
  ],
  declarations: [],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


问:
Trouble with regex / preg_match / str_replace with complicated string
I am having trouble with a complicated regex.  I have tried this every way I can think of, and I can always only get "almost" there --

I have a block of 5 messages:

```<code>---Agent 1: Wednesday 08/16/2017 | 11:43 AM ---

Message 1

--- Agent 1: Friday 06/09/2017 | 9:02 AM ---

Message 2

--- Agent 1: Friday 04/14/2017 | 10:35 AM ---

Message 3

--- Agent 1: Monday 02/13/2017 | 12:07 AM ---

This

is

message

3

 --- Agent 1: Monday 12/19/2016 | 1:31 PM ---

 Message 4

 --- Agent 1: Monday 10/24/2016 | 10:48 AM ---

 Message 5
</code>```

One problem is that some of them have a space before the first ---.  Another is multi-line messages.

What I am trying to do is peel out all the individual messages.  Basically everything between the first occurrence of --- and every other occurrence thereafter.  I would like my result to look like:

```<code>---Agent 1: Wednesday 08/16/2017 | 11:43 AM ---

Message 1
</code>```

I have tried variations of ---.*? (---) (matching every other ---) But then I have no way of parsing out the message itself.  I have also tried to manually do this:

```<code>(?<=\: )(.*?)(?= \|)|(\---)(\r\n|\r|\n)(\r\n|\r|\n)(.*?)(\r\n|\r|\n)(\r\n|\r|\n)(\---)
</code>```

Which works until you have a multi-line message. (message 3)

I have also tried multiple steps -- trimming the first or last --- using str_replace but this is foiled by the ones that have a preceding space!

It's always the second --- after the time, the multi-line message, or the preceding space before --- that trips me up.  Does anyone have a more elegant solution than the monstrosity I am creating?

答:
```<code>/---.*---\s*\R.*(?=---|$)/gsU
</code>```

---.*---\s*\R - selects the 1st line with message description. Than .*(?=---|$) gets the rest of a message up to start of the next one (---) or the end of the string.

Demo and a little explanation

Body:
I am having trouble with a complicated regex.  I have tried this every way I can think of, and I can always only get "almost" there --

I have a block of 5 messages:

---Agent 1: Wednesday 08/16/2017 | 11:43 AM ---

Message 1

--- Agent 1: Friday 06/09/2017 | 9:02 AM ---

Message 2

--- Agent 1: Friday 04/14/2017 | 10:35 AM ---

Message 3

--- Agent 1: Monday 02/13/2017 | 12:07 AM ---

This

is

message

3

 --- Agent 1: Monday 12/19/2016 | 1:31 PM ---

 Message 4

 --- Agent 1: Monday 10/24/2016 | 10:48 AM ---

 Message 5

One problem is that some of them have a space before the first ---.  Another is multi-line messages.

What I am trying to do is peel out all the individual messages.  Basically everything between the first occurrence of --- and every other occurrence thereafter.  I would like my result to look like:

---Agent 1: Wednesday 08/16/2017 | 11:43 AM ---

Message 1

I have tried variations of ---.*? (---) (matching every other ---) But then I have no way of parsing out the message itself.  I have also tried to manually do this:

(?<=\: )(.*?)(?= \|)|(\---)(\r\n|\r|\n)(\r\n|\r|\n)(.*?)(\r\n|\r|\n)(\r\n|\r|\n)(\---)

Which works until you have a multi-line message. (message 3)

I have also tried multiple steps -- trimming the first or last --- using str_replace but this is foiled by the ones that have a preceding space!

It's always the second --- after the time, the multi-line message, or the preceding space before --- that trips me up.  Does anyone have a more elegant solution than the monstrosity I am creating?

Body:
/---.*---\s*\R.*(?=---|$)/gsU

---.*---\s*\R - selects the 1st line with message description. Than .*(?=---|$) gets the rest of a message up to start of the next one (---) or the end of the string.

Demo and a little explanation


问:
How to get the value of 2nd td in html table on click of first td using jquery
I have a requirment where i need to get the value of 2nd td in html table on click of first column in html table. I am using jquery to achieve this.

```<code>$('.tbody').on('click','tr td:nth-child(1)', function () {
    var id = $(this).closest("td").find('td:eq(1)').text();
    alert(id)
});
</code>```

I am using onclick function to get the value of second td as shown in the above code.But i am getting an empty alert. I dont know where i have gone wrong please help.
As per my understanding $(this).closest("td").find('td:eq(1)').text() should search for next td and .text() method should display the value within td isn'tit?

Below snippet will reflect the issue mentioned above

Please help!

Thanks in advance!

$(function () {
    $('.tbody').on('click','tr td:nth-child(1)', function () {
        var id = $(this).closest("td").find('td:eq(1)').text();
        alert(id)
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#items {
    border-collapse: collapse;
    width: 100%;
}
#items th {
    background-color: #009999;
    color: white;
    border : 1px solid;
}
#items td{
    border : 1px solid;
}
#items tbody{
    height:200px;
    overflow-y:auto;
}
#items thead,.tbody{
    display:block;
}</code>```

         Fee Type
  Charges per Qty
  Qty

            a
            b
            c

            d
            e
            f

```

答:
The issue with your logic is that this refers to the td already, so closest('td') isn't going to get the element you need. It's also not the parent of the td you want to target either, so find() won't work. You need to use closest('tr') instead:

```<code>var id = $(this).closest("tr").find('td:eq(1)').text()
</code>```

However, the simplest method to achieve this would be to just use next() as the td elements are siblings:

$(function() {
  $('.tbody').on('click', 'tr td:nth-child(1)', function() {
    var id = $(this).next().text();
    console.log(id);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#items {
  border-collapse: collapse;
  width: 100%;
}

#items th {
  background-color: #009999;
  color: white;
  border: 1px solid;
}

#items td {
  border: 1px solid;
}

#items tbody {
  height: 200px;
  overflow-y: auto;
}

#items thead,
.tbody {
  display: block;
}</code>```

        Fee Type
        Charges per Qty
        Qty

        a
        b
        c

        d
        e
        f

```

Body:
I have a requirment where i need to get the value of 2nd td in html table on click of first column in html table. I am using jquery to achieve this.

$('.tbody').on('click','tr td:nth-child(1)', function () {
    var id = $(this).closest("td").find('td:eq(1)').text();
    alert(id)
});

I am using onclick function to get the value of second td as shown in the above code.But i am getting an empty alert. I dont know where i have gone wrong please help.
As per my understanding $(this).closest("td").find('td:eq(1)').text() should search for next td and .text() method should display the value within td isn'tit?

Below snippet will reflect the issue mentioned above

Please help!

Thanks in advance!

$(function () {
    $('.tbody').on('click','tr td:nth-child(1)', function () {
        var id = $(this).closest("td").find('td:eq(1)').text();
        alert(id)
    });
});

#items {
    border-collapse: collapse;
    width: 100%;
}
#items th {
    background-color: #009999;
    color: white;
    border : 1px solid;
}
#items td{
    border : 1px solid;
}
#items tbody{
    height:200px;
    overflow-y:auto;
}
#items thead,.tbody{
    display:block;
}

         Fee Type
  Charges per Qty
  Qty

            a
            b
            c

            d
            e
            f

Body:
The issue with your logic is that this refers to the td already, so closest('td') isn't going to get the element you need. It's also not the parent of the td you want to target either, so find() won't work. You need to use closest('tr') instead:

var id = $(this).closest("tr").find('td:eq(1)').text()

However, the simplest method to achieve this would be to just use next() as the td elements are siblings:

$(function() {
  $('.tbody').on('click', 'tr td:nth-child(1)', function() {
    var id = $(this).next().text();
    console.log(id);
  });
});

#items {
  border-collapse: collapse;
  width: 100%;
}

#items th {
  background-color: #009999;
  color: white;
  border: 1px solid;
}

#items td {
  border: 1px solid;
}

#items tbody {
  height: 200px;
  overflow-y: auto;
}

#items thead,
.tbody {
  display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <table class="table table-striped table-bordered table-hover table-condensed" style="width: 300px; " id="items">
    <thead>
      <tr>
        <th style="width:100px;">Fee Type</th>
        <th style="width:100px;">Charges per Qty</th>
        <th style="width:100px;">Qty</th>
      </tr>
    </thead>
    <tbody class="tbody">
      <tr>
        <td style="width:100px;">a</td>
        <td style="width:100px;">b</td>
        <td style="width:100px;">c</td>
      </tr>
      <tr>
        <td style="width:100px;">d</td>
        <td style="width:100px;">e</td>
        <td style="width:100px;">f</td>
      </tr>
    </tbody>
  </table>
</div>


答:
Sure. Cast one of the values instead of the result in the end

```<code>SELECT CAST(1 as DECIMAL(21,20)) / 3;
</code>```

SQLFiddle demo

Title: Precision MySql in division

Body:
mysql> SELECT CAST(1 / 3 AS DECIMAL(21,20));
+-------------------------------+
| CAST(1 / 3 AS DECIMAL(21,20)) |
+-------------------------------+
|        0.33333333300000000000 |
+-------------------------------+
1 row in set (0.00 sec)

Is it posible to change the output '0.33333333300000000000' to '0.33333333333333333333' ?

Body:
Sure. Cast one of the values instead of the result in the end

SELECT CAST(1 as DECIMAL(21,20)) / 3;

SQLFiddle demo


问:
When does a JSONObject become unordered?
I understand that a JSONObject contains key-value pairs that are not ordered. But, at what point does a JSONObject change its order? For instance, if I have a JSONObject such as

```<code>{"p1": 1, "p2": 2}
</code>```

Will it become unordered if I don't modify it?

答:
If you want to preserve the order predicted by insertion use :  </p>

```<code>      JSONObject object = new JSONObject(new LinkedHashMap());
</code>```

Body:
I understand that a JSONObject contains key-value pairs that are not ordered. But, at what point does a JSONObject change its order? For instance, if I have a JSONObject such as

{"p1": 1, "p2": 2}

Will it become unordered if I don't modify it?

Body:
If you want to preserve the order predicted by insertion use :

      JSONObject object = new JSONObject(new LinkedHashMap());


问:
How to reduce consecutive integers in an array to hyphenated range expressions?
In JavaScript, how can I convert a sequence of numbers in an array to a range of numbers?  In other words, I want to express consecutive occurring integers (no gaps) as hyphenated ranges.

[2,3,4,5,10,18,19,20] would become [2-5,10,18-20]

[1,6,7,9,10,12] would become [1,6-7,9-10,12]

[3,5,99] would remain [3,5,99]

[5,6,7,8,9,10,11] would become [5-11]

答:
Tiny ES6 module for you guys. It accepts a function to determine when we must break the sequence (breakDetectorFunc param - default is the simple thing for integer sequence input).
NOTICE: since input is abstract - there's no auto-sorting before processing, so if your sequence isn't sorted - do it prior to calling this module

```<code>function defaultIntDetector(a, b){
    return Math.abs(b - a) > 1;
}

/**
 * @param {Array} valuesArray
 * @param {Boolean} [allArraysResult=false] if true - [1,2,3,7] will return [[1,3], [7,7]]. Otherwise [[1.3], 7]
 * @param {SequenceToIntervalsBreakDetector} [breakDetectorFunc] must return true if value1 and value2 can't be in one sequence (if we need a gap here)
 * @return {Array}
 */
const sequenceToIntervals = function (valuesArray, allArraysResult, breakDetectorFunc) {
    if (!breakDetectorFunc){
        breakDetectorFunc = defaultIntDetector;
    }
    if (typeof(allArraysResult) === 'undefined'){
        allArraysResult = false;
    }

    const intervals = [];
    let from = 0, to;
    if (valuesArray instanceof Array) {
        const cnt = valuesArray.length;
        for (let i = 0; i < cnt; i++) {
            to = i;
            if (i < cnt - 1) { // i is not last (to compare to next)
                if (breakDetectorFunc(valuesArray[i], valuesArray[i + 1])) {
                    // break
                    appendLastResult();
                }
            }
        }
        appendLastResult();
    } else {
        throw new Error("input is not an Array");
    }

    function appendLastResult(){
        if (isFinite(from) && isFinite(to)) {
            const vFrom = valuesArray[from];
            const vTo = valuesArray[to];

            if (from === to) {
                intervals.push(
                    allArraysResult
                        ? [vFrom, vTo] // same values array item
                        : vFrom // just a value, no array
                );
            } else if (Math.abs(from - to) === 1) { // sibling items
                if (allArraysResult) {
                    intervals.push([vFrom, vFrom]);
                    intervals.push([vTo, vTo]);
                } else {
                    intervals.push(vFrom, vTo);
                }
            } else {
                intervals.push([vFrom, vTo]); // true interval
            }
            from = to + 1;
        }
    }

    return intervals;
};

module.exports = sequenceToIntervals;

/** @callback SequenceToIntervalsBreakDetector
 @param value1
 @param value2
 @return bool
 */
</code>```

first argument is the input sequence sorted array, second is a boolean flag controlling the output mode: if true - single item (outside the intervals) will be returned as arrays anyway: [1,7],[9,9],[10,10],[12,20], otherwise single items returned as they appear in the input array

for your sample input

```<code>[2,3,4,5,10,18,19,20]
</code>```

it will return:

```<code>sequenceToIntervals([2,3,4,5,10,18,19,20], true) // [[2,5], [10,10], [18,20]]
sequenceToIntervals([2,3,4,5,10,18,19,20], false) // [[2,5], 10, [18,20]]
sequenceToIntervals([2,3,4,5,10,18,19,20]) // [[2,5], 10, [18,20]]
</code>```

Body:
Tiny ES6 module for you guys. It accepts a function to determine when we must break the sequence (breakDetectorFunc param - default is the simple thing for integer sequence input).
NOTICE: since input is abstract - there's no auto-sorting before processing, so if your sequence isn't sorted - do it prior to calling this module

function defaultIntDetector(a, b){
    return Math.abs(b - a) > 1;
}

/**
 * @param {Array} valuesArray
 * @param {Boolean} [allArraysResult=false] if true - [1,2,3,7] will return [[1,3], [7,7]]. Otherwise [[1.3], 7]
 * @param {SequenceToIntervalsBreakDetector} [breakDetectorFunc] must return true if value1 and value2 can't be in one sequence (if we need a gap here)
 * @return {Array}
 */
const sequenceToIntervals = function (valuesArray, allArraysResult, breakDetectorFunc) {
    if (!breakDetectorFunc){
        breakDetectorFunc = defaultIntDetector;
    }
    if (typeof(allArraysResult) === 'undefined'){
        allArraysResult = false;
    }

    const intervals = [];
    let from = 0, to;
    if (valuesArray instanceof Array) {
        const cnt = valuesArray.length;
        for (let i = 0; i < cnt; i++) {
            to = i;
            if (i < cnt - 1) { // i is not last (to compare to next)
                if (breakDetectorFunc(valuesArray[i], valuesArray[i + 1])) {
                    // break
                    appendLastResult();
                }
            }
        }
        appendLastResult();
    } else {
        throw new Error("input is not an Array");
    }

    function appendLastResult(){
        if (isFinite(from) && isFinite(to)) {
            const vFrom = valuesArray[from];
            const vTo = valuesArray[to];

            if (from === to) {
                intervals.push(
                    allArraysResult
                        ? [vFrom, vTo] // same values array item
                        : vFrom // just a value, no array
                );
            } else if (Math.abs(from - to) === 1) { // sibling items
                if (allArraysResult) {
                    intervals.push([vFrom, vFrom]);
                    intervals.push([vTo, vTo]);
                } else {
                    intervals.push(vFrom, vTo);
                }
            } else {
                intervals.push([vFrom, vTo]); // true interval
            }
            from = to + 1;
        }
    }

    return intervals;
};

module.exports = sequenceToIntervals;

/** @callback SequenceToIntervalsBreakDetector
 @param value1
 @param value2
 @return bool
 */

first argument is the input sequence sorted array, second is a boolean flag controlling the output mode: if true - single item (outside the intervals) will be returned as arrays anyway: [1,7],[9,9],[10,10],[12,20], otherwise single items returned as they appear in the input array

for your sample input

[2,3,4,5,10,18,19,20]

it will return:

sequenceToIntervals([2,3,4,5,10,18,19,20], true) // [[2,5], [10,10], [18,20]]
sequenceToIntervals([2,3,4,5,10,18,19,20], false) // [[2,5], 10, [18,20]]
sequenceToIntervals([2,3,4,5,10,18,19,20]) // [[2,5], 10, [18,20]]


问:
Role Based Access Control
Is there any open-source, PHP based, role-based access control system that can be used for CodeIgniter?

答:
Maybe I'm misunderstanding the question, but isn't the whole point of Role-Based Access Control (RBAC) to avoid Access Control Lists (ACLs)?

RBAC differs from access control lists (ACLs) (...) in that it assigns permissions to specific operations with meaning in the organization, rather than to low-level data objects. For example, an access control list could be used to grant or deny write access to a particular system file, but it would not say in what ways that file could be changed. In an RBAC-based system, an operation might be to create a 'credit account' transaction in a financial application (...). The assignment of permission to perform a particular operation is meaningful because the operations are fine-grained and themselves have meaning within the application.
(Quote: Wikipedia)

I don't know the specifics on Zend_ACL or the other implementations mentioned, but if they are ACL-based, I would not recommend using them for role-based authorization.

OwnerDisplayName: jericho

Title: Role Based Access Control

OwnerDisplayName: Jens Roland


问:
stl vector reserve
I was trying to pre-allocate a vector of integer like this

```<code>vector<int> tmp_color; tmp_color.reserve(node_obj[node].c_max);
    for(int tmp_color_idx = 0; tmp_color_idx < node_obj[node].c_max; tmp_color_idx++)
         tmp_color[tmp_color_idx] = tmp_color_idx;
</code>```

where node_obj[node].c_max is > 0 (I checked). size of tmp_color appears to be zero anyways, after the for loop. If there something wrong with the code?

Thanks

答:
If you want to make assignments in the loop as you wrote I suggest the following way:</p>

```<code>vector<int> tmp_color(node_obj[node].c_max);
for(int tmp_color_idx = 0; tmp_color_idx < node_obj[node].c_max; tmp_color_idx++)
     tmp_color[tmp_color_idx] = tmp_color_idx;
</code>```

Title: stl vector reserve

Body:
I was trying to pre-allocate a vector of integer like this

vector<int> tmp_color; tmp_color.reserve(node_obj[node].c_max);
    for(int tmp_color_idx = 0; tmp_color_idx < node_obj[node].c_max; tmp_color_idx++)
         tmp_color[tmp_color_idx] = tmp_color_idx;

where node_obj[node].c_max is > 0 (I checked). size of tmp_color appears to be zero anyways, after the for loop. If there something wrong with the code?

Thanks

Body:
If you want to make assignments in the loop as you wrote I suggest the following way:

vector<int> tmp_color(node_obj[node].c_max);
for(int tmp_color_idx = 0; tmp_color_idx < node_obj[node].c_max; tmp_color_idx++)
     tmp_color[tmp_color_idx] = tmp_color_idx;


问:
How to find any element in a HashMap where a given condition about that element is true

Given an object, MyObj which for our purposes holds String message among other fields.

Given a HashMap, Map <MultiKey<String>,MyObj> map.

I want to loop through the HashMap finding any element where the MyObj's message is searchValue. I'm essentially trying to use stream().anyMatch() on a Map, I simply want to know if searchValue exists even once anywhere - i.e. short circuiting is preferable.

Foreach loop:

```<code>map.forEach((k,v) -> {
    if (v.message.equalsIgnoreCase(searchValue)) {
        return true;
    }
}
</code>```

The issue with this is that it doesn't terminate early, neither break or return can be used in this lambda to terminate the loop early.

I see the stream anyMatch() function:

```<code> map.entrySet().stream().anymatch(....
</code>```

but I can't figure out the proper syntax - if that will work in this case at all (can it still be used if I'm not comparing the map's elements, rather I'm comparing each element's fields).

答:
Working answers from previous posters (is there a way to tell which is more efficient?)

```<code> //Note: anyMatch can be switched with noneMatch if need be
</code>```

@JimGarrison: (seems the shortest/readable):

```<code>if (map.values().stream().anyMatch(v -> v.message.equalsIgnoreCase(searchValue))
    {...}
</code>```

@Louis Wasserman:

```<code>if (map.values().stream().map(v -> v.message).anyMatch(searchValue::equalsIgnoreCase))
   {...}
</code>```

@P3trur0:

```<code>if (null != map.values().stream().filter(v -> v.message.equalsIgnoreCase(searchValue)).findAny().orElse(null))
    {...}
</code>```

Body:
Given an object, MyObj which for our purposes holds String message among other fields.

Given a HashMap, Map <MultiKey<String>,MyObj> map.

I want to loop through the HashMap finding any element where the MyObj's message is searchValue. I'm essentially trying to use stream().anyMatch() on a Map, I simply want to know if searchValue exists even once anywhere - i.e. short circuiting is preferable.

Foreach loop:

map.forEach((k,v) -> {
    if (v.message.equalsIgnoreCase(searchValue)) {
        return true;
    }
}

The issue with this is that it doesn't terminate early, neither break or return can be used in this lambda to terminate the loop early.

I see the stream anyMatch() function:

 map.entrySet().stream().anymatch(....

but I can't figure out the proper syntax - if that will work in this case at all (can it still be used if I'm not comparing the map's elements, rather I'm comparing each element's fields).

Body:
Working answers from previous posters (is there a way to tell which is more efficient?)

 //Note: anyMatch can be switched with noneMatch if need be

@JimGarrison: (seems the shortest/readable):

if (map.values().stream().anyMatch(v -> v.message.equalsIgnoreCase(searchValue))
    {...}

@Louis Wasserman:

if (map.values().stream().map(v -> v.message).anyMatch(searchValue::equalsIgnoreCase))
   {...}

@P3trur0:

if (null != map.values().stream().filter(v -> v.message.equalsIgnoreCase(searchValue)).findAny().orElse(null))
    {...}


问:
Force git to run post-receive hook, even if everything is "up-to-date"
How do I force git to run a post-receive hook on a server even if I don't have a new commit to push?

Background

I use git to automatically deploy a website to a server. I have a bare repo in a protected area of the server and a post-receive hook that checks out the contents and systematically copies over certain files into a public_html folder. (Inspired by this tutorial)

I got tired of modifying the post-receive hook manually on the server, so my post-receive hook now actually copies over a new version of itself from the repo:

```<code>#!/bin/sh

rm -rf ~/../protected/*
GIT_WORK_TREE=~/../protected git checkout -f

# Rewrite over this file with any updates from the post-receive file
cp ~/../protected/post-receive hooks/post-receive

# Delete public_html
# Copy stuff public_html
</code>```

The problem, of course, is that the new post-receive hook never gets run. A seemingly simple solution would be merely to push again, but now  everything is already up to date. This is annoying, because it requires me to fake a new commit every time I update the post-receive hook. Is there a way to invoke the post-receive hook without faking a commit or sshing in?

What I tried

```<code>git push
git push -f
</code>```

答:
In my case i login into remote and run:

$ sh project.git/hooks/post-receive

works fine!

Body:
How do I force git to run a post-receive hook on a server even if I don't have a new commit to push?

Background

I use git to automatically deploy a website to a server. I have a bare repo in a protected area of the server and a post-receive hook that checks out the contents and systematically copies over certain files into a public_html folder. (Inspired by this tutorial)

I got tired of modifying the post-receive hook manually on the server, so my post-receive hook now actually copies over a new version of itself from the repo:

#!/bin/sh

rm -rf ~/../protected/*
GIT_WORK_TREE=~/../protected git checkout -f

# Rewrite over this file with any updates from the post-receive file
cp ~/../protected/post-receive hooks/post-receive

# Delete public_html
# Copy stuff public_html

The problem, of course, is that the new post-receive hook never gets run. A seemingly simple solution would be merely to push again, but now  everything is already up to date. This is annoying, because it requires me to fake a new commit every time I update the post-receive hook. Is there a way to invoke the post-receive hook without faking a commit or sshing in?

What I tried

git push
git push -f


问:
Swift get associated value in enums without switch
I have enum:

```<code>enum RetailDemandReturnOperation {
    case salesReturn(value: MSRetailSalesReturnRealm)
    case demand(value: MSRetailDemandRealm)
}
</code>```

MSRetailDemandRealm and MSRetailDemandRealm are both implement same protocol, that have variables title and stats. I want to extract this values, but i don't care of which object actually stored in. Consider following:

```<code> switch data! {
        case .salesReturn(let object):
            titleString = object.title
            statistics = object.stats
        case .demand(let object):
            titleString = object.title
            statistics = object.stats
          break
        }
</code>```

I have to go in each enum value to get property of protocol. Is any way i can do it shorter and cleaner? Get associated value, no matter what it is, as long as it conforms to my protocol, and get protocol values?
Thanks.

答:
You could add a property to your enum that returns the protocol. For example:

```<code>enum RetailDemandReturnOperation {
    case salesReturn(value: MSRetailSalesReturnRealm)
    case demand(value: MSRetailDemandRealm)

    var realm: MSRetailRealm {
        switch self {
        case .salesReturn(let realm):
            return realm
        case .demand(let realm):
            return realm
        }
    }
}
</code>```

Then, when you want to access those properties on a specific value of the enum, just use:

```<code>let operation = RetailDemandReturnOperation.salesReturn(value: MSRetailSalesReturnRealm())
let title = operation.realm.title
</code>```

Body:
I have enum:

enum RetailDemandReturnOperation {
    case salesReturn(value: MSRetailSalesReturnRealm)
    case demand(value: MSRetailDemandRealm)
}

MSRetailDemandRealm and MSRetailDemandRealm are both implement same protocol, that have variables title and stats. I want to extract this values, but i don't care of which object actually stored in. Consider following:

 switch data! {
        case .salesReturn(let object):
            titleString = object.title
            statistics = object.stats
        case .demand(let object):
            titleString = object.title
            statistics = object.stats
          break
        }

I have to go in each enum value to get property of protocol. Is any way i can do it shorter and cleaner? Get associated value, no matter what it is, as long as it conforms to my protocol, and get protocol values?
Thanks.

Body:
You could add a property to your enum that returns the protocol. For example:

enum RetailDemandReturnOperation {
    case salesReturn(value: MSRetailSalesReturnRealm)
    case demand(value: MSRetailDemandRealm)

    var realm: MSRetailRealm {
        switch self {
        case .salesReturn(let realm):
            return realm
        case .demand(let realm):
            return realm
        }
    }
}

Then, when you want to access those properties on a specific value of the enum, just use:

let operation = RetailDemandReturnOperation.salesReturn(value: MSRetailSalesReturnRealm())
let title = operation.realm.title


问:
convert string data in dataframe into double
I have a csv file containing double type.When i load to a dataframe i got this message telling me that the type string is java.lang.String cannot be cast to java.lang.Double although my data are numeric.How do i get a dataframe from this csv file containing double type.how should i modify my code.

```<code>import org.apache.spark.sql._
import org.apache.spark.sql.functions._
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.types.{ArrayType, DoubleType}
import org.apache.spark.sql.functions.split
import scala.collection.mutable._

object Example extends App {

val spark = SparkSession.builder.master("local").appName("my-spark-app").getOrCreate()
val data=spark.read.csv("C://lpsa.data").toDF("col1","col2","col3","col4","col5","col6","col7","col8","col9")
val data2=data.select("col2","col3","col4","col5","col6","col7")
</code>```

What sould i make to transform each row in the dataframe into double type? Thanks

答:
I believe using sparks inferSchema option comes in handy while reading the csv file. Below is the code to automatically detect your columns as double type :

```<code>val data = spark.read
                .format("csv")
                .option("header", "false")
                .option("inferSchema", "true")
                .load("C://lpsa.data").toDF()

Note: I am using spark version 2.2.0
</code>```

Body:
I have a csv file containing double type.When i load to a dataframe i got this message telling me that the type string is java.lang.String cannot be cast to java.lang.Double although my data are numeric.How do i get a dataframe from this csv file containing double type.how should i modify my code.

import org.apache.spark.sql._
import org.apache.spark.sql.functions._
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.types.{ArrayType, DoubleType}
import org.apache.spark.sql.functions.split
import scala.collection.mutable._

object Example extends App {

val spark = SparkSession.builder.master("local").appName("my-spark-app").getOrCreate()
val data=spark.read.csv("C://lpsa.data").toDF("col1","col2","col3","col4","col5","col6","col7","col8","col9")
val data2=data.select("col2","col3","col4","col5","col6","col7")

What sould i make to transform each row in the dataframe into double type? Thanks

Body:
I believe using sparks inferSchema option comes in handy while reading the csv file. Below is the code to automatically detect your columns as double type :

val data = spark.read
                .format("csv")
                .option("header", "false")
                .option("inferSchema", "true")
                .load("C://lpsa.data").toDF()

Note: I am using spark version 2.2.0


问:
How to efficiently alias a float as both a named member and an element of an array?
I am implementing a particle-based fluid simulation. To represent vectors such as velocity, acceleration etc I have defined a class that looks like this

```<code>class Vec3f {
public:
    float x, y, z;

    // ... bunch of constructors, operators and utility functions
}
</code>```

I'm using the library nanoflann for kd-tree searches. To accommodate for arbitrary class designs, nanoflann requires a user-defined adaptor class that the kd-tree class then queries to get info about the particle dataset. One function that the adaptor has to offer, as described in the nanoflann documentation is the following.

```<code>// Must return the dim'th component of the idx'th point in the class:
inline T kdtree_get_pt(const size_t idx, int dim) const { ... }
</code>```

The problem is that this interface does not work seamlessly with the x, y, z representation. Naively, it would need to do something like this

```<code>inline float kdtree_get_pt(const size_t idx, int dim) const {
    switch(dim) {
    case 0:
        return particlearray[idx].x;
    case 1:
        return particlearray[idx].y;
    case 2:
        return particlearray[idx].z;
    }
}
</code>```

Building and querying the kd-tree consumes a significant portion of my app's runtime and kd_tree_get_pt gets queried multiple times in the process so I need it to be optimized. The following solution should be faster.

```<code>class Vec3f {
public:
    float values[3];
    // ...
}

// Then inside the adaptor class
inline float kdtree_get_pt(const size_t idx, int dim) const {
    return particlearrray[idx].values[dim];
}
</code>```

However, I much prefer the x, y, z interface for my equations. Now that the problem is clear, my question is how can I keep the x, y, z notation for my equations without making kdtree_get_pt suboptimal.

Solutions I have considered:

Vec3f has member float values[3] and getters in the form of float& x(). The function call should be optimized away completely so this almost works but I do not want to have to add the parentheses in my equations if I can avoid it. eg I want to be able to write vec1.x - vec2.x instead of vec1.x() - vec2.x(). As far as I know, C++ does not offer a way to "disguise" a function call as a member variable, excluding preprocessor macros which I do not consider a safe solution.

Vec3f has members float values[3] and float& x, y, z where the latter are initialized to point to the corresponding floats in the array. I thought they would be optimized away as they are known at compile time and obviously cannot change value after initialization, but even with optimizations on, MSVC++ seems to actually store the float&s as can be seen by sizeof(Vec3f) growing by 12 bytes after their addition. This doubles the storage size of my dataset which raises a concern for cache misses when working with arbitrarily large datasets.

kdtree_get_pt uses float& values[3] to point to x, y, z. This might eliminate the branching cost, but I don't believe the extra level of indirection, nor the need to initialize all 3 references can be optimized away so it is presumably slower than the return particlearrray[idx][dim]` version.

kdtree_get_pt uses reinterpret_cast or pointer magic to directly point into Vec3f's members. Given a Vec3f object's address, I believe x, y, z are guaranteed to be stored in that order with the first one stored at the same address as the one given by the & operator on the Vec3f object, but even so I'm confused as to whether there exists a well-defined way to observe them.

答:
However, I much prefer the x, y, z interface for my equations. Now that the problem is clear, my question is how can I keep the x, y, z

Declare x,y,z as local references before calculation:

```<code>auto& [x1, y1, z1] = v1.values;
auto& [x2, y2, z2] = v2.values;
return x1*x2 + y1*y2 + z1*z2;
</code>```

For pre-C++17, you need more verbose:

```<code>auto& x = values[0];
auto& y = values[1];
auto& z = values[2];
</code>```

The compiler will not need to use any storage for these references.

This of course introduces some repetition; One line (in C++17) per vector per function.

Extra parentheses introduced by your first suggestion is another good way to go. Whether the introduction of parentheses is better or worse than local reference declaration boiler plate depends on the use case and personal preference.

Edit: Another alternative: Define operator[] and use named constants for indices.

```<code>namespace axes {
    enum axes {
        x, y, z
    };
}

struct Vec3f {
    float values[3];
    float& operator[](size_t index)       { return values[index]; }
    float  operator[](size_t index) const { return values[index]; }
};

// usage
using namespace axes;
return v1[x]*v2[x] + v1[y]*v2[y] + v1[z]*v2[z];
</code>```

Body:
I am implementing a particle-based fluid simulation. To represent vectors such as velocity, acceleration etc I have defined a class that looks like this

class Vec3f {
public:
    float x, y, z;

    // ... bunch of constructors, operators and utility functions
}

I'm using the library nanoflann for kd-tree searches. To accommodate for arbitrary class designs, nanoflann requires a user-defined adaptor class that the kd-tree class then queries to get info about the particle dataset. One function that the adaptor has to offer, as described in the nanoflann documentation is the following.

// Must return the dim'th component of the idx'th point in the class:
inline T kdtree_get_pt(const size_t idx, int dim) const { ... }

The problem is that this interface does not work seamlessly with the x, y, z representation. Naively, it would need to do something like this

inline float kdtree_get_pt(const size_t idx, int dim) const {
    switch(dim) {
    case 0:
        return particlearray[idx].x;
    case 1:
        return particlearray[idx].y;
    case 2:
        return particlearray[idx].z;
    }
}

Building and querying the kd-tree consumes a significant portion of my app's runtime and kd_tree_get_pt gets queried multiple times in the process so I need it to be optimized. The following solution should be faster.

class Vec3f {
public:
    float values[3];
    // ...
}

// Then inside the adaptor class
inline float kdtree_get_pt(const size_t idx, int dim) const {
    return particlearrray[idx].values[dim];
}

However, I much prefer the x, y, z interface for my equations. Now that the problem is clear, my question is how can I keep the x, y, z notation for my equations without making kdtree_get_pt suboptimal.

Solutions I have considered:

Vec3f has member float values[3] and getters in the form of float& x(). The function call should be optimized away completely so this almost works but I do not want to have to add the parentheses in my equations if I can avoid it. eg I want to be able to write vec1.x - vec2.x instead of vec1.x() - vec2.x(). As far as I know, C++ does not offer a way to "disguise" a function call as a member variable, excluding preprocessor macros which I do not consider a safe solution.

Vec3f has members float values[3] and float& x, y, z where the latter are initialized to point to the corresponding floats in the array. I thought they would be optimized away as they are known at compile time and obviously cannot change value after initialization, but even with optimizations on, MSVC++ seems to actually store the float&s as can be seen by sizeof(Vec3f) growing by 12 bytes after their addition. This doubles the storage size of my dataset which raises a concern for cache misses when working with arbitrarily large datasets.

kdtree_get_pt uses float& values[3] to point to x, y, z. This might eliminate the branching cost, but I don't believe the extra level of indirection, nor the need to initialize all 3 references can be optimized away so it is presumably slower than the return particlearrray[idx][dim]` version.

kdtree_get_pt uses reinterpret_cast or pointer magic to directly point into Vec3f's members. Given a Vec3f object's address, I believe x, y, z are guaranteed to be stored in that order with the first one stored at the same address as the one given by the & operator on the Vec3f object, but even so I'm confused as to whether there exists a well-defined way to observe them.

Body:
However, I much prefer the x, y, z interface for my equations. Now that the problem is clear, my question is how can I keep the x, y, z

Declare x,y,z as local references before calculation:

auto& [x1, y1, z1] = v1.values;
auto& [x2, y2, z2] = v2.values;
return x1*x2 + y1*y2 + z1*z2;

For pre-C++17, you need more verbose:

auto& x = values[0];
auto& y = values[1];
auto& z = values[2];

The compiler will not need to use any storage for these references.

This of course introduces some repetition; One line (in C++17) per vector per function.

Extra parentheses introduced by your first suggestion is another good way to go. Whether the introduction of parentheses is better or worse than local reference declaration boiler plate depends on the use case and personal preference.

Edit: Another alternative: Define operator[] and use named constants for indices.

namespace axes {
    enum axes {
        x, y, z
    };
}

struct Vec3f {
    float values[3];
    float& operator[](size_t index)       { return values[index]; }
    float  operator[](size_t index) const { return values[index]; }
};

// usage
using namespace axes;
return v1[x]*v2[x] + v1[y]*v2[y] + v1[z]*v2[z];


问:
Merge commits from multiple users
Our organization has decided to use Github to make simultaneous code modification possible. One of the features we are looking for is to be able to merge all the changes made on one file by multiple developers and replace the existing (or create a new) file. We are not really sure if this is possible.

I used Github before but I had never tried collaborating with other people. I just mainly use it to control my development progress.

Main question:
2 commits from different users.

Is it possible to merge 2 commits (or more) from multiple users if the changes they are proposing only affects the same file?

NOTE:

Working A: Removed and edited some lines

Working B: Added some new lines

答: Yes. You can use git merge or git cherry-pick (depends how you want history of project to look like). If all users have write access to the same repo, you may want to allow them to pull and push from/to specific branch instead.</p>

Title: Merge commits from multiple users


问:
DragDropContext is an invalid component
I'm trying to create a DragDropContext but failing.

```<code>var root = <CommentBox url="/metis/api/shifts" pollInterval={2000} />;

var AppDnD = ReactDnD.DragDropContext(ReactDnDMultiBackend.default(RDMBHTML5toTouch.default))(root);

ReactDOM.render(AppDnD, document.getElementById('content'));
</code>```

This gives...

ReactDOM.render(): Invalid component element. Instead of passing a
  class like Foo, pass React.createElement(Foo) or .

... in the console.

I thought that decorating a React object results in a new React object. So why doesn't the render method accept this object?

答:
There is difference between React component and React element. In the docs of react-dnd, it is written that ReactDnD.DragDropContext returns a component (which means AppDnD is a component), but React.render expect an element as first parameter. So pass an element to render method like this

ReactDOM.render(<AppDnD />, document.getElementById('content'));

Title: DragDropContext is an invalid component

Body:
I'm trying to create a DragDropContext but failing.

var root = <CommentBox url="/metis/api/shifts" pollInterval={2000} />;

var AppDnD = ReactDnD.DragDropContext(ReactDnDMultiBackend.default(RDMBHTML5toTouch.default))(root);

ReactDOM.render(AppDnD, document.getElementById('content'));

This gives...

ReactDOM.render(): Invalid component element. Instead of passing a
  class like Foo, pass React.createElement(Foo) or .

... in the console.

I thought that decorating a React object results in a new React object. So why doesn't the render method accept this object?


问:
elasticsearch date range get yesterday
I'm looking a way to get the data from "yesterday"
instead of:

```<code>"range" : {
    "price" : {
        "gt" : "2014-11-24",
        "lt" : "2014-11-26"
    }
}
</code>```

I would like something like:

```<code>"range" : {
    "price" : {
        "eq" : "2014-11-25"
    }
}
</code>```

Does anybody think it could be possible?

I'm thinking of something like:

```<code>"range" : {
    "price" : {
        "gt" : "now-2d",
        "lt" : "now"
    }
}
</code>```

But I would like to get data from 00:00 am to  00:00 pm

答:
The answer from @andrei-stefan is the way to do this, but I wanted to add a little extra example for other people hitting this question.

If you wanted to get data from yesterday between 12:00pm and 1:00pm rather than the whole day, you could do that with a little more date math:

```<code>  "query": {
    "range": {
      "price": {
        "gt": "now-1d/d+12h",
        "lt": "now-1d/d+13h"
      }
    }
  }
</code>```

https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#date-math

Title: elasticsearch date range get yesterday

Body:
I'm looking a way to get the data from "yesterday"
instead of:

"range" : {
    "price" : {
        "gt" : "2014-11-24",
        "lt" : "2014-11-26"
    }
}

I would like something like:

"range" : {
    "price" : {
        "eq" : "2014-11-25"
    }
}

Does anybody think it could be possible?

I'm thinking of something like:

"range" : {
    "price" : {
        "gt" : "now-2d",
        "lt" : "now"
    }
}

But I would like to get data from 00:00 am to  00:00 pm

Body:
The answer from @andrei-stefan is the way to do this, but I wanted to add a little extra example for other people hitting this question.

If you wanted to get data from yesterday between 12:00pm and 1:00pm rather than the whole day, you could do that with a little more date math:

  "query": {
    "range": {
      "price": {
        "gt": "now-1d/d+12h",
        "lt": "now-1d/d+13h"
      }
    }
  }

https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#date-math


问:
how to speed up load time for MFC ribbon application
I have a native MFC C++ application for which I've got a ribbon UI based version and a toolbar based version.  Both EXEs are similar size (~30mb), but running the ribbon based version takes about 25s whereas the toolbar version takes about 5s.  This is just to get the frame window displayed with tools.  I've profiled the start up of the ribbon UI based version, and sure enough the time is being spent in CMFCRibbonBar::LoadFromResource and deeper down in

```<code>BOOL CMFCRibbonInfoLoader::LoadImage(CMFCRibbonInfo::XImage& image, BOOL bSingle)
{
'
'
'
    image.m_Image.SetTransparentColor(GetGlobalData()->clrBtnFace);  // 15%
    image.m_Image.SmoothResize(dblScale);                            // 64%
'
}
</code>```

Digging deeper, a lot of time seems to be spent manually shading the toolbar ~44% of the total time.

Is there any way to speed up this load time, possibly by setting a non-transparent drawing scheme?  25 seconds to run a program seems a bit excessive, this is on an 8 core 4ghz AMD 8350 with the EXE image coming from an SSD.

Edit:  Tried the following which helped understand the problem but doesn't really make for a useful answer.

After some poking around, it seems a call to  afxGlobalData.EnableRibbonImageScale(FALSE); disables the scaling but can leave poor results visually on some monitors. If the image sizes are correct for the monitor to start with, 40x40 pixels on my 1920x1080 display, the scaling will also get skipped. I haven't tried it yet, but I'd imagine if you specify HDPI images for all the ribbon controls and you are lucky enough to get 1:1 scaling for your HDPI images, it would also get skipped. Searching the MFC source code (\Program Files (x86)\Microsoft Visual Studio 14.0\VC\atlmfc\include\afxglobals.h) for m_bIsRibbonImageScale and m_dblRibbonImageScale yield most of the relevant code.

If the large button images aren't 32x32 the ribbon editor seems to treat them as they were, and chops the base BMP up incorrectly.  So resizing a the base large button BMP to 40x40 resulted in garbage on screen.

Edit: I had thought Vlad's answer would work, but apparently the XML used in an MFC ribbon resource is not Ribbon XML.  See related question on MSDN here.

Edit Further discussion on MSDN here

答:
Problem solved: Configuration -> Manifest Tool -> Input And Output -> Enable DPI Awareness NO

NO, is the solution. The default value is unfortunately YES.

Body:
I have a native MFC C++ application for which I've got a ribbon UI based version and a toolbar based version.  Both EXEs are similar size (~30mb), but running the ribbon based version takes about 25s whereas the toolbar version takes about 5s.  This is just to get the frame window displayed with tools.  I've profiled the start up of the ribbon UI based version, and sure enough the time is being spent in CMFCRibbonBar::LoadFromResource and deeper down in

BOOL CMFCRibbonInfoLoader::LoadImage(CMFCRibbonInfo::XImage& image, BOOL bSingle)
{
'
'
'
    image.m_Image.SetTransparentColor(GetGlobalData()->clrBtnFace);  // 15%
    image.m_Image.SmoothResize(dblScale);                            // 64%
'
}

Digging deeper, a lot of time seems to be spent manually shading the toolbar ~44% of the total time.

Is there any way to speed up this load time, possibly by setting a non-transparent drawing scheme?  25 seconds to run a program seems a bit excessive, this is on an 8 core 4ghz AMD 8350 with the EXE image coming from an SSD.

Edit:  Tried the following which helped understand the problem but doesn't really make for a useful answer.

After some poking around, it seems a call to  afxGlobalData.EnableRibbonImageScale(FALSE); disables the scaling but can leave poor results visually on some monitors. If the image sizes are correct for the monitor to start with, 40x40 pixels on my 1920x1080 display, the scaling will also get skipped. I haven't tried it yet, but I'd imagine if you specify HDPI images for all the ribbon controls and you are lucky enough to get 1:1 scaling for your HDPI images, it would also get skipped. Searching the MFC source code (\Program Files (x86)\Microsoft Visual Studio 14.0\VC\atlmfc\include\afxglobals.h) for m_bIsRibbonImageScale and m_dblRibbonImageScale yield most of the relevant code.

If the large button images aren't 32x32 the ribbon editor seems to treat them as they were, and chops the base BMP up incorrectly.  So resizing a the base large button BMP to 40x40 resulted in garbage on screen.

Edit: I had thought Vlad's answer would work, but apparently the XML used in an MFC ribbon resource is not Ribbon XML.  See related question on MSDN here.

Edit Further discussion on MSDN here


问:
Class conforming to Codable protocol fails with encodeWithCoder: unrecognized selector sent to instance
I know that there are several questions similar to this, that tend to all revolve around the class not conforming to the protocol properly, but that should not be the immediate issue here.

The following is a condensed version of the code that is currently giving me this problem:

```<code>enum Binary: Int {
    case a = 0
    case b = 1
    case c = 9
}

final class MyClass: NSCoder {
    var string: String?
    var date: Date?
    var binary: Binary = .c

    override init() { }

    enum CodingKeys: CodingKey {
        case string, date, binary
    }
}

extension MyClass: Codable {
    convenience init(from decoder: Decoder) throws {
        self.init()

        let values = try decoder.container(keyedBy: CodingKeys.self)
        string = try values.decode(String.self, forKey: .string)
        date = try values.decode(Date.self, forKey: .date)
        binary = try Binary(rawValue: values.decode(Int.self, forKey: .binary)) ?? .c
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(string, forKey: .string)
        try container.encode(date, forKey: .date)
        try container.encode(binary.rawValue, forKey: .binary)
    }
}
</code>```

I have created the following class which then attempts to call MyClass with the purpose of writing & reading it to UserDefaults:

```<code>class MyClassController {
    private let myClass: MyClass

    init() {
        self.myClass = MyClass()
        self.myClass.string = "string"
        self.myClass.date = Date()
        self.myClass.binary = .a
    }

    func writeMyClass() {
        let encodedData = NSKeyedArchiver.archivedData(withRootObject: myClass)
        UserDefaults.standard.set(encodedData, forKey: String(describing: MyClass.self))
    }

    func readMyClass() {
        if let decoded = UserDefaults.standard.object(forKey: String(describing: MyClass.self)) as? Data,
            let myClass = NSKeyedUnarchiver.unarchiveObject(with: decoded as Data) as? MyClass {
            print("string: \(myClass.string ?? "nil") date: \(myClass.date ?? Date()) binary: \(myClass.binary)")
        }
    }
}
</code>```

As soon as I call the writeMyClass function though, I get this error:

[DemoDecoder.MyClass encodeWithCoder:]: unrecognized selector sent to
  instance #blahblah#

Two things I have also tried:

Adding func encode(with aCoder: NSCoder) to MyClass

Removed all properties from MyClass & CodingKeys and the init/encode functions

答:
You have a lot of mismatched attempts and various encoding/decoding mechanisms.

NSKeyedArchiver and NSKeyedUnarchiver require that all involved types conform to the NSCoding protocol. This is the older mechanism from the Objective-C frameworks.

The protocols Codable, Encoder, and Decoder are new to Swift 4. Such data types should be used with Swift encoder and decoders such as JSONEncoder and JSONDecoder or PropertyListEncoder and PropertyListDecoder.

I suggest you remove the reference to NSCoder and remove the uses of NSKeyedArchiver and NSKeyedUnarchiver. Since you have implemented the Codable protocol, use an appropriate Swift encoder and decoder. In your case you want to use PropertyListEncoder and PropertyListDecoder.

Once that is done you should probably change MyClass to be a struct instead of a class.

You should also avoid use UserDefaults to store data. Write the encoded data to a plist file instead.

Body:
I know that there are several questions similar to this, that tend to all revolve around the class not conforming to the protocol properly, but that should not be the immediate issue here.

The following is a condensed version of the code that is currently giving me this problem:

enum Binary: Int {
    case a = 0
    case b = 1
    case c = 9
}

final class MyClass: NSCoder {
    var string: String?
    var date: Date?
    var binary: Binary = .c

    override init() { }

    enum CodingKeys: CodingKey {
        case string, date, binary
    }
}

extension MyClass: Codable {
    convenience init(from decoder: Decoder) throws {
        self.init()

        let values = try decoder.container(keyedBy: CodingKeys.self)
        string = try values.decode(String.self, forKey: .string)
        date = try values.decode(Date.self, forKey: .date)
        binary = try Binary(rawValue: values.decode(Int.self, forKey: .binary)) ?? .c
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(string, forKey: .string)
        try container.encode(date, forKey: .date)
        try container.encode(binary.rawValue, forKey: .binary)
    }
}

I have created the following class which then attempts to call MyClass with the purpose of writing & reading it to UserDefaults:

class MyClassController {
    private let myClass: MyClass

    init() {
        self.myClass = MyClass()
        self.myClass.string = "string"
        self.myClass.date = Date()
        self.myClass.binary = .a
    }

    func writeMyClass() {
        let encodedData = NSKeyedArchiver.archivedData(withRootObject: myClass)
        UserDefaults.standard.set(encodedData, forKey: String(describing: MyClass.self))
    }

    func readMyClass() {
        if let decoded = UserDefaults.standard.object(forKey: String(describing: MyClass.self)) as? Data,
            let myClass = NSKeyedUnarchiver.unarchiveObject(with: decoded as Data) as? MyClass {
            print("string: \(myClass.string ?? "nil") date: \(myClass.date ?? Date()) binary: \(myClass.binary)")
        }
    }
}

As soon as I call the writeMyClass function though, I get this error:

[DemoDecoder.MyClass encodeWithCoder:]: unrecognized selector sent to
  instance #blahblah#

Two things I have also tried:

Adding func encode(with aCoder: NSCoder) to MyClass

Removed all properties from MyClass & CodingKeys and the init/encode functions


问:
Android - how to get ListView to line up underneath Text View
I am attempting to put a ListView beneath a Text View in an Android App. However, the first line of the ListView shows up on the same line as the TextView. How do I get this to move underneath?

Here is the layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    <TextView android:id="@+id/android:question"
          android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/dummy_question" />
    <ListView android:id="@+id/android:list"
          android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    <TextView android:id="@+id/android:empty"
          android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/no_notes"/>

</LinearLayout>
</code>```

答:
I see two issues. First, as chirag mentioned, you need to set the ListView orientation. Second, a listView cannot 'wrap content' for height. What would it wrap to? One row, two? Basically, a listView has no idea how tall you want it to be. Try this:</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:orientation="vertical">

<TextView android:id="@+id/android:question"
      android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/dummy_question" />
<ListView android:id="@+id/android:list"
      android:layout_width="wrap_content"
        android:layout_height="0px" android:layout_weight="1" />
<TextView android:id="@+id/android:empty"
      android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/no_notes"/>
</LinearLayout>
</code>```

Body:
I am attempting to put a ListView beneath a Text View in an Android App. However, the first line of the ListView shows up on the same line as the TextView. How do I get this to move underneath?

Here is the layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    <TextView android:id="@+id/android:question"
          android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/dummy_question" />
    <ListView android:id="@+id/android:list"
          android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    <TextView android:id="@+id/android:empty"
          android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/no_notes"/>

</LinearLayout>

Body:
I see two issues. First, as chirag mentioned, you need to set the ListView orientation. Second, a listView cannot 'wrap content' for height. What would it wrap to? One row, two? Basically, a listView has no idea how tall you want it to be. Try this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:orientation="vertical">

<TextView android:id="@+id/android:question"
      android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/dummy_question" />
<ListView android:id="@+id/android:list"
      android:layout_width="wrap_content"
        android:layout_height="0px" android:layout_weight="1" />
<TextView android:id="@+id/android:empty"
      android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/no_notes"/>
</LinearLayout>


问:
Convert Object To Byte Array without Serialization nor Padding
It seems easy but I can't see it easy at all. My question is I have a struct and I need to convert it to byte stream without any additional bytes for types nor padding nor metadata. Assume I have a struct

```<code>[StructLayout(LayoutKind.Sequential)]
public struct MyStruct
{
    public ushort a;
    public uint b;
    public uint c;
    public ushort d;
}
</code>```

Remark: I can't change the pack here to 1(Project constrains), so using the following solution won't work as there's a padding added

```<code>int size = Marshal.SizeOf(typeof(T));
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(str, ptr, true);
Marshal.Copy(ptr, arr, 0, size);
Marshal.FreeHGlobal(ptr);
</code>```

Also Remark: I can't use Binary format serialization as there's a metadata added.  All what I want simply if a=1 b=2 c=3 d=4 to get binary format in a GENERIC WAY as

```<code>    arr {byte[12]}  byte[]
    [0]  1  byte
    [1]  0  byte
    [2]  2  byte
    [3]  0  byte
    [4]  0  byte
    [5]  0  byte
    [6]  3  byte
    [7]  0  byte
    [8]  0  byte
    [9]  0  byte
    [10] 4  byte
    [11] 0  byte
</code>```

Any help?

答:
Thanks all for your valuable answers/comments! I have found a workaround I will remove the padding manually

```<code>        static byte[] getBytes<T>(T str) where T : struct
    {

        int size = Marshal.SizeOf(typeof(T));
        int Pack = str.GetType().StructLayoutAttribute.Pack;
        byte[] arr = new byte[size];
        IntPtr ptr = Marshal.AllocHGlobal(size);
        Marshal.StructureToPtr(str, ptr, true);
        Marshal.Copy(ptr, arr, 0, size);
        Marshal.FreeHGlobal(ptr);
        arr = RemovePadding<T>(arr.ToList(), str, str.GetType().StructLayoutAttribute.Pack);
        return arr;
    }
    static byte[] RemovePadding<T>(List<byte> buffer, T str, int Pack)
    {
        int largestsize = 0;
        int index = 0;
        int RowOfMemory = 0;

        //Get all fields
        var fields = str.GetType().GetFields();

        //After MSDN
        //The alignment of the type is the size of its largest element (1, 2, 4, 8, etc., bytes) or the specified packing size, whichever is smaller.
        foreach (var item in fields)
        {
            if (Marshal.SizeOf(item.FieldType) > largestsize)
                largestsize = Marshal.SizeOf(item.FieldType);
        }
        if (largestsize < Pack) Pack = largestsize;

        //Find and remove padding from all memory rows
        foreach (var item in fields)
        {
            int size = Marshal.SizeOf(item.FieldType);
            if (RowOfMemory != 0 && (RowOfMemory + size) > Pack)
            {
                int paddingsize = Math.Abs(Pack - RowOfMemory);
                buffer.RemoveRange(index, paddingsize);
                RowOfMemory = size % Pack;
            }
            else if ((RowOfMemory + size) < Pack)
            {
                RowOfMemory += size;
            }
            else if ((RowOfMemory + size) == Pack)
            {
                RowOfMemory = 0;
            }
            index += size;
        }
        if (RowOfMemory != 0)
        {
            int paddingsize = Math.Abs(Pack - RowOfMemory);
            buffer.RemoveRange(index, paddingsize);
        }
        return buffer.ToArray();
    }
</code>```

I will not count this as a right answer, may be someone found a better solution.

Body:
It seems easy but I can't see it easy at all. My question is I have a struct and I need to convert it to byte stream without any additional bytes for types nor padding nor metadata. Assume I have a struct

[StructLayout(LayoutKind.Sequential)]
public struct MyStruct
{
    public ushort a;
    public uint b;
    public uint c;
    public ushort d;
}

Remark: I can't change the pack here to 1(Project constrains), so using the following solution won't work as there's a padding added

int size = Marshal.SizeOf(typeof(T));
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(str, ptr, true);
Marshal.Copy(ptr, arr, 0, size);
Marshal.FreeHGlobal(ptr);

Also Remark: I can't use Binary format serialization as there's a metadata added.  All what I want simply if a=1 b=2 c=3 d=4 to get binary format in a GENERIC WAY as

    arr {byte[12]}  byte[]
    [0]  1  byte
    [1]  0  byte
    [2]  2  byte
    [3]  0  byte
    [4]  0  byte
    [5]  0  byte
    [6]  3  byte
    [7]  0  byte
    [8]  0  byte
    [9]  0  byte
    [10] 4  byte
    [11] 0  byte

Any help?

Body:
Thanks all for your valuable answers/comments! I have found a workaround I will remove the padding manually

        static byte[] getBytes<T>(T str) where T : struct
    {

        int size = Marshal.SizeOf(typeof(T));
        int Pack = str.GetType().StructLayoutAttribute.Pack;
        byte[] arr = new byte[size];
        IntPtr ptr = Marshal.AllocHGlobal(size);
        Marshal.StructureToPtr(str, ptr, true);
        Marshal.Copy(ptr, arr, 0, size);
        Marshal.FreeHGlobal(ptr);
        arr = RemovePadding<T>(arr.ToList(), str, str.GetType().StructLayoutAttribute.Pack);
        return arr;
    }
    static byte[] RemovePadding<T>(List<byte> buffer, T str, int Pack)
    {
        int largestsize = 0;
        int index = 0;
        int RowOfMemory = 0;

        //Get all fields
        var fields = str.GetType().GetFields();

        //After MSDN
        //The alignment of the type is the size of its largest element (1, 2, 4, 8, etc., bytes) or the specified packing size, whichever is smaller.
        foreach (var item in fields)
        {
            if (Marshal.SizeOf(item.FieldType) > largestsize)
                largestsize = Marshal.SizeOf(item.FieldType);
        }
        if (largestsize < Pack) Pack = largestsize;

        //Find and remove padding from all memory rows
        foreach (var item in fields)
        {
            int size = Marshal.SizeOf(item.FieldType);
            if (RowOfMemory != 0 && (RowOfMemory + size) > Pack)
            {
                int paddingsize = Math.Abs(Pack - RowOfMemory);
                buffer.RemoveRange(index, paddingsize);
                RowOfMemory = size % Pack;
            }
            else if ((RowOfMemory + size) < Pack)
            {
                RowOfMemory += size;
            }
            else if ((RowOfMemory + size) == Pack)
            {
                RowOfMemory = 0;
            }
            index += size;
        }
        if (RowOfMemory != 0)
        {
            int paddingsize = Math.Abs(Pack - RowOfMemory);
            buffer.RemoveRange(index, paddingsize);
        }
        return buffer.ToArray();
    }

I will not count this as a right answer, may be someone found a better solution.


问:
How to convert multiple arrays into one array of multiple objects?
Given the following arrays:

```<code>let x = [a, b, c, d];
let y = [e, f, g, h];
let w = [i, j, k, l];
</code>```

How to generated a new array of objects that look like that:

```<code>let z = [
    {x: a, y: e, w: i},
    {x: b, y: f, w: j},
    {x: c, y: g, w: k},
    {x: d, y: h, w: l}
];
</code>```

This is what I came up so far:

```<code>for(var i; i < x.length; i++) {

    x = x[i];
    y = y[i];
    w = w[i];

    obj = {
        x: x,
        y: y,
        w: w
    };

    z = [];
    z.push(obj);
}
</code>```

Thanks!

答:
You could use an array with the keys for the object and reduce the array with the arrays.

var x = ['a', 'b', 'c', 'd'],
    y = ['e', 'f', 'g', 'h'],
    w = ['i', 'j', 'k', 'l'],
    keys = ['x', 'y', 'w'],
    result = [x, y, w].reduce(function (r, a, i) {
        a.forEach(function (v, j) {
            r[j] = r[j] || {}
            r[j][keys[i]] = v;
        });
        return r;
    }, []);

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
Given the following arrays:

let x = [a, b, c, d];
let y = [e, f, g, h];
let w = [i, j, k, l];

How to generated a new array of objects that look like that:

let z = [
    {x: a, y: e, w: i},
    {x: b, y: f, w: j},
    {x: c, y: g, w: k},
    {x: d, y: h, w: l}
];

This is what I came up so far:

for(var i; i < x.length; i++) {

    x = x[i];
    y = y[i];
    w = w[i];

    obj = {
        x: x,
        y: y,
        w: w
    };

    z = [];
    z.push(obj);
}

Thanks!

Body:
You could use an array with the keys for the object and reduce the array with the arrays.

var x = ['a', 'b', 'c', 'd'],
    y = ['e', 'f', 'g', 'h'],
    w = ['i', 'j', 'k', 'l'],
    keys = ['x', 'y', 'w'],
    result = [x, y, w].reduce(function (r, a, i) {
        a.forEach(function (v, j) {
            r[j] = r[j] || {}
            r[j][keys[i]] = v;
        });
        return r;
    }, []);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Receiving a Task<T> from another process on same machine
I have two internal processes which I use to upload long sdos strings to an API. Process 1 reads these from another stream. Process 1 (client) sends strings to process 2 (server) via a [ServiceContract] and a [MessageContract]. Process 2 then sends this to an API which in turn processes the sdos and uploads to a server.

```<code>[MessageContract]
public class CallRequestMessage
{
    [MessageHeader]
    public string Sdos;
    [MessageHeader]
    public int ArrayLength;
    [MessageBodyMember]
    public Stream SdosStream;
}

[MessageContract]
public class CallResponseMessage
{
    [MessageHeader]
    public Task<ResultCode> Task;
}
</code>```

Since the bulk of the time processing the string is in the API, I want to try and return a Task<ResultCode> from my server that will get a result from the API once the processing has concluded. Then my threads can work on client-side processing (in this case, reading the sdos strings from a stream input).

My problem is that the tasks returned to the client seem to be different to the ones that I create on the server. On the server I have the code

```<code>task = Task<ResultCode>.Factory.StartNew(() =>
{
    ResultCode res;
    lock (SyncObject)
        res = upload(/* input */)
    return res;
});

// ...other code

return new CallResponseMessage { Task = task };
</code>```

where upload is a method in the API, accessed by process 2 by using a [DllImportAttribute].

Using logs I have seen that the task does complete on the server (all sdos are uploaded), however on the client side, all tasks appear to not have started, and so retrieving the results is not possible directly.

An alternative approach that I thought of would be to return nothing from the server, and add a separate method that retrospectively goes to the server, awaits the tasks, and returns an aggregated result. I would like to try and get the task back directly, though, as this implementation may be a model for future services in my projects.

Thank you for any help.

答:
There are no Task instances across process boundaries. The server's task is the Task that sends the data to the client. The client task is the task that receives the data. If you use the asnyc methods on the auto-generated WCF clients, by default, WCF will not stream the data from server to client, so your normal flow will be:

Start client task -> Send request -> Start server task -> End server task -> Send response -> End client task

In order for the server tasks to be performed asynchronously, you can design your service methods with the task asynchronous pattern (TAP). This example is from the official documentation:

```<code>public class SampleService:ISampleService
{
   // ...
   public async Task<string> SampleMethodTaskAsync(string msg)
   {
      return Task<string>.Factory.StartNew(() =>
      {
         return msg;
      });
   }
   // ...
}
</code>```

The benefits of tasks on client and server is not so much that the client can receive while the server sends the data, but to allow the server to process more incoming requests while other requests are waiting for long running operations (e.g. data access) and the client to do something useful while the data is received.

Your options are:

Use seperate asynchronous server and client operations

Unless you are transferring large amounts of data and performance is critical, there is nothing wrong with the situation. You can still use tasks for async programming. However, your approach of returning a task won't work. Use the described combination of async service methods and the auto-generated async client methods. You will essentially achieve the same result, which is that both, client and server will perform the operation asynchronously.

Stream the data

If you must start processing on the client while the server is sending the data (which only brings you a practical benefit for large amounts of data), you can stream the data from the server. This issue is too large to cover here, but a good point to start is the official documentation.

Body:
I have two internal processes which I use to upload long sdos strings to an API. Process 1 reads these from another stream. Process 1 (client) sends strings to process 2 (server) via a [ServiceContract] and a [MessageContract]. Process 2 then sends this to an API which in turn processes the sdos and uploads to a server.

[MessageContract]
public class CallRequestMessage
{
    [MessageHeader]
    public string Sdos;
    [MessageHeader]
    public int ArrayLength;
    [MessageBodyMember]
    public Stream SdosStream;
}

[MessageContract]
public class CallResponseMessage
{
    [MessageHeader]
    public Task<ResultCode> Task;
}

Since the bulk of the time processing the string is in the API, I want to try and return a Task<ResultCode> from my server that will get a result from the API once the processing has concluded. Then my threads can work on client-side processing (in this case, reading the sdos strings from a stream input).

My problem is that the tasks returned to the client seem to be different to the ones that I create on the server. On the server I have the code

task = Task<ResultCode>.Factory.StartNew(() =>
{
    ResultCode res;
    lock (SyncObject)
        res = upload(/* input */)
    return res;
});

// ...other code

return new CallResponseMessage { Task = task };

where upload is a method in the API, accessed by process 2 by using a [DllImportAttribute].

Using logs I have seen that the task does complete on the server (all sdos are uploaded), however on the client side, all tasks appear to not have started, and so retrieving the results is not possible directly.

An alternative approach that I thought of would be to return nothing from the server, and add a separate method that retrospectively goes to the server, awaits the tasks, and returns an aggregated result. I would like to try and get the task back directly, though, as this implementation may be a model for future services in my projects.

Thank you for any help.

Body:
There are no Task instances across process boundaries. The server's task is the Task that sends the data to the client. The client task is the task that receives the data. If you use the asnyc methods on the auto-generated WCF clients, by default, WCF will not stream the data from server to client, so your normal flow will be:

Start client task -> Send request -> Start server task -> End server task -> Send response -> End client task

In order for the server tasks to be performed asynchronously, you can design your service methods with the task asynchronous pattern (TAP). This example is from the official documentation:

public class SampleService:ISampleService
{
   // ...
   public async Task<string> SampleMethodTaskAsync(string msg)
   {
      return Task<string>.Factory.StartNew(() =>
      {
         return msg;
      });
   }
   // ...
}

The benefits of tasks on client and server is not so much that the client can receive while the server sends the data, but to allow the server to process more incoming requests while other requests are waiting for long running operations (e.g. data access) and the client to do something useful while the data is received.

Your options are:

Use seperate asynchronous server and client operations

Unless you are transferring large amounts of data and performance is critical, there is nothing wrong with the situation. You can still use tasks for async programming. However, your approach of returning a task won't work. Use the described combination of async service methods and the auto-generated async client methods. You will essentially achieve the same result, which is that both, client and server will perform the operation asynchronously.

Stream the data

If you must start processing on the client while the server is sending the data (which only brings you a practical benefit for large amounts of data), you can stream the data from the server. This issue is too large to cover here, but a good point to start is the official documentation.


问:
Bash as a C lib?
I've got a project where I want to do some stuff that would be trivial in bash but where I want/need a binary with has zero external dependencies. So, has anyone written a self contained lib (i.e. not a wrapper around system()) that lets you do bash like stuff from inside C?

Off hand, the things I expect to need are: cp, rm, wget, tftp, ar, tar, guzip and maybe dpkg but I think I can side step that one.

To answer the comments: I'm looking for something along the lines of a statically linked busy-box but where I don't need a shell file as a program for it and where things I don't use automatically don't even get linked in.

答:
You have a lot of custom requirements, and as you say, you don't want "things I don't use don't even get[ting] linked in", so you're going to have to do a lot of hand-hacking.

If you compile all the external dependencies into object files, you should be able to link them in to your own tool (assuming no namespace conflicts; a big assumption, but not too bad if you're careful), you should be able to do it if you just excise their main() functions.

In fact, for the dependencies, you can probably even just rename their main(), and have the tool available to you as if you were calling it from the command-line yourself, by packing their argc/argv, though this would likely have some overhead, rather than calling the individual functions yourself.

The aforementioned busybox already offers all the features you require (even tar and wget) except for dpkg, and since there's already a lib for that, I'd say you're well on your way.

Title: Bash as a C lib?