问:
Is decision logic a client or server side responsibility?
I had some debate with a colleague regard how the logic of add/delete entries should work.

So the problem is that an object has following properties

```<code>{
   foo: []
}
</code>```

When adding more to the foo list, user can click save

Wherein a REST method is called to add the new entries in the foo property.

So next time the object looks like following

```<code>{
   foo: [1, 2, 3]
}
</code>```

User this time delete 1 and then re-adds it. And click save.
Nothing should happen.

The actual call to REST method occurs when save is clicked.

My colleague, says to simplify things on client side, it should only need to call the REST method which does add. And the REST method should add all the entries again. So he wants the add method to basically remove every entries related to that object and re-add all of them again.

I'm against this because it does unneeded work. I could write logic to check which entry is new. However since this is a business class of application I don't think putting that logic on server side is a good idea because of cost. Instead I think it should be resolved on the client side.

So that the REST method to add does what it does, it adds new entries, and not do two things which are delete all entries and then add all entries.

Examples on call to REST method

```<code>Add
POST: REST/{objectId}?entries=1,2,3
</code>```

Result entries = [1,2,3]

```<code>Remove
DELETE: REST/{objectId}?entries=1
</code>```

Result entries = [2,3]

答:
My colleague, says to simplify things on client side, it should only need to call the REST method which does add. And the REST method should add all the entries again. So he wants the add method to basically remove every entries related to that object and re-add all of them again.

I disagree with that. Imagine yo have 10k entries, why delete 9 999 entries just to delete one item?

I'm against this because it does unneeded work.

You are right. In addition, maybe you will do unnecessary requests to database and deteriorate access to it.

The client must not know this logic. it doesn't have all elements to take the decision to add or delete an element into the resource. So, the client asks to API to do an action and the API answers it if the action is done or not.

If you put the logic in the backend your API in more reusable. Tomorrow, you have another client of your API, why rewrite the logic of add or delete in the client side? Normally, it's the same.

Body:
I had some debate with a colleague regard how the logic of add/delete entries should work.

So the problem is that an object has following properties

{
   foo: []
}

When adding more to the foo list, user can click save

Wherein a REST method is called to add the new entries in the foo property.

So next time the object looks like following

{
   foo: [1, 2, 3]
}

User this time delete 1 and then re-adds it. And click save.
Nothing should happen.

The actual call to REST method occurs when save is clicked.

My colleague, says to simplify things on client side, it should only need to call the REST method which does add. And the REST method should add all the entries again. So he wants the add method to basically remove every entries related to that object and re-add all of them again.

I'm against this because it does unneeded work. I could write logic to check which entry is new. However since this is a business class of application I don't think putting that logic on server side is a good idea because of cost. Instead I think it should be resolved on the client side.

So that the REST method to add does what it does, it adds new entries, and not do two things which are delete all entries and then add all entries.

Examples on call to REST method

Add
POST: REST/{objectId}?entries=1,2,3

Result entries = [1,2,3]

Remove
DELETE: REST/{objectId}?entries=1

Result entries = [2,3]


来源: stackexchange

问:
What's the easiest way to implement collision detection in an XNA Game w/ C#?
I'm basically working on a Pong clone, and I wanted to add collision. The way I wanted it to work, is that the paddles would each be divided into 4 sections (not visually), and the ball will react differently depending on which section it hits.

As far as collision goes, I only know rectangle collision, and that's basically the entire paddle as a whole. I do not know how to make it so the paddle has 4 possible points of collision with different reactions.

答:
Just to add another dimension to the answers, this is a classic build vs buy decision :-) If you want to build, by all means do it yourself. However if you would rather just focus on your game, there are plenty of libraries out there that you could leverage for this functionality:

Farseer Physics (http://farseerphysics.codeplex.com/), focused on 2D, perfect IMO for what you describe above

Physics2D (http://sites.google.com/site/physics2d/)

JigLibX (http://jiglibx.codeplex.com/)

There's a really good list of other engines which will likely be more comprehensive than what I could provide in an SO answer on XNA Wiki:

http://www.xnawiki.com/index.php?title=Physics_Engine

ContentLicense: CC BY-SA 2.5


问:
Last table row at the end of the page
I want my table to look like this image:

My table looks like this image:

So, how to do that?

How my table is generated:

```<code><table id="chiru_inv" class="table table-striped table-hover table-bordered table-responsive">
   <tr>
    <td colspan="4" align="center">
      <h1>Company</br><span style="font-size: 75%;">Number</span></h1>
    </td>
  <tr>
    <td colspan="2">
      <h3><span style="float: left;">Bill No.: 4</span></h3>
    </td>
    <td colspan="2">
      <h3><span style="float: right;">Date: </span></h3>
    </td>
  </tr>
  </tr>
  <tr>
    <td colspan="4">
      <h3>Customer: </h3>
    </td>
  </tr>
  <tr>
    <th>Sr.</th>
    <th>Item</th>
    <th>Qty</th>
    <th>Amount</th>
  </tr>
    <?php
    $i = 0;
    $total = 0;
        while($rowc)
        {
            extract($rowc);
            $i++;

?>

    <tr>
      <td style="border-top:none !important; border-bottom:none !important;">
      <?php echo $i; ?>
      </td>
      <td style="border-top:none !important; border-bottom:none !important;">
      <?php
      $itm = $IRN;
      $stmti = $user_home->runQuery('SELECT * FROM item WHERE IRN = :iinv ');
    $stmti->bindParam(':iinv',$itm);
    $stmti->execute();
    $rowci = $stmti->fetch(PDO::FETCH_ASSOC);
      echo $rowci['Name'];
      $srv = $SRN;
      $stmts = $user_home->runQuery('SELECT * FROM service WHERE SRN = :sinv ');
    $stmts->bindParam(':sinv',$srv);
    $stmts->execute();
    $rowcs = $stmts->fetch(PDO::FETCH_ASSOC);
      ?>
       (<?php echo $rowcs['Name']; ?>)
      </td>
      <td style="border-top:none !important; border-bottom:none !important;">
      <?php echo $Quantity; ?>
      </td>
      <td style="border-top:none !important; border-bottom:none !important;">
      <?php echo $Amnt; ?>
      </td>
    </tr>

            <?php
            $total = $total + $Amnt;
        $rowc=$stmt->fetch(PDO::FETCH_ASSOC);
        }
        ?>

    <tr>
      <td colspan="2"><strong><?php echo getIndianCurrency($total); ?>Only</strong></td>
      <td><strong>Total:</strong></td>
      <td><strong><?php echo $total; ?></strong></td>
    </tr>

</table>
</code>```

The table can have only 1 row, or 2 or it can have 4 rows also!

For all the rows, table should always be like this only.

The rows of the table change according to the records in the database.

答:
```<code>    <table id="chiru_inv" class="table table-striped table-hover table-bordered table-responsive">
       <tr>
        <td colspan="4" align="center">
          <h1>Company</br><span style="font-size: 75%;">Number</span></h1>
        </td>
      <tr>
        <td colspan="2">
          <h3><span style="float: left;">Bill No.: 4</span></h3>
        </td>
        <td colspan="2">
          <h3><span style="float: right;">Date: </span></h3>
        </td>
      </tr>
      </tr>
      <tr>
        <td colspan="4">
          <h3>Customer: </h3>
        </td>
      </tr>
      <tr>
        <th>Sr.</th>
        <th>Item</th>
        <th>Qty</th>
        <th>Amount</th>
      </tr>
        <?php
    $i = 0;
    $total = 0;
    $stmttr = $user_home->runQuery("SELECT * FROM invoice WHERE BRN = :inv"); // Your query
    $stmttr->bindParam(':inv',$irn);
$allRows = $stmttr->rowCount(); // Count Total rows available in result
$tri = 0; // initiate variable to check <tr> status
        while($rowc)
        {
            extract($rowc);
            $i++;

?>

    <tr  <?php if(++$tri==$allrows) { ?> style="padding-bottom: 100px;"<?php } ?>   >
          <td style="border-top:none !important; border-bottom:none !important;">
          <?php echo $i; ?>
          </td>
          <td style="border-top:none !important; border-bottom:none !important;">
          <?php
          $itm = $IRN;
          $stmti = $user_home->runQuery('SELECT * FROM item WHERE IRN = :iinv ');
        $stmti->bindParam(':iinv',$itm);
        $stmti->execute();
        $rowci = $stmti->fetch(PDO::FETCH_ASSOC);
          echo $rowci['Name'];
          $srv = $SRN;
          $stmts = $user_home->runQuery('SELECT * FROM service WHERE SRN = :sinv ');
        $stmts->bindParam(':sinv',$srv);
        $stmts->execute();
        $rowcs = $stmts->fetch(PDO::FETCH_ASSOC);
          ?>
           (<?php echo $rowcs['Name']; ?>)
          </td>
          <td style="border-top:none !important; border-bottom:none !important;">
          <?php echo $Quantity; ?>
          </td>
          <td style="border-top:none !important; border-bottom:none !important;">
          <?php echo $Amnt; ?>
          </td>
        </tr>

                <?php
                $total = $total + $Amnt;
            $rowc=$stmt->fetch(PDO::FETCH_ASSOC);
            }
            ?>

        <tr>
          <td colspan="2"><strong><?php echo getIndianCurrency($total); ?>Only</strong></td>
          <td><strong>Total:</strong></td>
          <td><strong><?php echo $total; ?></strong></td>
        </tr>

    </table>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Last table row at the end of the page

Body:
I want my table to look like this image:

My table looks like this image:

So, how to do that?

How my table is generated:

Company
Number

Bill No.: 4

Date:

Customer:

    Sr.
    Item
    Qty
    Amount

    <?php
    $i = 0;
    $total = 0;
        while($rowc)
        {
            extract($rowc);
            $i++;

?>

      <?php echo $i; ?>

      <?php
      $itm = $IRN;
      $stmti = $user_home->runQuery('SELECT * FROM item WHERE IRN = :iinv ');
    $stmti->bindParam(':iinv',$itm);
    $stmti->execute();
    $rowci = $stmti->fetch(PDO::FETCH_ASSOC);
      echo $rowci['Name'];
      $srv = $SRN;
      $stmts = $user_home->runQuery('SELECT * FROM service WHERE SRN = :sinv ');
    $stmts->bindParam(':sinv',$srv);
    $stmts->execute();
    $rowcs = $stmts->fetch(PDO::FETCH_ASSOC);
      ?>
       (<?php echo $rowcs['Name']; ?>)

      <?php echo $Quantity; ?>

      <?php echo $Amnt; ?>

            <?php
            $total = $total + $Amnt;
        $rowc=$stmt->fetch(PDO::FETCH_ASSOC);
        }
        ?>

      <?php echo getIndianCurrency($total); ?>Only
      Total:
      <?php echo $total; ?>

The table can have only 1 row, or 2 or it can have 4 rows also!

For all the rows, table should always be like this only.

The rows of the table change according to the records in the database.

Body:
    <table id="chiru_inv" class="table table-striped table-hover table-bordered table-responsive">
       <tr>
        <td colspan="4" align="center">
          <h1>Company</br><span style="font-size: 75%;">Number</span></h1>
        </td>
      <tr>
        <td colspan="2">
          <h3><span style="float: left;">Bill No.: 4</span></h3>
        </td>
        <td colspan="2">
          <h3><span style="float: right;">Date: </span></h3>
        </td>
      </tr>
      </tr>
      <tr>
        <td colspan="4">
          <h3>Customer: </h3>
        </td>
      </tr>
      <tr>
        <th>Sr.</th>
        <th>Item</th>
        <th>Qty</th>
        <th>Amount</th>
      </tr>
        <?php
    $i = 0;
    $total = 0;
    $stmttr = $user_home->runQuery("SELECT * FROM invoice WHERE BRN = :inv"); // Your query
    $stmttr->bindParam(':inv',$irn);
$allRows = $stmttr->rowCount(); // Count Total rows available in result
$tri = 0; // initiate variable to check <tr> status
        while($rowc)
        {
            extract($rowc);
            $i++;

?>

    <tr  <?php if(++$tri==$allrows) { ?> style="padding-bottom: 100px;"<?php } ?>   >
          <td style="border-top:none !important; border-bottom:none !important;">
          <?php echo $i; ?>
          </td>
          <td style="border-top:none !important; border-bottom:none !important;">
          <?php
          $itm = $IRN;
          $stmti = $user_home->runQuery('SELECT * FROM item WHERE IRN = :iinv ');
        $stmti->bindParam(':iinv',$itm);
        $stmti->execute();
        $rowci = $stmti->fetch(PDO::FETCH_ASSOC);
          echo $rowci['Name'];
          $srv = $SRN;
          $stmts = $user_home->runQuery('SELECT * FROM service WHERE SRN = :sinv ');
        $stmts->bindParam(':sinv',$srv);
        $stmts->execute();
        $rowcs = $stmts->fetch(PDO::FETCH_ASSOC);
          ?>
          &nbsp;(<?php echo $rowcs['Name']; ?>)
          </td>
          <td style="border-top:none !important; border-bottom:none !important;">
          <?php echo $Quantity; ?>
          </td>
          <td style="border-top:none !important; border-bottom:none !important;">
          <?php echo $Amnt; ?>
          </td>
        </tr>

                <?php
                $total = $total + $Amnt;
            $rowc=$stmt->fetch(PDO::FETCH_ASSOC);
            }
            ?>

        <tr>
          <td colspan="2"><strong><?php echo getIndianCurrency($total); ?>Only</strong></td>
          <td><strong>Total:</strong></td>
          <td><strong><?php echo $total; ?></strong></td>
        </tr>

    </table>


问:
How detect my std::function is still available?
Im using std::function and std::bind for my async thread callback system.
but sometimes my system delete my object even some threads are not done.
here some example code

```<code>#include <iostream>
#include <functional>

using namespace std;

class Character {
public:
    Character() { a = 10; }

    void Print() { cout << a << endl; }

private:
    int a;

};

void main() {
    Character* pChar = new Character();

    std::function<void()> callback = std::bind(&Character::Print, pChar);
    callback(); // it's fine

    delete pChar;

    callback(); // fail

    if (callback)   // this if doesn't work
        callback();

    // i want to check callback is still available
}
</code>```

please help me to do this.

答:
Instead of an raw pointer, you may use std::weak_ptr, something like:

```<code>void safePrint(std::weak_ptr<Character> w)
{
    auto pChar = w.lock();
    if (pChar) {
        pChar->Print();
    }
}

int main() {
    auto pChar = make_shared<Character>();

    auto callback = std::bind(&safePrint, std::weak_ptr<Character>(pChar));
    callback(); // it's fine

    pChar.reset();

    callback(); // won't print, and don't crash :)
}
</code>```

Body:
Im using std::function and std::bind for my async thread callback system.
but sometimes my system delete my object even some threads are not done.
here some example code

#include <iostream>
#include <functional>

using namespace std;

class Character {
public:
    Character() { a = 10; }

    void Print() { cout << a << endl; }

private:
    int a;

};

void main() {
    Character* pChar = new Character();

    std::function<void()> callback = std::bind(&Character::Print, pChar);
    callback(); // it's fine

    delete pChar;

    callback(); // fail

    if (callback)   // this if doesn't work
        callback();

    // i want to check callback is still available
}

please help me to do this.

Body:
Instead of an raw pointer, you may use std::weak_ptr, something like:

void safePrint(std::weak_ptr<Character> w)
{
    auto pChar = w.lock();
    if (pChar) {
        pChar->Print();
    }
}

int main() {
    auto pChar = make_shared<Character>();

    auto callback = std::bind(&safePrint, std::weak_ptr<Character>(pChar));
    callback(); // it's fine

    pChar.reset();

    callback(); // won't print, and don't crash :)
}


答:
So, let's suppose that you currently have

```<code>{ foo = [1, 3, 4] }.
</code>```

A POST method is called:

```<code>REST/{objectId}?entries=1,2
</code>```

What happens? Based on your description, I would suppose it would result in

```<code>{ foo = [1, 2] }
</code>```

not [1, 2, 3, 4]. If that's the case, then I think your colleague is right. You have to remove existing items, and re-add the newly specified entries. In this case, your REST method should really be PUT not POST.

Now, on the other hand, if you expect the result to be

```<code>{ foo = [1, 2, 3, 4] }
</code>```

not [1, 2], then your approach seems more reasonable. In this case, your REST method seems to be semantically closer to PATCH than POST.

This is an interesting example since you're manipulating "sub-resources" not the resource itself ({...} in your example, which includes foo).

Title: Is decision logic a client or server side responsibility?

Body:
So, let's suppose that you currently have

{ foo = [1, 3, 4] }.

A POST method is called:

REST/{objectId}?entries=1,2

What happens? Based on your description, I would suppose it would result in

{ foo = [1, 2] }

not [1, 2, 3, 4]. If that's the case, then I think your colleague is right. You have to remove existing items, and re-add the newly specified entries. In this case, your REST method should really be PUT not POST.

Now, on the other hand, if you expect the result to be

{ foo = [1, 2, 3, 4] }

not [1, 2], then your approach seems more reasonable. In this case, your REST method seems to be semantically closer to PATCH than POST.

This is an interesting example since you're manipulating "sub-resources" not the resource itself ({...} in your example, which includes foo).


问:
Rails - ActiveAdmin and Papertrail - a DRY approach
I have lot of Models where I use PaperTrail, like:

```<code>class User < ActiveRecord::Base
  has_paper_trail
end
</code>```

In the ActiveAdmin model's file I have:

```<code>ActiveAdmin.register User do

  ...

  # versioning part
  action_item :history, only: :show do
    link_to('History', history_backend_user_path(user), method: :get)
  end

  sidebar :versionate, :partial => "layouts/version", :only => :show

  member_action :history do
    @user = User.find(params[:id])
    @versions = @user.versions.reorder(created_at: :desc)
    render "layouts/history"
  end
end
</code>```

I have to repeat this lines for every model and I'm wondering how I could dry it up.

答:
I finally ended up with the following solution which is working (note also that all the references to User resource have been generalized):

```<code># app/admin-shared/active_admin_loggable.rb

module ActiveAdminLoggable
  def self.extended(base)
    base.instance_eval do
      action_item :history, only: :show do
        link_to('History',
                eval("history_backend_#{resource.class.to_s.downcase}_path(#{resource.class.to_s.downcase})"),
                method: :get
        )
      end

      sidebar :versionate, :partial => "layouts/version", :only => :show

      member_action :history do
        @this_resource = eval("resource.class").find(params[:id])
        @versions = @this_resource.versions.reorder(created_at: :desc)
        render "layouts/history"
      end
    end
  end
end
</code>```

and:

```<code># app/admin/user.rb
ActiveAdmin.register User do
  extend ActiveAdminLoggable
  ...
end
</code>```

Body:
I have lot of Models where I use PaperTrail, like:

class User < ActiveRecord::Base
  has_paper_trail
end

In the ActiveAdmin model's file I have:

ActiveAdmin.register User do

  ...

  # versioning part
  action_item :history, only: :show do
    link_to('History', history_backend_user_path(user), method: :get)
  end

  sidebar :versionate, :partial => "layouts/version", :only => :show

  member_action :history do
    @user = User.find(params[:id])
    @versions = @user.versions.reorder(created_at: :desc)
    render "layouts/history"
  end
end

I have to repeat this lines for every model and I'm wondering how I could dry it up.

Body:
I finally ended up with the following solution which is working (note also that all the references to User resource have been generalized):

# app/admin-shared/active_admin_loggable.rb

module ActiveAdminLoggable
  def self.extended(base)
    base.instance_eval do
      action_item :history, only: :show do
        link_to('History',
                eval("history_backend_#{resource.class.to_s.downcase}_path(#{resource.class.to_s.downcase})"),
                method: :get
        )
      end

      sidebar :versionate, :partial => "layouts/version", :only => :show

      member_action :history do
        @this_resource = eval("resource.class").find(params[:id])
        @versions = @this_resource.versions.reorder(created_at: :desc)
        render "layouts/history"
      end
    end
  end
end

and:

# app/admin/user.rb
ActiveAdmin.register User do
  extend ActiveAdminLoggable
  ...
end


问:
WPF - Trigger on ColumnHeader's displayIndex greater than value
I am looking for way to make trigger on datagrid that display context menu when clicked on header, which has DisplayIndex greater than 2.

This is what I have now:

```<code>                <Style TargetType="{x:Type DataGridColumnHeader}">

                    <Style.Triggers>
                        <Trigger Property="DisplayIndex"  Value="2">
                            <Setter Property="ContextMenu"
                                 Value="{StaticResource ColumnHeaderContextMenu1}" />
                        </Trigger>
                    </Style.Triggers>
                </Style>
</code>```

Is there any way to do that? Reason why I need this is that user will add columns dynamicly so he will need (sometimes) delete them.

答:
Handled this in other way. The code might be usefull:

xaml:

```<code><DataGrid.ColumnHeaderStyle>
                    <Style TargetType="DataGridColumnHeader">
                        <EventSetter Event="MouseRightButtonDown"  Handler="DataGridColumnHeader_MouseRightButtonDown" />
                    </Style>
                </DataGrid.ColumnHeaderStyle>
</code>```

Code behind:

```<code>private void DataGridColumnHeader_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (((DataGridColumnHeader)sender).DisplayIndex < 2)
            {
                return;
            }

            var x = DataContext as BrygadzistaViewModel;
            x.ColumnHeaderToDelete = ((DataGridColumnHeader)sender).Content.ToString();

            ContextMenu cm = new ContextMenu();
            MenuItem mi = new MenuItem();
            mi.Header = "Usuń";
            mi.Command = x.DeleteDay;
            cm.Items.Add(mi);

            cm.IsOpen = true;
        }
</code>```

Wonder if there is better way to to this ;)

Body:
I am looking for way to make trigger on datagrid that display context menu when clicked on header, which has DisplayIndex greater than 2.

This is what I have now:

                </Style>

Is there any way to do that? Reason why I need this is that user will add columns dynamicly so he will need (sometimes) delete them.

Body:
Handled this in other way. The code might be usefull:

xaml:

<DataGrid.ColumnHeaderStyle>
                    <Style TargetType="DataGridColumnHeader">
                        <EventSetter Event="MouseRightButtonDown"  Handler="DataGridColumnHeader_MouseRightButtonDown" />
                    </Style>
                </DataGrid.ColumnHeaderStyle>

Code behind:

private void DataGridColumnHeader_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (((DataGridColumnHeader)sender).DisplayIndex < 2)
            {
                return;
            }

            var x = DataContext as BrygadzistaViewModel;
            x.ColumnHeaderToDelete = ((DataGridColumnHeader)sender).Content.ToString();

            ContextMenu cm = new ContextMenu();
            MenuItem mi = new MenuItem();
            mi.Header = "Usuń";
            mi.Command = x.DeleteDay;
            cm.Items.Add(mi);

            cm.IsOpen = true;
        }

Wonder if there is better way to to this ;)


问:
NHibernate: eager-reload transient object deep nested child properties
I want to keep an entity, being configured by the user on several pages, in Session. This entity is loaded with NHibernate, with some of its properties/collections lazy-loaded. Say:

Session["order"] = new Order(productRepository.Get(id))

on some next page, get Session["order"] and now work with it

but, at this time order is OK but its Product (and nested stuff) is broken since they're lazy-loaded in different session.

Is it possible to tell NHibernate that I want to eager-load my transient order's properties to the deepest level? Or, the only solution will be to eager-load at the time of
productRepository.Get(id)
? Like,
Session.LoadNestedProperties(order, Eager);

Update: http://www.ribbing.net/index.php?option=com_content&task=view&id=35&Itemid=1 seems to solve the issue. However I'm not sure that reflection is great...

答:
You could eager load all the graph with the objects you need, which is a little bit tricky.

Or you could try the following:

I assume your Order has a single Product. This Product is your problem since it becomes a detached object when the user visits the second page. You could use something like:

session.Update(myorder.Product)

to reattach the Product instance to the current session. After that lazy loading should work fine.


问:
TypeError: util.promisify is not a function?
I'm trying to promisify zlib.gunzip in my react application:

```<code>const zlib = require('zlib')
const util = require('util')

const gunzipPromisified = util.promisify(zlib.gunzip)
</code>```

But I get this error:

TypeError: util.promisify is not a function

That works fine if I put it in a standalone script file and run it through node.

If I try:

```<code>import zlib from 'zlib'
import util from 'util'

const gunzipPromisified = util.promisify(zlib.gunzip)
</code>```

I get something even fancier:

TypeError: __WEBPACK_IMPORTED_MODULE_8_util___default.a.promisify is not a function

What am I missing?

[Edit] The node.js version installed on my laptop is 8.9.1.

[Edit] As somebody commented, the node.js installed in my local development environment has nothing to do with what the app code has access to in the browser. So now my question is, how do I determine what API I have access to in the browser?

答:
I had the same problem, it got fixed by updating Node to a version higher than Node 7. </p>

```<code>n latest
</code>```

<p>In my case Node 9.2.0 as this was added later. </p>

Body:
I'm trying to promisify zlib.gunzip in my react application:

const zlib = require('zlib')
const util = require('util')

const gunzipPromisified = util.promisify(zlib.gunzip)

But I get this error:

TypeError: util.promisify is not a function

That works fine if I put it in a standalone script file and run it through node.

If I try:

import zlib from 'zlib'
import util from 'util'

const gunzipPromisified = util.promisify(zlib.gunzip)

I get something even fancier:

TypeError: __WEBPACK_IMPORTED_MODULE_8_util___default.a.promisify is not a function

What am I missing?

[Edit] The node.js version installed on my laptop is 8.9.1.

[Edit] As somebody commented, the node.js installed in my local development environment has nothing to do with what the app code has access to in the browser. So now my question is, how do I determine what API I have access to in the browser?

Body:
I had the same problem, it got fixed by updating Node to a version higher than Node 7.

n latest

In my case Node 9.2.0 as this was added later.


问:
Difference between Docker Swarm vs Swarm mode?
What difference between initialization swarm over this commands:

```<code>docker swarm init --advertise-addr <manager-ip>
docker -H <worker-ip> swarm join --token <worker-token>
</code>```

And this one:

```<code>docker run swarm manage <consul-ip>
docker -H <worker-ip> run swarm join --advertise=<worker-ip> <consul-ip>
</code>```

Why we need swarm image?

答:
If you run using docker containers, you can have multiple instances of swarm running from one server. And moreover, the swarm network will run in a sandbox environment rather than on your host OS.

You need swarm image if you want to run it in a docker container.

Body:
What difference between initialization swarm over this commands:

docker swarm init --advertise-addr <manager-ip>
docker -H <worker-ip> swarm join --token <worker-token>

And this one:

docker run swarm manage <consul-ip>
docker -H <worker-ip> run swarm join --advertise=<worker-ip> <consul-ip>

Why we need swarm image?


问:
Using CSS to hide the last row conditionally
```<code><table>
<tbody>
<tr class = "row">
  <td class = "A"> </td>
  <td class = "A"> </td>
  <td class = "A B"> </td>
</tr>

<tr class = "row">
  <td class = "A B"> </td>
  <td class = "A B"> </td>
  <td class = "A B"> </td>
</tr>
</tbody>
</table>
</code>```

How to hide the last row if all of its children td contains class B.

I have a calendar that dynamically generate the row and I want to hide the  cell that does not belong to this current month (indicate by class "B"). I want to hide the entire row if all of its children satisfy this condition.

Currently I have

```<code>  tbody {
    tr:last-child {
      display: none;
    }
  }
</code>```

But this will not work as sometimes the last row is partially filled and I dont want to hide it.

Not sure if it is possible with pure CSS selector.

答:
Since I am using React, I am trying to avoid using Javascript to manipulate dom element. I have discovered a way to do it with CSS

```<code>tbody {
    tr:last-child {
      td:first-child.B {
        display:none;
      }
      td:first-child.B ~ td  {
          display:none;
      }
    }
  }
</code>```

First I select the last row tr:last-child and

td:first-child.B In this last row the first child that contains B class will not be displayed

td:first-child.B ~ td In the same last row, the siblings that has the first child containing B class will not be display too

Body:
How to hide the last row if all of its children td contains class B.

I have a calendar that dynamically generate the row and I want to hide the  cell that does not belong to this current month (indicate by class "B"). I want to hide the entire row if all of its children satisfy this condition.

Currently I have

  tbody {
    tr:last-child {
      display: none;
    }
  }

But this will not work as sometimes the last row is partially filled and I dont want to hide it.

Not sure if it is possible with pure CSS selector.

Body:
Since I am using React, I am trying to avoid using Javascript to manipulate dom element. I have discovered a way to do it with CSS

tbody {
    tr:last-child {
      td:first-child.B {
        display:none;
      }
      td:first-child.B ~ td  {
          display:none;
      }
    }
  }

First I select the last row tr:last-child and

td:first-child.B In this last row the first child that contains B class will not be displayed

td:first-child.B ~ td In the same last row, the siblings that has the first child containing B class will not be display too


问:
Javax Transformer fails on high concurrent environment
I have a platform with a Singleton Bean where I load a Transformer instance (because the xslt is so big to create an instance on every request) .

At normal load everything works fine , but making a stress test with a huge number of concurrent requests the transformer starts to throw an ArrayIndexOutOfBoundsException and stops working so I have to restart my server instance or redeploy the application.

This is the way I create my instance when the application is deployed:

```<code>private Transformer createCFDI33TransformerInstance() {

            InputStream in = new URL("http://www.sat.gob.mx/sitio_internet/cfd/3/cadenaoriginal_3_3/cadenaoriginal_3_3.xslt").openStream();

            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer
                    = factory.newTransformer(new StreamSource(in));
            Logger.getLogger(PadeSingleton.class.getName()).log(Level.INFO, " Se ha cargado la instancia de XSLT");
            return transformer;
        } catch (TransformerConfigurationException | IOException ex) {
// Loading a remote instance was not possible so I will load a local instance
            Logger.getLogger(PadeSingleton.class.getName()).log(Level.SEVERE, "No fue posible cargar una nueva instancia de cadena original, se usara la del sistema", ex);
            InputStream in = CFDIv33Tools.class.getClassLoader()
                    .getResourceAsStream("com/soft/cadenaoriginal_3_3.xslt");

            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer;
            try {
                transformer = factory.newTransformer(new StreamSource(in));
                Logger.getLogger(PadeSingleton.class.getName()).log(Level.WARNING, "No fue posible cargar la instancia, se cargara una local");
            } catch (TransformerConfigurationException ex1) {
                Logger.getLogger(PadeSingleton.class.getName()).log(Level.SEVERE, null, ex1);
                // Estamos en problemas
                throw new Exception("Error critico");
            }
            return transformer;
        }
    }
</code>```

So in other bean I inject my Singleton Bean and call a method to get my Transformer instance.

```<code>public static String transform(String xml, Transformer instance) throws Exception {

        StringWriter writer = new StringWriter();

        try {

            instance.transform(new StreamSource(new StringReader(xml)), new StreamResult(writer));

        } catch (TransformerException e) {
            throw new Exception("El comprobante contiene simbolos no permitidos o esta mal formado", e);
        }

        return writer.toString();
    }
</code>```

In  this method is where I get an ArrayIndexOutOfBoundsException

```<code>Caused by: javax.xml.transform.TransformerException: java.lang.ArrayIndexOutOfBoundsException: -1
    at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:746)
    at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:351)
    at com.icontech.pade.common.xml.tools.CFDIv33Tools.calcularCadenaOriginalV2(CFDIv33Tools.java:93)
    ... 138 more
</code>```

I repeat this happens when I making a stress test, when this exception is throwed the following requests fails with this same exception. I suppose my instance is corrupted.. or something.

答:
The Transformer is not thread-safe. You should create a single Templates object representing the compiled stylesheet, and then instantiate a new Transformer object for each transformation.

(In principle the Transformer is serially reusable, so you could reuse a transformer within the same thread once one transformation is finished. I don't know if there are any benefits in doing that with Xalan; in the case of Saxon, it's better to create a new Transformer each time.)

Body:
I have a platform with a Singleton Bean where I load a Transformer instance (because the xslt is so big to create an instance on every request) .

At normal load everything works fine , but making a stress test with a huge number of concurrent requests the transformer starts to throw an ArrayIndexOutOfBoundsException and stops working so I have to restart my server instance or redeploy the application.

This is the way I create my instance when the application is deployed:

private Transformer createCFDI33TransformerInstance() {

            InputStream in = new URL("http://www.sat.gob.mx/sitio_internet/cfd/3/cadenaoriginal_3_3/cadenaoriginal_3_3.xslt").openStream();

            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer
                    = factory.newTransformer(new StreamSource(in));
            Logger.getLogger(PadeSingleton.class.getName()).log(Level.INFO, " Se ha cargado la instancia de XSLT");
            return transformer;
        } catch (TransformerConfigurationException | IOException ex) {
// Loading a remote instance was not possible so I will load a local instance
            Logger.getLogger(PadeSingleton.class.getName()).log(Level.SEVERE, "No fue posible cargar una nueva instancia de cadena original, se usara la del sistema", ex);
            InputStream in = CFDIv33Tools.class.getClassLoader()
                    .getResourceAsStream("com/soft/cadenaoriginal_3_3.xslt");

            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer;
            try {
                transformer = factory.newTransformer(new StreamSource(in));
                Logger.getLogger(PadeSingleton.class.getName()).log(Level.WARNING, "No fue posible cargar la instancia, se cargara una local");
            } catch (TransformerConfigurationException ex1) {
                Logger.getLogger(PadeSingleton.class.getName()).log(Level.SEVERE, null, ex1);
                // Estamos en problemas
                throw new Exception("Error critico");
            }
            return transformer;
        }
    }

So in other bean I inject my Singleton Bean and call a method to get my Transformer instance.

public static String transform(String xml, Transformer instance) throws Exception {

        StringWriter writer = new StringWriter();

        try {

            instance.transform(new StreamSource(new StringReader(xml)), new StreamResult(writer));

        } catch (TransformerException e) {
            throw new Exception("El comprobante contiene simbolos no permitidos o esta mal formado", e);
        }

        return writer.toString();
    }

In  this method is where I get an ArrayIndexOutOfBoundsException

Caused by: javax.xml.transform.TransformerException: java.lang.ArrayIndexOutOfBoundsException: -1
    at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:746)
    at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:351)
    at com.icontech.pade.common.xml.tools.CFDIv33Tools.calcularCadenaOriginalV2(CFDIv33Tools.java:93)
    ... 138 more

I repeat this happens when I making a stress test, when this exception is throwed the following requests fails with this same exception. I suppose my instance is corrupted.. or something.


问:
Design pattern tracking method calls/callers
I don't know what to do in a specific software designing situation. Just searched the internet for solution, but did not find a satisfying answer. So i just want to know your expertise and what the best pratice would be.
I have got a system with several layers of abstraction to begin with. The API shown to the user is a simple class with a compact number of methods. Calling those methods will trigger a avalanche of method calls all the way through the whole abstraction. Certain decissions will be made along the way. Each element on this way can send there decissions and reasons for that decissions via a messageing system back to whoever wants to read it. The system is also logging all the calls and the decissions, which is quite important - well rather the most important. To be honest that is the core issue.

The problem is: I want to know WHO called a certain Method. So i can hand some kind of handle down the way and every abstraction knows: "Right, this guy wants that. So i can log: This guy wanted that."

Why i believe i need this is, because different other systems will be able to use that api. Maybe a GUI wants to drop a command, maybe a HTTP driven remote controller, maybe a hardware trigger, maybe an auto executing routine.

I don't want to let the system make decissions basing on WHO called. I know that would be the absolute opposite of what i intended in abstracting all thouse layers. I just want to log properly. WHO wanted to do WHAT.

Right now i just cannot see the wood for the trees. I just let hand out the API a ticket like object instance. The system is registering that ticket with a id. The API users have to hand in the ticket when calling a command so the system knows who just called.

Well, to put the question to single sentence:
Is there a good pattern for tracking/identifying the caller of a method?

edit:
Altough it is a general problem the used language in this situation is c#!

答:
You could use the [CallerMemberName] attribute:

```<code>public void SomeMethod(string name, [CallerMemberName] string callerName = null)
{
    Console.Writeline($"SomeMethod was called from {callerName}");
    ...
}
</code>```

Body:
You could use the [CallerMemberName] attribute:

public void SomeMethod(string name, [CallerMemberName] string callerName = null)
{
    Console.Writeline($"SomeMethod was called from {callerName}");
    ...
}


问:
Alternative to FogBugz?
FogBugz is great bug tracking and project management software. But it is not free and non-open source. Is there a good enough, open-source and free application, which can be used as replacement to FogBugz?

Actually, I like EBS (Evidence-based Scheduling) feature in FogBugz. Are there good trackers with this feature?

答:
There is Bugzilla, which is an open source issue tracking system.

Here is a more extensive list

http://en.wikipedia.org/wiki/Comparison_of_issue-tracking_systems

Title: Alternative to FogBugz?


问:
How to set the position of the bootstrap notification icon
Can anyone tell me the way to set the Bootstrap notification icon position

Sample code

$('body').notify({
    message: 'Hello World',
    type: 'danger'
});```

My problem here is notification icon and the notification message are not aligning. see the below image.

In the above picture text and the icon are not aligning.

答:
Thanks for all your answers. I have tried the provided CSS styles on the sample project.It was working on it, but when it comes to my project it won't work.

After few hours of investigation, I have found that the issue is due to the test size.
I just posted this answer to tell the cause of the issue.

Body:
Can anyone tell me the way to set the Bootstrap notification icon position

Sample code

$('body').notify({
    message: 'Hello World',
    type: 'danger'
});

My problem here is notification icon and the notification message are not aligning. see the below image.

In the above picture text and the icon are not aligning.


问:
Detect a Price In Brackets in a String (PHP)
I'm looking to analyse strings in PHP. They appear as such:

Premium Upgrade (€10.00)

I want to detect when a string contains '(€10.00)', however the price will change. Hence I'm guessing a RegEx for 'Bracket, Float, Bracket' The end result is I want to remove the price from the string, however, its possible something else may appear in the brackets e.g.

Premium Upgrade (Per Person)

And hence I can't just explode or substring on the first opening brackets. However, there could be two, or more, brackets e.g.

Premium Upgrade (Per Person) (€10.00)

Hence in this instance, I would need to output:

Premium Upgrade (Per Person)

Thus my high level flow would be:

Check string, does it contact brackets and float?

Yes, remove the brackets and float, leaving other brackets in place, proceed.

No brackets and float? Leave as is, proceed.

My pysedo code is:

```<code>//Get my string
$str = $meta->display_key;

//I need a RegEx here to detect my bracket and float e.g. (€X.YY)
if (strpos($str, '(') !== false) {
    //Need to remove brackets and float here, but leave all other brackets in place.
    $formatted_string  = substr($str, 0, strrpos($str, '('));
}

//Do nothing, the string doesn't match my criteria
else $display_key_formatted = $str;
</code>```

答:
To delete a price in brackets that is in the (+CURRENCY_SYMBOL+FLOAT_OR_INT_NUMBER+) you may use

```<code>$res = preg_replace('~\s*\(\p{Sc}\d[.\d]*\)~u', '', $s);
</code>```

See the regex demo

Details

\s* - 0+ whitespaces

\( - a (

\p{Sc} - any currency char

\d - a digit

[.\d]* - 0+ chars that are either . or a digit

\) - a )

See the PHP demo:

```<code>$re = '/\s*\(\p{Sc}\d[.\d]*\)/u';
$str = ' TEXT (text) (€10.00)';
$res = preg_replace($re, '', $str);
echo $res; // =>  TEXT (text)
</code>```

Body:
I'm looking to analyse strings in PHP. They appear as such:

Premium Upgrade (€10.00)

I want to detect when a string contains '(€10.00)', however the price will change. Hence I'm guessing a RegEx for 'Bracket, Float, Bracket' The end result is I want to remove the price from the string, however, its possible something else may appear in the brackets e.g.

Premium Upgrade (Per Person)

And hence I can't just explode or substring on the first opening brackets. However, there could be two, or more, brackets e.g.

Premium Upgrade (Per Person) (€10.00)

Hence in this instance, I would need to output:

Premium Upgrade (Per Person)

Thus my high level flow would be:

Check string, does it contact brackets and float?

Yes, remove the brackets and float, leaving other brackets in place, proceed.

No brackets and float? Leave as is, proceed.

My pysedo code is:

//Get my string
$str = $meta->display_key;

//I need a RegEx here to detect my bracket and float e.g. (€X.YY)
if (strpos($str, '(') !== false) {
    //Need to remove brackets and float here, but leave all other brackets in place.
    $formatted_string  = substr($str, 0, strrpos($str, '('));
}

//Do nothing, the string doesn't match my criteria
else $display_key_formatted = $str;

Body:
To delete a price in brackets that is in the (+CURRENCY_SYMBOL+FLOAT_OR_INT_NUMBER+) you may use

$res = preg_replace('~\s*\(\p{Sc}\d[.\d]*\)~u', '', $s);

See the regex demo

Details

\s* - 0+ whitespaces

\( - a (

\p{Sc} - any currency char

\d - a digit

[.\d]* - 0+ chars that are either . or a digit

\) - a )

See the PHP demo:

$re = '/\s*\(\p{Sc}\d[.\d]*\)/u';
$str = ' TEXT (text) (€10.00)';
$res = preg_replace($re, '', $str);
echo $res; // =>  TEXT (text)


问:
Symfony 3.3 memcached
I've tried diffrent ways of using memcached. I did not find complete explanation, solution, good practice on how to use it with Symfony 3.3.

Question 1: https://symfony.com/blog/new-in-symfony-3-3-memcached-cache-adapter.

Maybe I'm not seeing something here but how do I tell Symfony what I would like to cache(metadata, query, results - I am using doctrine)? Where I can find more configuration options? Is there something I can read about it?

Question 2: http://www.inanzzz.com/index.php/post/7rum/using-doctrine-memcached-caching-with-query-builder-in-symfony

Running stats commands showed some items in memory but there's no performance increase. Nothing at all. I followed steps very carefully. Does any one know do I have to do something more to see the actual results?

I don't think it matters but as example I am using simple endpoint which is getting list of posts from database.

答:
Question 1: how to use cache?

Please see this example from the blog you referred to (New in Symfony 3.3: Memcached Cache Adapter):

```<code>$cacheProduct = $this->get('app.cache.products')->getItem($productId);
if (!$cacheProduct->isHit()) {
    $product = ...
    $cacheProduct->set($product);
    $this->get('app.cache.products')->save($cacheProduct);
} else {
    $product = $cacheProduct->get();
}
</code>```

This cache adapter will allow you to store data in memory. This example uses memcache, but you can also use Redis for example. You have to decide which part of your code is too 'expensive' to perform at every request and can be cached. It's also up to you when the cache should be invalidated, which can be a real pain:

There are two hard things in computer science: cache invalidation, naming things, and off-by-one errors.
  https://twitter.com/codinghorror/status/506010907021828096

The blog is about Symfony's Cache Component, but there is  DoctrineCacheBundle too. The difference between them can cause some confusion, because you can use Doctrine Cache without Doctrine ORM and vice versa.

If you want Doctrine to use metadata_cache, result_cache or query_cache take a look at the configuration reference. Unfortunately I couldn't find any useful documentation about it's usage on Symfony.com.

Question 2: no performance increase?

I think you're not using any caching mechanisms right now, so try to do so.

You can open a separate question with more details if you still encounter problems after you implemented caching mechanisms.

Title: Symfony 3.3 memcached

Body:
Question 1: how to use cache?

Please see this example from the blog you referred to (New in Symfony 3.3: Memcached Cache Adapter):

$cacheProduct = $this->get('app.cache.products')->getItem($productId);
if (!$cacheProduct->isHit()) {
    $product = ...
    $cacheProduct->set($product);
    $this->get('app.cache.products')->save($cacheProduct);
} else {
    $product = $cacheProduct->get();
}

This cache adapter will allow you to store data in memory. This example uses memcache, but you can also use Redis for example. You have to decide which part of your code is too 'expensive' to perform at every request and can be cached. It's also up to you when the cache should be invalidated, which can be a real pain:

There are two hard things in computer science: cache invalidation, naming things, and off-by-one errors.
  https://twitter.com/codinghorror/status/506010907021828096

The blog is about Symfony's Cache Component, but there is  DoctrineCacheBundle too. The difference between them can cause some confusion, because you can use Doctrine Cache without Doctrine ORM and vice versa.

If you want Doctrine to use metadata_cache, result_cache or query_cache take a look at the configuration reference. Unfortunately I couldn't find any useful documentation about it's usage on Symfony.com.

Question 2: no performance increase?

I think you're not using any caching mechanisms right now, so try to do so.

You can open a separate question with more details if you still encounter problems after you implemented caching mechanisms.


问:
ImageView in CardView not show radius on Android 4.3
Here my layout xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/catalog_item_card_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    card_view:cardCornerRadius="5dp"
    card_view:cardUseCompatPadding="true">

    <android.support.constraint.ConstraintLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/imageViewPhoto"
            android:layout_width="wrap_content"
            android:layout_height="160dp"
            android:src="@drawable/test_merchant_preview"
            card_view:layout_constraintLeft_toLeftOf="parent"
            card_view:layout_constraintRight_toRightOf="parent"
            card_view:layout_constraintTop_toTopOf="parent" />

    </android.support.constraint.ConstraintLayout>

</android.support.v7.widget.CardView>
</code>```

Here result on Andrdoid 5.0+

As you can see the ImageView success show with radius. OK.

Now I run app on Android 4.3.

And here result:

As you can see the ImageView show without radius.
Why?

答:
ImageView in CardView not show radius on Android 4.3

CardView  elevation only work on android 5.0 and above

CardView uses elevation property on Lollipop for shadows and falls back to a custom emulated shadow implementation on older platforms.

Due to expensive nature of rounded corner clipping, on platforms before Lollipop, CardView does not clip its children that intersect with rounded corners. Instead, it adds padding to avoid such intersection

more information read here

Body:
Here my layout xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/catalog_item_card_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    card_view:cardCornerRadius="5dp"
    card_view:cardUseCompatPadding="true">

    <android.support.constraint.ConstraintLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/imageViewPhoto"
            android:layout_width="wrap_content"
            android:layout_height="160dp"
            android:src="@drawable/test_merchant_preview"
            card_view:layout_constraintLeft_toLeftOf="parent"
            card_view:layout_constraintRight_toRightOf="parent"
            card_view:layout_constraintTop_toTopOf="parent" />

    </android.support.constraint.ConstraintLayout>

</android.support.v7.widget.CardView>

Here result on Andrdoid 5.0+

As you can see the ImageView success show with radius. OK.

Now I run app on Android 4.3.

And here result:

As you can see the ImageView show without radius.
Why?


问:
Ruby current class
How do I determine the current open class in Ruby?</p>

答:
In my case, the name method was overwrote, I find to_s give me this same result

```<code>class Foo
 puts self.name
 puts self.to_s
end
#=> Foo
#=> Foo
</code>```

Title: Ruby current class

Body:
In my case, the name method was overwrote, I find to_s give me this same result

class Foo
 puts self.name
 puts self.to_s
end
#=> Foo
#=> Foo


问:
scons fails to resolve relative source path
I have the following project structure:

```<code>/prj
    SConstruct
    /src
        /app
        /lib1
        /lib2
        /...
</code>```

'/prj/src/lib1' structure:

```<code>/lib1
    /src
    /test
    SConscript
</code>```

'lib1/SConscript':

```<code>SConscript('test/test1/SConscript',
            exports = 'env',
            variant_dir = '#build/release/lib1/test',
            duplicate = 0)
</code>```

and, finally, 'test' directory:

```<code>/test
    /common
        helpers.cpp
    /test1
        SConscript
        main.cpp
</code>```

In 'test/test1/SConscript' sources specified as:

```<code>Sources = ['../common/helpers.cpp', 'main.cpp']
</code>```

Result:

```<code>scons: *** [build/release/lib1/common/helpers.o]
Source `build/release/lib1/common/helpers.cpp' not found,
needed by target `build/release/lib1/common/helpers.o'
</code>```

As can be seen the problem is that scons tries to find out the source file 'helpers.cpp' in build directory, not in source one.

Some research shows that the problem raised when source file path begins with '../'. When all sources defined underneath 'SConscript' file all is Ok.

Scons v2.5.1 and v3.0.1 demonstrate the same behavior.

What I did wrong? I've found this answer where the author advised:

You could use ../test.cpp as filename

but I doing exactly the same. Is such scons behavior intended or this is a bug?

答:
Your "code" in "lib1/SConscript":

```<code>SConscript('test/test1/SConscript',
            exports = 'env',
            variant_dir = '#build/release/lib1/test',
            duplicate = 0)
</code>```

uses the name of the given "test/test1/SConscript" and implicitly links the folder "test/test1" as "variant folder" (=variant_dir) to the target directory "#build/release/lib1/test". So if a required file can't be found in "#build/release/lib1/test", SCons tries to do an alternative "lookup" in "test/test1/". But this link is not automatically set for the "common" folder as well, and that's why the lookup of the "helpers.cpp" fails. This is the intended behaviour and correct in SCons.

A solution for your current problem would be to move the "test/test1/SConscript" one folder level higher, include the sources there as "common/helpers.cpp" and "test/main.cpp" and call this new SConscript from "lib1/SConscript" as:

```<code>SConscript('test/SConscript',
            exports = 'env',
            variant_dir = '#build/release/lib1/test',
            duplicate = 0)
</code>```

Body:
I have the following project structure:

/prj
    SConstruct
    /src
        /app
        /lib1
        /lib2
        /...

'/prj/src/lib1' structure:

/lib1
    /src
    /test
    SConscript

'lib1/SConscript':

SConscript('test/test1/SConscript',
            exports = 'env',
            variant_dir = '#build/release/lib1/test',
            duplicate = 0)

and, finally, 'test' directory:

/test
    /common
        helpers.cpp
    /test1
        SConscript
        main.cpp

In 'test/test1/SConscript' sources specified as:

Sources = ['../common/helpers.cpp', 'main.cpp']

Result:

scons: *** [build/release/lib1/common/helpers.o]
Source `build/release/lib1/common/helpers.cpp' not found,
needed by target `build/release/lib1/common/helpers.o'

As can be seen the problem is that scons tries to find out the source file 'helpers.cpp' in build directory, not in source one.

Some research shows that the problem raised when source file path begins with '../'. When all sources defined underneath 'SConscript' file all is Ok.

Scons v2.5.1 and v3.0.1 demonstrate the same behavior.

What I did wrong? I've found this answer where the author advised:

You could use ../test.cpp as filename

but I doing exactly the same. Is such scons behavior intended or this is a bug?

Body:
Your "code" in "lib1/SConscript":

SConscript('test/test1/SConscript',
            exports = 'env',
            variant_dir = '#build/release/lib1/test',
            duplicate = 0)

uses the name of the given "test/test1/SConscript" and implicitly links the folder "test/test1" as "variant folder" (=variant_dir) to the target directory "#build/release/lib1/test". So if a required file can't be found in "#build/release/lib1/test", SCons tries to do an alternative "lookup" in "test/test1/". But this link is not automatically set for the "common" folder as well, and that's why the lookup of the "helpers.cpp" fails. This is the intended behaviour and correct in SCons.

A solution for your current problem would be to move the "test/test1/SConscript" one folder level higher, include the sources there as "common/helpers.cpp" and "test/main.cpp" and call this new SConscript from "lib1/SConscript" as:

SConscript('test/SConscript',
            exports = 'env',
            variant_dir = '#build/release/lib1/test',
            duplicate = 0)


问:
Error installing package pdftools in R server
I am using R server on Windows and I need to extract the text of thousands of pdf documents (in order to extract specific data). Thus, I need to install the package "pdftools", though when I do the command to install it :

```<code>install.packages("pdftools")
</code>```

I get the following error :

```<code>Installing package into ‘/home/allusers/recette/R/x86_64-redhat-linux-gnu-library/3.4’

(as ‘lib’ is unspecified)
trying URL 'https://cran.rstudio.com/src/contrib/pdftools_1.5.tar.gz'
Content type 'application/x-gzip' length 811447 bytes (792 KB)

==================================================
downloaded 792 KB

* installing *source* package ‘pdftools’ ...
** package ‘pdftools’ successfully unpacked and MD5 sums checked
Package poppler-cpp was not found in the pkg-config search path.
Perhaps you should add the directory containing `poppler-cpp.pc'
to the PKG_CONFIG_PATH environment variable
No package 'poppler-cpp' found
Using PKG_CFLAGS=-I/usr/include/poppler/cpp -I/usr/include/poppler
Using PKG_LIBS=-lpoppler-cpp

------------------------- ANTICONF ERROR ---------------------------
Configuration failed because poppler-cpp was not found. Try installing:
 * deb: libpoppler-cpp-dev (Debian, Ubuntu, etc)
 * rpm: poppler-cpp-devel (Fedora, CentOS, RHEL)
 * csw: poppler_dev (Solaris)
 * brew: poppler (Mac OSX)
If poppler-cpp is already installed, check that 'pkg-config' is in your
PATH and PKG_CONFIG_PATH contains a poppler-cpp.pc file. If pkg-config
is unavailable you can set INCLUDE_DIR and LIB_DIR manually via:
R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'
--------------------------------------------------------------------

ERROR: configuration failed for package ‘pdftools’
* removing ‘/home/allusers/recette/R/x86_64-redhat-linux-gnu-library/3.4/pdftools’
Warning in install.packages :
  installation of package ‘pdftools’ had non-zero exit status

The downloaded source packages are in
    ‘/tmp/Rtmp3ZNfGJ/downloaded_packages’
</code>```

Did this happen to anyone before? Also I get that the error comes from "poppler-cpp". Thus I tried to install the package "poppler-cpp" but I get the following error cause this is not available for the 3.4.1 R version

```<code>Warning in install.packages :
  package ‘poppler-cpp’ is not available (for R version 3.4.1)
</code>```

Update : Writing this command in the terminal worked

```<code>$ sudo yum install poppler-cpp-devel
</code>```

But then another error showed :

```<code>Error in .shlib_internal(args) :
  C++11 standard requested but CXX11 is not defined
</code>```

答:
Have you try to install in the terminal libpoppler-cpp-dev?

Open the terminal (ctrl+alt+t) and write:

```<code>sudo apt-get install libpoppler-cpp-dev
</code>```

Body:
I am using R server on Windows and I need to extract the text of thousands of pdf documents (in order to extract specific data). Thus, I need to install the package "pdftools", though when I do the command to install it :

install.packages("pdftools")

I get the following error :

Installing package into ‘/home/allusers/recette/R/x86_64-redhat-linux-gnu-library/3.4’

(as ‘lib’ is unspecified)
trying URL 'https://cran.rstudio.com/src/contrib/pdftools_1.5.tar.gz'
Content type 'application/x-gzip' length 811447 bytes (792 KB)

==================================================
downloaded 792 KB

* installing *source* package ‘pdftools’ ...
** package ‘pdftools’ successfully unpacked and MD5 sums checked
Package poppler-cpp was not found in the pkg-config search path.
Perhaps you should add the directory containing `poppler-cpp.pc'
to the PKG_CONFIG_PATH environment variable
No package 'poppler-cpp' found
Using PKG_CFLAGS=-I/usr/include/poppler/cpp -I/usr/include/poppler
Using PKG_LIBS=-lpoppler-cpp

------------------------- ANTICONF ERROR ---------------------------
Configuration failed because poppler-cpp was not found. Try installing:
 * deb: libpoppler-cpp-dev (Debian, Ubuntu, etc)
 * rpm: poppler-cpp-devel (Fedora, CentOS, RHEL)
 * csw: poppler_dev (Solaris)
 * brew: poppler (Mac OSX)
If poppler-cpp is already installed, check that 'pkg-config' is in your
PATH and PKG_CONFIG_PATH contains a poppler-cpp.pc file. If pkg-config
is unavailable you can set INCLUDE_DIR and LIB_DIR manually via:
R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'
--------------------------------------------------------------------

ERROR: configuration failed for package ‘pdftools’
* removing ‘/home/allusers/recette/R/x86_64-redhat-linux-gnu-library/3.4/pdftools’
Warning in install.packages :
  installation of package ‘pdftools’ had non-zero exit status

The downloaded source packages are in
    ‘/tmp/Rtmp3ZNfGJ/downloaded_packages’

Did this happen to anyone before? Also I get that the error comes from "poppler-cpp". Thus I tried to install the package "poppler-cpp" but I get the following error cause this is not available for the 3.4.1 R version

Warning in install.packages :
  package ‘poppler-cpp’ is not available (for R version 3.4.1)

Update : Writing this command in the terminal worked

$ sudo yum install poppler-cpp-devel

But then another error showed :

Error in .shlib_internal(args) :
  C++11 standard requested but CXX11 is not defined

Body:
Have you try to install in the terminal libpoppler-cpp-dev?

Open the terminal (ctrl+alt+t) and write:

sudo apt-get install libpoppler-cpp-dev


问:
Maps shows blank/nothing
My application shows blank google map on a fragment. I just call that fragment from MainActivity. I have searched/read on google, but none did help me at. I am not getting any error and I have used proper APIs Keys.
The following are my classes/mxls:

```<code>public class MainActivity extends AppCompatActivity {

    private Button map_me;
    private Button bCordinates;
    public static Location mLastKnownLocation;
    private FusedLocationProviderClient mFusedLocationProviderClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        try {
            if (true) {
                Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
                locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
                    @Override
                    public void onComplete(@NonNull Task<Location> task) {
                        if (task.isSuccessful()) {

                            //Get the Location of the current device
                            mLastKnownLocation = task.getResult();
                        }
                    }
                });
            }
        } catch (SecurityException e)  {
            Log.e("Exception: %s", e.getMessage());
        }

        bCordinates = (Button)findViewById(R.id.bcordinates);
        bCordinates.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view)
            {
                Toast.makeText(getApplicationContext(),""+mLastKnownLocation.getLatitude()+" , " +
                        " "+mLastKnownLocation.getLongitude(),Toast.LENGTH_LONG).show();
            }
        });

        map_me = (Button)findViewById(R.id.bmap);
        map_me.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FragmentManager fragmentManager = getFragmentManager();
                android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                MyMapFragment myMapFragment = new MyMapFragment();
                fragmentTransaction.add(R.id.fragment_container, myMapFragment);
                fragmentTransaction.commit();
              }
        });
    }
}
</code>```

```<code>public class MyMapFragment extends Fragment implements OnMapReadyCallback {

private GoogleMap googleMap;
private MapView mapView;
private View view;
private FusedLocationProviderClient mFusedLocationProviderClient;

public MyMapFragment() {

}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.map_layout, container, false);
    return view;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    mapView = (MapView) getView().findViewById(R.id.map);
    if(mapView!=null)
    {
        mapView.onCreate(null);
        mapView.onResume();
        mapView.getMapAsync(this);
    }
}

@Override
public void onMapReady(final GoogleMap mGoogleMap) {
    {
        googleMap = mGoogleMap;
        LatLng mLatLng = new LatLng(mLastKnownLocation.getLatitude(),
                mLastKnownLocation.getLongitude());

        googleMap.addMarker(new MarkerOptions().position(mLatLng).title("You're here"));
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mLatLng,15));
        mapView.onResume();
    }
}
}
</code>```

map fragment layout

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MyMapFragment">

    <com.google.android.gms.maps.MapView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/map"
        />

</FrameLayout>
</code>```

main activity layout

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.bdushimi.android2.MainActivity"
    >

    <Button
        android:id="@+id/bmap"
        android:layout_width="88dp"
        android:layout_height="wrap_content"
        android:text="MAP Me!"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginStart="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintHorizontal_bias="0.067"
        tools:layout_editor_absoluteY="32dp" />

    <Button
        android:id="@+id/btext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TEXT ME!"
        tools:layout_editor_absoluteY="32dp"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintHorizontal_bias="0.464" />

    <Button
        android:id="@+id/bcordinates"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Cordinates"
        android:layout_marginEnd="8dp"
        tools:layout_editor_absoluteY="32dp"
        android:layout_marginRight="28dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintHorizontal_bias="0.949"
        app:layout_constraintLeft_toLeftOf="parent" />

    <LinearLayout
        android:id="@+id/fragment_container"
        android:layout_width="333dp"
        android:layout_height="370dp"
        android:orientation="vertical"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="125dp"
        app:layout_constraintHorizontal_bias="0.514"></LinearLayout>
</android.support.constraint.ConstraintLayout>
</code>```

Please, help me to find out what I am doing wrong.

答:
I think you should use MapFragment or SupportMapFragment in your map layout xml file according to your usability.

For now :
Replace :

with :

```<code><fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/headerLayout"
        tools:context="com.dxs.rnf.winwin.main.ui.fragments.DashboardMapFragment"
        android:name="com.google.android.gms.maps.MapFragment"/>
</code>```

Note : Also check your GOOGLE_API_KEY

Title: Maps shows blank/nothing

Body:
My application shows blank google map on a fragment. I just call that fragment from MainActivity. I have searched/read on google, but none did help me at. I am not getting any error and I have used proper APIs Keys.
The following are my classes/mxls:

public class MainActivity extends AppCompatActivity {

    private Button map_me;
    private Button bCordinates;
    public static Location mLastKnownLocation;
    private FusedLocationProviderClient mFusedLocationProviderClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        try {
            if (true) {
                Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
                locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
                    @Override
                    public void onComplete(@NonNull Task<Location> task) {
                        if (task.isSuccessful()) {

                            //Get the Location of the current device
                            mLastKnownLocation = task.getResult();
                        }
                    }
                });
            }
        } catch (SecurityException e)  {
            Log.e("Exception: %s", e.getMessage());
        }

        bCordinates = (Button)findViewById(R.id.bcordinates);
        bCordinates.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view)
            {
                Toast.makeText(getApplicationContext(),""+mLastKnownLocation.getLatitude()+" , " +
                        " "+mLastKnownLocation.getLongitude(),Toast.LENGTH_LONG).show();
            }
        });

        map_me = (Button)findViewById(R.id.bmap);
        map_me.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FragmentManager fragmentManager = getFragmentManager();
                android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                MyMapFragment myMapFragment = new MyMapFragment();
                fragmentTransaction.add(R.id.fragment_container, myMapFragment);
                fragmentTransaction.commit();
              }
        });
    }
}

public class MyMapFragment extends Fragment implements OnMapReadyCallback {

private GoogleMap googleMap;
private MapView mapView;
private View view;
private FusedLocationProviderClient mFusedLocationProviderClient;

public MyMapFragment() {

}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.map_layout, container, false);
    return view;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    mapView = (MapView) getView().findViewById(R.id.map);
    if(mapView!=null)
    {
        mapView.onCreate(null);
        mapView.onResume();
        mapView.getMapAsync(this);
    }
}

@Override
public void onMapReady(final GoogleMap mGoogleMap) {
    {
        googleMap = mGoogleMap;
        LatLng mLatLng = new LatLng(mLastKnownLocation.getLatitude(),
                mLastKnownLocation.getLongitude());

        googleMap.addMarker(new MarkerOptions().position(mLatLng).title("You're here"));
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mLatLng,15));
        mapView.onResume();
    }
}
}

map fragment layout

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MyMapFragment">

    <com.google.android.gms.maps.MapView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/map"
        />

</FrameLayout>

main activity layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.bdushimi.android2.MainActivity"
    >

    <Button
        android:id="@+id/bmap"
        android:layout_width="88dp"
        android:layout_height="wrap_content"
        android:text="MAP Me!"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginStart="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintHorizontal_bias="0.067"
        tools:layout_editor_absoluteY="32dp" />

    <Button
        android:id="@+id/btext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TEXT ME!"
        tools:layout_editor_absoluteY="32dp"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintHorizontal_bias="0.464" />

    <Button
        android:id="@+id/bcordinates"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Cordinates"
        android:layout_marginEnd="8dp"
        tools:layout_editor_absoluteY="32dp"
        android:layout_marginRight="28dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintHorizontal_bias="0.949"
        app:layout_constraintLeft_toLeftOf="parent" />

    <LinearLayout
        android:id="@+id/fragment_container"
        android:layout_width="333dp"
        android:layout_height="370dp"
        android:orientation="vertical"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="125dp"
        app:layout_constraintHorizontal_bias="0.514"></LinearLayout>
</android.support.constraint.ConstraintLayout>

Please, help me to find out what I am doing wrong.

Body:
I think you should use MapFragment or SupportMapFragment in your map layout xml file according to your usability.

For now :
Replace :

with :

<fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/headerLayout"
        tools:context="com.dxs.rnf.winwin.main.ui.fragments.DashboardMapFragment"
        android:name="com.google.android.gms.maps.MapFragment"/>

Note : Also check your GOOGLE_API_KEY


问:
asp.net Panel get elements with Javascript
i m trying to get all elements of a asp panel with a js.
i tried with

```<code>function t1()
{

    var v = document.getElementById('<%=pnlFiltri.ClientID %>').elements;
    alert(v.length)
}

 <asp:Panel ID="pnlFiltri" runat="server" DefaultButton="Upload">
    <asp:TextBox runat="server" type="text" id="tb_Descr" name="Editbox1" value=""/>
 </asp:Panel>

 <asp:Button ID="Upload" runat="server" Text="Upload" OnClientClick="t1();return false;" OnClick="b1_Click"/>
</code>```

but not working...

答:
Try this : </p>

```<code> function t1()
    {

        var v = document.getElementById('<%=pnlFiltri.ClientID %>');
        var array = v.getElementById("<%=tb_Descr.ClientID %>");
        for (var n = 0; n < array.length; ++n) {
         alert("textbox");
       }
    }

<asp:Panel ID="pnlFiltri" runat="server" DefaultButton="Upload">
    <asp:TextBox runat="server" type="text" id="tb_Descr" name="Editbox1" value=""/>
 </asp:Panel>
</code>```

Body:
i m trying to get all elements of a asp panel with a js.
i tried with

function t1()
{

    var v = document.getElementById('<%=pnlFiltri.ClientID %>').elements;
    alert(v.length)
}

 <asp:Panel ID="pnlFiltri" runat="server" DefaultButton="Upload">
    <asp:TextBox runat="server" type="text" id="tb_Descr" name="Editbox1" value=""/>
 </asp:Panel>

 <asp:Button ID="Upload" runat="server" Text="Upload" OnClientClick="t1();return false;" OnClick="b1_Click"/>

but not working...

Body:
Try this :

 function t1()
    {

        var v = document.getElementById('<%=pnlFiltri.ClientID %>');
        var array = v.getElementById("<%=tb_Descr.ClientID %>");
        for (var n = 0; n < array.length; ++n) {
         alert("textbox");
       }
    }

<asp:Panel ID="pnlFiltri" runat="server" DefaultButton="Upload">
    <asp:TextBox runat="server" type="text" id="tb_Descr" name="Editbox1" value=""/>
 </asp:Panel>


问:
Create json array format in android
I want to create json request string. How can I do that? This is my following array:

```<code>[1,2,3,4,5];
</code>```

Now I want to create this type of json request:

```<code>{
    "contact_approve":[
    {
    "contact_id":1
    },
    {
    "contact_id":2
    },
    {
    "contact_id":3
    },
    {
    "contact_id":4
    },
    {
    "contact_id":5
    },
    ]

}
</code>```

Does anyone has the idea about how to create this type of json string?

答:
Here is code:

```<code>  try {
        JSONObject jsonObject = new JSONObject();
        JSONArray array = new JSONArray();
        int[] dataArray = {1,2,3,4,5};
        for( int i=0;i<dataArray.length;i++) {
            JSONObject internalObject = new JSONObject();
            internalObject.put("contact_id",dataArray[i]);
            array.put(internalObject);

        }
        jsonObject.put("contact_approve", array);

        System.out.print(jsonObject);
        Log.v("JsonObject",jsonObject.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }
</code>```

Thanks

Title: Create json array format in android

Body:
I want to create json request string. How can I do that? This is my following array:

[1,2,3,4,5];

Now I want to create this type of json request:

{
    "contact_approve":[
    {
    "contact_id":1
    },
    {
    "contact_id":2
    },
    {
    "contact_id":3
    },
    {
    "contact_id":4
    },
    {
    "contact_id":5
    },
    ]

}

Does anyone has the idea about how to create this type of json string?

Body:
Here is code:

  try {
        JSONObject jsonObject = new JSONObject();
        JSONArray array = new JSONArray();
        int[] dataArray = {1,2,3,4,5};
        for( int i=0;i<dataArray.length;i++) {
            JSONObject internalObject = new JSONObject();
            internalObject.put("contact_id",dataArray[i]);
            array.put(internalObject);

        }
        jsonObject.put("contact_approve", array);

        System.out.print(jsonObject);
        Log.v("JsonObject",jsonObject.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }

Thanks


问:
Converting UTC dates to other timezones
I'm converting a UTC time to another timezone, using this method:

```<code>SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date parsed = format.parse("2011-03-01 15:10:37");
TimeZone tz = TimeZone.getTimeZone("America/Chicago");
format.setTimeZone(tz);

String result = format.format(parsed);
</code>```

So the input is 2011-03-01 15:10:37 but the output of this (value of result) is 2011-03-01 05:40:37. While it seems off, and according to this link, it should be 2011-03-01 09:10:37.

What am I doing wrong?

答:
Following code works fine for me to change a date from one tz to another. It considers the DayLightSaving also. </p>

```<code>public static Calendar changeTimezoneOfDate(Date date, TimeZone fromTZ, TimeZone toTZ) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    long millis = calendar.getTimeInMillis();
    long fromOffset = fromTZ.getOffset(millis);
    long toOffset = toTZ.getOffset(millis);
    long convertedTime = millis - (fromOffset - toOffset);
    Calendar c = Calendar.getInstance();
    c.setTimeInMillis(convertedTime);
    return c;
}
</code>```

Title: Converting UTC dates to other timezones

Body:
I'm converting a UTC time to another timezone, using this method:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date parsed = format.parse("2011-03-01 15:10:37");
TimeZone tz = TimeZone.getTimeZone("America/Chicago");
format.setTimeZone(tz);

String result = format.format(parsed);

So the input is 2011-03-01 15:10:37 but the output of this (value of result) is 2011-03-01 05:40:37. While it seems off, and according to this link, it should be 2011-03-01 09:10:37.

What am I doing wrong?

Body:
Following code works fine for me to change a date from one tz to another. It considers the DayLightSaving also.

public static Calendar changeTimezoneOfDate(Date date, TimeZone fromTZ, TimeZone toTZ) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    long millis = calendar.getTimeInMillis();
    long fromOffset = fromTZ.getOffset(millis);
    long toOffset = toTZ.getOffset(millis);
    long convertedTime = millis - (fromOffset - toOffset);
    Calendar c = Calendar.getInstance();
    c.setTimeInMillis(convertedTime);
    return c;
}


问:
What is <?= in C++?

Possible Duplicate:

  C extension: <? and >? operators

Take a look at the top answer (by sclo) to problem D of this Google Code Jam. It's C++ code, it must have compiled, and it contains statements such as this one:

```<code>double& ret = F[mask][cur][b];
if(j==cur) {
  ret<?=f(tmp,j,b||bad[i])+M[cur][i];   // WTF is <?=   ???
}
</code>```

This doesn't compile in my Visual Studio 2008. What does the <?= mean?

答:
It's a now deprecated g++ extension to the c++ language.

a <? b
is the minimum, returning the smaller of the numeric values a and b;

a >? b
is the maximum, returning the larger of the numeric values a and b.

There are also compound versions

<?=

and

>?=

that do assignment as well.

Title: What is <?= in C++?

Body:
Possible Duplicate:

  C extension: <? and >? operators

Take a look at the top answer (by sclo) to problem D of this Google Code Jam. It's C++ code, it must have compiled, and it contains statements such as this one:

double& ret = F[mask][cur][b];
if(j==cur) {
  ret<?=f(tmp,j,b||bad[i])+M[cur][i];   // WTF is <?=   ???
}

This doesn't compile in my Visual Studio 2008. What does the <?= mean?


问:
Query to produce data only within the asked hour range
Oracle SQL:

I been trying to get this some snippet of query working. When you run it, it prompts you for an hour, and displays no records. I don’t want the query to have a static hour as it will need to be run 4 times a day.
So from the ‘&date’ input, I want it to show data for the past 24 hours. Is that possible?

```<code>dt_time = timestamp(6) field

select distinct to_char(dt_ time,'dd/mm/yyyy hh24'), fault_description
from order
where to_char(dt_time,'hh24') <= '&date' -24
order by to_char(dt_ time,'dd/mm/yyyy hh24');
</code>```

Example, if you enter 10 (when query executed) it will show the data from 10(:00) through to 10(:00)next day

[Hope there is enough info for someone to answer, please]

答:
You can use NUMTODSINTERVAL in a CTE to get the hour as user input.

```<code>WITH t_hour( h ) AS
  ( SELECT NUMTODSINTERVAL(&d,'HOUR' ) h FROM DUAL
  )
SELECT DISTINCT TO_CHAR(dt_time,'dd/mm/yyyy hh24'),
  fault_description
FROM ORDER
CROSS JOIN t_hour
WHERE dt_time BETWEEN TRUNC(SYSDATE) + h AND TRUNC(SYSDATE) + 1 + h
ORDER BY 1;
</code>```

Body:
Oracle SQL:

I been trying to get this some snippet of query working. When you run it, it prompts you for an hour, and displays no records. I don’t want the query to have a static hour as it will need to be run 4 times a day.
So from the ‘&date’ input, I want it to show data for the past 24 hours. Is that possible?

dt_time = timestamp(6) field

select distinct to_char(dt_ time,'dd/mm/yyyy hh24'), fault_description
from order
where to_char(dt_time,'hh24') <= '&date' -24
order by to_char(dt_ time,'dd/mm/yyyy hh24');

Example, if you enter 10 (when query executed) it will show the data from 10(:00) through to 10(:00)next day

[Hope there is enough info for someone to answer, please]

Body:
You can use NUMTODSINTERVAL in a CTE to get the hour as user input.

WITH t_hour( h ) AS
  ( SELECT NUMTODSINTERVAL(&d,'HOUR' ) h FROM DUAL
  )
SELECT DISTINCT TO_CHAR(dt_time,'dd/mm/yyyy hh24'),
  fault_description
FROM ORDER
CROSS JOIN t_hour
WHERE dt_time BETWEEN TRUNC(SYSDATE) + h AND TRUNC(SYSDATE) + 1 + h
ORDER BY 1;


问:
what is the SQL query to get all dates list from specific date to today date
I need to get all dates from 01-01-2016 to todays date.

Example:

```<code>01-01-2016
02-01-2016
03-01-2016
.
.
.
01-02-2016
.
.
.
17-11-2017
</code>```

Any help would be appreciated.

答:
You need to have a numbers table for this to work..

```<code>select dateadd(day,Number,'01-01-2016') from numbers
where
dateadd(day,Number,'01-01-2016')<=getdate()
</code>```

To create  numbers table

```<code>USE Model
GO

CREATE TABLE Numbers
(
    Number INT NOT NULL,
    CONSTRAINT PK_Numbers
        PRIMARY KEY CLUSTERED (Number)
        WITH FILLFACTOR = 100
)

INSERT INTO Numbers
SELECT
    (a.Number * 256) + b.Number AS Number
FROM
    (
        SELECT number
        FROM master..spt_values
        WHERE
            type = 'P'
            AND number <= 255
    ) a (Number),
    (
        SELECT number
        FROM master..spt_values
        WHERE
            type = 'P'
            AND number <= 255
    ) b (Number)
GO
</code>```

References:

http://dataeducation.com/you-require-a-numbers-table/

Body:
I need to get all dates from 01-01-2016 to todays date.

Example:

01-01-2016
02-01-2016
03-01-2016
.
.
.
01-02-2016
.
.
.
17-11-2017

Any help would be appreciated.

Body:
You need to have a numbers table for this to work..

select dateadd(day,Number,'01-01-2016') from numbers
where
dateadd(day,Number,'01-01-2016')<=getdate()

To create  numbers table

USE Model
GO

CREATE TABLE Numbers
(
    Number INT NOT NULL,
    CONSTRAINT PK_Numbers
        PRIMARY KEY CLUSTERED (Number)
        WITH FILLFACTOR = 100
)

INSERT INTO Numbers
SELECT
    (a.Number * 256) + b.Number AS Number
FROM
    (
        SELECT number
        FROM master..spt_values
        WHERE
            type = 'P'
            AND number <= 255
    ) a (Number),
    (
        SELECT number
        FROM master..spt_values
        WHERE
            type = 'P'
            AND number <= 255
    ) b (Number)
GO

References:

http://dataeducation.com/you-require-a-numbers-table/


问:
Avoid resize a section while resizing the screen
When a resize the screen, the text get another size.
I wan't to avoid this and show a scroll bar.
Could you help me please  ?

This is my code :

article {
  width: 100%;
  height: 100%;
}

section.apropos {
  background-color: white;
  color: #666666;
  font-family: Calibri;
  height: 100%;
  width: auto;
  padding-top: 95px;
  padding-left: 20%;
  padding-right: 20%;
  text-align: justify;
  min-width: auto;
  min-height: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <nav>
    <ul>
      <li><a> Notre entreprise</a></li>
      <li class="m"><a> Nous connaitre</a></li>
      <li class="m">Nos métiers</li>
      <li class="m"><a>Nous contacter</a></li>
    </ul>
  </nav>
</header>

<body>
  <article>

    <section class="apropos">
      <h1> A PROPOS DE NOUS </h1> <br/>
      <p> Lorem ipsum dolor sit amet consecteturLorem ipsum dolor sit amet consecteturLorem ipsum dolor sit amet consecteturLorem ipsum dolor sit amet consectetur</p>

      <p> Lorem ipsum dolor sit amet consecteturLorem ipsum dolor sit amet consectetur Lorem ipsum dolor sit amet consecteturLorem ipsum dolor sit amet consectetur</p>
    </section>

    <section class="NotreMetier" id="NotreMetier">

    </section>

  </article>
</body></code>```

Thanks in advance.

答:
Use width: and height: to make it fixed (400px and 300px in my example).
Optionally use overflow: scroll; to give your element scrollbars if the content is bigger than its size.

article {
  width: 400px;
  height: 300px;
  overflow: scroll;
}

section.apropos {
  background-color: white;
  color: #666666;
  font-family: Calibri;
  width: auto;
  padding-top: 95px;
  padding-left: 20%;
  padding-right: 20%;
  text-align: justify;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<header>
  <nav>
    <ul>
      <li><a> Notre entreprise</a></li>
      <li class="m"><a> Nous connaitre</a></li>
      <li class="m">Nos métiers</li>
      <li class="m"><a>Nous contacter</a></li>
    </ul>
  </nav>
</header>
  <article>

    <section class="apropos">
      <h1> A PROPOS DE NOUS </h1> <br/>
      <p> Lorem ipsum dolor sit amet consecteturLorem ipsum dolor sit amet consecteturLorem ipsum dolor sit amet consecteturLorem ipsum dolor sit amet consectetur</p>

      <p> Lorem ipsum dolor sit amet consecteturLorem ipsum dolor sit amet consectetur Lorem ipsum dolor sit amet consecteturLorem ipsum dolor sit amet consectetur</p>
    </section>

    <section class="NotreMetier" id="NotreMetier">

    </section>

  </article>
</body></code>```

Body:
When a resize the screen, the text get another size.
I wan't to avoid this and show a scroll bar.
Could you help me please  ?

This is my code :

article {
  width: 100%;
  height: 100%;
}

section.apropos {
  background-color: white;
  color: #666666;
  font-family: Calibri;
  height: 100%;
  width: auto;
  padding-top: 95px;
  padding-left: 20%;
  padding-right: 20%;
  text-align: justify;
  min-width: auto;
  min-height: auto;
}

 Notre entreprise

 Nous connaitre

Nos métiers

Nous contacter

 A PROPOS DE NOUS

 Lorem ipsum dolor sit amet consecteturLorem ipsum dolor sit amet consecteturLorem ipsum dolor sit amet consecteturLorem ipsum dolor sit amet consectetur

 Lorem ipsum dolor sit amet consecteturLorem ipsum dolor sit amet consectetur Lorem ipsum dolor sit amet consecteturLorem ipsum dolor sit amet consectetur

Thanks in advance.

Body:
Use width: and height: to make it fixed (400px and 300px in my example).
Optionally use overflow: scroll; to give your element scrollbars if the content is bigger than its size.

article {
  width: 400px;
  height: 300px;
  overflow: scroll;
}

section.apropos {
  background-color: white;
  color: #666666;
  font-family: Calibri;
  width: auto;
  padding-top: 95px;
  padding-left: 20%;
  padding-right: 20%;
  text-align: justify;
}

<body>
<header>
  <nav>
    <ul>
      <li><a> Notre entreprise</a></li>
      <li class="m"><a> Nous connaitre</a></li>
      <li class="m"><a onclick='onLinkClick()'>Nos métiers</a></li>
      <li class="m"><a>Nous contacter</a></li>
    </ul>
  </nav>
</header>
  <article>

    <section class="apropos">
      <h1> A PROPOS DE NOUS </h1> <br/>
      <p> Lorem ipsum dolor sit amet consecteturLorem ipsum dolor sit amet consecteturLorem ipsum dolor sit amet consecteturLorem ipsum dolor sit amet consectetur</p>

      <p> Lorem ipsum dolor sit amet consecteturLorem ipsum dolor sit amet consectetur Lorem ipsum dolor sit amet consecteturLorem ipsum dolor sit amet consectetur</p>
    </section>

    <section class="NotreMetier" id="NotreMetier">

    </section>

  </article>
</body>


答:
Well it's simple you can use Gson library to convert objects to json like below;

```<code>Gson gson = new Gson();
String json = gson.toJson({your object you want to convert to json});
</code>```

Another thing to mention is if you are sending request to server you don't even need to do json serialization on your own, Use Retrofit and it will do this for you.

Title: Create json array format in android

Body:
Well it's simple you can use Gson library to convert objects to json like below;

Gson gson = new Gson();
String json = gson.toJson({your object you want to convert to json});

Another thing to mention is if you are sending request to server you don't even need to do json serialization on your own, Use Retrofit and it will do this for you.